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
cfb150cba7842e1033a871f07188c672d740e25c
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/comma.lean
353c2675b75fec6cd677f5562a3901c45c6ed69b
[ "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
7,395
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johan Commelin, Bhavik Mehta -/ import category_theory.natural_isomorphism /-! # Comma categories A comma category is a construction in category theory, which builds a category out of two functors with a common codomain. Specifically, for functors `L : A ⥤ T` and `R : B ⥤ T`, an object in `comma L R` is a morphism `hom : L.obj left ⟶ R.obj right` for some objects `left : A` and `right : B`, and a morphism in `comma L R` between `hom : L.obj left ⟶ R.obj right` and `hom' : L.obj left' ⟶ R.obj right'` is a commutative square ``` L.obj left ⟶ L.obj left' | | hom | | hom' ↓ ↓ R.obj right ⟶ R.obj right', ``` where the top and bottom morphism come from morphisms `left ⟶ left'` and `right ⟶ right'`, respectively. ## Main definitions * `comma L R`: the comma category of the functors `L` and `R`. * `over X`: the over category of the object `X` (developed in `over.lean`). * `under X`: the under category of the object `X` (also developed in `over.lean`). * `arrow T`: the arrow category of the category `T` (developed in `arrow.lean`). ## References * <https://ncatlab.org/nlab/show/comma+category> ## Tags comma, slice, coslice, over, under, arrow -/ namespace category_theory -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ u₁ u₂ u₃ variables {A : Type u₁} [category.{v₁} A] variables {B : Type u₂} [category.{v₂} B] variables {T : Type u₃} [category.{v₃} T] /-- The objects of the comma category are triples of an object `left : A`, an object `right : B` and a morphism `hom : L.obj left ⟶ R.obj right`. -/ structure comma (L : A ⥤ T) (R : B ⥤ T) : Type (max u₁ u₂ v₃) := (left : A . obviously) (right : B . obviously) (hom : L.obj left ⟶ R.obj right) -- Satisfying the inhabited linter instance comma.inhabited [inhabited T] : inhabited (comma (𝟭 T) (𝟭 T)) := { default := { left := default T, right := default T, hom := 𝟙 (default T) } } variables {L : A ⥤ T} {R : B ⥤ T} /-- A morphism between two objects in the comma category is a commutative square connecting the morphisms coming from the two objects using morphisms in the image of the functors `L` and `R`. -/ @[ext] structure comma_morphism (X Y : comma L R) := (left : X.left ⟶ Y.left . obviously) (right : X.right ⟶ Y.right . obviously) (w' : L.map left ≫ Y.hom = X.hom ≫ R.map right . obviously) -- Satisfying the inhabited linter instance comma_morphism.inhabited [inhabited (comma L R)] : inhabited (comma_morphism (default (comma L R)) (default (comma L R))) := { default := { left := 𝟙 _, right := 𝟙 _ } } restate_axiom comma_morphism.w' attribute [simp, reassoc] comma_morphism.w instance comma_category : category (comma L R) := { hom := comma_morphism, id := λ X, { left := 𝟙 X.left, right := 𝟙 X.right }, comp := λ X Y Z f g, { left := f.left ≫ g.left, right := f.right ≫ g.right } } namespace comma section variables {X Y Z : comma L R} {f : X ⟶ Y} {g : Y ⟶ Z} @[simp] lemma id_left : ((𝟙 X) : comma_morphism X X).left = 𝟙 X.left := rfl @[simp] lemma id_right : ((𝟙 X) : comma_morphism X X).right = 𝟙 X.right := rfl @[simp] lemma comp_left : (f ≫ g).left = f.left ≫ g.left := rfl @[simp] lemma comp_right : (f ≫ g).right = f.right ≫ g.right := rfl end variables (L) (R) /-- The functor sending an object `X` in the comma category to `X.left`. -/ @[simps] def fst : comma L R ⥤ A := { obj := λ X, X.left, map := λ _ _ f, f.left } /-- The functor sending an object `X` in the comma category to `X.right`. -/ @[simps] def snd : comma L R ⥤ B := { obj := λ X, X.right, map := λ _ _ f, f.right } /-- We can interpret the commutative square constituting a morphism in the comma category as a natural transformation between the functors `fst ⋙ L` and `snd ⋙ R` from the comma category to `T`, where the components are given by the morphism that constitutes an object of the comma category. -/ @[simps] def nat_trans : fst L R ⋙ L ⟶ snd L R ⋙ R := { app := λ X, X.hom } section variables {L₁ L₂ L₃ : A ⥤ T} {R₁ R₂ R₃ : B ⥤ T} /-- Construct an isomorphism in the comma category given isomorphisms of the objects whose forward directions give a commutative square. -/ @[simps] def iso_mk {X Y : comma L₁ R₁} (l : X.left ≅ Y.left) (r : X.right ≅ Y.right) (h : L₁.map l.hom ≫ Y.hom = X.hom ≫ R₁.map r.hom) : X ≅ Y := { hom := { left := l.hom, right := r.hom }, inv := { left := l.inv, right := r.inv, w' := by { erw [L₁.map_inv l.hom, iso.inv_comp_eq, reassoc_of h, ← R₁.map_comp], simp } } } /-- A natural transformation `L₁ ⟶ L₂` induces a functor `comma L₂ R ⥤ comma L₁ R`. -/ @[simps] def map_left (l : L₁ ⟶ L₂) : comma L₂ R ⥤ comma L₁ R := { obj := λ X, { left := X.left, right := X.right, hom := l.app X.left ≫ X.hom }, map := λ X Y f, { left := f.left, right := f.right } } /-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `L` is naturally isomorphic to the identity functor. -/ @[simps] def map_left_id : map_left R (𝟙 L) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- The functor `comma L₁ R ⥤ comma L₃ R` induced by the composition of two natural transformations `l : L₁ ⟶ L₂` and `l' : L₂ ⟶ L₃` is naturally isomorphic to the composition of the two functors induced by these natural transformations. -/ @[simps] def map_left_comp (l : L₁ ⟶ L₂) (l' : L₂ ⟶ L₃) : (map_left R (l ≫ l')) ≅ (map_left R l') ⋙ (map_left R l) := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- A natural transformation `R₁ ⟶ R₂` induces a functor `comma L R₁ ⥤ comma L R₂`. -/ @[simps] def map_right (r : R₁ ⟶ R₂) : comma L R₁ ⥤ comma L R₂ := { obj := λ X, { left := X.left, right := X.right, hom := X.hom ≫ r.app X.right }, map := λ X Y f, { left := f.left, right := f.right } } /-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `R` is naturally isomorphic to the identity functor. -/ @[simps] def map_right_id : map_right L (𝟙 R) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } /-- The functor `comma L R₁ ⥤ comma L R₃` induced by the composition of the natural transformations `r : R₁ ⟶ R₂` and `r' : R₂ ⟶ R₃` is naturally isomorphic to the composition of the functors induced by these natural transformations. -/ @[simps] def map_right_comp (r : R₁ ⟶ R₂) (r' : R₂ ⟶ R₃) : (map_right L (r ≫ r')) ≅ (map_right L r) ⋙ (map_right L r') := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } end end comma end category_theory
594a83194004de09835c93569d68b877bdcabec0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/big_operators/finsupp.lean
3ebc4941540447e383d8239eac2686ce4bcb865d
[ "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
23,214
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.finsupp.indicator import algebra.big_operators.pi import algebra.big_operators.ring import algebra.big_operators.order import group_theory.submonoid.membership /-! # Big operators for finsupps > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains theorems relevant to big operators in finitely supported functions. -/ noncomputable theory open finset function open_locale big_operators variables {α ι γ A B C : Type*} [add_comm_monoid A] [add_comm_monoid B] [add_comm_monoid C] variables {t : ι → A → C} (h0 : ∀ i, t i 0 = 0) (h1 : ∀ i x y, t i (x + y) = t i x + t i y) variables {s : finset α} {f : α → (ι →₀ A)} (i : ι) variables (g : ι →₀ A) (k : ι → A → γ → B) (x : γ) variables {β M M' N P G H R S : Type*} namespace finsupp /-! ### Declarations about `sum` and `prod` In most of this section, the domain `β` is assumed to be an `add_monoid`. -/ section sum_prod /-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/ @[to_additive "`sum f g` is the sum of `g a (f a)` over the support of `f`. "] def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N := ∏ a in f.support, g a (f a) variables [has_zero M] [has_zero M'] [comm_monoid N] @[to_additive] lemma prod_of_support_subset (f : α →₀ M) {s : finset α} (hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) : f.prod g = ∏ x in s, g x (f x) := finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx @[to_additive] lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) : f.prod g = ∏ i, g i (f i) := f.prod_of_support_subset (subset_univ _) g (λ x _, h x) @[simp, to_additive] lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) : (single a b).prod h = h a b := calc (single a b).prod h = ∏ x in {a}, h x (single a b x) : prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero ... = h a b : by simp @[to_additive] lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N} (h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) := finset.prod_subset support_map_range $ λ _ _ H, by rw [not_mem_support_iff.1 H, h0] @[simp, to_additive] lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl @[to_additive] lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) : f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) := finset.prod_comm @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, } @[simp] lemma sum_ite_self_eq [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (a = x) v 0) = f a := begin classical, convert f.sum_ite_eq a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] end /-- A restatement of `prod_ite_eq` with the equality test reversed. -/ @[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."] lemma prod_ite_eq' [decidable_eq α] (f : α →₀ M) (a : α) (b : α → M → N) : f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 := by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', } @[simp] lemma sum_ite_self_eq' [decidable_eq α] {N : Type*} [add_comm_monoid N] (f : α →₀ N) (a : α) : f.sum (λ x v, ite (x = a) v 0) = f a := begin classical, convert f.sum_ite_eq' a (λ x, id), simp [ite_eq_right_iff.2 eq.symm] end @[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) : f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) := f.prod_fintype _ $ λ a, pow_zero _ /-- If `g` maps a second argument of 0 to 1, then multiplying it over the result of `on_finset` is the same as multiplying it over the original `finset`. -/ @[to_additive "If `g` maps a second argument of 0 to 0, summing it over the result of `on_finset` is the same as summing it over the original `finset`."] lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N} (hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) : (on_finset s f hf).prod g = ∏ a in s, g a (f a) := finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt } /-- Taking a product over `f : α →₀ M` is the same as multiplying the value on a single element `y ∈ f.support` by the product over `erase y f`. -/ @[to_additive /-" Taking a sum over over `f : α →₀ M` is the same as adding the value on a single element `y ∈ f.support` to the sum over `erase y f`. "-/] lemma mul_prod_erase (f : α →₀ M) (y : α) (g : α → M → N) (hyf : y ∈ f.support) : g y (f y) * (erase y f).prod g = f.prod g := begin classical, rw [finsupp.prod, finsupp.prod, ←finset.mul_prod_erase _ _ hyf, finsupp.support_erase, finset.prod_congr rfl], intros h hx, rw finsupp.erase_ne (ne_of_mem_erase hx), end /-- Generalization of `finsupp.mul_prod_erase`: if `g` maps a second argument of 0 to 1, then its product over `f : α →₀ M` is the same as multiplying the value on any element `y : α` by the product over `erase y f`. -/ @[to_additive /-" Generalization of `finsupp.add_sum_erase`: if `g` maps a second argument of 0 to 0, then its sum over `f : α →₀ M` is the same as adding the value on any element `y : α` to the sum over `erase y f`. "-/] lemma mul_prod_erase' (f : α →₀ M) (y : α) (g : α → M → N) (hg : ∀ (i : α), g i 0 = 1) : g y (f y) * (erase y f).prod g = f.prod g := begin classical, by_cases hyf : y ∈ f.support, { exact finsupp.mul_prod_erase f y g hyf }, { rw [not_mem_support_iff.mp hyf, hg y, erase_of_not_mem_support hyf, one_mul] }, end @[to_additive] lemma _root_.submonoid_class.finsupp_prod_mem {S : Type*} [set_like S N] [submonoid_class S N] (s : S) (f : α →₀ M) (g : α → M → N) (h : ∀ c, f c ≠ 0 → g c (f c) ∈ s) : f.prod g ∈ s := prod_mem $ λ i hi, h _ (finsupp.mem_support_iff.mp hi) @[to_additive] lemma prod_congr {f : α →₀ M} {g1 g2 : α → M → N} (h : ∀ x ∈ f.support, g1 x (f x) = g2 x (f x)) : f.prod g1 = f.prod g2 := finset.prod_congr rfl h end sum_prod end finsupp @[to_additive] lemma map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] {H : Type*} [monoid_hom_class H N P] (h : H) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_prod h _ _ /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ @[to_additive "Deprecated, use `_root_.map_finsupp_sum` instead."] protected lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ @[to_additive "Deprecated, use `_root_.map_finsupp_sum` instead."] protected lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P] (h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g /-- Deprecated, use `_root_.map_finsupp_sum` instead. -/ protected lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) := map_finsupp_sum h f g /-- Deprecated, use `_root_.map_finsupp_prod` instead. -/ protected lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S] (h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) := map_finsupp_prod h f g @[to_additive] lemma monoid_hom.coe_finsupp_prod [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) : ⇑(f.prod g) = f.prod (λ i fi, g i fi) := monoid_hom.coe_finset_prod _ _ @[simp, to_additive] lemma monoid_hom.finsupp_prod_apply [has_zero β] [monoid N] [comm_monoid P] (f : α →₀ β) (g : α → β → N →* P) (x : N) : f.prod g x = f.prod (λ i fi, g i fi x) := monoid_hom.finset_prod_apply _ _ _ namespace finsupp lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) : single a s.sum = (s.map (single a)).sum := multiset.induction_on s (single_zero _) $ λ a s ih, by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons] lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) : single a (∑ b in s, f b) = ∑ b in s, single a (f b) := begin transitivity, apply single_multiset_sum, rw [multiset.map_map], refl end lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) := single_finset_sum _ _ _ @[to_additive] lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M} (h0 : ∀a, h a 0 = 1) : (-g).prod h = g.prod (λa b, h a (- b)) := prod_map_range_index h0 end finsupp namespace finsupp lemma finset_sum_apply [add_comm_monoid N] (S : finset ι) (f : ι → α →₀ N) (a : α) : (∑ i in S, f i) a = ∑ i in S, f i a := (apply_add_hom a : (α →₀ N) →+ _).map_sum _ _ @[simp] lemma sum_apply [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} : (f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) := finset_sum_apply _ _ _ lemma coe_finset_sum [add_comm_monoid N] (S : finset ι) (f : ι → α →₀ N) : ⇑(∑ i in S, f i) = ∑ i in S, f i := (coe_fn_add_hom : (α →₀ N) →+ _).map_sum _ _ lemma coe_sum [has_zero M] [add_comm_monoid N] (f : α →₀ M) (g : α → M → β →₀ N) : ⇑(f.sum g) = f.sum (λ a₁ b, g a₁ b) := coe_finset_sum _ _ lemma support_sum [decidable_eq β] [has_zero M] [add_comm_monoid N] {f : α →₀ M} {g : α → M → (β →₀ N)} : (f.sum g).support ⊆ f.support.bUnion (λa, (g a (f a)).support) := have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0), from assume a₁ h, let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in ⟨a, mem_support_iff.mp ha, ne⟩, by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bUnion, sum_apply, exists_prop] lemma support_finset_sum [decidable_eq β] [add_comm_monoid M] {s : finset α} {f : α → (β →₀ M)} : (finset.sum s f).support ⊆ s.bUnion (λ x, (f x).support) := begin rw ←finset.sup_eq_bUnion, induction s using finset.cons_induction_on with a s ha ih, { refl }, { rw [finset.sum_cons, finset.sup_cons], exact support_add.trans (finset.union_subset_union (finset.subset.refl _) ih), }, end @[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} : f.sum (λa b, (0 : N)) = 0 := finset.sum_const_zero @[simp, to_additive] lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} : f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ := finset.prod_mul_distrib @[simp, to_additive] lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M} {h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ := (map_prod ((monoid_hom.id G)⁻¹) _ _).symm @[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M} {h₁ h₂ : α → M → G} : f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ := finset.sum_sub_distrib /-- Taking the product under `h` is an additive-to-multiplicative homomorphism of finsupps, if `h` is an additive-to-multiplicative homomorphism on the support. This is a more general version of `finsupp.prod_add_index'`; the latter has simpler hypotheses. -/ @[to_additive "Taking the product under `h` is an additive homomorphism of finsupps, if `h` is an additive homomorphism on the support. This is a more general version of `finsupp.sum_add_index'`; the latter has simpler hypotheses."] lemma prod_add_index [decidable_eq α] [add_zero_class M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀ a ∈ f.support ∪ g.support, h a 0 = 1) (h_add : ∀ (a ∈ f.support ∪ g.support) b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := begin rw [finsupp.prod_of_support_subset f (subset_union_left _ g.support) h h_zero, finsupp.prod_of_support_subset g (subset_union_right f.support _) h h_zero, ←finset.prod_mul_distrib, finsupp.prod_of_support_subset (f + g) finsupp.support_add h h_zero], exact finset.prod_congr rfl (λ x hx, (by apply h_add x hx)), end /-- Taking the product under `h` is an additive-to-multiplicative homomorphism of finsupps, if `h` is an additive-to-multiplicative homomorphism. This is a more specialized version of `finsupp.prod_add_index` with simpler hypotheses. -/ @[to_additive "Taking the sum under `h` is an additive homomorphism of finsupps, if `h` is an additive homomorphism. This is a more specific version of `finsupp.sum_add_index` with simpler hypotheses."] lemma prod_add_index' [add_zero_class M] [comm_monoid N] {f g : α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f + g).prod h = f.prod h * g.prod h := by classical; exact prod_add_index (λ a ha, h_zero a) (λ a ha, h_add a) @[simp] lemma sum_hom_add_index [add_zero_class M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) : (f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) := sum_add_index' (λ a, (h a).map_zero) (λ a, (h a).map_add) @[simp] lemma prod_hom_add_index [add_zero_class M] [comm_monoid N] {f g : α →₀ M} (h : α → multiplicative M →* N) : (f + g).prod (λ a b, h a (multiplicative.of_add b)) = f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) := prod_add_index' (λ a, (h a).map_one) (λ a, (h a).map_mul) /-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)` and monoid homomorphisms `(α →₀ M) →+ N`. -/ def lift_add_hom [add_zero_class M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) := { to_fun := λ F, { to_fun := λ f, f.sum (λ x, F x), map_zero' := finset.sum_empty, map_add' := λ _ _, sum_add_index' (λ x, (F x).map_zero) (λ x, (F x).map_add) }, inv_fun := λ F x, F.comp $ single_add_hom x, left_inv := λ F, by { ext, simp }, right_inv := λ F, by { ext, simp }, map_add' := λ F G, by { ext, simp } } @[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N] (F : α → M →+ N) (f : α →₀ M) : lift_add_hom F f = f.sum (λ x, F x) := rfl @[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) : lift_add_hom.symm F x = F.comp (single_add_hom x) := rfl lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N] (F : (α →₀ M) →+ N) (x : α) (y : M) : lift_add_hom.symm F x y = F (single x y) := rfl @[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] : lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ := lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) : f.sum single = f := add_monoid_hom.congr_fun lift_add_hom_single_add_hom f @[simp] lemma sum_univ_single [add_comm_monoid M] [fintype α] (i : α) (m : M) : ∑ (j : α), (single i m) j = m := by simp [single] @[simp] lemma sum_univ_single' [add_comm_monoid M] [fintype α] (i : α) (m : M) : ∑ (j : α), (single j m) i = m := by simp [single] @[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) (b : M) : lift_add_hom f (single a b) = f a b := sum_single_index (f a).map_zero @[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N) (a : α) : (lift_add_hom f).comp (single_add_hom a) = f a := add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] (g : N →+ P) (f : α → M →+ N) : g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) := lift_add_hom.symm_apply_eq.1 $ funext $ λ a, by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single] lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β} {h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) : (f - g).sum h = f.sum h - g.sum h := (lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g @[to_additive] lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} : (v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) := begin rw [prod, prod, support_emb_domain, finset.prod_map], simp_rw emb_domain_apply, end @[to_additive] lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N] {s : finset ι} {g : ι → α →₀ M} {h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : ∏ i in s, (g i).prod h = (∑ i in s, g i).prod h := finset.cons_induction_on s rfl $ λ a s has ih, by rw [prod_cons, ih, sum_cons, prod_add_index' h_zero h_add] @[to_additive] lemma prod_sum_index [add_comm_monoid M] [add_comm_monoid N] [comm_monoid P] {f : α →₀ M} {g : α → M → β →₀ N} {h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) : (f.sum g).prod h = f.prod (λa b, (g a b).prod h) := (prod_finset_sum_index h_zero h_add).symm lemma multiset_sum_sum_index [add_comm_monoid M] [add_comm_monoid N] (f : multiset (α →₀ M)) (h : α → M → N) (h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) : (f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum := multiset.induction_on f rfl $ assume a s ih, by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index' h₀ h₁, ih] lemma support_sum_eq_bUnion {α : Type*} {ι : Type*} {M : Type*} [decidable_eq α] [add_comm_monoid M] {g : ι → α →₀ M} (s : finset ι) (h : ∀ i₁ i₂, i₁ ≠ i₂ → disjoint (g i₁).support (g i₂).support) : (∑ i in s, g i).support = s.bUnion (λ i, (g i).support) := begin classical, apply finset.induction_on s, { simp }, { intros i s hi, simp only [hi, sum_insert, not_false_iff, bUnion_insert], intro hs, rw [finsupp.support_add_eq, hs], rw [hs, finset.disjoint_bUnion_right], intros j hj, refine h _ _ (ne_of_mem_of_not_mem hj hi).symm } end lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} : multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) := (multiset.map_add_monoid_hom m).map_sum _ f.support lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} : multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) := (multiset.sum_add_monoid_hom : multiset N →+ N).map_sum _ f.support /-- For disjoint `f1` and `f2`, and function `g`, the product of the products of `g` over `f1` and `f2` equals the product of `g` over `f1 + f2` -/ @[to_additive "For disjoint `f1` and `f2`, and function `g`, the sum of the sums of `g` over `f1` and `f2` equals the sum of `g` over `f1 + f2`"] lemma prod_add_index_of_disjoint [add_comm_monoid M] {f1 f2 : α →₀ M} (hd : disjoint f1.support f2.support) {β : Type*} [comm_monoid β] (g : α → M → β) : (f1 + f2).prod g = f1.prod g * f2.prod g := have ∀ {f1 f2 : α →₀ M}, disjoint f1.support f2.support → ∏ x in f1.support, g x (f1 x + f2 x) = f1.prod g := λ f1 f2 hd, finset.prod_congr rfl (λ x hx, by simp only [not_mem_support_iff.mp (disjoint_left.mp hd hx), add_zero]), begin classical, simp_rw [← this hd, ← this hd.symm, add_comm (f2 _), finsupp.prod, support_add_eq hd, prod_union hd, add_apply] end lemma prod_dvd_prod_of_subset_of_dvd [add_comm_monoid M] [comm_monoid N] {f1 f2 : α →₀ M} {g1 g2 : α → M → N} (h1 : f1.support ⊆ f2.support) (h2 : ∀ (a : α), a ∈ f1.support → g1 a (f1 a) ∣ g2 a (f2 a)) : f1.prod g1 ∣ f2.prod g2 := begin classical, simp only [finsupp.prod, finsupp.prod_mul], rw [←sdiff_union_of_subset h1, prod_union sdiff_disjoint], apply dvd_mul_of_dvd_right, apply prod_dvd_prod_of_dvd, exact h2, end lemma indicator_eq_sum_single [add_comm_monoid M] (s : finset α) (f : Π a ∈ s, M) : indicator s f = ∑ x in s.attach, single x (f x x.2) := begin rw [← sum_single (indicator s f), sum, sum_subset (support_indicator_subset _ _), ← sum_attach], { refine finset.sum_congr rfl (λ x hx, _), rw [indicator_of_mem], }, intros i _ hi, rw [not_mem_support_iff.mp hi, single_zero], end @[simp, to_additive] lemma prod_indicator_index [has_zero M] [comm_monoid N] {s : finset α} (f : Π a ∈ s, M) {h : α → M → N} (h_zero : ∀ a ∈ s, h a 0 = 1) : (indicator s f).prod h = ∏ x in s.attach, h x (f x x.2) := begin rw [prod_of_support_subset _ (support_indicator_subset _ _) h h_zero, ← prod_attach], refine finset.prod_congr rfl (λ x hx, _), rw [indicator_of_mem], end end finsupp theorem finset.sum_apply' : (∑ k in s, f k) i = ∑ k in s, f k i := (finsupp.apply_add_hom i : (ι →₀ A) →+ A).map_sum f s theorem finsupp.sum_apply' : g.sum k x = g.sum (λ i b, k i b x) := finset.sum_apply _ _ _ section include h0 h1 open_locale classical theorem finsupp.sum_sum_index' : (∑ x in s, f x).sum t = ∑ x in s, (f x).sum t := finset.induction_on s rfl $ λ a s has ih, by simp_rw [finset.sum_insert has, finsupp.sum_add_index' h0 h1, ih] end section variables [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] lemma finsupp.sum_mul (b : S) (s : α →₀ R) {f : α → R → S} : (s.sum f) * b = s.sum (λ a c, (f a c) * b) := by simp only [finsupp.sum, finset.sum_mul] lemma finsupp.mul_sum (b : S) (s : α →₀ R) {f : α → R → S} : b * (s.sum f) = s.sum (λ a c, b * (f a c)) := by simp only [finsupp.sum, finset.mul_sum] end namespace nat /-- If `0 : ℕ` is not in the support of `f : ℕ →₀ ℕ` then `0 < ∏ x in f.support, x ^ (f x)`. -/ lemma prod_pow_pos_of_zero_not_mem_support {f : ℕ →₀ ℕ} (hf : 0 ∉ f.support) : 0 < f.prod pow := finset.prod_pos (λ a ha, pos_iff_ne_zero.mpr (pow_ne_zero _ (λ H, by {subst H, exact hf ha}))) end nat
736aa1dc4a3318e506bd2f8474feb69c2ed5dadb
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Compiler/LCNF/Specialize.lean
5145651fb3632e171a8f1807b88c292d4828f3dd
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
14,427
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.Specialize import Lean.Compiler.LCNF.Simp import Lean.Compiler.LCNF.SpecInfo import Lean.Compiler.LCNF.PrettyPrinter import Lean.Compiler.LCNF.ToExpr import Lean.Compiler.LCNF.Level import Lean.Compiler.LCNF.PhaseExt import Lean.Compiler.LCNF.MonadScope import Lean.Compiler.LCNF.Closure import Lean.Compiler.LCNF.FVarUtil namespace Lean.Compiler.LCNF namespace Specialize abbrev Cache := SMap Expr Name structure CacheEntry where key : Expr declName : Name deriving Inhabited def addEntry (cache : Cache) (e : CacheEntry) : Cache := cache.insert e.key e.declName builtin_initialize specCacheExt : SimplePersistentEnvExtension CacheEntry Cache ← registerSimplePersistentEnvExtension { addEntryFn := addEntry addImportedFn := fun es => (mkStateFromImportedEntries addEntry {} es).switch } def cacheSpec (key : Expr) (declName : Name) : CoreM Unit := modifyEnv fun env => specCacheExt.addEntry env { key, declName } def findSpecCache? (key : Expr) : CoreM (Option Name) := return specCacheExt.getState (← getEnv) |>.find? key structure Context where /-- Set of free variables in scope. The "collector" uses this information when collecting dependencies for code specialization. -/ scope : FVarIdSet := {} /-- Set of let-declarations in scope that do not depend on parameters. -/ ground : FVarIdSet := {} /-- Name of the declaration being processed -/ declName : Name structure State where decls : Array Decl := #[] abbrev SpecializeM := ReaderT Context $ StateRefT State CompilerM instance : MonadScope SpecializeM where getScope := return (← read).scope withScope f := withReader (fun ctx => { ctx with scope := f ctx.scope }) /-- Return `true` if `e` is a ground term. That is, it contains only free variables tagged as ground -/ def isGround [TraverseFVar α] (e : α) : SpecializeM Bool := do let s := (← read).ground return allFVar (s.contains ·) e @[inline] def withLetDecl (decl : LetDecl) (x : SpecializeM α) : SpecializeM α := do let grd ← isGround decl.value let fvarId := decl.fvarId withReader (fun { scope, ground, declName } => { declName, scope := scope.insert fvarId, ground := if grd then ground.insert fvarId else ground }) x namespace Collector /-! # Dependency collector for the code specialization function. During code specialization, we select which arguments are going to be used during the specialization. Then, we have to collect their dependencies. For example, suppose are trying to specialize the following `IO.println` and `List.forM` applications in the following example: ``` def f xs a.1 := let _x.2 := @instMonadEIO IO.Error let _x.5 := instToStringString let _x.9 := instToStringNat let _x.6 := "hello" let _x.61 := @IO.println String _x.5 _x.6 a.1 -- (*) cases _x.61 | EStateM.Result.ok a.6 a.7 => fun _f.72 _y.69 _y.70 := let _x.71 := @IO.println Nat _x.9 _y.69 _y.70 -- (*) _x.71 let _x.65 := @List.forM (fun α => PUnit → EStateM.Result IO.Error PUnit α) _x.2 Nat xs _f.72 a.7 -- (*) ... ... ``` For `IO.println` the `SpecArgInfo` is `[N, I, O, O]`, i.e., only the first two arguments are considered for code specialization. The first one is computationally neutral, and the second one is an instance. For `List.forM`, we have `[N, I, N, O, H]`. In this case, the fifth argument (tagged as `H`) is a function. Note that the actual `List.forM` application has 6 arguments, the extra argument comes from the `IO` monad. For the first `IO.println` application, the collector collects `_x.5`. For the `List.forM`, it collects `_x.2`, `_x.9`, and `_f.72`. The collected values are used to construct a key to identify the specialization. Arguments that were not considered are replaced with `lcErased`. The key is used to make sure we don't keep generating the same specialization over and over again. This is not an optimization, it is essential to prevent the code specializer from looping while specializing recursive functions. The keys for these two applications are the terms. ``` @IO.println Nat instToStringNat lcErased lcErased ``` and ``` @List.forM (fun α => PUnit → EStateM.Result IO.Error PUnit α) (@instMonadEIO IO.Error) Nat lcErased (fun _y.69 _y.70 => let _x.71 := @IO.println Nat instToStringNat _y.69 _y.70; _x.71) ``` The keys never contain free variables or loose bound variables. -/ /-- Given the specialization mask `paramsInfo` and the arguments `args`, collect their dependencies, and return an array `mask` of size `paramsInfo.size` s.t. - `mask[i] = some args[i]` if `paramsInfo[i] != .other` - `mask[i] = none`, otherwise. That is, `mask` contains only the arguments that are contributing to the code specialization. We use this information to compute a "key" to uniquely identify the code specialization, and creating the specialized code. -/ def collect (paramsInfo : Array SpecParamInfo) (args : Array Arg) : SpecializeM (Array (Option Arg) × Array Param × Array CodeDecl) := do let ctx ← read let lctx := (← getThe CompilerM.State).lctx let abstract (fvarId : FVarId) : Bool := -- We convert let-declarations that are not ground into parameters !lctx.funDecls.contains fvarId && !ctx.ground.contains fvarId Closure.run (inScope := ctx.scope.contains) (abstract := abstract) do let mut argMask := #[] for paramInfo in paramsInfo, arg in args do match paramInfo with | .other => argMask := argMask.push none | .fixedNeutral | .user | .fixedInst | .fixedHO => argMask := argMask.push (some arg) Closure.collectArg arg return argMask end Collector /-- Return `true` if it is worth using arguments `args` for specialization given the parameter specialization information. -/ def shouldSpecialize (paramsInfo : Array SpecParamInfo) (args : Array Arg) : SpecializeM Bool := do for paramInfo in paramsInfo, arg in args do match paramInfo with | .other => pure () | .fixedNeutral => pure () -- If we want to monomorphize types such as `Array`, we need to change here | .fixedInst | .user => if (← isGround arg) then return true | .fixedHO => return true -- TODO: check whether this is too aggressive return false /-- Convert the given declarations into `Expr`, and "zeta-reduce" them into body. This function is used to compute the key that uniquely identifies an code specialization. -/ def expandCodeDecls (decls : Array CodeDecl) (body : LetValue) : CompilerM Expr := do let xs := decls.map (mkFVar ·.fvarId) let values := decls.map fun | .let decl => decl.value.toExpr | .fun decl | .jp decl => decl.toExpr let rec go (i : Nat) (subst : Array Expr) : Expr := if h : i < values.size then let value := values[i].abstractRange i xs let value := value.instantiateRev subst go (i+1) (subst.push value) else (body.toExpr.abstract xs).instantiateRev subst return go 0 #[] termination_by go => values.size - i /-- Create the "key" that uniquely identifies a code specialization. `params` and `decls` are the declarations collected by the `collect` function above. The result contains the list of universe level parameter names the key that `params`, `decls`, and `body` depends on. We use this information to create the new auxiliary declaration and resulting application. -/ def mkKey (params : Array Param) (decls : Array CodeDecl) (body : LetValue) : CompilerM (Expr × List Name) := do let body ← expandCodeDecls decls body let key := ToExpr.run do ToExpr.withParams params do ToExpr.mkLambdaM params (← ToExpr.abstractM body) return normLevelParams key open Internalize in /-- Specialize `decl` using - `us`: the universe level used to instantiate `decl.name` - `argMask`: arguments that are being used to specialize the declaration. - `params`: new parameters that arguments in `argMask` depend on. - `decls`: local declarations that arguments in `argMask` depend on. - `levelParamsNew`: the universe level parameters for the new declaration. -/ def mkSpecDecl (decl : Decl) (us : List Level) (argMask : Array (Option Arg)) (params : Array Param) (decls : Array CodeDecl) (levelParamsNew : List Name) : SpecializeM Decl := do let nameNew := decl.name ++ `_at_ ++ (← read).declName ++ (`spec).appendIndexAfter (← get).decls.size /- Recall that we have just retrieved `decl` using `getDecl?`, and it may have free variable identifiers that overlap with the free-variables in `params` and `decls` (i.e., the "closure"). Recall that `params` and `decls` are internalized, but `decl` is not. Thus, we internalize `decl` before glueing these "pieces" together. We erase the internalized information after we are done. -/ let decl ← decl.internalize try go decl nameNew |>.run' {} finally eraseDecl decl where go (decl : Decl) (nameNew : Name) : InternalizeM Decl := do let mut params ← params.mapM internalizeParam let decls ← decls.mapM internalizeCodeDecl for param in decl.params, arg in argMask do if let some arg := arg then let arg ← normArg arg modify fun s => s.insert param.fvarId arg.toExpr else -- Keep the parameter let param := { param with type := param.type.instantiateLevelParamsNoCache decl.levelParams us } params := params.push (← internalizeParam param) for param in decl.params[argMask.size:] do let param := { param with type := param.type.instantiateLevelParamsNoCache decl.levelParams us } params := params.push (← internalizeParam param) let value := decl.instantiateValueLevelParams us let value ← internalizeCode value let value := attachCodeDecls decls value let type ← value.inferType let type ← mkForallParams params type let safe := decl.safe let recursive := decl.recursive let decl := { name := nameNew, levelParams := levelParamsNew, params, type, value, safe, recursive, inlineAttr? := none : Decl } return decl.setLevelParams /-- Given the specialization mask `paramsInfo` and the arguments `args`, return the arguments that have not been considered for specialization. -/ def getRemainingArgs (paramsInfo : Array SpecParamInfo) (args : Array Arg) : Array Arg := Id.run do let mut result := #[] for info in paramsInfo, arg in args do if info matches .other then result := result.push arg return result ++ args[paramsInfo.size:] mutual /-- Try to specialize the function application in the given let-declaration. `k` is the continuation for the let-declaration. -/ partial def specializeApp? (e : LetValue) : SpecializeM (Option LetValue) := do let .const declName us args := e | return none if args.isEmpty then return none if (← Meta.isInstance declName) then return none let some paramsInfo ← getSpecParamInfo? declName | return none unless (← shouldSpecialize paramsInfo args) do return none let some decl ← getDecl? declName | return none trace[Compiler.specialize.candidate] "{e.toExpr}, {paramsInfo}" let (argMask, params, decls) ← Collector.collect paramsInfo args let keyBody := .const declName us (argMask.filterMap id) let (key, levelParamsNew) ← mkKey params decls keyBody trace[Compiler.specialize.candidate] "key: {key}" assert! !key.hasLooseBVars assert! !key.hasFVar let usNew := levelParamsNew.map mkLevelParam let argsNew := params.map (.fvar ·.fvarId) ++ getRemainingArgs paramsInfo args if let some declName ← findSpecCache? key then trace[Compiler.specialize.step] "cached: {declName}" return some (.const declName usNew argsNew) else let specDecl ← mkSpecDecl decl us argMask params decls levelParamsNew trace[Compiler.specialize.step] "new: {specDecl.name}" cacheSpec key specDecl.name specDecl.saveBase let specDecl ← specDecl.etaExpand specDecl.saveBase let specDecl ← specDecl.simp {} let specDecl ← specDecl.simp { etaPoly := true, inlinePartial := true, implementedBy := true } let value ← withReader (fun _ => { declName := specDecl.name }) do withParams specDecl.params <| visitCode specDecl.value let specDecl := { specDecl with value } modify fun s => { s with decls := s.decls.push specDecl } return some (.const specDecl.name usNew argsNew) partial def visitFunDecl (funDecl : FunDecl) : SpecializeM FunDecl := do let value ← withParams funDecl.params <| visitCode funDecl.value funDecl.update' funDecl.type value partial def visitCode (code : Code) : SpecializeM Code := do match code with | .let decl k => let mut decl := decl if let some value ← specializeApp? decl.value then decl ← decl.updateValue value let k ← withLetDecl decl <| visitCode k return code.updateLet! decl k | .fun decl k | .jp decl k => let decl ← visitFunDecl decl let k ← withFVar decl.fvarId <| visitCode k return code.updateFun! decl k | .cases c => let alts ← c.alts.mapMonoM fun alt => match alt with | .default k => return alt.updateCode (← visitCode k) | .alt _ ps k => withParams ps do return alt.updateCode (← visitCode k) return code.updateAlts! alts | .unreach .. | .jmp .. | .return .. => return code end def main (decl : Decl) : SpecializeM Decl := do if (← decl.isTemplateLike) then return decl else let value ← withParams decl.params <| visitCode decl.value return { decl with value } end Specialize partial def Decl.specialize (decl : Decl) : CompilerM (Array Decl) := do let (decl, s) ← Specialize.main decl |>.run { declName := decl.name } |>.run {} return s.decls.push decl def specialize : Pass where phase := .base name := `specialize run := fun decls => do saveSpecParamInfo decls decls.foldlM (init := #[]) fun decls decl => return decls ++ (← decl.specialize) builtin_initialize registerTraceClass `Compiler.specialize (inherited := true) registerTraceClass `Compiler.specialize.candidate registerTraceClass `Compiler.specialize.step end Lean.Compiler.LCNF
7fb8076e09a9f3f0ee32db43938713360d0dc97d
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/tactic/core.lean
9fac519ec0fe65e770f0bd5f3bc6dfb1cee13a50
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
94,617
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import data.dlist.basic import logic.function.basic import control.basic import meta.expr import meta.rb_map import data.bool import tactic.binder_matching import tactic.lean_core_docs import tactic.interactive_expr import system.io universe variable u attribute [derive [has_reflect, decidable_eq]] tactic.transparency instance : has_lt pos := { lt := λ x y, (x.line, x.column) < (y.line, y.column) } namespace expr open tactic /-- Given an expr `α` representing a type with numeral structure, `of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) /-- Given an expr `α` representing a type with numeral structure, `of_int α n` creates the `α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/ meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner /-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/ meta def traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es /-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`, with initial value `a`. -/ meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) /-- `kreplace e old new` replaces all occurrences of the expression `old` in `e` with `new`. The occurrences of `old` in `e` are determined using keyed matching with transparency `md`; see `kabstract` for details. If `unify` is true, we may assign metavariables in `e` as we match subterms of `e` against `old`. -/ meta def kreplace (e old new : expr) (md := semireducible) (unify := tt) : tactic expr := do e ← kabstract e old md unify, pure $ e.instantiate_var new end expr namespace interaction_monad open result variables {σ : Type} {α : Type u} /-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.read` in core. meta def get_state : interaction_monad σ σ := λ state, success state state /-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.write` in core. meta def set_state (state : σ) : interaction_monad σ unit := λ _, success () state /-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result, subsequently restoring the original state. If `tac` fails, then `run_with_state` does too. -/ meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α := λ s, match tac state with | success val _ := success val s | exception fn pos _ := exception fn pos s end end interaction_monad namespace format /-- `join' [a,b,c]` produces the format object `abc`. It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/ meta def join' (xs : list format) : format := xs.foldl compose nil /-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`, where `.` represents `format.join`. -/ meta def intercalate (x : format) : list format → format := join' ∘ list.intersperse x /-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)` the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z` each line break is decided independently -/ meta def soft_break : format := group line /-- Format a list as a comma separated list, without any brackets. -/ meta def comma_separated {α : Type*} [has_to_format α] : list α → format | [] := nil | xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) end format section format open format /-- format a `list` by separating elements with `soft_break` instead of `line` -/ meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format := bracket "[" "]" (comma_separated l) end format namespace tactic open function export interaction_monad (get_state set_state run_with_state) /-- Private work function for `add_local_consts_as_local_hyps`: given `mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local hypothesis created as a result and `(var :: rest) : list expr` of more local variables we examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the back of the queue and recurse. If it does not, then we perform replacements inside the type of `var` using the `mappings`, create a new associate local hypothesis, add this to the list of mappings, and recurse. We are done once all local hypotheses have been processed. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ private meta def add_local_consts_as_local_hyps_aux : list (expr × expr) → list expr → tactic (list (expr × expr)) | mappings [] := return mappings | mappings (var :: rest) := do /- Determine if `var` contains any local variables in the lift `rest`. -/ let is_dependent := var.local_type.fold ff $ λ e n b, if b then b else e ∈ rest, /- If so, then skip it---add it to the end of the variable queue. -/ if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var]) else do /- Otherwise, replace all of the local constants referenced by the type of `var` with the respective new corresponding local hypotheses as recorded in the list `mappings`. -/ let new_type := var.local_type.replace_subexprs mappings, /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/ hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type), /- Process the next variable in the queue, with the mapping list updated to include the local hypothesis which we just created. -/ add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest /-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the tactic state. This is harder than it sounds, since the list of local constants which we have been passed can have dependencies between their types. For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as a new local hypothesis, not the old local constant `n` with the same name. Of course, these dependencies can be nested arbitrarily deep. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) := /- The `list.reverse` below is a performance optimisation since the list of available variables reported by the system is often mostly the reverse of the order in which they are dependent. -/ add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of `type`. -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of `fn`'s type. -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity private meta def get_app_fn_args_whnf_aux (md : transparency) (unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) := λ args e, do e ← whnf e md unfold_ginductive, match e with | (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t | _ := pure (e, args) end /-- For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e` is normalised as necessary; for example: ``` get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)]) ``` The returned expression is in whnf, but the arguments are generally not. -/ meta def get_app_fn_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (expr × list expr) := get_app_fn_args_whnf_aux md unfold_ginductive [] e /-- `get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expression is in whnf. -/ meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr | e md unfold_ginductive := do e ← whnf e md unfold_ginductive, match e with | (expr.app f _) := get_app_fn_whnf f md unfold_ginductive | _ := pure e end /-- `get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`, where `C` is a constant, after normalisation with transparency `md`. If so, the name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. -/ meta def get_app_fn_const_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic name := do f ← get_app_fn_whnf e md unfold_ginductive, match f with | (expr.const n _) := pure n | _ := fail format! "expected a constant (possibly applied to some arguments), but got:\n{e}" end /-- `get_app_args_whnf e md unfold_ginductive` is like `expr.get_app_args e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expressions are not necessarily in whnf. -/ meta def get_app_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (list expr) := prod.snd <$> get_app_fn_args_whnf e md unfold_ginductive /-- `pis loc_consts f` is used to create a pi expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with pi binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``pis [a, b] `(f a b)`` will return the expression `Π (a : Ta) (b : Tb), f a b`. -/ meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with lambda binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``lambdas [a, b] `(f a b)`` will return the expression `λ (a : Ta) (b : Tb), f a b`. -/ meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f -- TODO: move to `declaration` namespace in `meta/expr.lean` /-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named `ls`, type `t`, and body `e`. -/ meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) /-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this to the environment as a theorem with name `n` and universe parameters `ls`. -/ meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ expr.const n $ ls.map level.param /-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`. This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare situations the latter will fail but the former will succeed. -/ meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α /-- `mk_fresh_name` returns identifiers starting with underscores, which are not legal when emitted by tactic programs. `mk_user_fresh_name` turns the useful source of random names provided by `mk_fresh_name` into names which are usable by tactic programs. The returned name has four components which are all strings. -/ meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute' attr_name decl_name` checks whether `decl_name` exists and has attribute `attr_name`. -/ meta def has_attribute' (attr_name decl_name : name) : tactic bool := succeeds (has_attribute attr_name decl_name) /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance /-- `local_decls` returns a dictionary mapping names to their corresponding declarations. Covers all declarations from the current file. -/ meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file e d.to_name then s.insert d.to_name d else s), pure xs /-- `get_decls_from` returns a dictionary mapping names to their corresponding declarations. Covers all declarations the files listed in `fs`, with the current file listed as `none`. The path of the file names is expected to be relative to the root of the project (i.e. the location of `leanpkg.toml` when it is present); e.g. `"src/tactic/core.lean"` Possible issue: `get_decls_from` uses `get_cwd`, the current working directory, which may not always point at the root of the project. It would work better if it searched for the root directory or, better yet, if Lean exposed its path information. -/ meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) := do root ← unsafe_run_io $ io.env.get_cwd, let fs := fs.map (option.map $ λ path, root ++ "/" ++ path), err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists, guard (err = []) <|> fail format!"File not found: {err}", e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, let source := e.decl_olean d.to_name in if source ∈ fs ∧ (source = none → e.in_current_file d.to_name) then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries `nm_2`, `nm_3`, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ```lean do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) /-- Replace every universe metavariable in an expression with a universe parameter. (This is useful when making new declarations.) -/ meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do e.list_univ_meta_vars.enum.mmap (λ n, do let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)), unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))), instantiate_mvars e /-- `mk_local n` creates a dummy local variable with name `n`. The type of this local constant is a constant with name `n`, so it is very unlikely to be a meaningful expression. -/ meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) /-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`, `y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`. -/ meta def mk_psigma : list expr → tactic expr | [] := mk_const ``punit | [x@(expr.local_const _ _ _ _)] := pure x | (x@(expr.local_const _ _ _ _) :: xs) := do y ← mk_psigma xs, α ← infer_type x, β ← infer_type y, t ← lambdas [x] β >>= instantiate_mvars, r ← mk_mapp ``psigma.mk [α,t], pure $ r x y | _ := fail "mk_psigma expects a list of local constants" /-- Update the type of a local constant or metavariable. For local constants and metavariables obtained via, for example, `tactic.get_local`, the type stored in the expression is not necessarily the same as the type returned by `infer_type`. This tactic, given a local constant or metavariable, updates the stored type to match the output of `infer_type`. If the input is not a local constant or metavariable, `update_type` does nothing. -/ meta def update_type : expr → tactic expr | e@(expr.local_const ppname uname binfo _) := expr.local_const ppname uname binfo <$> infer_type e | e@(expr.mvar ppname uname _) := expr.mvar ppname uname <$> infer_type e | e := pure e /-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term and unused variable names. -/ meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name) | 0 e hs ns := return (hs.reverse, e, ns) | (n + 1) e hs ns := do t ← infer_type e, if t.is_app_of `eq then return (hs.reverse, e, ns) else do [(_, [h, h'], _)] ← cases_core e (ns.take 1), elim_gen_prod n h' (h :: hs) (ns.drop 1) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) /-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/ meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] /-- Given `elab_def`, a tactic to solve the current goal, `extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it to close the goal. If `trusted` is false, it will be a meta definition. -/ meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map expr.to_implicit_local_const <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n /-- Attempts to close the goal with `dec_trivial`. -/ meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion. -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Runs a tactic for a result, reverting the state after completion or error. -/ meta def retrieve' {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) (λ msg pos s', result.exception msg pos s) /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t /-- Given a tactic `tac` that takes an expression and returns a new expression and a proof of equality, use that tactic to change the type of the hypotheses listed in `hs`, as well as the goal if `tgt = tt`. Returns `tt` if any types were successfully changed. -/ meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) /-- `revert_after e` reverts all local constants after local constant `e`. -/ meta def revert_after (e : expr) : tactic ℕ := do l ← local_context, [pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}", let l := l.drop pos.succ, -- all local hypotheses after `e` revert_lst l /-- `revert_target_deps` reverts all local constants on which the target depends (recursively). Returns the number of local constants that have been reverted. -/ meta def revert_target_deps : tactic ℕ := do tgt ← target, ctx ← local_context, l ← ctx.mfilter (kdepends_on tgt), n ← revert_lst l, if l = [] then return n else do m ← revert_target_deps, return (m + n) /-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`. `generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the goal, in which case it just calls `assert`. In contrast to `generalize` it already introduces the generalized variable. -/ meta def generalize' (e : expr) (n : name) : tactic expr := (generalize e n >> intro n) <|> note n none e /-- `intron_no_renames n` calls `intro` `n` times, using the pretty-printing name provided by the binder to name the new local constant. Unlike `intron`, it does not rename introduced constants if the names shadow existing constants. -/ meta def intron_no_renames : ℕ → tactic unit | 0 := pure () | (n+1) := do expr.pi pp_n _ _ _ ← target, intro pp_n, intron_no_renames n /-- `get_univ_level t` returns the universe level of a type `t` -/ meta def get_univ_level (t : expr) (md := semireducible) (unfold_ginductive := tt) : tactic level := do expr.sort u ← infer_type t >>= λ s, whnf s md unfold_ginductive | fail "get_univ_level: argument is not a type", return u /-! ### Various tactics related to local definitions (local constants of the form `x : α := t`) We call `t` the value of `x`. -/ /-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined locally using a `let` expression. Otherwise it fails. -/ meta def local_def_value (e : expr) : tactic expr := pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad. tactic.unsafe.type_context.run $ do lctx <- tactic.unsafe.type_context.get_local_context, some ldecl <- return $ lctx.get_local_decl e.local_uniq_name | tactic.unsafe.type_context.fail format!"No such hypothesis {s}.", some let_val <- return ldecl.value | tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.", return let_val /-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form `e : α := t`) and otherwise fails. -/ meta def is_local_def (e : expr) : tactic unit := do ctx ← unsafe.type_context.get_local_context.run, (some decl) ← pure $ ctx.get_local_decl e.local_uniq_name | fail format!"is_local_def: {e} is not a local constant", when decl.value.is_none $ fail format!"is_local_def: {e} is not a local definition" /-- Returns the local definitions from the context. A local definition is a local constant of the form `e : α := t`. The local definitions are returned in the order in which they appear in the context. -/ meta def local_defs : tactic (list expr) := do ctx ← unsafe.type_context.get_local_context.run, ctx' ← local_context, ctx'.mfilter $ λ h, do (some decl) ← pure $ ctx.get_local_decl h.local_uniq_name | fail format!"local_defs: local {h} not found in the local context", pure decl.value.is_some /-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs` (using membership to `vs` instead of a predicate) and breaks `xs` when matches are found. whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition running up to the first match. -/ private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) : list α → list α → list (list α) | [] acc := [acc.reverse] | (l :: ls) acc := if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l] else partition_local_deps_aux ls (l :: acc) /-- `partition_local_deps vs`, with `vs` a list of local constants, reorders `vs` in the order they appear in the local context together with the variables that follow them. If local context is `[a,b,c,d,e,f]`, and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`. The head of each list is one of the variables given as a parameter. -/ meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) := do ls ← local_context, pure (partition_local_deps_aux vs ls []).tail.reverse /-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ... changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type correctness. This tactic is called `clearbody` in Coq. -/ meta def clear_value (vs : list expr) : tactic unit := do ls ← partition_local_deps vs, ls.mmap' $ λ vs, do { revert_lst vs, (expr.elet v t d b) ← target | fail format!"Cannot clear the body of {vs.head}. It is not a local definition.", let e := expr.pi v binder_info.default t b, type_check e <|> fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.", g ← mk_meta_var e, h ← note `h none g, tactic.exact $ h d, gs ← get_goals, set_goals $ g :: gs }, ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name /-- `context_has_local_def` is true iff there is at least one local definition in the context. -/ meta def context_has_local_def : tactic bool := do ctx ← local_context, ctx.many (succeeds ∘ local_def_value) /-- `context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the context up to and including `h` is a local definition. -/ meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do ff ← succeeds (local_def_value h) | pure tt, ctx ← local_context, let ctx := ctx.take_while (≠ h), ctx.many (succeeds ∘ local_def_value) /-- If the expression `h` is a local variable with type `x = t` or `t = x`, where `x` is a local constant, `tactic.subst' h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. If `h` is another local variable, then we find a local constant with type `h = t` or `t = h` and substitute `t` for `h`. This is like `tactic.subst`, but fails with a nicer error message if the substituted variable is a local definition. It is trickier to fix this in core, since `tactic.is_local_def` is in mathlib. -/ meta def subst' (h : expr) : tactic unit := do e ← do { -- we first find the variable being substituted away t ← infer_type h, let (f, args) := t.get_app_fn_args, if (f.const_name = `eq ∨ f.const_name = `heq) then do { let lhs := args.inth 1, let rhs := args.ilast, if rhs.is_local_constant then return rhs else if lhs.is_local_constant then return lhs else fail "subst tactic failed, hypothesis '{h.local_pp_name}' is not of the form (x = t) or (t = x)." } else return h }, success_if_fail (is_local_def e) <|> fail format!("Cannot substitute variable {e.local_pp_name}, " ++ "it is a local definition. If you really want to do this, use `clear_value` first."), subst h /-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions, `simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting expression and a proof of equality. -/ meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg /-- Caches unary type classes on a type `α : Type.{univ}`. -/ meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) /-- Creates an `instance_cache` for the type `α`. -/ meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache /-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of `n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance via type class resolution, and updates the cache. -/ meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr /-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`, `append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/ meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) /-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/ meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) /-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) := if n = 0 then c.mk_app ``has_zero.zero [] else do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, (c, one) ← c.mk_app ``has_one.one [], return (c, n.binary_rec one $ λ b n e, if n = 0 then one else cond b ((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) ((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])) /-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr) | (n : ℕ) := c.of_nat n | -[1+ n] := do (c, e) ← c.of_nat (n+1), c.mk_app ``has_neg.neg [e] end instance_cache /-- A variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) /-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/ meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] /-- When `struct_n` is the name of a structure type, `subobject_names struct_n` returns two lists of names `(instances, fields)`. The names in `instances` are the projections from `struct_n` to the structures that it extends (assuming it was defined with `old_structure_cmd false`). The names in `fields` are the standard fields of `struct_n`. -/ meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, c ← match env.constructors_of struct_n with | [c] := pure c | [] := if env.is_inductive struct_n then fail format!"{struct_n} does not have constructors" else fail format!"{struct_n} is not an inductive type" | _ := fail "too many constructors" end, vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do (_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function /-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name of the projection is `prefix.name`. `struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/ meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n /-- Return a list of all type classes which can be instantiated for the given expression. -/ meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) /-- Finds an instance of an implication `cond → tgt`. Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention `e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used, since it has been "proven" by a metavariable. -/ meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do f ← mk_meta_var cond, e ← assertv `c cond f, swap, reset_instance_cache, inst ← mk_instance tgt, return (e, inst) open nat /-- Create a list of `n` fresh metavariables. -/ meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- `apply_list l`, for `l : list (tactic expr)`, tries to apply the lemmas generated by the tactics in `l` on the first goal, and fail if none succeeds. -/ meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit | [] := fail "no matching rule" | (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t /-- Constructs a list of `tactic expr` given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list. We need to return a list of `tactic expr`, rather than just `expr`, because these expressions will be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck. -/ meta def build_list_expr_for_apply : list pexpr → tactic (list (tactic expr)) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← l.mmap (λ n, _root_.to_pexpr <$> mk_const n), -- We reverse the list of lemmas marked with an attribute, -- on the assumption that lemmas proved earlier are more often applicable -- than lemmas proved later. This is a performance optimization. build_list_expr_for_apply (m.reverse ++ t)) <|> return ((i_to_expr_for_apply h) :: tail) /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies a lemma from the list until it can't. -/ meta def apply_rules (hs : list pexpr) (n : nat) (opt : apply_cfg) : tactic unit := do l ← lock_tactic_state $ build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt l) /-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`. Fails if there is nothing named `h` in the local context. -/ meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' /-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp`` or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an `iff`, returns an expression with the `iff` converted to either the forwards or backwards implication, as requested. -/ meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0) | _ f := none /-- `iff_mp_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/ meta def iff_mp_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mp ty (λ_, e) /-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/ meta def iff_mpr_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mpr ty (λ_, e) /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the forward implication. -/ meta def iff_mp (e : expr) : tactic expr := do t ← infer_type e, iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the reverse implication. -/ meta def iff_mpr (e : expr) : tactic expr := do t ← infer_type e, iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Attempts to apply `e`, and if that fails, if `e` is an `iff`, try applying both directions separately. -/ meta def apply_iff (e : expr) : tactic (list (name × expr)) := let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap) /-- Configuration options for `apply_any`: * `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again. * `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again. * `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`. -/ meta structure apply_any_opt extends apply_cfg := (use_symmetry : bool := tt) (use_exfalso : bool := tt) /-- This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s, and evaluates these as thunks before trying to apply them. We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`. -/ meta def apply_any_thunk (lemmas : list (tactic expr)) (opt : apply_any_opt := {}) (tac : tactic unit := skip) (on_success : expr → tactic unit := (λ _, skip)) (on_failure : tactic unit := skip) : tactic unit := do let modes := [skip] ++ (if opt.use_symmetry then [symmetry] else []) ++ (if opt.use_exfalso then [exfalso] else []), modes.any_of (λ m, do m, lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|> (on_failure >> fail "apply_any tactic failed; no lemma could be applied") /-- `apply_any lemmas` tries to apply one of the list `lemmas` to the current goal. `apply_any lemmas opt` allows control over how lemmas are applied. `opt` has fields: * `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.) * `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.) * `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`). `apply_any lemmas tac` calls the tactic `tac` after a successful application. Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange recursive invocations of `apply_any`. -/ meta def apply_any (lemmas : list expr) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := apply_any_thunk (lemmas.map pure) opt tac /-- Try to apply a hypothesis from the local context to the goal. -/ meta def apply_assumption : tactic unit := local_context >>= apply_any /-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails if this is not a definitional equality. `change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e` by reverting `h`, changing the goal, and reintroducing hypotheses. -/ meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`, assuming `olde` and `newe` are defeq when elaborated. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), when (repl_tp ≠ tp) $ change_core repl_tp (some h) /-- Returns a list of all metavariables in the current partial proof. This can differ from the list of goals, since the goals can be manually edited. -/ meta def metavariables : tactic (list expr) := expr.list_meta_vars <$> result /-- `sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`, and fail otherwise. -/ meta def sorry_if_contains_sorry : tactic unit := do g ← target, guard g.contains_sorry <|> fail "goal does not contain `sorrry`", tactic.admit /-- Fail if the target contains a metavariable. -/ meta def no_mvars_in_target : tactic unit := expr.has_meta_var <$> target >>= guardb ∘ bnot /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do g :: _ ← get_goals, is_proof g >>= guardb /-- Succeeds only if we can construct an instance showing the current goal is a subsingleton type. -/ meta def subsingleton_goal : tactic unit := do g :: _ ← get_goals, ty ← infer_type g >>= instantiate_mvars, to_expr ``(subsingleton %%ty) >>= mk_instance >> skip /-- Succeeds only if the current goal is "terminal", in the sense that no other goals depend on it (except possibly through shared metavariables; see `independent_goal`). -/ meta def terminal_goal : tactic unit := propositional_goal <|> subsingleton_goal <|> do g₀ :: _ ← get_goals, mvars ← (λ L, list.erase L g₀) <$> metavariables, mvars.mmap' $ λ g, do t ← infer_type g >>= instantiate_mvars, d ← kdepends_on t g₀, monad.whenb d $ pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.") /-- Succeeds only if the current goal is "independent", in the sense that no other goals depend on it, even through shared meta-variables. -/ meta def independent_goal : tactic unit := no_mvars_in_target >> terminal_goal /-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`, it only unfolds reducible definitions, so it sometimes fails faster. -/ meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} /-- Apply a tactic as many times as possible, collecting the results in a list. Fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate t, return (r :: L) /-- Introduces one or more variables and returns the new local constants. Fails if `intro` cannot be applied. -/ meta def intros1 : tactic (list expr) := iterate1 intro1 /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders {α : Type} (t : tactic α) : tactic α := do v ← intros, r ← t, revert_lst v, return r namespace interactive /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders (i : itactic) : itactic := tactic.under_binders i end interactive /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results, and reverting to the original `tactic_state`. -/ -- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`. meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) := λ s, result.success (tactics.map $ λ t : tactic α, match t s with | result.success a s' := [a] | _ := [] end).join s /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results sorted by the value produced by a subsequent execution of the `sort_by` tactic, and reverting to the original `tactic_state`. -/ meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) : tactic (list (α × ℕ)) := λ s, result.success ((tactics.map $ λ t : tactic α, match (do a ← t, n ← sort_by, return (a, n)) s with | result.success a s' := [a] | _ := [] end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s /-- Return target after instantiating metavars and whnf. -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] add_tactic_doc { name := "fsplit", category := doc_category.tactic, decl_names := [`tactic.interactive.fsplit], tags := ["logic", "goal management"] } /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] add_tactic_doc { name := "injections_and_clear", category := doc_category.tactic, decl_names := [`tactic.interactive.injections_and_clear], tags := ["context management"] } /-- Calls `cases` on every local hypothesis, succeeding if it succeeds on at least one hypothesis. -/ meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed /-- `note_anon t v`, given a proof `v : t`, adds `h : t` to the current context, where the name `h` is fresh. `note_anon none v` will infer the type `t` from `v`. -/ -- While `note` provides a default value for `t`, it doesn't seem this could ever be used. meta def note_anon (t : option expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, note h t v /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|> fail format!"No hypothesis found of the form: {t'}" /-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), old::other_goals ← get_goals, t ← infer_type old, new_goal ← mk_meta_var (t.pis lc), set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- Instantiates metavariables that appear in the current goal. -/ meta def instantiate_mvars_in_target : tactic unit := target >>= instantiate_mvars >>= change /-- Instantiates metavariables in all goals. -/ meta def instantiate_mvars_in_goals : tactic unit := all_goals' $ instantiate_mvars_in_target /-- Protect the declaration `n` -/ meta def mk_protected (n : name) : tactic unit := do env ← get_env, set_env (env.mk_protected n) end tactic namespace lean.parser open tactic interaction_monad /-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the current line. -/ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left /-- Inner recursion for `emit_code_here`. -/ meta def emit_code_here_aux : string → ℕ → lean.parser unit | str slen := do left ← emit_command_here str, let llen := left.length, when (llen < slen ∧ llen ≠ 0) (emit_code_here_aux left llen) /-- `emit_code_here str` behaves as if the string `str` were placed at the current location in source code. -/ meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length /-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the top level, giving access to operations like `emit_code_here`. -/ @[user_command] meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit := do e ← lean.parser.pexpr 0, p ← eval_pexpr (lean.parser unit) e, p add_tactic_doc { name := "run_parser", category := doc_category.cmd, decl_names := [``run_parser_cmd], tags := ["parsing"] } /-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`). This function deserves a C++ implementation in core lean, and will fail if it is not called from the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/ meta def get_current_namespace : lean.parser name := do n ← tactic.mk_user_fresh_name, emit_code_here $ sformat!"def {n} := ()", nfull ← tactic.resolve_constant n, return $ nfull.get_nth_prefix n.components.length /-- `get_variables` returns a list of existing variable names, along with their types and binder info. -/ meta def get_variables : lean.parser (list (name × binder_info × expr)) := list.map expr.get_local_const_kind <$> list_available_include_vars /-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been "included" by an `include v` statement and are not (yet) `omit`ed. -/ meta def get_included_variables : lean.parser (list (name × binder_info × expr)) := do ns ← list_include_var_names, list.filter (λ v, v.1 ∈ ns) <$> get_variables /-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the local context---precisely those variables which would be ambiently accessible if we were in a tactic-mode block where the goals had types `es.mmap to_expr`, for example. Returns a new `ts : tactic_state` with these local variables added, and `mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable `var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/ meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr) : lean.parser (tactic_state × list (expr × expr)) := do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the declared variables to a fake `tactic_state`, and perform the resolution. At the end, `to_expr e` has done the work of determining which variables were actually referenced, which we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for `pexpr`s). -/ vars ← list_available_include_vars, fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard them on this first pass. (We return the mappings generated by our second invocation of this function below.) -/ add_local_consts_as_local_hyps vars, es.mmap to_expr }, /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were referenced in `e` when it was resolved to `fake_e`. It is important that we include variables of the kind a) because we want `simp` to have access to declared local instances, and it is important that we only restrict to variables of kind a) and b) together since we do not to recognise a hypothesis which is posited as a `variable` in the environment but not referenced in the `pexpr` we were passed. One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want simp to use arbitrary hypotheses which were declared as `variables` in the local environment but not referenced in the expression to simplify (as one would be expect generally in tactic mode). -/ included_vars ← list_include_var_names, let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name, /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the `pexpr` list which we were passed.) -/ let directly_included_vars := vars.filter $ λ var, (var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars), /- Inflate the list `directly_included_vars` to include those variables which are "implicitly included" by virtue of reference to one or multiple others. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. -/ let all_implicitly_included_vars := expr.all_implicitly_included_variables vars directly_included_vars, /- Capture a tactic state where both of these kinds of variables have been added as local hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/ lean.parser.of_tactic $ do { mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars, ts ← get_state, return (ts, mappings) } end lean.parser namespace tactic variables {α : Type} /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ```lean instance : monad id := {! !} ``` invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under construction.") produces: ```lean instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {fs} }", return [(out,"")] } add_tactic_doc { name := "instance_stub", category := doc_category.hole_cmd, decl_names := [`tactic.instance_stub], tags := ["instances"] } /-- Like `resolve_name` except when the list of goals is empty. In that situation `resolve_name` fails whereas `resolve_name'` simply proceeds on a dummy goal -/ meta def resolve_name' (n : name) : tactic pexpr := do [] ← get_goals | resolve_name n, g ← mk_mvar, set_goals [g], resolve_name n <* set_goals [] private meta def strip_prefix' (n : name) : list string → name → tactic name | s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous | s (name.mk_string a p) := do let n' := s.foldl (flip name.mk_string) name.anonymous, do { n'' ← tactic.resolve_constant n', if n'' = n then pure n' else strip_prefix' (a :: s) p } <|> strip_prefix' (a :: s) p | s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n /-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/ meta def strip_prefix : name → tactic name | n@(name.mk_string a a_1) := if (`_private).is_prefix_of n then let n' := n.update_prefix name.anonymous in n' <$ resolve_name' n' <|> pure n else strip_prefix' n [a] a_1 | n := pure n /-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/ meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= open_pis, let vs := vs.filter (λ v, v.is_default_local), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, f ← strip_prefix f, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ```lean meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression") produces: ```lean meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } add_tactic_doc { name := "Match Stub", category := doc_category.hole_cmd, decl_names := [`tactic.match_stub], tags := ["pattern matching"] } /-- Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition") in the following: ```lean meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` produces: ```lean meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking "Equations Stub" on the following: ```lean meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ```lean meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← open_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } add_tactic_doc { name := "Equations Stub", category := doc_category.hole_cmd, decl_names := [`tactic.eqn_stub], tags := ["pattern matching"] } /-- This command lists the constructors that can be used to satisfy the expected type. Invoking "List Constructors" ("Show the list of constructors of the expected type") in the following hole: ```lean def foo : ℤ ⊕ ℕ := {! !} ``` produces: ```lean def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ```lean sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← open_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, c ← strip_prefix c, pure format!"\n{c} : {t}\n" }, fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt), let out := format.to_string format!"{{! {fs} !}", trace (format.join ts).to_string, return [(out,"")] } add_tactic_doc { name := "List Constructors", category := doc_category.hole_cmd, decl_names := [`tactic.list_constructors_hole], tags := ["goal information"] } /-- Makes the declaration `classical.prop_decidable` available to type class inference. This asserts that all propositions are decidable, but does not have computational content. -/ meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache open expr /-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so, returns the expression `f ∘ g ∘ h`. -/ meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] /-- Given two expressions `e₀` and `e₁`, return the expression `` `(%%e₀ ↔ %%e₁)``. -/ meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁) /-- From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types /-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`. It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime, add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm lmm', copy_attribute `functor_norm lmm lmm' } add_tactic_doc { name := "higher_order", category := doc_category.attr, decl_names := [`tactic.higher_order_attr], tags := ["lemma derivation"] } attribute [higher_order map_comp_pure] map_pure /-- Copies a definition into the `tactic.interactive` namespace to make it usable in proof scripts. It allows one to write ```lean @[interactive] meta def my_tactic := ... ``` instead of ```lean meta def my_tactic := ... run_cmd add_interactive [``my_tactic] ``` -/ @[user_attribute] meta def interactive_attr : user_attribute := { name := `interactive, descr := "Put a definition in the `tactic.interactive` namespace to make it usable in proof scripts.", after_set := some $ λ tac _ _, add_interactive [tac] } add_tactic_doc { name := "interactive", category := doc_category.attr, decl_names := [``tactic.interactive_attr], tags := ["environment"] } /-- Use `refine` to partially discharge the goal, or call `fconstructor` and try again. -/ private meta def use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> use_aux) /-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to the expected type. ```lean example : ∃ x : ℤ, x = x := by tactic.use ``(42) ``` See the doc string for `tactic.interactive.use` for more information. -/ protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target /-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the local context. -/ meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l /-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/ meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end /-- `setup_tactic_parser` is a user command that opens the namespaces used in writing interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`. It does *not* use the `namespace` command, so it will typically be used after `namespace tactic.interactive`. -/ @[user_command] meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit := emit_code_here " open lean open lean.parser open interactive interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many . " /-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if `tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/ meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α := λ s, match tac s with | (result.success r s') := (finalizer >> pure r) s' | (result.exception msg p s') := (finalizer >> result.exception msg p) s' end /-- `on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed. -/ meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s' := (handler *> result.exception msg p) s' | ok := ok end /-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/ meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s := let msg (_ : unit) : format := match msg with | some msg := add_msg ++ format.line ++ msg () | none := add_msg end in result.exception msg p s | ok := ok end /-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails, returns the error message. -/ meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/ meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s' | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`. -/ meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit := do x ← retrieve_or_report_error t, match x with | (sum.inl _) := skip | (sum.inr msg) := if p msg then skip else fail msg end add_tactic_doc { name := "setup_tactic_parser", category := doc_category.cmd, decl_names := [`tactic.setup_tactic_parser_cmd], tags := ["parsing", "notation"] } /-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message of `t`. -/ meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- ``trace_if_enabled `n msg`` traces the message `msg` only if tracing is enabled for the name `n`. Create new names registered for tracing with `declare_trace n`. Then use `set_option trace.n true/false` to enable or disable tracing for `n`. -/ meta def trace_if_enabled (n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit := when_tracing n (trace msg) /-- ``trace_state_if_enabled `n msg`` prints the tactic state, preceded by the optional string `msg`, only if tracing is enabled for the name `n`. -/ meta def trace_state_if_enabled (n : name) (msg : string := "") : tactic unit := when_tracing n ((if msg = "" then skip else trace msg) >> trace_state) /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := let expected_msg := (msg'.iget ()).to_string in if msg = expected_msg then result.success () s else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end /-- Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`. -/ meta def tactic_statement (g : expr) : tactic string := do g ← instantiate_mvars g, g ← head_beta g, r ← pp (replace_mvars g), if g.has_meta_var then return (sformat!"Try this: refine {r}") else return (sformat!"Try this: exact {r}") /-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the initial goals and returns the goals `tac` ended on. -/ meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) := do gs' ← get_goals, set_goals gs, finally (prod.mk <$> tac <*> get_goals) (set_goals gs') /-- like `with_local_goals` but discards the resulting goals -/ meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α := prod.fst <$> with_local_goals gs tac /-- Representation of a proof goal that lends itself to comparison. The following goal: ```lean l₀ : T, l₁ : T ⊢ ∀ v : T, foo ``` is represented as ``` (2, ∀ l₀ l₁ v : T, foo) ``` The number 2 indicates that first the two bound variables of the `∀` are actually local constant. Comparing two such goals with `=` rather than `=ₐ` or `is_def_eq` tells us that proof script should not see the difference between the two. -/ meta def packaged_goal := ℕ × expr /-- proof state made of multiple `goal` meant for comparing the result of running different tactics -/ meta def proof_state := list packaged_goal meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩ meta instance proof_state.inhabited : inhabited proof_state := (infer_instance : inhabited (list packaged_goal)) /-- create a `packaged_goal` corresponding to the current goal -/ meta def get_packaged_goal : tactic packaged_goal := do ls ← local_context, tgt ← target >>= instantiate_mvars, tgt ← pis ls tgt, pure (ls.length, tgt) /-- `goal_of_mvar g`, with `g` a meta variable, creates a `packaged_goal` corresponding to `g` interpretted as a proof goal -/ meta def goal_of_mvar (g : expr) : tactic packaged_goal := with_local_goals' [g] get_packaged_goal /-- `get_proof_state` lists the user visible goal for each goal of the current state and for each goal, abstracts all of the meta variables of the other gaols. This produces a list of goals in the form of `ℕ × expr` where the `expr` encodes the following proof state: ```lean 2 goals l₁ : t₁, l₂ : t₂, l₃ : t₃ ⊢ tgt₁ ⊢ tgt₂ ``` as ```lean [ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁), (0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ] ``` with 2 goals, the first 2 bound variables encode the meta variable of all the goals, the next 3 (in the first goal) and 0 (in the second goal) are the local constants. This representation allows us to compare goals and proof states while ignoring information like the unique name of local constants and the equality or difference of meta variables that encode the same goal. -/ meta def get_proof_state : tactic proof_state := do gs ← get_goals, gs.mmap $ λ g, do ⟨n,g⟩ ← goal_of_mvar g, g ← gs.mfoldl (λ g v, do g ← kabstract g v reducible ff, pure $ pi `goal binder_info.default `(true) g ) g, pure (n,g) /-- Run `tac` in a disposable proof state and return the state. See `proof_state`, `goal` and `get_proof_state`. -/ meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) := try_core $ retrieve $ tac >> get_proof_state open lean interactive /-- A type alias for `tactic format`, standing for "pretty print format". -/ meta def pformat := tactic format /-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/ meta def pformat.mk (fmt : format) : pformat := pure fmt /-- an alias for `pp`. -/ meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s /-- See `format!` in `init/meta/interactive_base.lean`. The main differences are that `pp` is called instead of `to_fmt` and that we can use arguments of type `tactic α` in the quotations. Now, consider the following: ```lean e ← to_expr ``(3 + 7), trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add -- (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...` trace pformat!"{e}" -- outputs `3 + 7` ``` The difference is significant. And now, the following is expressible: ```lean e ← to_expr ``(3 + 7), trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ` ``` See also: `trace!` and `fail!` -/ @[user_notation] meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr := do e ← parse_pformat "" s.to_list, return ``(%%e : pformat) /-- The combination of `pformat` and `fail`. -/ @[user_notation] meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= fail) /-- The combination of `pformat` and `trace`. -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := do e ← get_env, s ← e.decl_olean `tactic.reset_instance_cache, return $ s.popn_back 17 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- Runs a tactic by name. If it is a `tactic string`, return whatever string it returns. If it is a `tactic unit`, return the name. (This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.) -/ meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n)) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail! "name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`" /-- auxiliary function for `apply_under_n_pis` -/ private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr | n 0 _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd | n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd) | n (k+1) t := apply_under_n_pis_aux n 0 t /-- Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr := apply_under_n_pis_aux func arg 0 n pi_expr /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_n_pis func arg pi_expr pi_expr.pi_arity /-- If `func` is a `pexpr` representing a function that takes an argument `a`, `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`. When `tgt` is a `pi` expr, `func` is elaborated in a context with the domain of `tgt`. Examples: * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument. * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`. * ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0 -/ meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ := lock_tactic_state $ do mv ← mk_mvar, solve_aux tgt $ intros >> to_expr ``(%%func %%mv), expr.pi_arity <$> (infer_type mv >>= instantiate_mvars) /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo` looks for `foo` in all imported files. When possible, make `foo` non-private rather than using this feature. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . add_tactic_doc { name := "import_private", category := doc_category.cmd, decl_names := [`tactic.import_private_cmd], tags := ["renaming"] } /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← (tk "with" *> many ident) <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } /-- Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns the name of the declaration that defines this attribute. Fails if there is no user attribute with this name. Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/ meta def get_user_attribute_name (attr_name : name) : tactic name := do ns ← attribute.get_instances `user_attribute, ns.mfirst (λ nm, do d ← get_decl nm, e ← mk_app `user_attribute.name [d.value], attr_nm ← eval_expr name e, guard $ attr_nm = attr_name, return nm) <|> fail!"'{attr_name}' is not a user attribute." /-- A tactic to set either a basic attribute or a user attribute. If the the user attribute has a parameter, the default value will be used. This tactic raises an error if there is no `inhabited` instance for the parameter type. -/ meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt) (prio : option nat := none) : tactic unit := do get_decl c_name <|> fail!"unknown declaration {c_name}", s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio), sum.inr msg ← return s | skip, if msg = (format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string then do user_attr_nm ← get_user_attribute_name attr_name, user_attr_const ← mk_const user_attr_nm, tac ← eval_pexpr (tactic unit) ``(user_attribute.set %%user_attr_const %%c_name (default _) %%persistent) <|> fail! ("Cannot set attribute @[{attr_name}].\n" ++ "The corresponding user attribute {user_attr_nm} " ++ "has a parameter without a default value.\n" ++ "Solution: provide an `inhabited` instance."), tac else fail msg end tactic /-- `find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`), and returns the value associated with this key if it exists. Otherwise, it fails. -/ meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) : tactic (expr × v) := m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
e3aeb072578dc0c1c15d0d94bf79af55b5214416
4fa161becb8ce7378a709f5992a594764699e268
/src/data/equiv/local_equiv.lean
cf85ad2bc32f1bfa177032a61f031b4322eb2ced
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
21,866
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.equiv.basic /-! # Local equivalences This files defines equivalences between subsets of given types. An element `e` of `local_equiv α β` is made of two maps `e.to_fun` and `e.inv_fun` respectively from α to β and from β to α (just like equivs), which are inverse to each other on the subsets `e.source` and `e.target` of respectively α and β. They are designed in particular to define charts on manifolds. The main functionality is `e.trans f`, which composes the two local equivalences by restricting the source and target to the maximal set where the composition makes sense. As for equivs, we register a coercion to functions and use it in our simp normal form: we write `e x` and `e.symm y` instead of `e.to_fun x` and `e.inv_fun y`. ## Main definitions `equiv.to_local_equiv`: associating a local equiv to an equiv, with source = target = univ `local_equiv.symm` : the inverse of a local equiv `local_equiv.trans` : the composition of two local equivs `local_equiv.refl` : the identity local equiv `local_equiv.of_set` : the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local equivs (see below in implementation notes) ## Implementation notes There are at least three possible implementations of local equivalences: * equivs on subtypes * pairs of functions taking values in `option α` and `option β`, equal to none where the local equivalence is not defined * pairs of functions defined everywhere, keeping the source and target as additional data Each of these implementations has pros and cons. * When dealing with subtypes, one still need to define additional API for composition and restriction of domains. Checking that one always belongs to the right subtype makes things very tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for instance). * With option-valued functions, the composition is very neat (it is just the usual composition, and the domain is restricted automatically). These are implemented in `pequiv.lean`. For manifolds, where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of overhead as one would need to extend all classes of smoothness to option-valued maps. * The local_equiv version as explained above is easier to use for manifolds. The drawback is that there is extra useless data (the values of `to_fun` and `inv_fun` outside of `source` and `target`). In particular, the equality notion between local equivs is not "the right one", i.e., coinciding source and target and equality there. Moreover, there are no local equivs in this sense between an empty type and a nonempty type. Since empty types are not that useful, and since one almost never needs to talk about equal local equivs, this is not an issue in practice. Still, we introduce an equivalence relation `eq_on_source` that captures this right notion of equality, and show that many properties are invariant under this equivalence relation. -/ open function set variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Local equivalence between subsets `source` and `target` of α and β respectively. The (global) maps `to_fun : α → β` and `inv_fun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `to_fun` outside of `source` and of `inv_fun` outside of `target` are irrelevant. -/ @[nolint has_inhabited_instance] structure local_equiv (α : Type*) (β : Type*) := (to_fun : α → β) (inv_fun : β → α) (source : set α) (target : set β) (map_source' : ∀{x}, x ∈ source → to_fun x ∈ target) (map_target' : ∀{x}, x ∈ target → inv_fun x ∈ source) (left_inv' : ∀{x}, x ∈ source → inv_fun (to_fun x) = x) (right_inv' : ∀{x}, x ∈ target → to_fun (inv_fun x) = x) /-- Associating a local_equiv to an equiv-/ def equiv.to_local_equiv (e : equiv α β) : local_equiv α β := { to_fun := e.to_fun, inv_fun := e.inv_fun, source := univ, target := univ, map_source' := λx hx, mem_univ _, map_target' := λy hy, mem_univ _, left_inv' := λx hx, e.left_inv x, right_inv' := λx hx, e.right_inv x } namespace local_equiv variables (e : local_equiv α β) (e' : local_equiv β γ) /-- The inverse of a local equiv -/ protected def symm : local_equiv β α := { to_fun := e.inv_fun, inv_fun := e.to_fun, source := e.target, target := e.source, map_source' := e.map_target', map_target' := e.map_source', left_inv' := e.right_inv', right_inv' := e.left_inv' } instance : has_coe_to_fun (local_equiv α β) := ⟨_, local_equiv.to_fun⟩ @[simp] theorem coe_mk (f : α → β) (g s t ml mr il ir) : (local_equiv.mk f g s t ml mr il ir : α → β) = f := rfl @[simp] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) : ((local_equiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl @[simp] lemma to_fun_as_coe : e.to_fun = e := rfl @[simp] lemma inv_fun_as_coe : e.inv_fun = e.symm := rfl @[simp] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h protected lemma maps_to : maps_to e e.source e.target := λ _, e.map_source @[simp] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to @[simp] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h protected lemma left_inv_on : left_inv_on e.symm e e.source := λ _, e.left_inv @[simp] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h protected lemma right_inv_on : right_inv_on e.symm e e.target := λ _, e.right_inv /-- Associating to a local_equiv an equiv between the source and the target -/ protected def to_equiv : equiv (e.source) (e.target) := { to_fun := λ x, ⟨e x, e.map_source x.mem⟩, inv_fun := λ y, ⟨e.symm y, e.map_target y.mem⟩, left_inv := λ⟨x, hx⟩, subtype.eq $ e.left_inv hx, right_inv := λ⟨y, hy⟩, subtype.eq $ e.right_inv hy } @[simp] lemma symm_source : e.symm.source = e.target := rfl @[simp] lemma symm_target : e.symm.target = e.source := rfl @[simp] lemma symm_symm : e.symm.symm = e := by { cases e, refl } /-- A local equiv induces a bijection between its source and target -/ lemma bij_on_source : bij_on e e.source e.target := inv_on.bij_on ⟨e.left_inv_on, e.right_inv_on⟩ e.maps_to e.symm_maps_to lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := begin refine subset.antisymm (λx hx, _) (λx hx, _), { rcases (mem_image _ _ _).1 hx with ⟨y, ys, hy⟩, rw ← hy, split, { apply e.map_source, exact h ys }, { rwa [mem_preimage, e.left_inv (h ys)] } }, { rw ← e.right_inv hx.1, exact mem_image_of_mem _ hx.2 } end lemma inv_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := begin ext, split, { rintros ⟨hx, xs⟩, simp only [mem_preimage, hx, e.left_inv, mem_preimage] at xs, exact ⟨hx, xs⟩ }, { rintros ⟨hx, xs⟩, simp [hx, xs] } end lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma image_source_eq_target : e '' e.source = e.target := e.bij_on_source.image_eq lemma source_subset_preimage_target : e.source ⊆ e ⁻¹' e.target := λx hx, e.map_source hx lemma inv_image_target_eq_source : e.symm '' e.target = e.source := e.symm.bij_on_source.image_eq lemma target_subset_preimage_source : e.target ⊆ e.symm ⁻¹' e.source := λx hx, e.map_target hx /-- Two local equivs that have the same `source`, same `to_fun` and same `inv_fun`, coincide. -/ @[ext] protected lemma ext {e e' : local_equiv α β} (h : ∀x, e x = e' x) (hsymm : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := begin have A : (e : α → β) = e', by { ext x, exact h x }, have B : (e.symm : β → α) = e'.symm, by { ext x, exact hsymm x }, have I : e '' e.source = e.target := e.image_source_eq_target, have I' : e' '' e'.source = e'.target := e'.image_source_eq_target, rw [A, hs, I'] at I, cases e; cases e', simp * at * end /-- Restricting a local equivalence to e.source ∩ s -/ protected def restr (s : set α) : local_equiv α β := { to_fun := e, inv_fun := e.symm, source := e.source ∩ s, target := e.target ∩ e.symm⁻¹' s, map_source' := λx hx, begin apply mem_inter, { apply e.map_source, exact hx.1 }, { rw [mem_preimage, e.left_inv], exact hx.2, exact hx.1 }, end, map_target' := λy hy, begin apply mem_inter, { apply e.map_target, exact hy.1 }, { exact hy.2 }, end, left_inv' := λx hx, e.left_inv hx.1, right_inv' := λy hy, e.right_inv hy.1 } @[simp] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl @[simp] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl @[simp] lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ s := rfl @[simp] lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' s := rfl lemma restr_eq_of_source_subset {e : local_equiv α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := local_equiv.ext (λ_, rfl) (λ_, rfl) (by simp [inter_eq_self_of_subset_left h]) @[simp] lemma restr_univ {e : local_equiv α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) /-- The identity local equiv -/ protected def refl (α : Type*) : local_equiv α α := (equiv.refl α).to_local_equiv @[simp] lemma refl_source : (local_equiv.refl α).source = univ := rfl @[simp] lemma refl_target : (local_equiv.refl α).target = univ := rfl @[simp] lemma refl_coe : (local_equiv.refl α : α → α) = id := rfl @[simp] lemma refl_symm : (local_equiv.refl α).symm = local_equiv.refl α := rfl @[simp] lemma refl_restr_source (s : set α) : ((local_equiv.refl α).restr s).source = s := by simp @[simp] lemma refl_restr_target (s : set α) : ((local_equiv.refl α).restr s).target = s := by { change univ ∩ id⁻¹' s = s, simp } /-- The identity local equiv on a set `s` -/ def of_set (s : set α) : local_equiv α α := { to_fun := id, inv_fun := id, source := s, target := s, map_source' := λx hx, hx, map_target' := λx hx, hx, left_inv' := λx hx, rfl, right_inv' := λx hx, rfl } @[simp] lemma of_set_source (s : set α) : (local_equiv.of_set s).source = s := rfl @[simp] lemma of_set_target (s : set α) : (local_equiv.of_set s).target = s := rfl @[simp] lemma of_set_coe (s : set α) : (local_equiv.of_set s : α → α) = id := rfl @[simp] lemma of_set_symm (s : set α) : (local_equiv.of_set s).symm = local_equiv.of_set s := rfl /-- Composing two local equivs if the target of the first coincides with the source of the second. -/ protected def trans' (e' : local_equiv β γ) (h : e.target = e'.source) : local_equiv α γ := { to_fun := e' ∘ e, inv_fun := e.symm ∘ e'.symm, source := e.source, target := e'.target, map_source' := λx hx, by simp [h.symm, hx], map_target' := λy hy, by simp [h, hy], left_inv' := λx hx, by simp [hx, h.symm], right_inv' := λy hy, by simp [hy, h] } /-- Composing two local equivs, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_equiv α γ := local_equiv.trans' (e.symm.restr (e'.source)).symm (e'.restr (e.target)) (inter_comm _ _) @[simp] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := rfl lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := begin symmetry, calc e.source ∩ e ⁻¹' (e.target ∩ e'.source) = (e.source ∩ e ⁻¹' (e.target)) ∩ e ⁻¹' (e'.source) : by rw [preimage_inter, inter_assoc] ... = e.source ∩ e ⁻¹' (e'.source) : by { congr' 1, apply inter_eq_self_of_subset_left e.source_subset_preimage_target } ... = (e.trans e').source : rfl end lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := begin rw [e.trans_source', e.inv_image_eq_source_inter_preimage, inter_comm], exact inter_subset_left _ _, end lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := image_source_eq_target (local_equiv.symm (local_equiv.restr (local_equiv.symm e) (e'.source))) lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_equiv γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, @preimage_comp α β γ, inter_assoc]) @[simp] lemma trans_refl : e.trans (local_equiv.refl β) = e := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source]) @[simp] lemma refl_trans : (local_equiv.refl α).trans e = e := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, preimage_id]) lemma trans_refl_restr (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e ⁻¹' s) := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source]) lemma trans_refl_restr' (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e.source ∩ e ⁻¹' s) := local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source], rw [← inter_assoc, inter_self] } lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source, inter_comm], rwa inter_assoc } /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. Then `e` and `e'` should really be considered the same local equiv. -/ def eq_on_source (e e' : local_equiv α β) : Prop := e.source = e'.source ∧ (e.source.eq_on e e') /-- `eq_on_source` is an equivalence relation -/ instance eq_on_source_setoid : setoid (local_equiv α β) := { r := eq_on_source, iseqv := ⟨ λe, by simp [eq_on_source], λe e' h, by { simp [eq_on_source, h.1.symm], exact λx hx, (h.2 hx).symm }, λe e' e'' h h', ⟨by rwa [← h'.1, ← h.1], λx hx, by { rw [← h'.2, h.2 hx], rwa ← h.1 }⟩⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- Two equivalent local equivs have the same source -/ lemma eq_on_source.source_eq {e e' : local_equiv α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local equivs coincide on the source -/ lemma eq_on_source.eq_on {e e' : local_equiv α β} (h : e ≈ e') : e.source.eq_on e e' := h.2 /-- Two equivalent local equivs have the same target -/ lemma eq_on_source.target_eq {e e' : local_equiv α β} (h : e ≈ e') : e.target = e'.target := by simp only [← image_source_eq_target, ← h.source_eq, h.2.image_eq] /-- If two local equivs are equivalent, so are their inverses. -/ lemma eq_on_source.symm' {e e' : local_equiv α β} (h : e ≈ e') : e.symm ≈ e'.symm := begin refine ⟨h.target_eq, eq_on_of_left_inv_on_of_right_inv_on e.left_inv_on _ _⟩; simp only [symm_source, h.target_eq, h.source_eq, e'.symm_maps_to], exact e'.right_inv_on.congr_right e'.symm_maps_to (h.source_eq ▸ h.eq_on.symm), end /-- Two equivalent local equivs have coinciding inverses on the target -/ lemma eq_on_source.symm_eq_on {e e' : local_equiv α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.eq_on /-- Composition of local equivs respects equivalence -/ lemma eq_on_source.trans' {e e' : local_equiv α β} {f f' : local_equiv β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := begin split, { rw [trans_source'', trans_source'', ← he.target_eq, ← hf.1], exact (he.symm'.eq_on.mono $ inter_subset_left _ _).image_eq }, { assume x hx, rw trans_source at hx, simp [(he.2 hx.1).symm, hf.2 hx.2] } end /-- Restriction of local equivs respects equivalence -/ lemma eq_on_source.restr {e e' : local_equiv α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := begin split, { simp [he.1] }, { assume x hx, simp only [mem_inter_eq, restr_source] at hx, exact he.2 hx.1 } end /-- Preimages are respected by equivalence -/ lemma eq_on_source.source_inter_preimage_eq {e e' : local_equiv α β} (he : e ≈ e') (s : set β) : e.source ∩ e ⁻¹' s = e'.source ∩ e' ⁻¹' s := begin ext x, simp only [mem_inter_eq, mem_preimage], split, { assume hx, rwa [← he.2 hx.1, ← he.source_eq] }, { assume hx, rwa [← (setoid.symm he).2 hx.1, he.source_eq] } end /-- Composition of a local equiv and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_equiv.of_set e.source := begin have A : (e.trans e.symm).source = e.source, by simp [trans_source, inter_eq_self_of_subset_left (source_subset_preimage_target _)], refine ⟨by simp [A], λx hx, _⟩, rw A at hx, simp [hx] end /-- Composition of the inverse of a local equiv and this local equiv is equivalent to the restriction of the identity to the target -/ lemma trans_symm_self : e.symm.trans e ≈ local_equiv.of_set e.target := trans_self_symm (e.symm) /-- Two equivalent local equivs are equal when the source and target are univ -/ lemma eq_of_eq_on_source_univ (e e' : local_equiv α β) (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := begin apply local_equiv.ext (λx, _) (λx, _) h.1, { apply h.2, rw s, exact mem_univ _ }, { apply h.symm'.2, rw [symm_source, t], exact mem_univ _ } end section prod /-- The product of two local equivs, as a local equiv on the product. -/ def prod (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv (α × γ) (β × δ) := { source := set.prod e.source e'.source, target := set.prod e.target e'.target, to_fun := λp, (e p.1, e' p.2), inv_fun := λp, (e.symm p.1, e'.symm p.2), map_source' := λp hp, by { simp at hp, simp [hp] }, map_target' := λp hp, by { simp at hp, simp [map_target, hp] }, left_inv' := λp hp, by { simp at hp, simp [hp] }, right_inv' := λp hp, by { simp at hp, simp [hp] } } @[simp] lemma prod_source (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl @[simp] lemma prod_target (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl @[simp] lemma prod_coe (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e') : α × γ → β × δ) = (λp, (e p.1, e' p.2)) := rfl @[simp] lemma prod_coe_symm (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e').symm : β × δ → α × γ) = (λp, (e.symm p.1, e'.symm p.2)) := rfl end prod end local_equiv namespace set -- All arguments are explicit to avoid missing information in the pretty printer output /-- A bijection between two sets `s : set α` and `t : set β` provides a local equivalence between `α` and `β`. -/ @[simps] noncomputable def bij_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (t : set β) (hf : bij_on f s t) : local_equiv α β := { to_fun := f, inv_fun := inv_fun_on f s, source := s, target := t, map_source' := hf.maps_to, map_target' := hf.surj_on.maps_to_inv_fun_on, left_inv' := hf.inv_on_inv_fun_on.1, right_inv' := hf.inv_on_inv_fun_on.2 } /-- A map injective on a subset of its domain provides a local equivalence. -/ @[simp] noncomputable def inj_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (hf : inj_on f s) : local_equiv α β := hf.bij_on_image.to_local_equiv f s (f '' s) end set namespace equiv /- equivs give rise to local_equiv. We set up simp lemmas to reduce most properties of the local equiv to that of the equiv. -/ variables (e : equiv α β) (e' : equiv β γ) @[simp] lemma to_local_equiv_coe : (e.to_local_equiv : α → β) = e := rfl @[simp] lemma to_local_equiv_symm_coe : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp] lemma to_local_equiv_source : e.to_local_equiv.source = univ := rfl @[simp] lemma to_local_equiv_target : e.to_local_equiv.target = univ := rfl @[simp] lemma refl_to_local_equiv : (equiv.refl α).to_local_equiv = local_equiv.refl α := rfl @[simp] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl @[simp] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [local_equiv.trans_source, equiv.to_local_equiv]) end equiv
87d2087b9d6a5e9c4323dce4b86d20640e0f1c00
492a7e27d49633a89f7ce6e1e28f676b062fcbc9
/src/monoidal_categories_reboot/monoidal_opposite.lean
ae63ebe0df3ec845e4264921f553b59290544cc6
[ "Apache-2.0" ]
permissive
semorrison/monoidal-categories-reboot
9edba30277de48a234b63813cf85b171772ce36f
48b5f1d535daba4e591672042a298ac36be2e6dd
refs/heads/master
1,642,472,396,149
1,560,587,477,000
1,560,587,477,000
156,465,626
0
1
null
1,541,549,278,000
1,541,549,278,000
null
UTF-8
Lean
false
false
1,146
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import .monoidal_functor_attributes open category_theory namespace category_theory.monoidal universes u₁ v₁ u₂ v₂ def mop (C : Sort u₁) : Sort u₁ := C def unmop {C : Sort u₁} (X : mop C) : C := X variables {C : Type u₁} [𝒞 : monoidal_category.{v₁} C] include 𝒞 instance underlying_category_monoidal_opposite : category.{v₁} (mop C) := 𝒞.to_category -- WIP -- instance monoidal_opposite : monoidal_category.{v₁} (mop C) := -- { tensor_obj := λ X Y, @monoidal_category.tensor_obj C _ Y X, -- tensor_hom := λ (X₁ Y₁ X₂ Y₂ : mop C) (f : X₁ ⟶ Y₁) (g : X₂ ⟶ Y₂), @monoidal_category.tensor_hom C _ _ _ _ _ g f, -- tensor_unit := @monoidal_category.tensor_unit C _, -- associator := λ X Y Z, (@monoidal_category.associator _ _ (unmop X) (unmop Y) (unmop Z)).symm, -- left_unitor := λ X, (@monoidal_category.right_unitor _), -- right_unitor := λ X, (@monoidal_category.left_unitor _) } end category_theory.monoidal
ea4e9173090598441450be5c3fabadf5e04a9190
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/monad_univ_lift.lean
012f22a8d7dd803ec04b707358ae500a15d28dc9
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
436
lean
universe variables u v def M : Type u → Type v := sorry instance : monad M := sorry def act1 : M unit := return () def act2 : M (Σ (A : Type), A) := return ⟨nat, 0⟩ def {t s} up {A : Type s} (a : M A) : M (ulift.{t} A) := sorry def {t s} down {A : Type s} (a : M (ulift.{t} A)) : M A := sorry prefix `↑`:10 := up.{1} prefix `↓`:10 := down.{1} def ex : M unit := ↓do ↑act1, act2, ↑act1, act2, ↑act1
3d547f5da2a7c19cd201e370d81a021f23ffaeff
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/elements_auto.lean
67fc078d6f9617c5f9ac441e5870abc18107591b
[]
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
6,221
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.comma import Mathlib.category_theory.groupoid import Mathlib.category_theory.punit import Mathlib.PostPort universes w v u namespace Mathlib /-! # The category of elements This file defines the category of elements, also known as (a special case of) the Grothendieck construction. Given a functor `F : C ⥤ Type`, an object of `F.elements` is a pair `(X : C, x : F.obj X)`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. ## Implementation notes This construction is equivalent to a special case of a comma construction, so this is mostly just a more convenient API. We prove the equivalence in `category_theory.category_of_elements.comma_equivalence`. ## References * [Emily Riehl, *Category Theory in Context*, Section 2.4][riehl2017] * <https://en.wikipedia.org/wiki/Category_of_elements> * <https://ncatlab.org/nlab/show/category+of+elements> ## Tags category of elements, Grothendieck construction, comma category -/ namespace category_theory /-- The type of objects for the category of elements of a functor `F : C ⥤ Type` is a pair `(X : C, x : F.obj X)`. -/ def functor.elements {C : Type u} [category C] (F : C ⥤ Type w) := sigma fun (c : C) => functor.obj F c /-- The category structure on `F.elements`, for `F : C ⥤ Type`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. -/ protected instance category_of_elements {C : Type u} [category C] (F : C ⥤ Type w) : category (functor.elements F) := category.mk namespace category_of_elements theorem ext {C : Type u} [category C] (F : C ⥤ Type w) {x : functor.elements F} {y : functor.elements F} (f : x ⟶ y) (g : x ⟶ y) (w : subtype.val f = subtype.val g) : f = g := subtype.ext_val w @[simp] theorem comp_val {C : Type u} [category C] {F : C ⥤ Type w} {p : functor.elements F} {q : functor.elements F} {r : functor.elements F} {f : p ⟶ q} {g : q ⟶ r} : subtype.val (f ≫ g) = subtype.val f ≫ subtype.val g := rfl @[simp] theorem id_val {C : Type u} [category C] {F : C ⥤ Type w} {p : functor.elements F} : subtype.val 𝟙 = 𝟙 := rfl end category_of_elements protected instance groupoid_of_elements {G : Type u} [groupoid G] (F : G ⥤ Type w) : groupoid (functor.elements F) := groupoid.mk fun (p q : functor.elements F) (f : p ⟶ q) => { val := inv (subtype.val f), property := sorry } namespace category_of_elements /-- The functor out of the category of elements which forgets the element. -/ @[simp] theorem π_map {C : Type u} [category C] (F : C ⥤ Type w) (X : functor.elements F) (Y : functor.elements F) (f : X ⟶ Y) : functor.map (π F) f = subtype.val f := Eq.refl (functor.map (π F) f) /-- A natural transformation between functors induces a functor between the categories of elements. -/ @[simp] theorem map_obj_fst {C : Type u} [category C] {F₁ : C ⥤ Type w} {F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) (t : functor.elements F₁) : sigma.fst (functor.obj (map α) t) = sigma.fst t := Eq.refl (sigma.fst (functor.obj (map α) t)) @[simp] theorem map_π {C : Type u} [category C] {F₁ : C ⥤ Type w} {F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) : map α ⋙ π F₂ = π F₁ := rfl /-- The forward direction of the equivalence `F.elements ≅ (*, F)`. -/ def to_comma {C : Type u} [category C] (F : C ⥤ Type w) : functor.elements F ⥤ comma (functor.from_punit PUnit) F := functor.mk (fun (X : functor.elements F) => comma.mk fun (_x : functor.obj (functor.from_punit PUnit) PUnit.unit) => sigma.snd X) fun (X Y : functor.elements F) (f : X ⟶ Y) => comma_morphism.mk @[simp] theorem to_comma_obj {C : Type u} [category C] (F : C ⥤ Type w) (X : functor.elements F) : functor.obj (to_comma F) X = comma.mk fun (_x : functor.obj (functor.from_punit PUnit) PUnit.unit) => sigma.snd X := rfl @[simp] theorem to_comma_map {C : Type u} [category C] (F : C ⥤ Type w) {X : functor.elements F} {Y : functor.elements F} (f : X ⟶ Y) : functor.map (to_comma F) f = comma_morphism.mk := rfl /-- The reverse direction of the equivalence `F.elements ≅ (*, F)`. -/ def from_comma {C : Type u} [category C] (F : C ⥤ Type w) : comma (functor.from_punit PUnit) F ⥤ functor.elements F := functor.mk (fun (X : comma (functor.from_punit PUnit) F) => sigma.mk (comma.right X) (comma.hom X PUnit.unit)) fun (X Y : comma (functor.from_punit PUnit) F) (f : X ⟶ Y) => { val := comma_morphism.right f, property := sorry } @[simp] theorem from_comma_obj {C : Type u} [category C] (F : C ⥤ Type w) (X : comma (functor.from_punit PUnit) F) : functor.obj (from_comma F) X = sigma.mk (comma.right X) (comma.hom X PUnit.unit) := rfl @[simp] theorem from_comma_map {C : Type u} [category C] (F : C ⥤ Type w) {X : comma (functor.from_punit PUnit) F} {Y : comma (functor.from_punit PUnit) F} (f : X ⟶ Y) : functor.map (from_comma F) f = { val := comma_morphism.right f, property := congr_fun (Eq.symm (comma_morphism.w' f)) PUnit.unit } := rfl /-- The equivalence between the category of elements `F.elements` and the comma category `(*, F)`. -/ def comma_equivalence {C : Type u} [category C] (F : C ⥤ Type w) : functor.elements F ≌ comma (functor.from_punit PUnit) F := equivalence.mk (to_comma F) (from_comma F) (nat_iso.of_components (fun (X : functor.elements F) => eq_to_iso sorry) sorry) (nat_iso.of_components (fun (X : comma (functor.from_punit PUnit) F) => iso.mk comma_morphism.mk comma_morphism.mk) sorry) @[simp] theorem comma_equivalence_functor {C : Type u} [category C] (F : C ⥤ Type w) : equivalence.functor (comma_equivalence F) = to_comma F := rfl @[simp] theorem comma_equivalence_inverse {C : Type u} [category C] (F : C ⥤ Type w) : equivalence.inverse (comma_equivalence F) = from_comma F := rfl end Mathlib
26644cd2b0772d00ca37de08066d0315145493e7
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/box_integral/box/basic.lean
463059270a838c2f59ea581e68809651484b158b
[ "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
17,896
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.set.intervals.monotone import topology.algebra.order.monotone_convergence import topology.metric_space.basic /-! # Rectangular boxes in `ℝⁿ` In this file we define rectangular boxes in `ℝⁿ`. As usual, we represent `ℝⁿ` as the type of functions `ι → ℝ` (usually `ι = fin n` for some `n`). When we need to interpret a box `[l, u]` as a set, we use the product `{x | ∀ i, l i < x i ∧ x i ≤ u i}` of half-open intervals `(l i, u i]`. We exclude `l i` because this way boxes of a partition are disjoint as sets in `ℝⁿ`. Currently, the only use cases for these constructions are the definitions of Riemann-style integrals (Riemann, Henstock-Kurzweil, McShane). ## Main definitions We use the same structure `box_integral.box` both for ambient boxes and for elements of a partition. Each box is stored as two points `lower upper : ι → ℝ` and a proof of `∀ i, lower i < upper i`. We define instances `has_mem (ι → ℝ) (box ι)` and `has_coe_t (box ι) (set $ ι → ℝ)` so that each box is interpreted as the set `{x | ∀ i, x i ∈ set.Ioc (I.lower i) (I.upper i)}`. This way boxes of a partition are pairwise disjoint and their union is exactly the original box. We require boxes to be nonempty, because this way coercion to sets is injective. The empty box can be represented as `⊥ : with_bot (box_integral.box ι)`. We define the following operations on boxes: * coercion to `set (ι → ℝ)` and `has_mem (ι → ℝ) (box_integral.box ι)` as described above; * `partial_order` and `semilattice_sup` instances such that `I ≤ J` is equivalent to `(I : set (ι → ℝ)) ⊆ J`; * `lattice` instances on `with_bot (box_integral.box ι)`; * `box_integral.box.Icc`: the closed box `set.Icc I.lower I.upper`; defined as a bundled monotone map from `box ι` to `set (ι → ℝ)`; * `box_integral.box.face I i : box (fin n)`: a hyperface of `I : box_integral.box (fin (n + 1))`; * `box_integral.box.distortion`: the maximal ratio of two lengths of edges of a box; defined as the supremum of `nndist I.lower I.upper / nndist (I.lower i) (I.upper i)`. We also provide a convenience constructor `box_integral.box.mk' (l u : ι → ℝ) : with_bot (box ι)` that returns the box `⟨l, u, _⟩` if it is nonempty and `⊥` otherwise. ## Tags rectangular box -/ open set function metric filter noncomputable theory open_locale nnreal classical topological_space namespace box_integral variables {ι : Type*} /-! ### Rectangular box: definition and partial order -/ /-- A nontrivial rectangular box in `ι → ℝ` with corners `lower` and `upper`. Repesents the product of half-open intervals `(lower i, upper i]`. -/ structure box (ι : Type*) := (lower upper : ι → ℝ) (lower_lt_upper : ∀ i, lower i < upper i) attribute [simp] box.lower_lt_upper namespace box variables (I J : box ι) {x y : ι → ℝ} instance : inhabited (box ι) := ⟨⟨0, 1, λ i, zero_lt_one⟩⟩ lemma lower_le_upper : I.lower ≤ I.upper := λ i, (I.lower_lt_upper i).le lemma lower_ne_upper (i) : I.lower i ≠ I.upper i := (I.lower_lt_upper i).ne instance : has_mem (ι → ℝ) (box ι) := ⟨λ x I, ∀ i, x i ∈ Ioc (I.lower i) (I.upper i)⟩ instance : has_coe_t (box ι) (set $ ι → ℝ) := ⟨λ I, {x | x ∈ I}⟩ @[simp] lemma mem_mk {l u x : ι → ℝ} {H} : x ∈ mk l u H ↔ ∀ i, x i ∈ Ioc (l i) (u i) := iff.rfl @[simp, norm_cast] lemma mem_coe : x ∈ (I : set (ι → ℝ)) ↔ x ∈ I := iff.rfl lemma mem_def : x ∈ I ↔ ∀ i, x i ∈ Ioc (I.lower i) (I.upper i) := iff.rfl lemma mem_univ_Ioc {I : box ι} : x ∈ pi univ (λ i, Ioc (I.lower i) (I.upper i)) ↔ x ∈ I := mem_univ_pi lemma coe_eq_pi : (I : set (ι → ℝ)) = pi univ (λ i, Ioc (I.lower i) (I.upper i)) := set.ext $ λ x, mem_univ_Ioc.symm @[simp] lemma upper_mem : I.upper ∈ I := λ i, right_mem_Ioc.2 $ I.lower_lt_upper i lemma exists_mem : ∃ x, x ∈ I := ⟨_, I.upper_mem⟩ lemma nonempty_coe : set.nonempty (I : set (ι → ℝ)) := I.exists_mem @[simp] lemma coe_ne_empty : (I : set (ι → ℝ)) ≠ ∅ := I.nonempty_coe.ne_empty @[simp] lemma empty_ne_coe : ∅ ≠ (I : set (ι → ℝ)) := I.coe_ne_empty.symm instance : has_le (box ι) := ⟨λ I J, ∀ ⦃x⦄, x ∈ I → x ∈ J⟩ lemma le_def : I ≤ J ↔ ∀ x ∈ I, x ∈ J := iff.rfl lemma le_tfae : tfae [I ≤ J, (I : set (ι → ℝ)) ⊆ J, Icc I.lower I.upper ⊆ Icc J.lower J.upper, J.lower ≤ I.lower ∧ I.upper ≤ J.upper] := begin tfae_have : 1 ↔ 2, from iff.rfl, tfae_have : 2 → 3, { intro h, simpa [coe_eq_pi, closure_pi_set, lower_ne_upper] using closure_mono h }, tfae_have : 3 ↔ 4, from Icc_subset_Icc_iff I.lower_le_upper, tfae_have : 4 → 2, from λ h x hx i, Ioc_subset_Ioc (h.1 i) (h.2 i) (hx i), tfae_finish end variables {I J} @[simp, norm_cast] lemma coe_subset_coe : (I : set (ι → ℝ)) ⊆ J ↔ I ≤ J := iff.rfl lemma le_iff_bounds : I ≤ J ↔ J.lower ≤ I.lower ∧ I.upper ≤ J.upper := (le_tfae I J).out 0 3 lemma injective_coe : injective (coe : box ι → set (ι → ℝ)) := begin rintros ⟨l₁, u₁, h₁⟩ ⟨l₂, u₂, h₂⟩ h, simp only [subset.antisymm_iff, coe_subset_coe, le_iff_bounds] at h, congr, exacts [le_antisymm h.2.1 h.1.1, le_antisymm h.1.2 h.2.2] end @[simp, norm_cast] lemma coe_inj : (I : set (ι → ℝ)) = J ↔ I = J := injective_coe.eq_iff @[ext] lemma ext (H : ∀ x, x ∈ I ↔ x ∈ J) : I = J := injective_coe $ set.ext H lemma ne_of_disjoint_coe (h : disjoint (I : set (ι → ℝ)) J) : I ≠ J := mt coe_inj.2 $ h.ne I.coe_ne_empty instance : partial_order (box ι) := { le := (≤), .. partial_order.lift (coe : box ι → set (ι → ℝ)) injective_coe } /-- Closed box corresponding to `I : box_integral.box ι`. -/ protected def Icc : box ι ↪o set (ι → ℝ) := order_embedding.of_map_le_iff (λ I : box ι, Icc I.lower I.upper) (λ I J, (le_tfae I J).out 2 0) lemma Icc_def : I.Icc = Icc I.lower I.upper := rfl @[simp] lemma upper_mem_Icc (I : box ι) : I.upper ∈ I.Icc := right_mem_Icc.2 I.lower_le_upper @[simp] lemma lower_mem_Icc (I : box ι) : I.lower ∈ I.Icc := left_mem_Icc.2 I.lower_le_upper protected lemma is_compact_Icc (I : box ι) : is_compact I.Icc := is_compact_Icc lemma Icc_eq_pi : I.Icc = pi univ (λ i, Icc (I.lower i) (I.upper i)) := (pi_univ_Icc _ _).symm lemma le_iff_Icc : I ≤ J ↔ I.Icc ⊆ J.Icc := (le_tfae I J).out 0 2 lemma antitone_lower : antitone (λ I : box ι, I.lower) := λ I J H, (le_iff_bounds.1 H).1 lemma monotone_upper : monotone (λ I : box ι, I.upper) := λ I J H, (le_iff_bounds.1 H).2 lemma coe_subset_Icc : ↑I ⊆ I.Icc := λ x hx, ⟨λ i, (hx i).1.le, λ i, (hx i).2⟩ /-! ### Supremum of two boxes -/ /-- `I ⊔ J` is the least box that includes both `I` and `J`. Since `↑I ∪ ↑J` is usually not a box, `↑(I ⊔ J)` is larger than `↑I ∪ ↑J`. -/ instance : has_sup (box ι) := ⟨λ I J, ⟨I.lower ⊓ J.lower, I.upper ⊔ J.upper, λ i, (min_le_left _ _).trans_lt $ (I.lower_lt_upper i).trans_le (le_max_left _ _)⟩⟩ instance : semilattice_sup (box ι) := { le_sup_left := λ I J, le_iff_bounds.2 ⟨inf_le_left, le_sup_left⟩, le_sup_right := λ I J, le_iff_bounds.2 ⟨inf_le_right, le_sup_right⟩, sup_le := λ I₁ I₂ J h₁ h₂, le_iff_bounds.2 ⟨le_inf (antitone_lower h₁) (antitone_lower h₂), sup_le (monotone_upper h₁) (monotone_upper h₂)⟩, .. box.partial_order, .. box.has_sup } /-! ### `with_bot (box ι)` In this section we define coercion from `with_bot (box ι)` to `set (ι → ℝ)` by sending `⊥` to `∅`. -/ instance with_bot_coe : has_coe_t (with_bot (box ι)) (set (ι → ℝ)) := ⟨λ o, o.elim ∅ coe⟩ @[simp, norm_cast] lemma coe_bot : ((⊥ : with_bot (box ι)) : set (ι → ℝ)) = ∅ := rfl @[simp, norm_cast] lemma coe_coe : ((I : with_bot (box ι)) : set (ι → ℝ)) = I := rfl lemma is_some_iff : ∀ {I : with_bot (box ι)}, I.is_some ↔ (I : set (ι → ℝ)).nonempty | ⊥ := by { erw option.is_some, simp } | (I : box ι) := by { erw option.is_some, simp [I.nonempty_coe] } lemma bUnion_coe_eq_coe (I : with_bot (box ι)) : (⋃ (J : box ι) (hJ : ↑J = I), (J : set (ι → ℝ))) = I := by induction I using with_bot.rec_bot_coe; simp [with_bot.coe_eq_coe] @[simp, norm_cast] lemma with_bot_coe_subset_iff {I J : with_bot (box ι)} : (I : set (ι → ℝ)) ⊆ J ↔ I ≤ J := begin induction I using with_bot.rec_bot_coe, { simp }, induction J using with_bot.rec_bot_coe, { simp [subset_empty_iff] }, simp end @[simp, norm_cast] lemma with_bot_coe_inj {I J : with_bot (box ι)} : (I : set (ι → ℝ)) = J ↔ I = J := by simp only [subset.antisymm_iff, ← le_antisymm_iff, with_bot_coe_subset_iff] /-- Make a `with_bot (box ι)` from a pair of corners `l u : ι → ℝ`. If `l i < u i` for all `i`, then the result is `⟨l, u, _⟩ : box ι`, otherwise it is `⊥`. In any case, the result interpreted as a set in `ι → ℝ` is the set `{x : ι → ℝ | ∀ i, x i ∈ Ioc (l i) (u i)}`. -/ def mk' (l u : ι → ℝ) : with_bot (box ι) := if h : ∀ i, l i < u i then ↑(⟨l, u, h⟩ : box ι) else ⊥ @[simp] lemma mk'_eq_bot {l u : ι → ℝ} : mk' l u = ⊥ ↔ ∃ i, u i ≤ l i := by { rw mk', split_ifs; simpa using h } @[simp] lemma mk'_eq_coe {l u : ι → ℝ} : mk' l u = I ↔ l = I.lower ∧ u = I.upper := begin cases I with lI uI hI, rw mk', split_ifs, { simp [with_bot.coe_eq_coe] }, { suffices : l = lI → u ≠ uI, by simpa, rintro rfl rfl, exact h hI } end @[simp] lemma coe_mk' (l u : ι → ℝ) : (mk' l u : set (ι → ℝ)) = pi univ (λ i, Ioc (l i) (u i)) := begin rw mk', split_ifs, { exact coe_eq_pi _ }, { rcases not_forall.mp h with ⟨i, hi⟩, rw [coe_bot, univ_pi_eq_empty], exact Ioc_eq_empty hi } end instance : has_inf (with_bot (box ι)) := ⟨λ I, with_bot.rec_bot_coe (λ J, ⊥) (λ I J, with_bot.rec_bot_coe ⊥ (λ J, mk' (I.lower ⊔ J.lower) (I.upper ⊓ J.upper)) J) I⟩ @[simp] lemma coe_inf (I J : with_bot (box ι)) : (↑(I ⊓ J) : set (ι → ℝ)) = I ∩ J := begin induction I using with_bot.rec_bot_coe, { change ∅ = _, simp }, induction J using with_bot.rec_bot_coe, { change ∅ = _, simp }, change ↑(mk' _ _) = _, simp only [coe_eq_pi, ← pi_inter_distrib, Ioc_inter_Ioc, pi.sup_apply, pi.inf_apply, coe_mk', coe_coe] end instance : lattice (with_bot (box ι)) := { inf_le_left := λ I J, begin rw [← with_bot_coe_subset_iff, coe_inf], exact inter_subset_left _ _ end, inf_le_right := λ I J, begin rw [← with_bot_coe_subset_iff, coe_inf], exact inter_subset_right _ _ end, le_inf := λ I J₁ J₂ h₁ h₂, begin simp only [← with_bot_coe_subset_iff, coe_inf] at *, exact subset_inter h₁ h₂ end, .. with_bot.semilattice_sup, .. box.with_bot.has_inf } @[simp, norm_cast] lemma disjoint_with_bot_coe {I J : with_bot (box ι)} : disjoint (I : set (ι → ℝ)) J ↔ disjoint I J := by { simp only [disjoint, ← with_bot_coe_subset_iff, coe_inf], refl } lemma disjoint_coe : disjoint (I : with_bot (box ι)) J ↔ disjoint (I : set (ι → ℝ)) J := disjoint_with_bot_coe.symm lemma not_disjoint_coe_iff_nonempty_inter : ¬disjoint (I : with_bot (box ι)) J ↔ (I ∩ J : set (ι → ℝ)).nonempty := by rw [disjoint_coe, set.not_disjoint_iff_nonempty_inter] /-! ### Hyperface of a box in `ℝⁿ⁺¹ = fin (n + 1) → ℝ` -/ /-- Face of a box in `ℝⁿ⁺¹ = fin (n + 1) → ℝ`: the box in `ℝⁿ = fin n → ℝ` with corners at `I.lower ∘ fin.succ_above i` and `I.upper ∘ fin.succ_above i`. -/ @[simps { simp_rhs := tt }] def face {n} (I : box (fin (n + 1))) (i : fin (n + 1)) : box (fin n) := ⟨I.lower ∘ fin.succ_above i, I.upper ∘ fin.succ_above i, λ j, I.lower_lt_upper _⟩ @[simp] lemma face_mk {n} (l u : fin (n + 1) → ℝ) (h : ∀ i, l i < u i) (i : fin (n + 1)) : face ⟨l, u, h⟩ i = ⟨l ∘ fin.succ_above i, u ∘ fin.succ_above i, λ j, h _⟩ := rfl @[mono] lemma face_mono {n} {I J : box (fin (n + 1))} (h : I ≤ J) (i : fin (n + 1)) : face I i ≤ face J i := λ x hx i, Ioc_subset_Ioc ((le_iff_bounds.1 h).1 _) ((le_iff_bounds.1 h).2 _) (hx _) lemma monotone_face {n} (i : fin (n + 1)) : monotone (λ I, face I i) := λ I J h, face_mono h i lemma maps_to_insert_nth_face_Icc {n} (I : box (fin (n + 1))) {i : fin (n + 1)} {x : ℝ} (hx : x ∈ Icc (I.lower i) (I.upper i)) : maps_to (i.insert_nth x) (I.face i).Icc I.Icc := λ y hy, fin.insert_nth_mem_Icc.2 ⟨hx, hy⟩ lemma maps_to_insert_nth_face {n} (I : box (fin (n + 1))) {i : fin (n + 1)} {x : ℝ} (hx : x ∈ Ioc (I.lower i) (I.upper i)) : maps_to (i.insert_nth x) (I.face i) I := λ y hy, by simpa only [mem_coe, mem_def, i.forall_iff_succ_above, hx, fin.insert_nth_apply_same, fin.insert_nth_apply_succ_above, true_and] lemma continuous_on_face_Icc {X} [topological_space X] {n} {f : (fin (n + 1) → ℝ) → X} {I : box (fin (n + 1))} (h : continuous_on f I.Icc) {i : fin (n + 1)} {x : ℝ} (hx : x ∈ Icc (I.lower i) (I.upper i)) : continuous_on (f ∘ i.insert_nth x) (I.face i).Icc := h.comp (continuous_on_const.fin_insert_nth i continuous_on_id) (I.maps_to_insert_nth_face_Icc hx) /-! ### Covering of the interior of a box by a monotone sequence of smaller boxes -/ /-- The interior of a box. -/ protected def Ioo : box ι →o set (ι → ℝ) := { to_fun := λ I, pi univ (λ i, Ioo (I.lower i) (I.upper i)), monotone' := λ I J h, pi_mono $ λ i hi, Ioo_subset_Ioo ((le_iff_bounds.1 h).1 i) ((le_iff_bounds.1 h).2 i) } lemma Ioo_subset_coe (I : box ι) : I.Ioo ⊆ I := λ x hx i, Ioo_subset_Ioc_self (hx i trivial) protected lemma Ioo_subset_Icc (I : box ι) : I.Ioo ⊆ I.Icc := I.Ioo_subset_coe.trans coe_subset_Icc lemma Union_Ioo_of_tendsto [fintype ι] {I : box ι} {J : ℕ → box ι} (hJ : monotone J) (hl : tendsto (lower ∘ J) at_top (𝓝 I.lower)) (hu : tendsto (upper ∘ J) at_top (𝓝 I.upper)) : (⋃ n, (J n).Ioo) = I.Ioo := have hl' : ∀ i, antitone (λ n, (J n).lower i), from λ i, (monotone_eval i).comp_antitone (antitone_lower.comp_monotone hJ), have hu' : ∀ i, monotone (λ n, (J n).upper i), from λ i, (monotone_eval i).comp (monotone_upper.comp hJ), calc (⋃ n, (J n).Ioo) = pi univ (λ i, ⋃ n, Ioo ((J n).lower i) ((J n).upper i)) : Union_univ_pi_of_monotone (λ i, (hl' i).Ioo (hu' i)) ... = I.Ioo : pi_congr rfl (λ i hi, Union_Ioo_of_mono_of_is_glb_of_is_lub (hl' i) (hu' i) (is_glb_of_tendsto_at_top (hl' i) (tendsto_pi_nhds.1 hl _)) (is_lub_of_tendsto_at_top (hu' i) (tendsto_pi_nhds.1 hu _))) lemma exists_seq_mono_tendsto (I : box ι) : ∃ J : ℕ →o box ι, (∀ n, (J n).Icc ⊆ I.Ioo) ∧ tendsto (lower ∘ J) at_top (𝓝 I.lower) ∧ tendsto (upper ∘ J) at_top (𝓝 I.upper) := begin choose a b ha_anti hb_mono ha_mem hb_mem hab ha_tendsto hb_tendsto using λ i, exists_seq_strict_anti_strict_mono_tendsto (I.lower_lt_upper i), exact ⟨⟨λ k, ⟨flip a k, flip b k, λ i, hab _ _ _⟩, λ k l hkl, le_iff_bounds.2 ⟨λ i, (ha_anti i).antitone hkl, λ i, (hb_mono i).monotone hkl⟩⟩, λ n x hx i hi, ⟨(ha_mem _ _).1.trans_le (hx.1 _), (hx.2 _).trans_lt (hb_mem _ _).2⟩, tendsto_pi_nhds.2 ha_tendsto, tendsto_pi_nhds.2 hb_tendsto⟩ end section distortion variable [fintype ι] /-- The distortion of a box `I` is the maximum of the ratios of the lengths of its edges. It is defined as the maximum of the ratios `nndist I.lower I.upper / nndist (I.lower i) (I.upper i)`. -/ def distortion (I : box ι) : ℝ≥0 := finset.univ.sup $ λ i : ι, nndist I.lower I.upper / nndist (I.lower i) (I.upper i) lemma distortion_eq_of_sub_eq_div {I J : box ι} {r : ℝ} (h : ∀ i, I.upper i - I.lower i = (J.upper i - J.lower i) / r) : distortion I = distortion J := begin simp only [distortion, nndist_pi_def, real.nndist_eq', h, map_div₀], congr' 1 with i, have : 0 < r, { by_contra hr, have := div_nonpos_of_nonneg_of_nonpos (sub_nonneg.2 $ J.lower_le_upper i) (not_lt.1 hr), rw ← h at this, exact this.not_lt (sub_pos.2 $ I.lower_lt_upper i) }, simp only [nnreal.finset_sup_div, div_div_div_cancel_right _ (real.nnabs.map_ne_zero.2 this.ne')] end lemma nndist_le_distortion_mul (I : box ι) (i : ι) : nndist I.lower I.upper ≤ I.distortion * nndist (I.lower i) (I.upper i) := calc nndist I.lower I.upper = (nndist I.lower I.upper / nndist (I.lower i) (I.upper i)) * nndist (I.lower i) (I.upper i) : (div_mul_cancel _ $ mt nndist_eq_zero.1 (I.lower_lt_upper i).ne).symm ... ≤ I.distortion * nndist (I.lower i) (I.upper i) : mul_le_mul_right' (finset.le_sup $ finset.mem_univ i) _ lemma dist_le_distortion_mul (I : box ι) (i : ι) : dist I.lower I.upper ≤ I.distortion * (I.upper i - I.lower i) := have A : I.lower i - I.upper i < 0, from sub_neg.2 (I.lower_lt_upper i), by simpa only [← nnreal.coe_le_coe, ← dist_nndist, nnreal.coe_mul, real.dist_eq, abs_of_neg A, neg_sub] using I.nndist_le_distortion_mul i lemma diam_Icc_le_of_distortion_le (I : box ι) (i : ι) {c : ℝ≥0} (h : I.distortion ≤ c) : diam I.Icc ≤ c * (I.upper i - I.lower i) := have (0 : ℝ) ≤ c * (I.upper i - I.lower i), from mul_nonneg c.coe_nonneg (sub_nonneg.2 $ I.lower_le_upper _), diam_le_of_forall_dist_le this $ λ x hx y hy, calc dist x y ≤ dist I.lower I.upper : real.dist_le_of_mem_pi_Icc hx hy ... ≤ I.distortion * (I.upper i - I.lower i) : I.dist_le_distortion_mul i ... ≤ c * (I.upper i - I.lower i) : mul_le_mul_of_nonneg_right h (sub_nonneg.2 (I.lower_le_upper i)) end distortion end box end box_integral
9e154bb337e7b44216826fa2036224e5acd49876
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebraic_geometry/AffineScheme.lean
82c60f1351940b9a19b83121b4c3be0c7ec95b1f
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
17,476
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import algebraic_geometry.Gamma_Spec_adjunction import algebraic_geometry.open_immersion import category_theory.limits.opposites /-! # Affine schemes We define the category of `AffineScheme`s as the essential image of `Spec`. We also define predicates about affine schemes and affine open sets. ## Main definitions * `algebraic_geometry.AffineScheme`: The category of affine schemes. * `algebraic_geometry.is_affine`: A scheme is affine if the canonical map `X ⟶ Spec Γ(X)` is an isomorphism. * `algebraic_geometry.Scheme.iso_Spec`: The canonical isomorphism `X ≅ Spec Γ(X)` for an affine scheme. * `algebraic_geometry.AffineScheme.equiv_CommRing`: The equivalence of categories `AffineScheme ≌ CommRingᵒᵖ` given by `AffineScheme.Spec : CommRingᵒᵖ ⥤ AffineScheme` and `AffineScheme.Γ : AffineSchemeᵒᵖ ⥤ CommRing`. * `algebraic_geometry.is_affine_open`: An open subset of a scheme is affine if the open subscheme is affine. * `algebraic_geometry.is_affine_open.from_Spec`: The immersion `Spec 𝒪ₓ(U) ⟶ X` for an affine `U`. -/ noncomputable theory open category_theory category_theory.limits opposite topological_space universe u namespace algebraic_geometry /-- The category of affine schemes -/ def AffineScheme := Scheme.Spec.ess_image /-- A Scheme is affine if the canonical map `X ⟶ Spec Γ(X)` is an isomorphism. -/ class is_affine (X : Scheme) : Prop := (affine : is_iso (Γ_Spec.adjunction.unit.app X)) attribute [instance] is_affine.affine /-- The canonical isomorphism `X ≅ Spec Γ(X)` for an affine scheme. -/ def Scheme.iso_Spec (X : Scheme) [is_affine X] : X ≅ Scheme.Spec.obj (op $ Scheme.Γ.obj $ op X) := as_iso (Γ_Spec.adjunction.unit.app X) lemma mem_AffineScheme (X : Scheme) : X ∈ AffineScheme ↔ is_affine X := ⟨λ h, ⟨functor.ess_image.unit_is_iso h⟩, λ h, @@mem_ess_image_of_unit_is_iso _ _ _ X h.1⟩ instance is_affine_AffineScheme (X : AffineScheme.{u}) : is_affine (X : Scheme.{u}) := (mem_AffineScheme _).mp X.prop instance Spec_is_affine (R : CommRingᵒᵖ) : is_affine (Scheme.Spec.obj R) := (mem_AffineScheme _).mp (Scheme.Spec.obj_mem_ess_image R) lemma is_affine_of_iso {X Y : Scheme} (f : X ⟶ Y) [is_iso f] [h : is_affine Y] : is_affine X := by { rw [← mem_AffineScheme] at h ⊢, exact functor.ess_image.of_iso (as_iso f).symm h } namespace AffineScheme /-- The `Spec` functor into the category of affine schemes. -/ @[derive [full, faithful, ess_surj], simps] def Spec : CommRingᵒᵖ ⥤ AffineScheme := Scheme.Spec.to_ess_image /-- The forgetful functor `AffineScheme ⥤ Scheme`. -/ @[derive [full, faithful], simps] def forget_to_Scheme : AffineScheme ⥤ Scheme := Scheme.Spec.ess_image_inclusion /-- The global section functor of an affine scheme. -/ def Γ : AffineSchemeᵒᵖ ⥤ CommRing := forget_to_Scheme.op ⋙ Scheme.Γ /-- The category of affine schemes is equivalent to the category of commutative rings. -/ def equiv_CommRing : AffineScheme ≌ CommRingᵒᵖ := equiv_ess_image_of_reflective.symm instance Γ_is_equiv : is_equivalence Γ.{u} := begin haveI : is_equivalence Γ.{u}.right_op.op := is_equivalence.of_equivalence equiv_CommRing.op, exact (functor.is_equivalence_trans Γ.{u}.right_op.op (op_op_equivalence _).functor : _), end instance : has_colimits AffineScheme.{u} := begin haveI := adjunction.has_limits_of_equivalence.{u} Γ.{u}, haveI : has_colimits AffineScheme.{u} ᵒᵖᵒᵖ := has_colimits_op_of_has_limits, exactI adjunction.has_colimits_of_equivalence.{u} (op_op_equivalence AffineScheme.{u}).inverse end instance : has_limits AffineScheme.{u} := begin haveI := adjunction.has_colimits_of_equivalence Γ.{u}, haveI : has_limits AffineScheme.{u} ᵒᵖᵒᵖ := limits.has_limits_op_of_has_colimits, exactI adjunction.has_limits_of_equivalence (op_op_equivalence AffineScheme.{u}).inverse end end AffineScheme /-- An open subset of a scheme is affine if the open subscheme is affine. -/ def is_affine_open {X : Scheme} (U : opens X.carrier) : Prop := is_affine (X.restrict U.open_embedding) lemma range_is_affine_open_of_open_immersion {X Y : Scheme} [is_affine X] (f : X ⟶ Y) [H : is_open_immersion f] : is_affine_open ⟨set.range f.1.base, H.base_open.open_range⟩ := begin refine is_affine_of_iso (is_open_immersion.iso_of_range_eq f (Y.of_restrict _) _).inv, exact subtype.range_coe.symm, apply_instance end lemma top_is_affine_open (X : Scheme) [is_affine X] : is_affine_open (⊤ : opens X.carrier) := begin convert range_is_affine_open_of_open_immersion (𝟙 X), ext1, exact set.range_id.symm end instance Scheme.affine_basis_cover_is_affine (X : Scheme) (i : X.affine_basis_cover.J) : is_affine (X.affine_basis_cover.obj i) := algebraic_geometry.Spec_is_affine _ lemma is_basis_affine_open (X : Scheme) : opens.is_basis { U : opens X.carrier | is_affine_open U } := begin rw opens.is_basis_iff_nbhd, rintros U x (hU : x ∈ (U : set X.carrier)), obtain ⟨S, hS, hxS, hSU⟩ := X.affine_basis_cover_is_basis.exists_subset_of_mem_open hU U.prop, refine ⟨⟨S, X.affine_basis_cover_is_basis.is_open hS⟩, _, hxS, hSU⟩, rcases hS with ⟨i, rfl⟩, exact range_is_affine_open_of_open_immersion _, end /-- The open immersion `Spec 𝒪ₓ(U) ⟶ X` for an affine `U`. -/ def is_affine_open.from_Spec {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : Scheme.Spec.obj (op $ X.presheaf.obj $ op U) ⟶ X := begin haveI : is_affine (X.restrict U.open_embedding) := hU, have : U.open_embedding.is_open_map.functor.obj ⊤ = U, { ext1, exact set.image_univ.trans subtype.range_coe }, exact Scheme.Spec.map (X.presheaf.map (eq_to_hom this.symm).op).op ≫ (X.restrict U.open_embedding).iso_Spec.inv ≫ X.of_restrict _ end instance is_affine_open.is_open_immersion_from_Spec {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : is_open_immersion hU.from_Spec := by { delta is_affine_open.from_Spec, apply_instance } lemma is_affine_open.from_Spec_range {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : set.range hU.from_Spec.1.base = (U : set X.carrier) := begin delta is_affine_open.from_Spec, erw [← category.assoc, Scheme.comp_val_base], rw [coe_comp, set.range_comp, set.range_iff_surjective.mpr, set.image_univ], exact subtype.range_coe, rw ← Top.epi_iff_surjective, apply_instance end lemma is_affine_open.from_Spec_image_top {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : hU.is_open_immersion_from_Spec.base_open.is_open_map.functor.obj ⊤ = U := by { ext1, exact set.image_univ.trans hU.from_Spec_range } lemma is_affine_open.is_compact {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : is_compact (U : set X.carrier) := begin convert @is_compact.image _ _ _ _ set.univ hU.from_Spec.1.base prime_spectrum.compact_space.1 (by continuity), convert hU.from_Spec_range.symm, exact set.image_univ end instance Scheme.quasi_compact_of_affine (X : Scheme) [is_affine X] : compact_space X.carrier := ⟨(top_is_affine_open X).is_compact⟩ lemma is_affine_open.from_Spec_base_preimage {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : (opens.map hU.from_Spec.val.base).obj U = ⊤ := begin ext1, change hU.from_Spec.1.base ⁻¹' (U : set X.carrier) = set.univ, rw [← hU.from_Spec_range, ← set.image_univ], exact set.preimage_image_eq _ PresheafedSpace.is_open_immersion.base_open.inj end lemma Scheme.Spec_map_presheaf_map_eq_to_hom {X : Scheme} {U V : opens X.carrier} (h : U = V) (W) : (Scheme.Spec.map (X.presheaf.map (eq_to_hom h).op).op).val.c.app W = eq_to_hom (by { cases h, dsimp, induction W using opposite.rec, congr, ext1, simpa }) := begin have : Scheme.Spec.map (X.presheaf.map (𝟙 (op U))).op = 𝟙 _, { rw [X.presheaf.map_id, op_id, Scheme.Spec.map_id] }, cases h, refine (Scheme.congr_app this _).trans _, erw category.id_comp, simpa end lemma is_affine_open.Spec_Γ_identity_hom_app_from_Spec {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : (Spec_Γ_identity.hom.app (X.presheaf.obj $ op U)) ≫ hU.from_Spec.1.c.app (op U) = (Scheme.Spec.obj _).presheaf.map (eq_to_hom hU.from_Spec_base_preimage).op := begin haveI : is_affine _ := hU, have e₁ := Spec_Γ_identity.hom.naturality (X.presheaf.map (eq_to_hom U.open_embedding_obj_top).op), rw ← is_iso.comp_inv_eq at e₁, have e₂ := Γ_Spec.adjunction_unit_app_app_top (X.restrict U.open_embedding), erw ← e₂ at e₁, simp only [functor.id_map, quiver.hom.unop_op, functor.comp_map, ← functor.map_inv, ← op_inv, LocallyRingedSpace.Γ_map, category.assoc, functor.right_op_map, inv_eq_to_hom] at e₁, delta is_affine_open.from_Spec Scheme.iso_Spec, rw [Scheme.comp_val_c_app, Scheme.comp_val_c_app, ← e₁], simp_rw category.assoc, erw ← X.presheaf.map_comp_assoc, rw ← op_comp, have e₃ : U.open_embedding.is_open_map.adjunction.counit.app U ≫ eq_to_hom U.open_embedding_obj_top.symm = U.open_embedding.is_open_map.functor.map (eq_to_hom U.inclusion_map_eq_top) := subsingleton.elim _ _, have e₄ : X.presheaf.map _ ≫ _ = _ := (as_iso (Γ_Spec.adjunction.unit.app (X.restrict U.open_embedding))) .inv.1.c.naturality_assoc (eq_to_hom U.inclusion_map_eq_top).op _, erw [e₃, e₄, ← Scheme.comp_val_c_app_assoc, iso.inv_hom_id], simp only [eq_to_hom_map, eq_to_hom_op, Scheme.Spec_map_presheaf_map_eq_to_hom], erw [Scheme.Spec_map_presheaf_map_eq_to_hom, category.id_comp], simpa only [eq_to_hom_trans] end @[elementwise] lemma is_affine_open.from_Spec_app_eq {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) : hU.from_Spec.1.c.app (op U) = Spec_Γ_identity.inv.app (X.presheaf.obj $ op U) ≫ (Scheme.Spec.obj _).presheaf.map (eq_to_hom hU.from_Spec_base_preimage).op := by rw [← hU.Spec_Γ_identity_hom_app_from_Spec, iso.inv_hom_id_app_assoc] lemma is_affine_open.basic_open_is_affine {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) (f : X.presheaf.obj (op U)) : is_affine_open (X.basic_open f) := begin convert range_is_affine_open_of_open_immersion (Scheme.Spec.map (CommRing.of_hom (algebra_map (X.presheaf.obj (op U)) (localization.away f))).op ≫ hU.from_Spec), ext1, have : hU.from_Spec.val.base '' (hU.from_Spec.val.base ⁻¹' (X.basic_open f : set X.carrier)) = (X.basic_open f : set X.carrier), { rw [set.image_preimage_eq_inter_range, set.inter_eq_left_iff_subset, hU.from_Spec_range], exact Scheme.basic_open_subset _ _ }, rw [subtype.coe_mk, Scheme.comp_val_base, ← this, coe_comp, set.range_comp], congr' 1, refine (congr_arg coe $ Scheme.preimage_basic_open hU.from_Spec f).trans _, refine eq.trans _ (prime_spectrum.localization_away_comap_range (localization.away f) f).symm, congr' 1, have : (opens.map hU.from_Spec.val.base).obj U = ⊤, { ext1, change hU.from_Spec.1.base ⁻¹' (U : set X.carrier) = set.univ, rw [← hU.from_Spec_range, ← set.image_univ], exact set.preimage_image_eq _ PresheafedSpace.is_open_immersion.base_open.inj }, refine eq.trans _ (basic_open_eq_of_affine f), have lm : ∀ s, (opens.map hU.from_Spec.val.base).obj U ⊓ s = s := λ s, this.symm ▸ top_inf_eq, refine eq.trans _ (lm _), refine eq.trans _ ((Scheme.Spec.obj $ op $ X.presheaf.obj $ op U).basic_open_res _ (eq_to_hom this).op), rw ← comp_apply, congr' 2, rw iso.eq_inv_comp, erw hU.Spec_Γ_identity_hom_app_from_Spec, end lemma Scheme.map_prime_spectrum_basic_open_of_affine (X : Scheme) [is_affine X] (f : Scheme.Γ.obj (op X)) : (opens.map X.iso_Spec.hom.1.base).obj (prime_spectrum.basic_open f) = X.basic_open f := begin rw ← basic_open_eq_of_affine, transitivity (opens.map X.iso_Spec.hom.1.base).obj ((Scheme.Spec.obj (op (Scheme.Γ.obj (op X)))).basic_open ((inv (X.iso_Spec.hom.1.c.app (op ((opens.map (inv X.iso_Spec.hom).val.base).obj ⊤)))) ((X.presheaf.map (eq_to_hom _)) f))), congr, { rw [← is_iso.inv_eq_inv, is_iso.inv_inv, is_iso.iso.inv_inv, nat_iso.app_hom], erw ← Γ_Spec.adjunction_unit_app_app_top, refl }, { rw eq_to_hom_map, refl }, { dsimp, congr }, { refine (Scheme.preimage_basic_open _ _).trans _, rw [is_iso.inv_hom_id_apply, Scheme.basic_open_res_eq] } end lemma is_basis_basic_open (X : Scheme) [is_affine X] : opens.is_basis (set.range (X.basic_open : X.presheaf.obj (op ⊤) → opens X.carrier)) := begin delta opens.is_basis, convert prime_spectrum.is_basis_basic_opens.inducing (Top.homeo_of_iso (Scheme.forget_to_Top.map_iso X.iso_Spec)).inducing using 1, ext, simp only [set.mem_image, exists_exists_eq_and], split, { rintro ⟨_, ⟨x, rfl⟩, rfl⟩, refine ⟨_, ⟨_, ⟨x, rfl⟩, rfl⟩, _⟩, exact congr_arg subtype.val (X.map_prime_spectrum_basic_open_of_affine x) }, { rintro ⟨_, ⟨_, ⟨x, rfl⟩, rfl⟩, rfl⟩, refine ⟨_, ⟨x, rfl⟩, _⟩, exact congr_arg subtype.val (X.map_prime_spectrum_basic_open_of_affine x).symm } end /-- The prime ideal of `𝒪ₓ(U)` corresponding to a point `x : U`. -/ noncomputable def is_affine_open.prime_ideal_of {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) (x : U) : prime_spectrum (X.presheaf.obj $ op U) := ((Scheme.Spec.map (X.presheaf.map (eq_to_hom $ show U.open_embedding.is_open_map.functor.obj ⊤ = U, from opens.ext (set.image_univ.trans subtype.range_coe)).op).op).1.base ((@@Scheme.iso_Spec (X.restrict U.open_embedding) hU).hom.1.base x)) lemma is_affine_open.from_Spec_prime_ideal_of {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) (x : U) : hU.from_Spec.val.base (hU.prime_ideal_of x) = x.1 := begin dsimp only [is_affine_open.from_Spec, subtype.coe_mk], erw [← Scheme.comp_val_base_apply, ← Scheme.comp_val_base_apply], simpa only [← functor.map_comp_assoc, ← functor.map_comp, ← op_comp, eq_to_hom_trans, op_id, eq_to_hom_refl, category_theory.functor.map_id, category.id_comp, iso.hom_inv_id_assoc] end lemma is_affine_open.is_localization_stalk_aux {X : Scheme} (U : opens X.carrier) [is_affine (X.restrict U.open_embedding)] : (inv (Γ_Spec.adjunction.unit.app (X.restrict U.open_embedding))).1.c.app (op ((opens.map U.inclusion).obj U)) = X.presheaf.map (eq_to_hom $ by rw opens.inclusion_map_eq_top : U.open_embedding.is_open_map.functor.obj ⊤ ⟶ (U.open_embedding.is_open_map.functor.obj ((opens.map U.inclusion).obj U))).op ≫ to_Spec_Γ (X.presheaf.obj $ op (U.open_embedding.is_open_map.functor.obj ⊤)) ≫ (Scheme.Spec.obj $ op $ X.presheaf.obj $ _).presheaf.map (eq_to_hom (by { rw [opens.inclusion_map_eq_top], refl }) : unop _ ⟶ ⊤).op := begin have e : (opens.map (inv (Γ_Spec.adjunction.unit.app (X.restrict U.open_embedding))).1.base).obj ((opens.map U.inclusion).obj U) = ⊤, by { rw [opens.inclusion_map_eq_top], refl }, rw [Scheme.inv_val_c_app, is_iso.comp_inv_eq, Scheme.app_eq _ e, Γ_Spec.adjunction_unit_app_app_top], simp only [category.assoc, eq_to_hom_op], erw ← functor.map_comp_assoc, rw [eq_to_hom_trans, eq_to_hom_refl, category_theory.functor.map_id, category.id_comp], erw Spec_Γ_identity.inv_hom_id_app_assoc, simp only [eq_to_hom_map, eq_to_hom_trans], end lemma is_affine_open.is_localization_stalk {X : Scheme} {U : opens X.carrier} (hU : is_affine_open U) (x : U) : is_localization.at_prime (X.presheaf.stalk x) (hU.prime_ideal_of x).as_ideal := begin haveI : is_affine _ := hU, haveI : nonempty U := ⟨x⟩, rcases x with ⟨x, hx⟩, let y := hU.prime_ideal_of ⟨x, hx⟩, have : hU.from_Spec.val.base y = x := hU.from_Spec_prime_ideal_of ⟨x, hx⟩, change is_localization y.as_ideal.prime_compl _, clear_value y, subst this, apply (is_localization.is_localization_iff_of_ring_equiv _ (as_iso $ PresheafedSpace.stalk_map hU.from_Spec.1 y).CommRing_iso_to_ring_equiv).mpr, convert structure_sheaf.is_localization.to_stalk _ _ using 1, delta structure_sheaf.stalk_algebra, congr' 1, rw ring_hom.algebra_map_to_algebra, refine (PresheafedSpace.stalk_map_germ hU.from_Spec.1 _ ⟨_, _⟩).trans _, delta is_affine_open.from_Spec Scheme.iso_Spec structure_sheaf.to_stalk, simp only [Scheme.comp_val_c_app, category.assoc], dsimp only [functor.op, as_iso_inv, unop_op], erw is_affine_open.is_localization_stalk_aux, simp only [category.assoc], conv_lhs { rw ← category.assoc }, erw [← X.presheaf.map_comp, Spec_Γ_naturality_assoc], congr' 1, simp only [← category.assoc], transitivity _ ≫ (structure_sheaf (X.presheaf.obj $ op U)).1.germ ⟨_, _⟩, { refl }, convert ((structure_sheaf (X.presheaf.obj $ op U)).1.germ_res (hom_of_le le_top) ⟨_, _⟩) using 2, rw category.assoc, erw nat_trans.naturality, rw [← LocallyRingedSpace.Γ_map_op, ← LocallyRingedSpace.Γ.map_comp_assoc, ← op_comp], erw ← Scheme.Spec.map_comp, rw [← op_comp, ← X.presheaf.map_comp], transitivity LocallyRingedSpace.Γ.map (quiver.hom.op $ Scheme.Spec.map (X.presheaf.map (𝟙 (op U))).op) ≫ _, { congr }, simp only [category_theory.functor.map_id, op_id], erw category_theory.functor.map_id, rw category.id_comp, refl end end algebraic_geometry
321d78b5e70f9cdb4e7a4645df5b0bcf0454c4aa
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/ring_theory/adjoin/basic.lean
73c19a8137cd7b7c4b75b241d080276df112f3da
[ "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
12,270
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 ring_theory.polynomial.basic import algebra.algebra.subalgebra /-! # Adjoining elements to form subalgebras This file develops the basic theory of subalgebras of an R-algebra generated by a set of elements. A basic interface for `adjoin` is set up, and various results about finitely-generated subalgebras and submodules are proved. ## Definitions * `fg (S : subalgebra R A)` : A predicate saying that the subalgebra is finitely-generated as an A-algebra ## Tags adjoin, algebra, finitely-generated algebra -/ universes u v w open submodule namespace algebra variables {R : Type u} {A : Type v} {B : Type w} section semiring variables [comm_semiring R] [semiring A] [semiring B] variables [algebra R A] [algebra R B] {s t : set A} open subsemiring theorem subset_adjoin : s ⊆ adjoin R s := algebra.gc.le_u_l s theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S := algebra.gc.l_le H theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:= algebra.gc _ _ theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t := algebra.gc.monotone_l H variables (R A) @[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ := show adjoin R ⊥ = ⊥, by { apply galois_connection.l_bot, exact algebra.gc } variables (R) {A} (s) theorem adjoin_eq_span : (adjoin R s).to_submodule = span R (submonoid.closure s) := begin apply le_antisymm, { intros r hr, rcases subsemiring.mem_closure_iff_exists_list.1 hr with ⟨L, HL, rfl⟩, clear hr, induction L with hd tl ih, { exact zero_mem _ }, rw list.forall_mem_cons at HL, rw [list.map_cons, list.sum_cons], refine submodule.add_mem _ _ (ih HL.2), replace HL := HL.1, clear ih tl, suffices : ∃ z r (hr : r ∈ submonoid.closure s), has_scalar.smul z r = list.prod hd, { rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr, exact smul_mem _ _ (subset_span hr) }, induction hd with hd tl ih, { exact ⟨1, 1, (submonoid.closure s).one_mem', one_smul _ _⟩ }, rw list.forall_mem_cons at HL, rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr], rcases HL.1 with ⟨hd, rfl⟩ | hs, { refine ⟨hd * z, r, hr, _⟩, rw [algebra.smul_def, algebra.smul_def, (algebra_map _ _).map_mul, _root_.mul_assoc] }, { exact ⟨z, hd * r, submonoid.mul_mem _ (submonoid.subset_closure hs) hr, (mul_smul_comm _ _ _).symm⟩ } }, refine span_le.2 _, change submonoid.closure s ≤ (adjoin R s).to_subsemiring.to_submonoid, exact submonoid.closure_le.2 subset_adjoin end lemma adjoin_image (f : A →ₐ[R] B) (s : set A) : adjoin R (f '' s) = (adjoin R s).map f := le_antisymm (adjoin_le $ set.image_subset _ subset_adjoin) $ subalgebra.map_le.2 $ adjoin_le $ set.image_subset_iff.1 subset_adjoin @[simp] lemma adjoin_insert_adjoin (x : A) : adjoin R (insert x ↑(adjoin R s)) = adjoin R (insert x s) := le_antisymm (adjoin_le (set.insert_subset.mpr ⟨subset_adjoin (set.mem_insert _ _), adjoin_mono (set.subset_insert _ _)⟩)) (algebra.adjoin_mono (set.insert_subset_insert algebra.subset_adjoin)) end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] variables [algebra R A] {s t : set A} open subsemiring variables (R s t) theorem adjoin_union : adjoin R (s ∪ t) = (adjoin R s).under (adjoin (adjoin R s) t) := le_antisymm (closure_mono $ set.union_subset (set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map R (adjoin R s) r, rfl⟩) (set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩)) (closure_le.2 $ set.union_subset (set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2) (set.subset.trans (set.subset_union_right _ _) subset_adjoin)) theorem adjoin_eq_range : adjoin R s = (mv_polynomial.aeval (coe : s → A)).range := le_antisymm (adjoin_le $ λ x hx, ⟨mv_polynomial.X ⟨x, hx⟩, mv_polynomial.eval₂_X _ _ _⟩) (λ x ⟨p, (hp : mv_polynomial.aeval coe p = x)⟩, hp ▸ mv_polynomial.induction_on p (λ r, by { rw [mv_polynomial.aeval_def, mv_polynomial.eval₂_C], exact (adjoin R s).algebra_map_mem r }) (λ p q hp hq, by rw alg_hom.map_add; exact subalgebra.add_mem _ hp hq) (λ p ⟨n, hn⟩ hp, by rw [alg_hom.map_mul, mv_polynomial.aeval_def _ (mv_polynomial.X _), mv_polynomial.eval₂_X]; exact subalgebra.mul_mem _ hp (subset_adjoin hn))) theorem adjoin_singleton_eq_range (x : A) : adjoin R {x} = (polynomial.aeval x).range := le_antisymm (adjoin_le $ set.singleton_subset_iff.2 ⟨polynomial.X, polynomial.eval₂_X _ _⟩) (λ y ⟨p, (hp : polynomial.aeval x p = y)⟩, hp ▸ polynomial.induction_on p (λ r, by { rw [polynomial.aeval_def, polynomial.eval₂_C], exact (adjoin R _).algebra_map_mem r }) (λ p q hp hq, by rw alg_hom.map_add; exact subalgebra.add_mem _ hp hq) (λ n r ih, by { rw [pow_succ', ← mul_assoc, alg_hom.map_mul, polynomial.aeval_def _ polynomial.X, polynomial.eval₂_X], exact subalgebra.mul_mem _ ih (subset_adjoin rfl) })) lemma adjoin_singleton_one : adjoin R ({1} : set A) = ⊥ := eq_bot_iff.2 $ adjoin_le $ set.singleton_subset_iff.2 $ set_like.mem_coe.2 $ one_mem _ theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t)).to_submodule = (adjoin R s).to_submodule * (adjoin R t).to_submodule := begin rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span], congr' 1 with z, simp [submonoid.closure_union, submonoid.mem_sup, set.mem_mul] end end comm_semiring section ring variables [comm_ring R] [ring A] variables [algebra R A] {s t : set A} variables {R s t} open ring theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_is_subring (closure s) := le_antisymm (adjoin_le subset_closure) (closure_subset subset_adjoin : closure s ≤ adjoin ℤ s) theorem mem_adjoin_iff {s : set A} {x : A} : x ∈ adjoin R s ↔ x ∈ closure (set.range (algebra_map R A) ∪ s) := ⟨λ hx, subsemiring.closure_induction hx subset_closure is_add_submonoid.zero_mem is_submonoid.one_mem (λ _ _, is_add_submonoid.add_mem) (λ _ _, is_submonoid.mul_mem), suffices closure (set.range ⇑(algebra_map R A) ∪ s) ⊆ adjoin R s, from @this x, closure_subset subsemiring.subset_closure⟩ theorem adjoin_eq_ring_closure (s : set A) : (adjoin R s : set A) = closure (set.range (algebra_map R A) ∪ s) := set.ext $ λ x, mem_adjoin_iff end ring section comm_ring variables [comm_ring R] [comm_ring A] variables [algebra R A] {s t : set A} variables {R s t} open ring theorem fg_trans (h1 : (adjoin R s).to_submodule.fg) (h2 : (adjoin (adjoin R s) t).to_submodule.fg) : (adjoin R (s ∪ t)).to_submodule.fg := begin rcases fg_def.1 h1 with ⟨p, hp, hp'⟩, rcases fg_def.1 h2 with ⟨q, hq, hq'⟩, refine fg_def.2 ⟨p * q, hp.mul hq, le_antisymm _ _⟩, { rw [span_le], rintros _ ⟨x, y, hx, hy, rfl⟩, change x * y ∈ _, refine is_submonoid.mul_mem _ _, { have : x ∈ (adjoin R s).to_submodule, { rw ← hp', exact subset_span hx }, exact adjoin_mono (set.subset_union_left _ _) this }, have : y ∈ (adjoin (adjoin R s) t).to_submodule, { rw ← hq', exact subset_span hy }, change y ∈ adjoin R (s ∪ t), rwa adjoin_union }, { intros r hr, change r ∈ adjoin R (s ∪ t) at hr, rw adjoin_union at hr, change r ∈ (adjoin (adjoin R s) t).to_submodule at hr, haveI := classical.dec_eq A, haveI := classical.dec_eq R, rw [← hq', ← set.image_id q, finsupp.mem_span_iff_total (adjoin R s)] at hr, rcases hr with ⟨l, hlq, rfl⟩, have := @finsupp.total_apply A A (adjoin R s), rw [this, finsupp.sum], refine sum_mem _ _, intros z hz, change (l z).1 * _ ∈ _, have : (l z).1 ∈ (adjoin R s).to_submodule := (l z).2, rw [← hp', ← set.image_id p, finsupp.mem_span_iff_total R] at this, rcases this with ⟨l2, hlp, hl⟩, have := @finsupp.total_apply A A R, rw this at hl, rw [←hl, finsupp.sum_mul], refine sum_mem _ _, intros t ht, change _ * _ ∈ _, rw smul_mul_assoc, refine smul_mem _ _ _, exact subset_span ⟨t, z, hlp ht, hlq hz, rfl⟩ } end end comm_ring end algebra namespace subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] /-- A subalgebra `S` is finitely generated if there exists `t : finset A` such that `algebra.adjoin R t = S`. -/ def fg (S : subalgebra R A) : Prop := ∃ t : finset A, algebra.adjoin R ↑t = S lemma fg_adjoin_finset (s : finset A) : (algebra.adjoin R (↑s : set A)).fg := ⟨s, rfl⟩ theorem fg_def {S : subalgebra R A} : S.fg ↔ ∃ t : set A, set.finite t ∧ algebra.adjoin R t = S := ⟨λ ⟨t, ht⟩, ⟨↑t, set.finite_mem_finset t, ht⟩, λ ⟨t, ht1, ht2⟩, ⟨ht1.to_finset, by rwa set.finite.coe_to_finset⟩⟩ theorem fg_bot : (⊥ : subalgebra R A).fg := ⟨∅, algebra.adjoin_empty R A⟩ theorem fg_of_fg_to_submodule {S : subalgebra R A} : S.to_submodule.fg → S.fg := λ ⟨t, ht⟩, ⟨t, le_antisymm (algebra.adjoin_le (λ x hx, show x ∈ S.to_submodule, from ht ▸ subset_span hx)) $ show S.to_submodule ≤ (algebra.adjoin R ↑t).to_submodule, from (λ x hx, span_le.mpr (λ x hx, algebra.subset_adjoin hx) (show x ∈ span R ↑t, by { rw ht, exact hx }))⟩ theorem fg_of_noetherian [is_noetherian R A] (S : subalgebra R A) : S.fg := fg_of_fg_to_submodule (is_noetherian.noetherian S.to_submodule) lemma fg_of_submodule_fg (h : (⊤ : submodule R A).fg) : (⊤ : subalgebra R A).fg := let ⟨s, hs⟩ := h in ⟨s, to_submodule_injective $ by { rw [algebra.top_to_submodule, eq_top_iff, ← hs, span_le], exact algebra.subset_adjoin }⟩ section open_locale classical lemma fg_map (S : subalgebra R A) (f : A →ₐ[R] B) (hs : S.fg) : (S.map f).fg := let ⟨s, hs⟩ := hs in ⟨s.image f, by rw [finset.coe_image, algebra.adjoin_image, hs]⟩ end lemma fg_of_fg_map (S : subalgebra R A) (f : A →ₐ[R] B) (hf : function.injective f) (hs : (S.map f).fg) : S.fg := let ⟨s, hs⟩ := hs in ⟨s.preimage f $ λ _ _ _ _ h, hf h, map_injective f hf $ by { rw [← algebra.adjoin_image, finset.coe_preimage, set.image_preimage_eq_of_subset, hs], rw [← alg_hom.coe_range, ← algebra.adjoin_le_iff, hs, ← algebra.map_top], exact map_mono le_top }⟩ lemma fg_top (S : subalgebra R A) : (⊤ : subalgebra R S).fg ↔ S.fg := ⟨λ h, by { rw [← S.range_val, ← algebra.map_top], exact fg_map _ _ h }, λ h, fg_of_fg_map _ S.val subtype.val_injective $ by { rw [algebra.map_top, range_val], exact h }⟩ lemma induction_on_adjoin [is_noetherian R A] (P : subalgebra R A → Prop) (base : P ⊥) (ih : ∀ (S : subalgebra R A) (x : A), P S → P (algebra.adjoin R (insert x S))) (S : subalgebra R A) : P S := begin classical, obtain ⟨t, rfl⟩ := S.fg_of_noetherian, refine finset.induction_on t _ _, { simpa using base }, intros x t hxt h, convert ih _ x h using 1, rw [finset.coe_insert, algebra.adjoin_insert_adjoin] end end subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] /-- The image of a Noetherian R-algebra under an R-algebra map is a Noetherian ring. -/ instance alg_hom.is_noetherian_ring_range (f : A →ₐ[R] B) [is_noetherian_ring A] : is_noetherian_ring f.range := is_noetherian_ring_range f.to_ring_hom theorem is_noetherian_ring_of_fg {S : subalgebra R A} (HS : S.fg) [is_noetherian_ring R] : is_noetherian_ring S := let ⟨t, ht⟩ := HS in ht ▸ (algebra.adjoin_eq_range R (↑t : set A)).symm ▸ by haveI : is_noetherian_ring (mv_polynomial (↑t : set A) R) := mv_polynomial.is_noetherian_ring; convert alg_hom.is_noetherian_ring_range _; apply_instance theorem is_noetherian_ring_closure (s : set R) (hs : s.finite) : @@is_noetherian_ring (ring.closure s) subset.ring := show is_noetherian_ring (subalgebra_of_is_subring (ring.closure s)), from algebra.adjoin_int s ▸ is_noetherian_ring_of_fg (subalgebra.fg_def.2 ⟨s, hs, rfl⟩)
711d6ab5a09289e29abce5c31ba28c7c7066d1bf
95a0255955cf617fa80fca1ebb7cb4864f620075
/move_to_lib.hlean
990567aba9b3e81fff13e80c02abef8132916a47
[ "Apache-2.0" ]
permissive
xuanYang/Spectral
1df58d41745b2103c2eb7fddfb5e86652343327d
af30b19099a6e28a1b989c26c0603f1ff52a1367
refs/heads/master
1,624,752,891,749
1,504,812,124,000
1,504,812,124,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,228
hlean
-- definitions, theorems and attributes which should be moved to files in the HoTT library import homotopy.sphere2 homotopy.cofiber homotopy.wedge hit.prop_trunc hit.set_quotient eq2 types.pointed2 open eq nat int susp pointed sigma is_equiv equiv fiber algebra trunc pi group is_trunc function unit prod bool attribute pType.sigma_char sigma_pi_equiv_pi_sigma sigma.coind_unc [constructor] attribute ap1_gen [unfold 8 9 10] attribute ap010 [unfold 7] -- TODO: homotopy_of_eq and apd10 should be the same -- TODO: there is also apd10_eq_of_homotopy in both pi and eq(?) namespace eq definition apd10_prepostcompose_nondep {A B C D : Type} (h : C → D) {g g' : B → C} (p : g = g') (f : A → B) (a : A) : apd10 (ap (λg a, h (g (f a))) p) a = ap h (apd10 p (f a)) := begin induction p, reflexivity end definition apd10_prepostcompose {A B : Type} {C : B → Type} {D : A → Type} (f : A → B) (h : Πa, C (f a) → D a) {g g' : Πb, C b} (p : g = g') (a : A) : apd10 (ap (λg a, h a (g (f a))) p) a = ap (h a) (apd10 p (f a)) := begin induction p, reflexivity end definition eq.rec_to {A : Type} {a₀ : A} {P : Π⦃a₁⦄, a₀ = a₁ → Type} {a₁ : A} (p₀ : a₀ = a₁) (H : P p₀) ⦃a₂ : A⦄ (p : a₀ = a₂) : P p := begin induction p₀, induction p, exact H end definition eq.rec_to2 {A : Type} {P : Π⦃a₀ a₁⦄, a₀ = a₁ → Type} {a₀ a₀' a₁' : A} (p' : a₀' = a₁') (p₀ : a₀ = a₀') (H : P p') ⦃a₁ : A⦄ (p : a₀ = a₁) : P p := begin induction p₀, induction p', induction p, exact H end definition eq.rec_right_inv {A : Type} (f : A ≃ A) {P : Π⦃a₀ a₁⦄, f a₀ = a₁ → Type} (H : Πa, P (right_inv f a)) ⦃a₀ a₁ : A⦄ (p : f a₀ = a₁) : P p := begin revert a₀ p, refine equiv_rect f⁻¹ᵉ _ _, intro a₀ p, exact eq.rec_to (right_inv f a₀) (H a₀) p, end definition eq.rec_equiv {A B : Type} {a₀ : A} (f : A ≃ B) {P : Π{a₁}, f a₀ = f a₁ → Type} (H : P (idpath (f a₀))) ⦃a₁ : A⦄ (p : f a₀ = f a₁) : P p := begin assert qr : Σ(q : a₀ = a₁), ap f q = p, { exact ⟨eq_of_fn_eq_fn f p, ap_eq_of_fn_eq_fn' f p⟩ }, cases qr with q r, apply transport P r, induction q, exact H end definition eq.rec_equiv_symm {A B : Type} {a₁ : A} (f : A ≃ B) {P : Π{a₀}, f a₀ = f a₁ → Type} (H : P (idpath (f a₁))) ⦃a₀ : A⦄ (p : f a₀ = f a₁) : P p := begin assert qr : Σ(q : a₀ = a₁), ap f q = p, { exact ⟨eq_of_fn_eq_fn f p, ap_eq_of_fn_eq_fn' f p⟩ }, cases qr with q r, apply transport P r, induction q, exact H end definition eq.rec_equiv_to_same {A B : Type} {a₀ : A} (f : A ≃ B) {P : Π{a₁}, f a₀ = f a₁ → Type} ⦃a₁' : A⦄ (p' : f a₀ = f a₁') (H : P p') ⦃a₁ : A⦄ (p : f a₀ = f a₁) : P p := begin revert a₁' p' H a₁ p, refine eq.rec_equiv f _, exact eq.rec_equiv f end definition eq.rec_equiv_to {A A' B : Type} {a₀ : A} (f : A ≃ B) (g : A' ≃ B) {P : Π{a₁}, f a₀ = g a₁ → Type} ⦃a₁' : A'⦄ (p' : f a₀ = g a₁') (H : P p') ⦃a₁ : A'⦄ (p : f a₀ = g a₁) : P p := begin assert qr : Σ(q : g⁻¹ (f a₀) = a₁), (right_inv g (f a₀))⁻¹ ⬝ ap g q = p, { exact ⟨eq_of_fn_eq_fn g (right_inv g (f a₀) ⬝ p), whisker_left _ (ap_eq_of_fn_eq_fn' g _) ⬝ !inv_con_cancel_left⟩ }, assert q'r' : Σ(q' : g⁻¹ (f a₀) = a₁'), (right_inv g (f a₀))⁻¹ ⬝ ap g q' = p', { exact ⟨eq_of_fn_eq_fn g (right_inv g (f a₀) ⬝ p'), whisker_left _ (ap_eq_of_fn_eq_fn' g _) ⬝ !inv_con_cancel_left⟩ }, induction qr with q r, induction q'r' with q' r', induction q, induction q', induction r, induction r', exact H end definition eq.rec_grading {A A' B : Type} {a : A} (f : A ≃ B) (g : A' ≃ B) {P : Π{b}, f a = b → Type} {a' : A'} (p' : f a = g a') (H : P p') ⦃b : B⦄ (p : f a = b) : P p := begin revert b p, refine equiv_rect g _ _, exact eq.rec_equiv_to f g p' H end definition eq.rec_grading_unbased {A B B' C : Type} (f : A ≃ B) (g : B ≃ C) (h : B' ≃ C) {P : Π{b c}, g b = c → Type} {a' : A} {b' : B'} (p' : g (f a') = h b') (H : P p') ⦃b : B⦄ ⦃c : C⦄ (q : f a' = b) (p : g b = c) : P p := begin induction q, exact eq.rec_grading (f ⬝e g) h p' H p end -- definition homotopy_group_homomorphism_pinv (n : ℕ) {A B : Type*} (f : A ≃* B) : -- π→g[n+1] f⁻¹ᵉ* ~ (homotopy_group_isomorphism_of_pequiv n f)⁻¹ᵍ := -- begin -- -- refine ptrunc_functor_phomotopy 0 !apn_pinv ⬝hty _, -- -- intro x, esimp, -- end -- definition natural_square_tr_eq {A B : Type} {a a' : A} {f g : A → B} -- (p : f ~ g) (q : a = a') : natural_square p q = square_of_pathover (apd p q) := -- idp lemma homotopy_group_isomorphism_of_ptrunc_pequiv {A B : Type*} (n k : ℕ) (H : n+1 ≤[ℕ] k) (f : ptrunc k A ≃* ptrunc k B) : πg[n+1] A ≃g πg[n+1] B := (ghomotopy_group_ptrunc_of_le H A)⁻¹ᵍ ⬝g homotopy_group_isomorphism_of_pequiv n f ⬝g ghomotopy_group_ptrunc_of_le H B section hsquare variables {A₀₀ A₂₀ A₄₀ A₀₂ A₂₂ A₄₂ A₀₄ A₂₄ A₄₄ : Type} {f₁₀ : A₀₀ → A₂₀} {f₃₀ : A₂₀ → A₄₀} {f₀₁ : A₀₀ → A₀₂} {f₂₁ : A₂₀ → A₂₂} {f₄₁ : A₄₀ → A₄₂} {f₁₂ : A₀₂ → A₂₂} {f₃₂ : A₂₂ → A₄₂} {f₀₃ : A₀₂ → A₀₄} {f₂₃ : A₂₂ → A₂₄} {f₄₃ : A₄₂ → A₄₄} {f₁₄ : A₀₄ → A₂₄} {f₃₄ : A₂₄ → A₄₄} definition trunc_functor_hsquare (n : ℕ₋₂) (h : hsquare f₁₀ f₁₂ f₀₁ f₂₁) : hsquare (trunc_functor n f₁₀) (trunc_functor n f₁₂) (trunc_functor n f₀₁) (trunc_functor n f₂₁) := λa, !trunc_functor_compose⁻¹ ⬝ trunc_functor_homotopy n h a ⬝ !trunc_functor_compose attribute hhconcat hvconcat [unfold_full] definition rfl_hhconcat (q : hsquare f₃₀ f₃₂ f₂₁ f₄₁) : homotopy.rfl ⬝htyh q ~ q := homotopy.rfl definition hhconcat_rfl (q : hsquare f₃₀ f₃₂ f₂₁ f₄₁) : q ⬝htyh homotopy.rfl ~ q := λx, !idp_con ⬝ ap_id (q x) definition rfl_hvconcat (q : hsquare f₃₀ f₃₂ f₂₁ f₄₁) : homotopy.rfl ⬝htyv q ~ q := λx, !idp_con definition hvconcat_rfl (q : hsquare f₃₀ f₃₂ f₂₁ f₄₁) : q ⬝htyv homotopy.rfl ~ q := λx, !ap_id end hsquare definition homotopy_group_succ_in_natural (n : ℕ) {A B : Type*} (f : A →* B) : hsquare (homotopy_group_succ_in A n) (homotopy_group_succ_in B n) (π→[n+1] f) (π→[n] (Ω→ f)) := trunc_functor_hsquare _ (loopn_succ_in_natural n f)⁻¹* definition homotopy2.refl {A} {B : A → Type} {C : Π⦃a⦄, B a → Type} (f : Πa (b : B a), C b) : f ~2 f := λa b, idp definition homotopy2.rfl [refl] {A} {B : A → Type} {C : Π⦃a⦄, B a → Type} {f : Πa (b : B a), C b} : f ~2 f := λa b, idp definition homotopy3.refl {A} {B : A → Type} {C : Πa, B a → Type} {D : Π⦃a⦄ ⦃b : B a⦄, C a b → Type} (f : Πa b (c : C a b), D c) : f ~3 f := λa b c, idp definition homotopy3.rfl {A} {B : A → Type} {C : Πa, B a → Type} {D : Π⦃a⦄ ⦃b : B a⦄, C a b → Type} {f : Πa b (c : C a b), D c} : f ~3 f := λa b c, idp definition eq_tr_of_pathover_con_tr_eq_of_pathover {A : Type} {B : A → Type} {a₁ a₂ : A} (p : a₁ = a₂) {b₁ : B a₁} {b₂ : B a₂} (q : b₁ =[p] b₂) : eq_tr_of_pathover q ⬝ tr_eq_of_pathover q⁻¹ᵒ = idp := by induction q; reflexivity end eq open eq namespace nat protected definition rec_down (P : ℕ → Type) (s : ℕ) (H0 : P s) (Hs : Πn, P (n+1) → P n) : P 0 := have Hp : Πn, P n → P (pred n), begin intro n p, cases n with n, { exact p }, { exact Hs n p } end, have H : Πn, P (s - n), begin intro n, induction n with n p, { exact H0 }, { exact Hp (s - n) p } end, transport P (nat.sub_self s) (H s) end nat namespace trunc_index open is_conn nat trunc is_trunc lemma minus_two_add_plus_two (n : ℕ₋₂) : -2+2+n = n := by induction n with n p; reflexivity; exact ap succ p protected definition of_nat_monotone {n k : ℕ} : n ≤ k → of_nat n ≤ of_nat k := begin intro H, induction H with k H K, { apply le.tr_refl }, { apply le.step K } end lemma add_plus_two_comm (n k : ℕ₋₂) : n +2+ k = k +2+ n := begin induction n with n IH, { exact minus_two_add_plus_two k }, { exact !succ_add_plus_two ⬝ ap succ IH} end end trunc_index namespace int private definition maxm2_le.lemma₁ {n k : ℕ} : n+(1:int) + -[1+ k] ≤ n := le.intro ( calc n + 1 + -[1+ k] + k = n + 1 + (-(k + 1)) + k : by reflexivity ... = n + 1 + (- 1 - k) + k : by krewrite (neg_add_rev k 1) ... = n + 1 + (- 1 - k + k) : add.assoc ... = n + 1 + (- 1 + -k + k) : by reflexivity ... = n + 1 + (- 1 + (-k + k)) : add.assoc ... = n + 1 + (- 1 + 0) : add.left_inv ... = n + (1 + (- 1 + 0)) : add.assoc ... = n : int.add_zero) private definition maxm2_le.lemma₂ {n : ℕ} {k : ℤ} : -[1+ n] + 1 + k ≤ k := le.intro ( calc -[1+ n] + 1 + k + n = - (n + 1) + 1 + k + n : by reflexivity ... = -n - 1 + 1 + k + n : by rewrite (neg_add n 1) ... = -n + (- 1 + 1) + k + n : by krewrite (int.add_assoc (-n) (- 1) 1) ... = -n + 0 + k + n : add.left_inv 1 ... = -n + k + n : int.add_zero ... = k + -n + n : int.add_comm ... = k + (-n + n) : int.add_assoc ... = k + 0 : add.left_inv n ... = k : int.add_zero) open trunc_index /- The function from integers to truncation indices which sends positive numbers to themselves, and negative numbers to negative 2. In particular -1 is sent to -2, but since we only work with pointed types, that doesn't matter for us -/ definition maxm2 [unfold 1] : ℤ → ℕ₋₂ := λ n, int.cases_on n trunc_index.of_nat (λk, -2) -- we also need the max -1 - function definition maxm1 [unfold 1] : ℤ → ℕ₋₂ := λ n, int.cases_on n trunc_index.of_nat (λk, -1) definition maxm2_le_maxm1 (n : ℤ) : maxm2 n ≤ maxm1 n := begin induction n with n n, { exact le.tr_refl n }, { exact minus_two_le -1 } end -- the is maxm1 minus 1 definition maxm1m1 [unfold 1] : ℤ → ℕ₋₂ := λ n, int.cases_on n (λ k, k.-1) (λ k, -2) definition maxm1_eq_succ (n : ℤ) : maxm1 n = (maxm1m1 n).+1 := begin induction n with n n, { reflexivity }, { reflexivity } end definition maxm2_le_maxm0 (n : ℤ) : maxm2 n ≤ max0 n := begin induction n with n n, { exact le.tr_refl n }, { exact minus_two_le 0 } end definition max0_le_of_le {n : ℤ} {m : ℕ} (H : n ≤ of_nat m) : nat.le (max0 n) m := begin induction n with n n, { exact le_of_of_nat_le_of_nat H }, { exact nat.zero_le m } end definition not_neg_succ_le_of_nat {n m : ℕ} : ¬m ≤ -[1+n] := by cases m: exact id definition maxm2_monotone {n m : ℤ} (H : n ≤ m) : maxm2 n ≤ maxm2 m := begin induction n with n n, { induction m with m m, { apply of_nat_le_of_nat, exact le_of_of_nat_le_of_nat H }, { exfalso, exact not_neg_succ_le_of_nat H }}, { apply minus_two_le } end definition sub_nat_le (n : ℤ) (m : ℕ) : n - m ≤ n := le.intro !sub_add_cancel definition sub_one_le (n : ℤ) : n - 1 ≤ n := sub_nat_le n 1 definition le_add_nat (n : ℤ) (m : ℕ) : n ≤ n + m := le.intro rfl definition le_add_one (n : ℤ) : n ≤ n + 1:= le_add_nat n 1 open trunc_index definition maxm2_le (n k : ℤ) : maxm2 (n+1+k) ≤ (maxm1m1 n).+1+2+(maxm1m1 k) := begin rewrite [-(maxm1_eq_succ n)], induction n with n n, { induction k with k k, { induction k with k IH, { apply le.tr_refl }, { exact succ_le_succ IH } }, { exact trunc_index.le_trans (maxm2_monotone maxm2_le.lemma₁) (maxm2_le_maxm1 n) } }, { krewrite (add_plus_two_comm -1 (maxm1m1 k)), rewrite [-(maxm1_eq_succ k)], exact trunc_index.le_trans (maxm2_monotone maxm2_le.lemma₂) (maxm2_le_maxm1 k) } end end int open int namespace pmap /- rename: pmap_eta in namespace pointed -/ definition eta {A B : Type*} (f : A →* B) : pmap.mk f (respect_pt f) = f := begin induction f, reflexivity end end pmap namespace lift definition is_trunc_plift [instance] [priority 1450] (A : Type*) (n : ℕ₋₂) [H : is_trunc n A] : is_trunc n (plift A) := is_trunc_lift A n end lift namespace trunc open trunc_index definition trunc_index_equiv_nat [constructor] : ℕ₋₂ ≃ ℕ := equiv.MK add_two sub_two add_two_sub_two sub_two_add_two definition is_set_trunc_index [instance] : is_set ℕ₋₂ := is_trunc_equiv_closed_rev 0 trunc_index_equiv_nat definition is_contr_ptrunc_minus_one (A : Type*) : is_contr (ptrunc -1 A) := is_contr_of_inhabited_prop pt -- TODO: redefine loopn_ptrunc_pequiv definition apn_ptrunc_functor (n : ℕ₋₂) (k : ℕ) {A B : Type*} (f : A →* B) : Ω→[k] (ptrunc_functor (n+k) f) ∘* (loopn_ptrunc_pequiv n k A)⁻¹ᵉ* ~* (loopn_ptrunc_pequiv n k B)⁻¹ᵉ* ∘* ptrunc_functor n (Ω→[k] f) := begin revert n, induction k with k IH: intro n, { reflexivity }, { exact sorry } end definition ptrunc_pequiv_natural [constructor] (n : ℕ₋₂) {A B : Type*} (f : A →* B) [is_trunc n A] [is_trunc n B] : f ∘* ptrunc_pequiv n A ~* ptrunc_pequiv n B ∘* ptrunc_functor n f := begin fapply phomotopy.mk, { intro a, induction a with a, reflexivity }, { refine !idp_con ⬝ _ ⬝ !idp_con⁻¹, refine !ap_compose'⁻¹ ⬝ _, apply ap_id } end definition ptr_natural [constructor] (n : ℕ₋₂) {A B : Type*} (f : A →* B) : ptrunc_functor n f ∘* ptr n A ~* ptr n B ∘* f := begin fapply phomotopy.mk, { intro a, reflexivity }, { reflexivity } end definition ptrunc_elim_pcompose (n : ℕ₋₂) {A B C : Type*} (g : B →* C) (f : A →* B) [is_trunc n B] [is_trunc n C] : ptrunc.elim n (g ∘* f) ~* g ∘* ptrunc.elim n f := begin fapply phomotopy.mk, { intro a, induction a with a, reflexivity }, { apply idp_con } end definition ptrunc_elim_ptr_phomotopy_pid (n : ℕ₋₂) (A : Type*): ptrunc.elim n (ptr n A) ~* pid (ptrunc n A) := begin fapply phomotopy.mk, { intro a, induction a with a, reflexivity }, { apply idp_con } end definition is_trunc_ptrunc_of_is_trunc [instance] [priority 500] (A : Type*) (n m : ℕ₋₂) [H : is_trunc n A] : is_trunc n (ptrunc m A) := is_trunc_trunc_of_is_trunc A n m definition ptrunc_pequiv_ptrunc_of_is_trunc {n m k : ℕ₋₂} {A : Type*} (H1 : n ≤ m) (H2 : n ≤ k) (H : is_trunc n A) : ptrunc m A ≃* ptrunc k A := have is_trunc m A, from is_trunc_of_le A H1, have is_trunc k A, from is_trunc_of_le A H2, pequiv.MK (ptrunc.elim _ (ptr k A)) (ptrunc.elim _ (ptr m A)) abstract begin refine !ptrunc_elim_pcompose⁻¹* ⬝* _, exact ptrunc_elim_phomotopy _ !ptrunc_elim_ptr ⬝* !ptrunc_elim_ptr_phomotopy_pid, end end abstract begin refine !ptrunc_elim_pcompose⁻¹* ⬝* _, exact ptrunc_elim_phomotopy _ !ptrunc_elim_ptr ⬝* !ptrunc_elim_ptr_phomotopy_pid, end end definition ptrunc_change_index {k l : ℕ₋₂} (p : k = l) (X : Type*) : ptrunc k X ≃* ptrunc l X := pequiv_ap (λ n, ptrunc n X) p definition ptrunc_functor_le {k l : ℕ₋₂} (p : l ≤ k) (X : Type*) : ptrunc k X →* ptrunc l X := have is_trunc k (ptrunc l X), from is_trunc_of_le _ p, ptrunc.elim _ (ptr l X) definition trunc_index.pred [unfold 1] (n : ℕ₋₂) : ℕ₋₂ := begin cases n with n, exact -2, exact n end /- A more general version of ptrunc_elim_phomotopy, where the proofs of truncatedness might be different -/ definition ptrunc_elim_phomotopy2 [constructor] (k : ℕ₋₂) {A B : Type*} {f g : A →* B} (H₁ : is_trunc k B) (H₂ : is_trunc k B) (p : f ~* g) : @ptrunc.elim k A B H₁ f ~* @ptrunc.elim k A B H₂ g := begin fapply phomotopy.mk, { intro x, induction x with a, exact p a }, { exact to_homotopy_pt p } end end trunc namespace is_trunc open trunc_index is_conn definition is_trunc_of_eq {n m : ℕ₋₂} (p : n = m) {A : Type} (H : is_trunc n A) : is_trunc m A := transport (λk, is_trunc k A) p H definition is_trunc_succ_succ_of_is_trunc_loop (n : ℕ₋₂) (A : Type*) (H : is_trunc (n.+1) (Ω A)) (H2 : is_conn 0 A) : is_trunc (n.+2) A := begin apply is_trunc_succ_of_is_trunc_loop, apply minus_one_le_succ, refine is_conn.elim -1 _ _, exact H end lemma is_trunc_of_is_trunc_loopn (m n : ℕ) (A : Type*) (H : is_trunc n (Ω[m] A)) (H2 : is_conn m A) : is_trunc (m + n) A := begin revert A H H2; induction m with m IH: intro A H H2, { rewrite [nat.zero_add], exact H }, rewrite [succ_add], apply is_trunc_succ_succ_of_is_trunc_loop, { apply IH, { apply is_trunc_equiv_closed _ !loopn_succ_in }, apply is_conn_loop }, exact is_conn_of_le _ (zero_le_of_nat (succ m)) end lemma is_trunc_of_is_set_loopn (m : ℕ) (A : Type*) (H : is_set (Ω[m] A)) (H2 : is_conn m A) : is_trunc m A := is_trunc_of_is_trunc_loopn m 0 A H H2 end is_trunc namespace sigma open sigma.ops definition sigma_eq_equiv_of_is_prop_right [constructor] {A : Type} {B : A → Type} (u v : Σa, B a) [H : Π a, is_prop (B a)] : u = v ≃ u.1 = v.1 := !sigma_eq_equiv ⬝e !sigma_equiv_of_is_contr_right definition ap_sigma_pr1 {A B : Type} {C : B → Type} {a₁ a₂ : A} (f : A → B) (g : Πa, C (f a)) (p : a₁ = a₂) : (ap (λa, ⟨f a, g a⟩) p)..1 = ap f p := by induction p; reflexivity definition ap_sigma_pr2 {A B : Type} {C : B → Type} {a₁ a₂ : A} (f : A → B) (g : Πa, C (f a)) (p : a₁ = a₂) : (ap (λa, ⟨f a, g a⟩) p)..2 = change_path (ap_sigma_pr1 f g p)⁻¹ (pathover_ap C f (apd g p)) := by induction p; reflexivity -- open sigma.ops -- definition eq.rec_sigma {A : Type} {B : A → Type} {a₀ : A} {b₀ : B a₀} -- {P : Π(a : A) (b : B a), ⟨a₀, b₀⟩ = ⟨a, b⟩ → Type} (H : P a₀ b₀ idp) {a : A} {b : B a} -- (p : ⟨a₀, b₀⟩ = ⟨a, b⟩) : P a b p := -- sorry -- definition sigma_pathover_equiv_of_is_prop {A : Type} {B : A → Type} {C : Πa, B a → Type} -- {a a' : A} {p : a = a'} {b : B a} {b' : B a'} {c : C a b} {c' : C a' b'} -- [Πa b, is_prop (C a b)] : ⟨b, c⟩ =[p] ⟨b', c'⟩ ≃ b =[p] b' := -- begin -- fapply equiv.MK, -- { exact pathover_pr1 }, -- { intro q, induction q, apply pathover_idp_of_eq, exact sigma_eq idp !is_prop.elimo }, -- { intro q, induction q, -- have c = c', from !is_prop.elim, induction this, -- rewrite [▸*, is_prop_elimo_self (C a) c] }, -- { esimp, generalize ⟨b, c⟩, intro x q, } -- end --rexact @(ap pathover_pr1) _ idpo _, end sigma open sigma namespace group -- definition is_equiv_isomorphism -- some extra instances for type class inference -- definition is_mul_hom_comm_homomorphism [instance] {G G' : AbGroup} (φ : G →g G') -- : @is_mul_hom G G' (@ab_group.to_group _ (AbGroup.struct G)) -- (@ab_group.to_group _ (AbGroup.struct G')) φ := -- homomorphism.struct φ -- definition is_mul_hom_comm_homomorphism1 [instance] {G G' : AbGroup} (φ : G →g G') -- : @is_mul_hom G G' _ -- (@ab_group.to_group _ (AbGroup.struct G')) φ := -- homomorphism.struct φ -- definition is_mul_hom_comm_homomorphism2 [instance] {G G' : AbGroup} (φ : G →g G') -- : @is_mul_hom G G' (@ab_group.to_group _ (AbGroup.struct G)) _ φ := -- homomorphism.struct φ definition pgroup_of_Group (X : Group) : pgroup X := pgroup_of_group _ idp definition isomorphism_ap {A : Type} (F : A → Group) {a b : A} (p : a = b) : F a ≃g F b := isomorphism_of_eq (ap F p) definition interchange (G : AbGroup) (a b c d : G) : (a * b) * (c * d) = (a * c) * (b * d) := calc (a * b) * (c * d) = a * (b * (c * d)) : by exact mul.assoc a b (c * d) ... = a * ((b * c) * d) : by exact ap (λ bcd, a * bcd) (mul.assoc b c d)⁻¹ ... = a * ((c * b) * d) : by exact ap (λ bc, a * (bc * d)) (mul.comm b c) ... = a * (c * (b * d)) : by exact ap (λ bcd, a * bcd) (mul.assoc c b d) ... = (a * c) * (b * d) : by exact (mul.assoc a c (b * d))⁻¹ definition homomorphism_comp_compute {G H K : Group} (g : H →g K) (f : G →g H) (x : G) : (g ∘g f) x = g (f x) := begin reflexivity end open option definition add_point_AbGroup [unfold 3] {X : Type} (G : X → AbGroup) : X₊ → AbGroup | (some x) := G x | none := trivial_ab_group_lift definition isomorphism_of_is_contr {G H : Group} (hG : is_contr G) (hH : is_contr H) : G ≃g H := trivial_group_of_is_contr G ⬝g (trivial_group_of_is_contr H)⁻¹ᵍ definition trunc_isomorphism_of_equiv {A B : Type} [inf_group A] [inf_group B] (f : A ≃ B) (h : is_mul_hom f) : Group.mk (trunc 0 A) (trunc_group A) ≃g Group.mk (trunc 0 B) (trunc_group B) := begin apply isomorphism_of_equiv (equiv.mk (trunc_functor 0 f) (is_equiv_trunc_functor 0 f)), intros x x', induction x with a, induction x' with a', apply ap tr, exact h a a' end end group open group namespace fiber definition is_contr_pfiber_pid (A : Type*) : is_contr (pfiber (pid A)) := is_contr.mk pt begin intro x, induction x with a p, esimp at p, cases p, reflexivity end end fiber namespace function variables {A B : Type} {f f' : A → B} open is_conn sigma.ops definition merely_constant {A B : Type} (f : A → B) : Type := Σb, Πa, merely (f a = b) definition merely_constant_pmap {A B : Type*} {f : A →* B} (H : merely_constant f) (a : A) : merely (f a = pt) := tconcat (tconcat (H.2 a) (tinverse (H.2 pt))) (tr (respect_pt f)) definition merely_constant_of_is_conn {A B : Type*} (f : A →* B) [is_conn 0 A] : merely_constant f := ⟨pt, is_conn.elim -1 _ (tr (respect_pt f))⟩ definition homotopy_group_isomorphism_of_is_embedding (n : ℕ) [H : is_succ n] {A B : Type*} (f : A →* B) [H2 : is_embedding f] : πg[n] A ≃g πg[n] B := begin apply isomorphism.mk (homotopy_group_homomorphism n f), induction H with n, apply is_equiv_of_equiv_of_homotopy (ptrunc_pequiv_ptrunc 0 (loopn_pequiv_loopn_of_is_embedding (n+1) f)), exact sorry end end function open function namespace is_conn open unit trunc_index nat is_trunc pointed.ops definition is_conn_zero {A : Type} (a₀ : trunc 0 A) (p : Πa a' : A, ∥ a = a' ∥) : is_conn 0 A := is_conn_succ_intro a₀ (λa a', is_conn_minus_one _ (p a a')) definition is_conn_zero_pointed {A : Type*} (p : Πa a' : A, ∥ a = a' ∥) : is_conn 0 A := is_conn_zero (tr pt) p definition is_conn_fiber (n : ℕ₋₂) {A B : Type} (f : A → B) (b : B) [is_conn n A] [is_conn (n.+1) B] : is_conn n (fiber f b) := is_conn_equiv_closed_rev _ !fiber.sigma_char _ definition is_conn_fun_compose {n : ℕ₋₂} {A B C : Type} (g : B → C) (f : A → B) (H : is_conn_fun n g) (K : is_conn_fun n f) : is_conn_fun n (g ∘ f) := sorry end is_conn namespace misc open is_conn open sigma.ops pointed trunc_index definition component [constructor] (A : Type*) : Type* := pType.mk (Σ(a : A), merely (pt = a)) ⟨pt, tr idp⟩ lemma is_conn_component [instance] (A : Type*) : is_conn 0 (component A) := is_contr.mk (tr pt) begin intro x, induction x with x, induction x with a p, induction p with p, induction p, reflexivity end definition component_incl [constructor] (A : Type*) : component A →* A := pmap.mk pr1 idp definition is_embedding_component_incl [instance] (A : Type*) : is_embedding (component_incl A) := is_embedding_pr1 _ definition component_intro [constructor] {A B : Type*} (f : A →* B) (H : merely_constant f) : A →* component B := begin fapply pmap.mk, { intro a, refine ⟨f a, _⟩, exact tinverse (merely_constant_pmap H a) }, exact subtype_eq !respect_pt end definition component_functor [constructor] {A B : Type*} (f : A →* B) : component A →* component B := component_intro (f ∘* component_incl A) !merely_constant_of_is_conn -- definition component_elim [constructor] {A B : Type*} (f : A →* B) (H : merely_constant f) : -- A →* component B := -- begin -- fapply pmap.mk, -- { intro a, refine ⟨f a, _⟩, exact tinverse (merely_constant_pmap H a) }, -- exact subtype_eq !respect_pt -- end definition loop_component (A : Type*) : Ω (component A) ≃* Ω A := loop_pequiv_loop_of_is_embedding (component_incl A) lemma loopn_component (n : ℕ) (A : Type*) : Ω[n+1] (component A) ≃* Ω[n+1] A := !loopn_succ_in ⬝e* loopn_pequiv_loopn n (loop_component A) ⬝e* !loopn_succ_in⁻¹ᵉ* -- lemma fundamental_group_component (A : Type*) : π₁ (component A) ≃g π₁ A := -- isomorphism_of_equiv (trunc_equiv_trunc 0 (loop_component A)) _ lemma homotopy_group_component (n : ℕ) (A : Type*) : πg[n+1] (component A) ≃g πg[n+1] A := homotopy_group_isomorphism_of_is_embedding (n+1) (component_incl A) definition is_trunc_component [instance] (n : ℕ₋₂) (A : Type*) [is_trunc n A] : is_trunc n (component A) := begin apply @is_trunc_sigma, intro a, cases n with n, { apply is_contr_of_inhabited_prop, exact tr !is_prop.elim }, { apply is_trunc_succ_of_is_prop }, end definition ptrunc_component' (n : ℕ₋₂) (A : Type*) : ptrunc (n.+2) (component A) ≃* component (ptrunc (n.+2) A) := begin fapply pequiv.MK', { exact ptrunc.elim (n.+2) (component_functor !ptr) }, { intro x, cases x with x p, induction x with a, refine tr ⟨a, _⟩, note q := trunc_functor -1 !tr_eq_tr_equiv p, exact trunc_trunc_equiv_left _ !minus_one_le_succ q }, { exact sorry }, { exact sorry } end definition ptrunc_component (n : ℕ₋₂) (A : Type*) : ptrunc n (component A) ≃* component (ptrunc n A) := begin cases n with n, exact sorry, cases n with n, exact sorry, exact ptrunc_component' n A end definition break_into_components (A : Type) : A ≃ Σ(x : trunc 0 A), Σ(a : A), ∥ tr a = x ∥ := calc A ≃ Σ(a : A) (x : trunc 0 A), tr a = x : by exact (@sigma_equiv_of_is_contr_right _ _ (λa, !is_contr_sigma_eq))⁻¹ᵉ ... ≃ Σ(x : trunc 0 A) (a : A), tr a = x : by apply sigma_comm_equiv ... ≃ Σ(x : trunc 0 A), Σ(a : A), ∥ tr a = x ∥ : by exact sigma_equiv_sigma_right (λx, sigma_equiv_sigma_right (λa, !trunc_equiv⁻¹ᵉ)) definition pfiber_pequiv_component_of_is_contr [constructor] {A B : Type*} (f : A →* B) [is_contr B] /- extra condition, something like trunc_functor 0 f is an embedding -/ : pfiber f ≃* component A := sorry end misc namespace category definition precategory_Group.{u} [instance] [constructor] : precategory.{u+1 u} Group := begin fapply precategory.mk, { exact λG H, G →g H }, { exact _ }, { exact λG H K ψ φ, ψ ∘g φ }, { exact λG, gid G }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp } end definition precategory_AbGroup.{u} [instance] [constructor] : precategory.{u+1 u} AbGroup := begin fapply precategory.mk, { exact λG H, G →g H }, { exact _ }, { exact λG H K ψ φ, ψ ∘g φ }, { exact λG, gid G }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp }, { intros, apply homomorphism_eq, esimp } end open iso definition Group_is_iso_of_is_equiv {G H : Group} (φ : G →g H) (H : is_equiv (group_fun φ)) : is_iso φ := begin fconstructor, { exact (isomorphism.mk φ H)⁻¹ᵍ }, { apply homomorphism_eq, rexact left_inv φ }, { apply homomorphism_eq, rexact right_inv φ } end definition Group_is_equiv_of_is_iso {G H : Group} (φ : G ⟶ H) (Hφ : is_iso φ) : is_equiv (group_fun φ) := begin fapply adjointify, { exact group_fun φ⁻¹ʰ }, { note p := right_inverse φ, exact ap010 group_fun p }, { note p := left_inverse φ, exact ap010 group_fun p } end definition Group_iso_equiv (G H : Group) : (G ≅ H) ≃ (G ≃g H) := begin fapply equiv.MK, { intro φ, induction φ with φ φi, constructor, exact Group_is_equiv_of_is_iso φ _ }, { intro v, induction v with φ φe, constructor, exact Group_is_iso_of_is_equiv φ _ }, { intro v, induction v with φ φe, apply isomorphism_eq, reflexivity }, { intro φ, induction φ with φ φi, apply iso_eq, reflexivity } end definition Group_props.{u} {A : Type.{u}} (v : (A → A → A) × (A → A) × A) : Prop.{u} := begin induction v with m v, induction v with i o, fapply trunctype.mk, { exact is_set A × (Πa, m a o = a) × (Πa, m o a = a) × (Πa b c, m (m a b) c = m a (m b c)) × (Πa, m (i a) a = o) }, { apply is_trunc_of_imp_is_trunc, intro v, induction v with H v, have is_prop (Πa, m a o = a), from _, have is_prop (Πa, m o a = a), from _, have is_prop (Πa b c, m (m a b) c = m a (m b c)), from _, have is_prop (Πa, m (i a) a = o), from _, apply is_trunc_prod } end definition Group.sigma_char2.{u} : Group.{u} ≃ Σ(A : Type.{u}) (v : (A → A → A) × (A → A) × A), Group_props v := begin fapply equiv.MK, { intro G, refine ⟨G, _⟩, induction G with G g, induction g with m s ma o om mo i mi, repeat (fconstructor; do 2 try assumption), }, { intro v, induction v with x v, induction v with y v, repeat induction y with x y, repeat induction v with x v, constructor, fconstructor, repeat assumption }, { intro v, induction v with x v, induction v with y v, repeat induction y with x y, repeat induction v with x v, reflexivity }, { intro v, repeat induction v with x v, reflexivity }, end open is_trunc section local attribute group.to_has_mul group.to_has_inv [coercion] theorem inv_eq_of_mul_eq {A : Type} (G H : group A) (p : @mul A G ~2 @mul A H) : @inv A G ~ @inv A H := begin have foo : Π(g : A), @inv A G g = (@inv A G g * g) * @inv A H g, from λg, !mul_inv_cancel_right⁻¹, cases G with Gs Gm Gh1 G1 Gh2 Gh3 Gi Gh4, cases H with Hs Hm Hh1 H1 Hh2 Hh3 Hi Hh4, change Gi ~ Hi, intro g, have p' : Gm ~2 Hm, from p, calc Gi g = Hm (Hm (Gi g) g) (Hi g) : foo ... = Hm (Gm (Gi g) g) (Hi g) : by rewrite p' ... = Hm G1 (Hi g) : by rewrite Gh4 ... = Gm G1 (Hi g) : by rewrite p' ... = Hi g : Gh2 end theorem one_eq_of_mul_eq {A : Type} (G H : group A) (p : @mul A (group.to_has_mul G) ~2 @mul A (group.to_has_mul H)) : @one A (group.to_has_one G) = @one A (group.to_has_one H) := begin cases G with Gm Gs Gh1 G1 Gh2 Gh3 Gi Gh4, cases H with Hm Hs Hh1 H1 Hh2 Hh3 Hi Hh4, exact (Hh2 G1)⁻¹ ⬝ (p H1 G1)⁻¹ ⬝ Gh3 H1, end end open prod.ops definition group_of_Group_props.{u} {A : Type.{u}} {m : A → A → A} {i : A → A} {o : A} (H : Group_props (m, (i, o))) : group A := ⦃group, mul := m, inv := i, one := o, is_set_carrier := H.1, mul_one := H.2.1, one_mul := H.2.2.1, mul_assoc := H.2.2.2.1, mul_left_inv := H.2.2.2.2⦄ theorem Group_eq_equiv_lemma2 {A : Type} {m m' : A → A → A} {i i' : A → A} {o o' : A} (H : Group_props (m, (i, o))) (H' : Group_props (m', (i', o'))) : (m, (i, o)) = (m', (i', o')) ≃ (m ~2 m') := begin have is_set A, from pr1 H, apply equiv_of_is_prop, { intro p, exact apd100 (eq_pr1 p)}, { intro p, apply prod_eq (eq_of_homotopy2 p), apply prod_eq: esimp [Group_props] at *; esimp, { apply eq_of_homotopy, exact inv_eq_of_mul_eq (group_of_Group_props H) (group_of_Group_props H') p }, { exact one_eq_of_mul_eq (group_of_Group_props H) (group_of_Group_props H') p }} end open sigma.ops theorem Group_eq_equiv_lemma {G H : Group} (p : (Group.sigma_char2 G).1 = (Group.sigma_char2 H).1) : ((Group.sigma_char2 G).2 =[p] (Group.sigma_char2 H).2) ≃ (is_mul_hom (equiv_of_eq (proof p qed : Group.carrier G = Group.carrier H))) := begin refine !sigma_pathover_equiv_of_is_prop ⬝e _, induction G with G g, induction H with H h, esimp [Group.sigma_char2] at p, induction p, refine !pathover_idp ⬝e _, induction g with s m ma o om mo i mi, induction h with σ μ μa ε εμ με ι μι, exact Group_eq_equiv_lemma2 (Group.sigma_char2 (Group.mk G (group.mk s m ma o om mo i mi))).2.2 (Group.sigma_char2 (Group.mk G (group.mk σ μ μa ε εμ με ι μι))).2.2 end definition isomorphism.sigma_char (G H : Group) : (G ≃g H) ≃ Σ(e : G ≃ H), is_mul_hom e := begin fapply equiv.MK, { intro φ, exact ⟨equiv_of_isomorphism φ, to_respect_mul φ⟩ }, { intro v, induction v with e p, exact isomorphism_of_equiv e p }, { intro v, induction v with e p, induction e, reflexivity }, { intro φ, induction φ with φ H, induction φ, reflexivity }, end definition Group_eq_equiv (G H : Group) : G = H ≃ (G ≃g H) := begin refine (eq_equiv_fn_eq_of_equiv Group.sigma_char2 G H) ⬝e _, refine !sigma_eq_equiv ⬝e _, refine sigma_equiv_sigma_right Group_eq_equiv_lemma ⬝e _, transitivity (Σ(e : (Group.sigma_char2 G).1 ≃ (Group.sigma_char2 H).1), @is_mul_hom _ _ _ _ (to_fun e)), apply sigma_ua, exact !isomorphism.sigma_char⁻¹ᵉ end definition to_fun_Group_eq_equiv {G H : Group} (p : G = H) : Group_eq_equiv G H p ~ isomorphism_of_eq p := begin induction p, reflexivity end definition Group_eq2 {G H : Group} {p q : G = H} (r : isomorphism_of_eq p ~ isomorphism_of_eq q) : p = q := begin apply eq_of_fn_eq_fn (Group_eq_equiv G H), apply isomorphism_eq, intro g, refine to_fun_Group_eq_equiv p g ⬝ r g ⬝ (to_fun_Group_eq_equiv q g)⁻¹, end definition Group_eq_equiv_Group_iso (G₁ G₂ : Group) : G₁ = G₂ ≃ G₁ ≅ G₂ := Group_eq_equiv G₁ G₂ ⬝e (Group_iso_equiv G₁ G₂)⁻¹ᵉ definition category_Group.{u} : category Group.{u} := category.mk precategory_Group begin intro G H, apply is_equiv_of_equiv_of_homotopy (Group_eq_equiv_Group_iso G H), intro p, induction p, fapply iso_eq, apply homomorphism_eq, reflexivity end definition category_AbGroup : category AbGroup := category.mk precategory_AbGroup sorry definition Grp.{u} [constructor] : Category := category.Mk Group.{u} category_Group definition AbGrp [constructor] : Category := category.Mk AbGroup category_AbGroup end category namespace sphere -- definition constant_sphere_map_sphere {n m : ℕ} (H : n < m) (f : S n →* S m) : -- f ~* pconst (S n) (S m) := -- begin -- assert H : is_contr (Ω[n] (S m)), -- { apply homotopy_group_sphere_le, }, -- apply phomotopy_of_eq, -- apply eq_of_fn_eq_fn !sphere_pmap_pequiv, -- apply @is_prop.elim -- end end sphere section injective_surjective open trunc fiber image /- do we want to prove this without funext before we move it? -/ variables {A B C : Type} (f : A → B) definition is_embedding_factor [is_set A] [is_set B] (g : B → C) (h : A → C) (H : g ∘ f ~ h) : is_embedding h → is_embedding f := begin induction H using homotopy.rec_on_idp, intro E, fapply is_embedding_of_is_injective, intro x y p, fapply @is_injective_of_is_embedding _ _ _ E _ _ (ap g p) end definition is_surjective_factor (g : B → C) (h : A → C) (H : g ∘ f ~ h) : is_surjective h → is_surjective g := begin induction H using homotopy.rec_on_idp, intro S, intro c, note p := S c, induction p, apply tr, fapply fiber.mk, exact f a, exact p end end injective_surjective -- Yuri Sulyma's code from HoTT MRC notation `⅀→`:(max+5) := susp_functor notation `⅀⇒`:(max+5) := susp_functor_phomotopy notation `Ω⇒`:(max+5) := ap1_phomotopy definition ap1_phomotopy_symm {A B : Type*} {f g : A →* B} (p : f ~* g) : (Ω⇒ p)⁻¹* = Ω⇒ (p⁻¹*) := begin induction p using phomotopy_rec_idp, rewrite ap1_phomotopy_refl, xrewrite [+refl_symm], rewrite ap1_phomotopy_refl end definition ap1_phomotopy_trans {A B : Type*} {f g h : A →* B} (q : g ~* h) (p : f ~* g) : Ω⇒ (p ⬝* q) = Ω⇒ p ⬝* Ω⇒ q := begin induction p using phomotopy_rec_idp, induction q using phomotopy_rec_idp, rewrite trans_refl, rewrite [+ap1_phomotopy_refl], rewrite trans_refl end namespace pointed definition to_homotopy_pt_mk {A B : Type*} {f g : A →* B} (h : f ~ g) (p : h pt ⬝ respect_pt g = respect_pt f) : to_homotopy_pt (phomotopy.mk h p) = p := to_right_inv !eq_con_inv_equiv_con_eq p variables {A₀₀ A₂₀ A₀₂ A₂₂ : Type*} {f₁₀ : A₀₀ →* A₂₀} {f₁₂ : A₀₂ →* A₂₂} {f₀₁ : A₀₀ →* A₀₂} {f₂₁ : A₂₀ →* A₂₂} definition psquare_transpose (p : psquare f₁₀ f₁₂ f₀₁ f₂₁) : psquare f₀₁ f₂₁ f₁₀ f₁₂ := p⁻¹* end pointed namespace pi definition pi_bool_left_nat {A B : bool → Type} (g : Πx, A x -> B x) : hsquare (pi_bool_left A) (pi_bool_left B) (pi_functor_right g) (prod_functor (g ff) (g tt)) := begin intro h, esimp end definition pi_bool_left_inv_nat {A B : bool → Type} (g : Πx, A x -> B x) : hsquare (pi_bool_left A)⁻¹ᵉ (pi_bool_left B)⁻¹ᵉ (prod_functor (g ff) (g tt)) (pi_functor_right g) := hhinverse (pi_bool_left_nat g) end pi namespace sum infix ` +→ `:62 := sum_functor variables {A₀₀ A₂₀ A₀₂ A₂₂ B₀₀ B₂₀ B₀₂ B₂₂ A A' B B' C C' : Type} {f₁₀ : A₀₀ → A₂₀} {f₁₂ : A₀₂ → A₂₂} {f₀₁ : A₀₀ → A₀₂} {f₂₁ : A₂₀ → A₂₂} {g₁₀ : B₀₀ → B₂₀} {g₁₂ : B₀₂ → B₂₂} {g₀₁ : B₀₀ → B₀₂} {g₂₁ : B₂₀ → B₂₂} {h₀₁ : B₀₀ → A₀₂} {h₂₁ : B₂₀ → A₂₂} definition sum_rec_hsquare [unfold 16] (h : hsquare f₁₀ f₁₂ f₀₁ f₂₁) (k : hsquare g₁₀ f₁₂ h₀₁ h₂₁) : hsquare (f₁₀ +→ g₁₀) f₁₂ (sum.rec f₀₁ h₀₁) (sum.rec f₂₁ h₂₁) := begin intro x, induction x with a b, exact h a, exact k b end definition sum_functor_hsquare [unfold 19] (h : hsquare f₁₀ f₁₂ f₀₁ f₂₁) (k : hsquare g₁₀ g₁₂ g₀₁ g₂₁) : hsquare (f₁₀ +→ g₁₀) (f₁₂ +→ g₁₂) (f₀₁ +→ g₀₁) (f₂₁ +→ g₂₁) := sum_rec_hsquare (λa, ap inl (h a)) (λb, ap inr (k b)) definition sum_functor_compose (g : B → C) (f : A → B) (g' : B' → C') (f' : A' → B') : (g ∘ f) +→ (g' ∘ f') ~ g +→ g' ∘ f +→ f' := begin intro x, induction x with a a': reflexivity end definition sum_rec_sum_functor (g : B → C) (g' : B' → C) (f : A → B) (f' : A' → B') : sum.rec g g' ∘ sum_functor f f' ~ sum.rec (g ∘ f) (g' ∘ f') := begin intro x, induction x with a a': reflexivity end definition sum_rec_same_compose (g : B → C) (f : A → B) : sum.rec (g ∘ f) (g ∘ f) ~ g ∘ sum.rec f f := begin intro x, induction x with a a': reflexivity end definition sum_rec_same (f : A → B) : sum.rec f f ~ f ∘ sum.rec id id := sum_rec_same_compose f id end sum namespace prod infix ` ×→ `:63 := prod_functor end prod namespace equiv definition rec_eq_of_equiv {A : Type} {P : A → A → Type} (e : Πa a', a = a' ≃ P a a') {a a' : A} (Q : P a a' → Type) (H : Π(q : a = a'), Q (e a a' q)) : Π(p : P a a'), Q p := equiv_rect (e a a') Q H definition rec_idp_of_equiv {A : Type} {P : A → A → Type} (e : Πa a', a = a' ≃ P a a') {a : A} (r : P a a) (s : e a a idp = r) (Q : Πa', P a a' → Type) (H : Q a r) ⦃a' : A⦄ (p : P a a') : Q a' p := rec_eq_of_equiv e _ begin intro q, induction q, induction s, exact H end p definition rec_idp_of_equiv_idp {A : Type} {P : A → A → Type} (e : Πa a', a = a' ≃ P a a') {a : A} (r : P a a) (s : e a a idp = r) (Q : Πa', P a a' → Type) (H : Q a r) : rec_idp_of_equiv e r s Q H r = H := begin induction s, refine !is_equiv_rect_comp ⬝ _, reflexivity end end equiv
aa64a0dcf5e009a2744aa31aba4e84ef62828304
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/normed_space/pi_Lp.lean
da14f060696deae741cb2ab2f08c7e154e3ed404
[ "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
35,904
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Jireh Loreaux -/ import analysis.mean_inequalities import data.fintype.order /-! # `L^p` distance on finite products of metric spaces Given finitely many metric spaces, one can put the max distance on their product, but there is also a whole family of natural distances, indexed by a parameter `p : ℝ≥0∞`, that also induce the product topology. We define them in this file. For `0 < p < ∞`, the distance on `Π i, α i` is given by $$ d(x, y) = \left(\sum d(x_i, y_i)^p\right)^{1/p}. $$, whereas for `p = 0` it is the cardinality of the set ${ i | x_i ≠ y_i}$. For `p = ∞` the distance is the supremum of the distances. We give instances of this construction for emetric spaces, metric spaces, normed groups and normed spaces. To avoid conflicting instances, all these are defined on a copy of the original Π-type, named `pi_Lp p α`. The assumpion `[fact (1 ≤ p)]` is required for the metric and normed space instances. We ensure that the topology, bornology and uniform structure on `pi_Lp p α` are (defeq to) the product topology, product bornology and product uniformity, to be able to use freely continuity statements for the coordinate functions, for instance. ## Implementation notes We only deal with the `L^p` distance on a product of finitely many metric spaces, which may be distinct. A closely related construction is `lp`, the `L^p` norm on a product of (possibly infinitely many) normed spaces, where the norm is $$ \left(\sum ‖f (x)‖^p \right)^{1/p}. $$ However, the topology induced by this construction is not the product topology, and some functions have infinite `L^p` norm. These subtleties are not present in the case of finitely many metric spaces, hence it is worth devoting a file to this specific case which is particularly well behaved. Another related construction is `measure_theory.Lp`, the `L^p` norm on the space of functions from a measure space to a normed space, where the norm is $$ \left(\int ‖f (x)‖^p dμ\right)^{1/p}. $$ This has all the same subtleties as `lp`, and the further subtlety that this only defines a seminorm (as almost everywhere zero functions have zero `L^p` norm). The construction `pi_Lp` corresponds to the special case of `measure_theory.Lp` in which the basis is a finite space equipped with the counting measure. To prove that the topology (and the uniform structure) on a finite product with the `L^p` distance are the same as those coming from the `L^∞` distance, we could argue that the `L^p` and `L^∞` norms are equivalent on `ℝ^n` for abstract (norm equivalence) reasons. Instead, we give a more explicit (easy) proof which provides a comparison between these two norms with explicit constants. We also set up the theory for `pseudo_emetric_space` and `pseudo_metric_space`. -/ open real set filter is_R_or_C bornology open_locale big_operators uniformity topology nnreal ennreal noncomputable theory /-- A copy of a Pi type, on which we will put the `L^p` distance. Since the Pi type itself is already endowed with the `L^∞` distance, we need the type synonym to avoid confusing typeclass resolution. Also, we let it depend on `p`, to get a whole family of type on which we can put different distances. -/ @[nolint unused_arguments] def pi_Lp (p : ℝ≥0∞) {ι : Type*} (α : ι → Type*) : Type* := Π (i : ι), α i instance (p : ℝ≥0∞) {ι : Type*} (α : ι → Type*) [Π i, inhabited (α i)] : inhabited (pi_Lp p α) := ⟨λ i, default⟩ namespace pi_Lp variables (p : ℝ≥0∞) (𝕜 𝕜' : Type*) {ι : Type*} (α : ι → Type*) (β : ι → Type*) /-- Canonical bijection between `pi_Lp p α` and the original Pi type. We introduce it to be able to compare the `L^p` and `L^∞` distances through it. -/ protected def equiv : pi_Lp p α ≃ Π (i : ι), α i := equiv.refl _ /-! Note that the unapplied versions of these lemmas are deliberately omitted, as they break the use of the type synonym. -/ @[simp] lemma equiv_apply (x : pi_Lp p α) (i : ι) : pi_Lp.equiv p α x i = x i := rfl @[simp] lemma equiv_symm_apply (x : Π i, α i) (i : ι) : (pi_Lp.equiv p α).symm x i = x i := rfl section dist_norm variables [fintype ι] /-! ### Definition of `edist`, `dist` and `norm` on `pi_Lp` In this section we define the `edist`, `dist` and `norm` functions on `pi_Lp p α` without assuming `[fact (1 ≤ p)]` or metric properties of the spaces `α i`. This allows us to provide the rewrite lemmas for each of three cases `p = 0`, `p = ∞` and `0 < p.to_real`. -/ section edist variables [Π i, has_edist (β i)] /-- Endowing the space `pi_Lp p β` with the `L^p` edistance. We register this instance separate from `pi_Lp.pseudo_emetric` since the latter requires the type class hypothesis `[fact (1 ≤ p)]` in order to prove the triangle inequality. Registering this separately allows for a future emetric-like structure on `pi_Lp p β` for `p < 1` satisfying a relaxed triangle inequality. The terminology for this varies throughout the literature, but it is sometimes called a *quasi-metric* or *semi-metric*. -/ instance : has_edist (pi_Lp p β) := { edist := λ f g, if hp : p = 0 then {i | f i ≠ g i}.to_finite.to_finset.card else (if p = ∞ then ⨆ i, edist (f i) (g i) else (∑ i, (edist (f i) (g i) ^ p.to_real)) ^ (1/p.to_real)) } variable {β} lemma edist_eq_card (f g : pi_Lp 0 β) : edist f g = {i | f i ≠ g i}.to_finite.to_finset.card := if_pos rfl lemma edist_eq_sum {p : ℝ≥0∞} (hp : 0 < p.to_real) (f g : pi_Lp p β) : edist f g = (∑ i, edist (f i) (g i) ^ p.to_real) ^ (1/p.to_real) := let hp' := ennreal.to_real_pos_iff.mp hp in (if_neg hp'.1.ne').trans (if_neg hp'.2.ne) lemma edist_eq_supr (f g : pi_Lp ∞ β) : edist f g = ⨆ i, edist (f i) (g i) := by { dsimp [edist], exact if_neg ennreal.top_ne_zero } end edist section edist_prop variables {β} [Π i, pseudo_emetric_space (β i)] /-- This holds independent of `p` and does not require `[fact (1 ≤ p)]`. We keep it separate from `pi_Lp.pseudo_emetric_space` so it can be used also for `p < 1`. -/ protected lemma edist_self (f : pi_Lp p β) : edist f f = 0 := begin rcases p.trichotomy with (rfl | rfl | h), { simp [edist_eq_card], }, { simp [edist_eq_supr], }, { simp [edist_eq_sum h, ennreal.zero_rpow_of_pos h, ennreal.zero_rpow_of_pos (inv_pos.2 $ h)]} end /-- This holds independent of `p` and does not require `[fact (1 ≤ p)]`. We keep it separate from `pi_Lp.pseudo_emetric_space` so it can be used also for `p < 1`. -/ protected lemma edist_comm (f g : pi_Lp p β) : edist f g = edist g f := begin rcases p.trichotomy with (rfl | rfl | h), { simp only [edist_eq_card, eq_comm, ne.def] }, { simp only [edist_eq_supr, edist_comm] }, { simp only [edist_eq_sum h, edist_comm] } end end edist_prop section dist variables [Π i, has_dist (α i)] /-- Endowing the space `pi_Lp p β` with the `L^p` distance. We register this instance separate from `pi_Lp.pseudo_metric` since the latter requires the type class hypothesis `[fact (1 ≤ p)]` in order to prove the triangle inequality. Registering this separately allows for a future metric-like structure on `pi_Lp p β` for `p < 1` satisfying a relaxed triangle inequality. The terminology for this varies throughout the literature, but it is sometimes called a *quasi-metric* or *semi-metric*. -/ instance : has_dist (pi_Lp p α) := { dist := λ f g, if hp : p = 0 then {i | f i ≠ g i}.to_finite.to_finset.card else (if p = ∞ then ⨆ i, dist (f i) (g i) else (∑ i, (dist (f i) (g i) ^ p.to_real)) ^ (1/p.to_real)) } variable {α} lemma dist_eq_card (f g : pi_Lp 0 α) : dist f g = {i | f i ≠ g i}.to_finite.to_finset.card := if_pos rfl lemma dist_eq_sum {p : ℝ≥0∞} (hp : 0 < p.to_real) (f g : pi_Lp p α) : dist f g = (∑ i, dist (f i) (g i) ^ p.to_real) ^ (1/p.to_real) := let hp' := ennreal.to_real_pos_iff.mp hp in (if_neg hp'.1.ne').trans (if_neg hp'.2.ne) lemma dist_eq_csupr (f g : pi_Lp ∞ α) : dist f g = ⨆ i, dist (f i) (g i) := by { dsimp [dist], exact if_neg ennreal.top_ne_zero } end dist section norm variables [Π i, has_norm (β i)] [Π i, has_zero (β i)] /-- Endowing the space `pi_Lp p β` with the `L^p` norm. We register this instance separate from `pi_Lp.seminormed_add_comm_group` since the latter requires the type class hypothesis `[fact (1 ≤ p)]` in order to prove the triangle inequality. Registering this separately allows for a future norm-like structure on `pi_Lp p β` for `p < 1` satisfying a relaxed triangle inequality. These are called *quasi-norms*. -/ instance has_norm : has_norm (pi_Lp p β) := { norm := λ f, if hp : p = 0 then {i | f i ≠ 0}.to_finite.to_finset.card else (if p = ∞ then ⨆ i, ‖f i‖ else (∑ i, ‖f i‖ ^ p.to_real) ^ (1 / p.to_real)) } variables {p β} lemma norm_eq_card (f : pi_Lp 0 β) : ‖f‖ = {i | f i ≠ 0}.to_finite.to_finset.card := if_pos rfl lemma norm_eq_csupr (f : pi_Lp ∞ β) : ‖f‖ = ⨆ i, ‖f i‖ := by { dsimp [norm], exact if_neg ennreal.top_ne_zero } lemma norm_eq_sum (hp : 0 < p.to_real) (f : pi_Lp p β) : ‖f‖ = (∑ i, ‖f i‖ ^ p.to_real) ^ (1 / p.to_real) := let hp' := ennreal.to_real_pos_iff.mp hp in (if_neg hp'.1.ne').trans (if_neg hp'.2.ne) end norm end dist_norm section aux /-! ### The uniformity on finite `L^p` products is the product uniformity In this section, we put the `L^p` edistance on `pi_Lp p α`, and we check that the uniformity coming from this edistance coincides with the product uniformity, by showing that the canonical map to the Pi type (with the `L^∞` distance) is a uniform embedding, as it is both Lipschitz and antiLipschitz. We only register this emetric space structure as a temporary instance, as the true instance (to be registered later) will have as uniformity exactly the product uniformity, instead of the one coming from the edistance (which is equal to it, but not defeq). See Note [forgetful inheritance] explaining why having definitionally the right uniformity is often important. -/ variables [fact (1 ≤ p)] [Π i, pseudo_metric_space (α i)] [Π i, pseudo_emetric_space (β i)] variables [fintype ι] /-- Endowing the space `pi_Lp p β` with the `L^p` pseudoemetric structure. This definition is not satisfactory, as it does not register the fact that the topology and the uniform structure coincide with the product one. Therefore, we do not register it as an instance. Using this as a temporary pseudoemetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure by the product one using this pseudoemetric space and `pseudo_emetric_space.replace_uniformity`. -/ def pseudo_emetric_aux : pseudo_emetric_space (pi_Lp p β) := { edist_self := pi_Lp.edist_self p, edist_comm := pi_Lp.edist_comm p, edist_triangle := λ f g h, begin unfreezingI { rcases p.dichotomy with (rfl | hp) }, { simp only [edist_eq_supr], casesI is_empty_or_nonempty ι, { simp only [csupr_of_empty, ennreal.bot_eq_zero, add_zero, nonpos_iff_eq_zero] }, exact supr_le (λ i, (edist_triangle _ (g i) _).trans $ add_le_add (le_supr _ i) (le_supr _ i))}, { simp only [edist_eq_sum (zero_lt_one.trans_le hp)], calc (∑ i, edist (f i) (h i) ^ p.to_real) ^ (1 / p.to_real) ≤ (∑ i, (edist (f i) (g i) + edist (g i) (h i)) ^ p.to_real) ^ (1 / p.to_real) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ zero_le_one.trans hp), refine finset.sum_le_sum (λ i hi, _), exact ennreal.rpow_le_rpow (edist_triangle _ _ _) (zero_le_one.trans hp), end ... ≤ (∑ i, edist (f i) (g i) ^ p.to_real) ^ (1 / p.to_real) + (∑ i, edist (g i) (h i) ^ p.to_real) ^ (1 / p.to_real) : ennreal.Lp_add_le _ _ _ hp }, end } local attribute [instance] pi_Lp.pseudo_emetric_aux /-- An auxiliary lemma used twice in the proof of `pi_Lp.pseudo_metric_aux` below. Not intended for use outside this file. -/ lemma supr_edist_ne_top_aux {ι : Type*} [finite ι] {α : ι → Type*} [Π i, pseudo_metric_space (α i)] (f g : pi_Lp ∞ α) : (⨆ i, edist (f i) (g i)) ≠ ⊤ := begin casesI nonempty_fintype ι, obtain ⟨M, hM⟩ := fintype.exists_le (λ i, (⟨dist (f i) (g i), dist_nonneg⟩ : ℝ≥0)), refine ne_of_lt ((supr_le $ λ i, _).trans_lt (@ennreal.coe_lt_top M)), simp only [edist, pseudo_metric_space.edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg], exact_mod_cast hM i, end /-- Endowing the space `pi_Lp p α` with the `L^p` pseudometric structure. This definition is not satisfactory, as it does not register the fact that the topology, the uniform structure, and the bornology coincide with the product ones. Therefore, we do not register it as an instance. Using this as a temporary pseudoemetric space instance, we will show that the uniform structure is equal (but not defeq) to the product one, and then register an instance in which we replace the uniform structure and the bornology by the product ones using this pseudometric space, `pseudo_metric_space.replace_uniformity`, and `pseudo_metric_space.replace_bornology`. See note [reducible non-instances] -/ @[reducible] def pseudo_metric_aux : pseudo_metric_space (pi_Lp p α) := pseudo_emetric_space.to_pseudo_metric_space_of_dist dist (λ f g, begin unfreezingI { rcases p.dichotomy with (rfl | h) }, { exact supr_edist_ne_top_aux f g }, { rw edist_eq_sum (zero_lt_one.trans_le h), exact ennreal.rpow_ne_top_of_nonneg (one_div_nonneg.2 (zero_le_one.trans h)) (ne_of_lt $ (ennreal.sum_lt_top $ λ i hi, ennreal.rpow_ne_top_of_nonneg (zero_le_one.trans h) (edist_ne_top _ _)))} end) (λ f g, begin unfreezingI { rcases p.dichotomy with (rfl | h) }, { rw [edist_eq_supr, dist_eq_csupr], { casesI is_empty_or_nonempty ι, { simp only [real.csupr_empty, csupr_of_empty, ennreal.bot_eq_zero, ennreal.zero_to_real] }, { refine le_antisymm (csupr_le $ λ i, _) _, { rw [←ennreal.of_real_le_iff_le_to_real (supr_edist_ne_top_aux f g), ←pseudo_metric_space.edist_dist], exact le_supr _ i, }, { refine ennreal.to_real_le_of_le_of_real (real.Sup_nonneg _ _) (supr_le $ λ i, _), { rintro - ⟨i, rfl⟩, exact dist_nonneg, }, { unfold edist, rw pseudo_metric_space.edist_dist, exact ennreal.of_real_le_of_real (le_csupr (fintype.bdd_above_range _) i), } } } } }, { have A : ∀ i, edist (f i) (g i) ^ p.to_real ≠ ⊤, from λ i, ennreal.rpow_ne_top_of_nonneg (zero_le_one.trans h) (edist_ne_top _ _), simp only [edist_eq_sum (zero_lt_one.trans_le h), dist_edist, ennreal.to_real_rpow, dist_eq_sum (zero_lt_one.trans_le h), ← ennreal.to_real_sum (λ i _, A i)] } end) local attribute [instance] pi_Lp.pseudo_metric_aux lemma lipschitz_with_equiv_aux : lipschitz_with 1 (pi_Lp.equiv p β) := begin intros x y, unfreezingI { rcases p.dichotomy with (rfl | h) }, { simpa only [ennreal.coe_one, one_mul, edist_eq_supr, edist, finset.sup_le_iff, finset.mem_univ, forall_true_left] using le_supr (λ i, edist (x i) (y i)), }, { have cancel : p.to_real * (1/p.to_real) = 1 := mul_div_cancel' 1 (zero_lt_one.trans_le h).ne', rw edist_eq_sum (zero_lt_one.trans_le h), simp only [edist, forall_prop_of_true, one_mul, finset.mem_univ, finset.sup_le_iff, ennreal.coe_one], assume i, calc edist (x i) (y i) = (edist (x i) (y i) ^ p.to_real) ^ (1/p.to_real) : by simp [← ennreal.rpow_mul, cancel, -one_div] ... ≤ (∑ i, edist (x i) (y i) ^ p.to_real) ^ (1 / p.to_real) : begin apply ennreal.rpow_le_rpow _ (one_div_nonneg.2 $ (zero_le_one.trans h)), exact finset.single_le_sum (λ i hi, (bot_le : (0 : ℝ≥0∞) ≤ _)) (finset.mem_univ i) end } end lemma antilipschitz_with_equiv_aux : antilipschitz_with ((fintype.card ι : ℝ≥0) ^ (1 / p).to_real) (pi_Lp.equiv p β) := begin intros x y, unfreezingI { rcases p.dichotomy with (rfl | h) }, { simp only [edist_eq_supr, ennreal.div_top, ennreal.zero_to_real, nnreal.rpow_zero, ennreal.coe_one, one_mul, supr_le_iff], exact λ i, finset.le_sup (finset.mem_univ i), }, { have pos : 0 < p.to_real := zero_lt_one.trans_le h, have nonneg : 0 ≤ 1 / p.to_real := one_div_nonneg.2 (le_of_lt pos), have cancel : p.to_real * (1/p.to_real) = 1 := mul_div_cancel' 1 (ne_of_gt pos), rw [edist_eq_sum pos, ennreal.to_real_div 1 p], simp only [edist, ←one_div, ennreal.one_to_real], calc (∑ i, edist (x i) (y i) ^ p.to_real) ^ (1 / p.to_real) ≤ (∑ i, edist (pi_Lp.equiv p β x) (pi_Lp.equiv p β y) ^ p.to_real) ^ (1 / p.to_real) : begin apply ennreal.rpow_le_rpow _ nonneg, apply finset.sum_le_sum (λ i hi, _), apply ennreal.rpow_le_rpow _ (le_of_lt pos), exact finset.le_sup (finset.mem_univ i) end ... = (((fintype.card ι : ℝ≥0)) ^ (1 / p.to_real) : ℝ≥0) * edist (pi_Lp.equiv p β x) (pi_Lp.equiv p β y) : begin simp only [nsmul_eq_mul, finset.card_univ, ennreal.rpow_one, finset.sum_const, ennreal.mul_rpow_of_nonneg _ _ nonneg, ←ennreal.rpow_mul, cancel], have : (fintype.card ι : ℝ≥0∞) = (fintype.card ι : ℝ≥0) := (ennreal.coe_nat (fintype.card ι)).symm, rw [this, ennreal.coe_rpow_of_nonneg _ nonneg] end } end lemma aux_uniformity_eq : 𝓤 (pi_Lp p β) = 𝓤[Pi.uniform_space _] := begin have A : uniform_inducing (pi_Lp.equiv p β) := (antilipschitz_with_equiv_aux p β).uniform_inducing (lipschitz_with_equiv_aux p β).uniform_continuous, have : (λ (x : pi_Lp p β × pi_Lp p β), ((pi_Lp.equiv p β) x.fst, (pi_Lp.equiv p β) x.snd)) = id, by ext i; refl, rw [← A.comap_uniformity, this, comap_id] end lemma aux_cobounded_eq : cobounded (pi_Lp p α) = @cobounded _ pi.bornology := calc cobounded (pi_Lp p α) = comap (pi_Lp.equiv p α) (cobounded _) : le_antisymm (antilipschitz_with_equiv_aux p α).tendsto_cobounded.le_comap (lipschitz_with_equiv_aux p α).comap_cobounded_le ... = _ : comap_id end aux /-! ### Instances on finite `L^p` products -/ instance uniform_space [Π i, uniform_space (β i)] : uniform_space (pi_Lp p β) := Pi.uniform_space _ lemma uniform_continuous_equiv [Π i, uniform_space (β i)] : uniform_continuous (pi_Lp.equiv p β) := uniform_continuous_id lemma uniform_continuous_equiv_symm [Π i, uniform_space (β i)] : uniform_continuous (pi_Lp.equiv p β).symm := uniform_continuous_id @[continuity] lemma continuous_equiv [Π i, uniform_space (β i)] : continuous (pi_Lp.equiv p β) := continuous_id @[continuity] lemma continuous_equiv_symm [Π i, uniform_space (β i)] : continuous (pi_Lp.equiv p β).symm := continuous_id variable [fintype ι] instance bornology [Π i, bornology (β i)] : bornology (pi_Lp p β) := pi.bornology -- throughout the rest of the file, we assume `1 ≤ p` variables [fact (1 ≤ p)] /-- pseudoemetric space instance on the product of finitely many pseudoemetric spaces, using the `L^p` pseudoedistance, and having as uniformity the product uniformity. -/ instance [Π i, pseudo_emetric_space (β i)] : pseudo_emetric_space (pi_Lp p β) := (pseudo_emetric_aux p β).replace_uniformity (aux_uniformity_eq p β).symm /-- emetric space instance on the product of finitely many emetric spaces, using the `L^p` edistance, and having as uniformity the product uniformity. -/ instance [Π i, emetric_space (α i)] : emetric_space (pi_Lp p α) := @emetric_space.of_t0_pseudo_emetric_space (pi_Lp p α) _ pi.t0_space /-- pseudometric space instance on the product of finitely many psuedometric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [Π i, pseudo_metric_space (β i)] : pseudo_metric_space (pi_Lp p β) := ((pseudo_metric_aux p β).replace_uniformity (aux_uniformity_eq p β).symm).replace_bornology $ λ s, filter.ext_iff.1 (aux_cobounded_eq p β).symm sᶜ /-- metric space instance on the product of finitely many metric spaces, using the `L^p` distance, and having as uniformity the product uniformity. -/ instance [Π i, metric_space (α i)] : metric_space (pi_Lp p α) := metric_space.of_t0_pseudo_metric_space _ lemma nndist_eq_sum {p : ℝ≥0∞} [fact (1 ≤ p)] {β : ι → Type*} [Π i, pseudo_metric_space (β i)] (hp : p ≠ ∞) (x y : pi_Lp p β) : nndist x y = (∑ i : ι, nndist (x i) (y i) ^ p.to_real) ^ (1 / p.to_real) := subtype.ext $ by { push_cast, exact dist_eq_sum (p.to_real_pos_iff_ne_top.mpr hp) _ _ } lemma nndist_eq_supr {β : ι → Type*} [Π i, pseudo_metric_space (β i)] (x y : pi_Lp ∞ β) : nndist x y = ⨆ i, nndist (x i) (y i) := subtype.ext $ by { push_cast, exact dist_eq_csupr _ _ } lemma lipschitz_with_equiv [Π i, pseudo_emetric_space (β i)] : lipschitz_with 1 (pi_Lp.equiv p β) := lipschitz_with_equiv_aux p β lemma antilipschitz_with_equiv [Π i, pseudo_emetric_space (β i)] : antilipschitz_with ((fintype.card ι : ℝ≥0) ^ (1 / p).to_real) (pi_Lp.equiv p β) := antilipschitz_with_equiv_aux p β lemma infty_equiv_isometry [Π i, pseudo_emetric_space (β i)] : isometry (pi_Lp.equiv ∞ β) := λ x y, le_antisymm (by simpa only [ennreal.coe_one, one_mul] using lipschitz_with_equiv ∞ β x y) (by simpa only [ennreal.div_top, ennreal.zero_to_real, nnreal.rpow_zero, ennreal.coe_one, one_mul] using antilipschitz_with_equiv ∞ β x y) variables (p β) /-- seminormed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance seminormed_add_comm_group [Π i, seminormed_add_comm_group (β i)] : seminormed_add_comm_group (pi_Lp p β) := { dist_eq := λ x y, begin unfreezingI { rcases p.dichotomy with (rfl | h) }, { simpa only [dist_eq_csupr, norm_eq_csupr, dist_eq_norm] }, { have : p ≠ ∞, { intros hp, rw [hp, ennreal.top_to_real] at h, linarith,} , simpa only [dist_eq_sum (zero_lt_one.trans_le h), norm_eq_sum (zero_lt_one.trans_le h), dist_eq_norm], } end, .. pi.add_comm_group, } /-- normed group instance on the product of finitely many normed groups, using the `L^p` norm. -/ instance normed_add_comm_group [Π i, normed_add_comm_group (α i)] : normed_add_comm_group (pi_Lp p α) := { ..pi_Lp.seminormed_add_comm_group p α } lemma nnnorm_eq_sum {p : ℝ≥0∞} [fact (1 ≤ p)] {β : ι → Type*} (hp : p ≠ ∞) [Π i, seminormed_add_comm_group (β i)] (f : pi_Lp p β) : ‖f‖₊ = (∑ i, ‖f i‖₊ ^ p.to_real) ^ (1 / p.to_real) := by { ext, simp [nnreal.coe_sum, norm_eq_sum (p.to_real_pos_iff_ne_top.mpr hp)] } lemma nnnorm_eq_csupr {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (f : pi_Lp ∞ β) : ‖f‖₊ = ⨆ i, ‖f i‖₊ := by { ext, simp [nnreal.coe_supr, norm_eq_csupr] } lemma norm_eq_of_nat {p : ℝ≥0∞} [fact (1 ≤ p)] {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (n : ℕ) (h : p = n) (f : pi_Lp p β) : ‖f‖ = (∑ i, ‖f i‖ ^ n) ^ (1/(n : ℝ)) := begin have := p.to_real_pos_iff_ne_top.mpr (ne_of_eq_of_ne h $ ennreal.nat_ne_top n), simp only [one_div, h, real.rpow_nat_cast, ennreal.to_real_nat, eq_self_iff_true, finset.sum_congr, norm_eq_sum this], end lemma norm_eq_of_L2 {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (x : pi_Lp 2 β) : ‖x‖ = sqrt (∑ (i : ι), ‖x i‖ ^ 2) := by { convert norm_eq_of_nat 2 (by norm_cast) _, rw sqrt_eq_rpow, norm_cast } lemma nnnorm_eq_of_L2 {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (x : pi_Lp 2 β) : ‖x‖₊ = nnreal.sqrt (∑ (i : ι), ‖x i‖₊ ^ 2) := subtype.ext $ by { push_cast, exact norm_eq_of_L2 x } lemma norm_sq_eq_of_L2 (β : ι → Type*) [Π i, seminormed_add_comm_group (β i)] (x : pi_Lp 2 β) : ‖x‖ ^ 2 = ∑ (i : ι), ‖x i‖ ^ 2 := begin suffices : ‖x‖₊ ^ 2 = ∑ (i : ι), ‖x i‖₊ ^ 2, { simpa only [nnreal.coe_sum] using congr_arg (coe : ℝ≥0 → ℝ) this }, rw [nnnorm_eq_of_L2, nnreal.sq_sqrt], end lemma dist_eq_of_L2 {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (x y : pi_Lp 2 β) : dist x y = (∑ i, dist (x i) (y i) ^ 2).sqrt := by simp_rw [dist_eq_norm, norm_eq_of_L2, pi.sub_apply] lemma nndist_eq_of_L2 {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (x y : pi_Lp 2 β) : nndist x y = (∑ i, nndist (x i) (y i) ^ 2).sqrt := subtype.ext $ by { push_cast, exact dist_eq_of_L2 _ _ } lemma edist_eq_of_L2 {β : ι → Type*} [Π i, seminormed_add_comm_group (β i)] (x y : pi_Lp 2 β) : edist x y = (∑ i, edist (x i) (y i) ^ 2) ^ (1 / 2 : ℝ) := by simp [pi_Lp.edist_eq_sum] variables [normed_field 𝕜] [normed_field 𝕜'] /-- The product of finitely many normed spaces is a normed space, with the `L^p` norm. -/ instance normed_space [Π i, seminormed_add_comm_group (β i)] [Π i, normed_space 𝕜 (β i)] : normed_space 𝕜 (pi_Lp p β) := { norm_smul_le := λ c f, begin unfreezingI { rcases p.dichotomy with (rfl | hp) }, { letI : module 𝕜 (pi_Lp ∞ β) := pi.module ι β 𝕜, suffices : ‖c • f‖₊ = ‖c‖₊ * ‖f‖₊, { exact_mod_cast nnreal.coe_mono this.le }, simpa only [nnnorm_eq_csupr, nnreal.mul_supr, ←nnnorm_smul] }, { have : p.to_real * (1 / p.to_real) = 1 := mul_div_cancel' 1 (zero_lt_one.trans_le hp).ne', simp only [norm_eq_sum (zero_lt_one.trans_le hp), norm_smul, mul_rpow, norm_nonneg, ←finset.mul_sum, pi.smul_apply], rw [mul_rpow (rpow_nonneg_of_nonneg (norm_nonneg _) _), ← rpow_mul (norm_nonneg _), this, rpow_one], exact finset.sum_nonneg (λ i hi, rpow_nonneg_of_nonneg (norm_nonneg _) _) }, end, .. (pi.module ι β 𝕜) } instance is_scalar_tower [Π i, seminormed_add_comm_group (β i)] [has_smul 𝕜 𝕜'] [Π i, normed_space 𝕜 (β i)] [Π i, normed_space 𝕜' (β i)] [Π i, is_scalar_tower 𝕜 𝕜' (β i)] : is_scalar_tower 𝕜 𝕜' (pi_Lp p β) := pi.is_scalar_tower instance smul_comm_class [Π i, seminormed_add_comm_group (β i)] [Π i, normed_space 𝕜 (β i)] [Π i, normed_space 𝕜' (β i)] [Π i, smul_comm_class 𝕜 𝕜' (β i)] : smul_comm_class 𝕜 𝕜' (pi_Lp p β) := pi.smul_comm_class instance finite_dimensional [Π i, seminormed_add_comm_group (β i)] [Π i, normed_space 𝕜 (β i)] [I : ∀ i, finite_dimensional 𝕜 (β i)] : finite_dimensional 𝕜 (pi_Lp p β) := finite_dimensional.finite_dimensional_pi' _ _ /- Register simplification lemmas for the applications of `pi_Lp` elements, as the usual lemmas for Pi types will not trigger. -/ variables {𝕜 𝕜' p α} [Π i, seminormed_add_comm_group (β i)] [Π i, normed_space 𝕜 (β i)] (c : 𝕜) variables (x y : pi_Lp p β) (x' y' : Π i, β i) (i : ι) @[simp] lemma zero_apply : (0 : pi_Lp p β) i = 0 := rfl @[simp] lemma add_apply : (x + y) i = x i + y i := rfl @[simp] lemma sub_apply : (x - y) i = x i - y i := rfl @[simp] lemma smul_apply : (c • x) i = c • x i := rfl @[simp] lemma neg_apply : (-x) i = - (x i) := rfl /-- The canonical map `pi_Lp.equiv` between `pi_Lp ∞ β` and `Π i, β i` as a linear isometric equivalence. -/ def equivₗᵢ : pi_Lp ∞ β ≃ₗᵢ[𝕜] Π i, β i := { map_add' := λ f g, rfl, map_smul' := λ c f, rfl, norm_map' := λ f, begin suffices : finset.univ.sup (λ i, ‖f i‖₊) = ⨆ i, ‖f i‖₊, { simpa only [nnreal.coe_supr] using congr_arg (coe : ℝ≥0 → ℝ) this }, refine antisymm (finset.sup_le (λ i _, le_csupr (fintype.bdd_above_range (λ i, ‖f i‖₊)) _)) _, casesI is_empty_or_nonempty ι, { simp only [csupr_of_empty, finset.univ_eq_empty, finset.sup_empty], }, { exact csupr_le (λ i, finset.le_sup (finset.mem_univ i)) }, end, .. pi_Lp.equiv ∞ β } variables {ι' : Type*} variables [fintype ι'] variables (p 𝕜) (E : Type*) [normed_add_comm_group E] [normed_space 𝕜 E] /-- An equivalence of finite domains induces a linearly isometric equivalence of finitely supported functions-/ def _root_.linear_isometry_equiv.pi_Lp_congr_left (e : ι ≃ ι') : pi_Lp p (λ i : ι, E) ≃ₗᵢ[𝕜] pi_Lp p (λ i : ι', E) := { to_linear_equiv := linear_equiv.Pi_congr_left' 𝕜 (λ i : ι, E) e, norm_map' := λ x, begin unfreezingI { rcases p.dichotomy with (rfl | h) }, { simp_rw [norm_eq_csupr, linear_equiv.Pi_congr_left'_apply 𝕜 (λ i : ι, E) e x _], exact e.symm.supr_congr (λ i, rfl) }, { simp only [norm_eq_sum (zero_lt_one.trans_le h)], simp_rw linear_equiv.Pi_congr_left'_apply 𝕜 (λ i : ι, E) e x _, congr, exact (fintype.sum_equiv (e.symm) _ _ (λ i, rfl)) } end, } variables {p 𝕜 E} @[simp] lemma _root_.linear_isometry_equiv.pi_Lp_congr_left_apply (e : ι ≃ ι') (v : pi_Lp p (λ i : ι, E)) : linear_isometry_equiv.pi_Lp_congr_left p 𝕜 E e v = equiv.Pi_congr_left' (λ i : ι, E) e v := rfl @[simp] lemma _root_.linear_isometry_equiv.pi_Lp_congr_left_symm (e : ι ≃ ι') : (linear_isometry_equiv.pi_Lp_congr_left p 𝕜 E e).symm = (linear_isometry_equiv.pi_Lp_congr_left p 𝕜 E e.symm) := linear_isometry_equiv.ext $ λ x, rfl @[simp] lemma _root_.linear_isometry_equiv.pi_Lp_congr_left_single [decidable_eq ι] [decidable_eq ι'] (e : ι ≃ ι') (i : ι) (v : E) : linear_isometry_equiv.pi_Lp_congr_left p 𝕜 E e (pi.single i v) = pi.single (e i) v := begin funext x, simp [linear_isometry_equiv.pi_Lp_congr_left, linear_equiv.Pi_congr_left', equiv.Pi_congr_left', pi.single, function.update, equiv.symm_apply_eq], end @[simp] lemma equiv_zero : pi_Lp.equiv p β 0 = 0 := rfl @[simp] lemma equiv_symm_zero : (pi_Lp.equiv p β).symm 0 = 0 := rfl @[simp] lemma equiv_add : pi_Lp.equiv p β (x + y) = pi_Lp.equiv p β x + pi_Lp.equiv p β y := rfl @[simp] lemma equiv_symm_add : (pi_Lp.equiv p β).symm (x' + y') = (pi_Lp.equiv p β).symm x' + (pi_Lp.equiv p β).symm y' := rfl @[simp] lemma equiv_sub : pi_Lp.equiv p β (x - y) = pi_Lp.equiv p β x - pi_Lp.equiv p β y := rfl @[simp] lemma equiv_symm_sub : (pi_Lp.equiv p β).symm (x' - y') = (pi_Lp.equiv p β).symm x' - (pi_Lp.equiv p β).symm y' := rfl @[simp] lemma equiv_neg : pi_Lp.equiv p β (-x) = -pi_Lp.equiv p β x := rfl @[simp] lemma equiv_symm_neg : (pi_Lp.equiv p β).symm (-x') = -(pi_Lp.equiv p β).symm x' := rfl @[simp] lemma equiv_smul : pi_Lp.equiv p β (c • x) = c • pi_Lp.equiv p β x := rfl @[simp] lemma equiv_symm_smul : (pi_Lp.equiv p β).symm (c • x') = c • (pi_Lp.equiv p β).symm x' := rfl /-- When `p = ∞`, this lemma does not hold without the additional assumption `nonempty ι` because the left-hand side simplifies to `0`, while the right-hand side simplifies to `‖b‖₊`. See `pi_Lp.nnnorm_equiv_symm_const'` for a version which exchanges the hypothesis `p ≠ ∞` for `nonempty ι`. -/ lemma nnnorm_equiv_symm_const {β} [seminormed_add_comm_group β] (hp : p ≠ ∞) (b : β) : ‖(pi_Lp.equiv p (λ _ : ι, β)).symm (function.const _ b)‖₊= fintype.card ι ^ (1 / p).to_real * ‖b‖₊ := begin rcases p.dichotomy with (h | h), { exact false.elim (hp h) }, { have ne_zero : p.to_real ≠ 0 := (zero_lt_one.trans_le h).ne', simp_rw [nnnorm_eq_sum hp, equiv_symm_apply, function.const_apply, finset.sum_const, finset.card_univ, nsmul_eq_mul, nnreal.mul_rpow, ←nnreal.rpow_mul, mul_one_div_cancel ne_zero, nnreal.rpow_one, ennreal.to_real_div, ennreal.one_to_real], }, end /-- When `is_empty ι`, this lemma does not hold without the additional assumption `p ≠ ∞` because the left-hand side simplifies to `0`, while the right-hand side simplifies to `‖b‖₊`. See `pi_Lp.nnnorm_equiv_symm_const` for a version which exchanges the hypothesis `nonempty ι`. for `p ≠ ∞`. -/ lemma nnnorm_equiv_symm_const' {β} [seminormed_add_comm_group β] [nonempty ι] (b : β) : ‖(pi_Lp.equiv p (λ _ : ι, β)).symm (function.const _ b)‖₊= fintype.card ι ^ (1 / p).to_real * ‖b‖₊ := begin unfreezingI { rcases (em $ p = ∞) with (rfl | hp) }, { simp only [equiv_symm_apply, ennreal.div_top, ennreal.zero_to_real, nnreal.rpow_zero, one_mul, nnnorm_eq_csupr, function.const_apply, csupr_const], }, { exact nnnorm_equiv_symm_const hp b, }, end /-- When `p = ∞`, this lemma does not hold without the additional assumption `nonempty ι` because the left-hand side simplifies to `0`, while the right-hand side simplifies to `‖b‖₊`. See `pi_Lp.norm_equiv_symm_const'` for a version which exchanges the hypothesis `p ≠ ∞` for `nonempty ι`. -/ lemma norm_equiv_symm_const {β} [seminormed_add_comm_group β] (hp : p ≠ ∞) (b : β) : ‖(pi_Lp.equiv p (λ _ : ι, β)).symm (function.const _ b)‖ = fintype.card ι ^ (1 / p).to_real * ‖b‖ := (congr_arg coe $ nnnorm_equiv_symm_const hp b).trans $ by simp /-- When `is_empty ι`, this lemma does not hold without the additional assumption `p ≠ ∞` because the left-hand side simplifies to `0`, while the right-hand side simplifies to `‖b‖₊`. See `pi_Lp.norm_equiv_symm_const` for a version which exchanges the hypothesis `nonempty ι`. for `p ≠ ∞`. -/ lemma norm_equiv_symm_const' {β} [seminormed_add_comm_group β] [nonempty ι] (b : β) : ‖(pi_Lp.equiv p (λ _ : ι, β)).symm (function.const _ b)‖ = fintype.card ι ^ (1 / p).to_real * ‖b‖ := (congr_arg coe $ nnnorm_equiv_symm_const' b).trans $ by simp lemma nnnorm_equiv_symm_one {β} [seminormed_add_comm_group β] (hp : p ≠ ∞) [has_one β] : ‖(pi_Lp.equiv p (λ _ : ι, β)).symm 1‖₊ = fintype.card ι ^ (1 / p).to_real * ‖(1 : β)‖₊ := (nnnorm_equiv_symm_const hp (1 : β)).trans rfl lemma norm_equiv_symm_one {β} [seminormed_add_comm_group β] (hp : p ≠ ∞) [has_one β] : ‖(pi_Lp.equiv p (λ _ : ι, β)).symm 1‖ = fintype.card ι ^ (1 / p).to_real * ‖(1 : β)‖ := (norm_equiv_symm_const hp (1 : β)).trans rfl variables (𝕜 p) /-- `pi_Lp.equiv` as a linear map. -/ @[simps {fully_applied := ff}] protected def linear_equiv : pi_Lp p β ≃ₗ[𝕜] Π i, β i := { to_fun := pi_Lp.equiv _ _, inv_fun := (pi_Lp.equiv _ _).symm, ..linear_equiv.refl _ _} section basis variables (ι) /-- A version of `pi.basis_fun` for `pi_Lp`. -/ def basis_fun : basis ι 𝕜 (pi_Lp p (λ _, 𝕜)) := basis.of_equiv_fun (pi_Lp.linear_equiv p 𝕜 (λ _ : ι, 𝕜)) @[simp] lemma basis_fun_apply [decidable_eq ι] (i) : basis_fun p 𝕜 ι i = (pi_Lp.equiv p _).symm (pi.single i 1) := by simp_rw [basis_fun, basis.coe_of_equiv_fun, pi_Lp.linear_equiv_symm_apply, pi.single] @[simp] lemma basis_fun_repr (x : pi_Lp p (λ i : ι, 𝕜)) (i : ι) : (basis_fun p 𝕜 ι).repr x i = x i := rfl lemma basis_fun_eq_pi_basis_fun : basis_fun p 𝕜 ι = (pi.basis_fun 𝕜 ι).map (pi_Lp.linear_equiv p 𝕜 (λ _ : ι, 𝕜)).symm := rfl @[simp] lemma basis_fun_map : (basis_fun p 𝕜 ι).map (pi_Lp.linear_equiv p 𝕜 (λ _ : ι, 𝕜)) = pi.basis_fun 𝕜 ι := rfl open_locale matrix lemma basis_to_matrix_basis_fun_mul (b : basis ι 𝕜 (pi_Lp p (λ i : ι, 𝕜))) (A : matrix ι ι 𝕜) : b.to_matrix (pi_Lp.basis_fun _ _ _) ⬝ A = matrix.of (λ i j, b.repr ((pi_Lp.equiv _ _).symm (Aᵀ j)) i) := begin have := basis_to_matrix_basis_fun_mul (b.map (pi_Lp.linear_equiv _ 𝕜 _)) A, simp_rw [←pi_Lp.basis_fun_map p, basis.map_repr, linear_equiv.trans_apply, pi_Lp.linear_equiv_symm_apply, basis.to_matrix_map, function.comp, basis.map_apply, linear_equiv.symm_apply_apply] at this, exact this, end end basis end pi_Lp
b9b2901a071bc6c1aabc8d98fcea080c8ea9dc4c
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/algebra/big_operators/order.lean
bdc3e34a9782d9c384661d97b5fe8e38c1aecb04
[ "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
14,475
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 -/ import algebra.big_operators.basic /-! # Results about big operators with values in an ordered algebraic structure. Mostly monotonicity results for the `∑` operation. -/ universes u v w open_locale big_operators variables {α : Type u} {β : Type v} {γ : Type w} namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (∑ x in s, g x) ≤ ∑ x in s, f (g x) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [linear_ordered_field α] {f : β → α} {s : finset β} : abs (∑ x in s, f x) ≤ ∑ x in s, abs (f x) := le_sum_of_subadditive _ abs_zero abs_add s f lemma abs_prod [linear_ordered_comm_ring α] {f : β → α} {s : finset β} : abs (∏ x in s, f x) = ∏ x in s, abs (f x) := (abs_hom.to_monoid_hom : α →* α).map_prod _ _ section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → (∑ x in s, f x) ≤ (∑ x in s, g x) := begin classical, apply finset.induction_on s, exact (λ _, le_refl _), assume a s ha ih h, have : f a + (∑ x in s, f x) ≤ g a + (∑ x in s, g x), from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] end theorem card_le_mul_card_image_of_maps_to [decidable_eq γ] {f : α → γ} {s : finset α} {t : finset γ} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * t.card := calc s.card = (∑ a in t, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_fiberwise Hf ... ≤ (∑ _ in t, n) : sum_le_sum hn ... = _ : by simp [mul_comm] theorem card_le_mul_card_image [decidable_eq γ] {f : α → γ} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := card_le_mul_card_image_of_maps_to (λ x, mem_image_of_mem _) n hn theorem mul_card_image_le_card_of_maps_to [decidable_eq γ] {f : α → γ} {s : finset α} {t : finset γ} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, n ≤ (s.filter (λ x, f x = a)).card) : n * t.card ≤ s.card := calc n * t.card = (∑ _ in t, n) : by simp [mul_comm] ... ≤ (∑ a in t, (s.filter (λ x, f x = a)).card) : sum_le_sum hn ... = s.card : by rw ← card_eq_sum_card_fiberwise Hf theorem mul_card_image_le_card [decidable_eq γ] {f : α → γ} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, n ≤ (s.filter (λ x, f x = a)).card) : n * (s.image f).card ≤ s.card := mul_card_image_le_card_of_maps_to (λ x, mem_image_of_mem _) n hn lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ (∑ x in s, f x) := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : (∑ x in s, f x) ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := by classical; calc (∑ x in s₁, f x) ≤ (∑ x in s₂ \ s₁, f x) + (∑ x in s₁, f x) : le_add_of_nonneg_left $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = ∑ x in s₂ \ s₁ ∪ s₁, f x : (sum_union sdiff_disjoint).symm ... = (∑ x in s₂, f x) : by rw [sdiff_union_of_subset h] lemma sum_mono_set_of_nonneg (hf : ∀ x, 0 ≤ f x) : monotone (λ s, ∑ x in s, f x) := λ s₁ s₂ hs, sum_le_sum_of_subset_of_nonneg hs $ λ x _ _, hf x lemma sum_fiberwise_le_sum_of_sum_fiber_nonneg [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} {f : α → β} (h : ∀ y ∉ t, (0 : β) ≤ ∑ x in s.filter (λ x, g x = y), f x) : (∑ y in t, ∑ x in s.filter (λ x, g x = y), f x) ≤ ∑ x in s, f x := calc (∑ y in t, ∑ x in s.filter (λ x, g x = y), f x) ≤ (∑ y in t ∪ s.image g, ∑ x in s.filter (λ x, g x = y), f x) : sum_le_sum_of_subset_of_nonneg (subset_union_left _ _) $ λ y hyts, h y ... = ∑ x in s, f x : sum_fiberwise_of_maps_to (λ x hx, mem_union.2 $ or.inr $ mem_image_of_mem _ hx) _ lemma sum_le_sum_fiberwise_of_sum_fiber_nonpos [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} {f : α → β} (h : ∀ y ∉ t, (∑ x in s.filter (λ x, g x = y), f x) ≤ 0) : (∑ x in s, f x) ≤ ∑ y in t, ∑ x in s.filter (λ x, g x = y), f x := @sum_fiberwise_le_sum_of_sum_fiber_nonneg α (order_dual β) _ _ _ _ _ _ _ h lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) := begin classical, apply finset.induction_on s, exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩, assume a s ha ih H, have : ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] end lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ (∑ x in s, f x) := have ∑ x in {a}, f x ≤ (∑ x in s, f x), from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_add_comm_monoid section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid β] @[simp] lemma sum_eq_zero_iff : ∑ x in s, f x = 0 ↔ ∀ x ∈ s, f x = 0 := sum_eq_zero_iff_of_nonneg $ λ x hx, zero_le (f x) lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_mono_set (f : α → β) : monotone (λ s, ∑ x in s, f x) := λ s₁ s₂ hs, sum_le_sum_of_subset hs lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := by classical; calc (∑ x in s₁, f x) = ∑ x in s₁.filter (λx, f x = 0), f x + ∑ x in s₁.filter (λx, f x ≠ 0), f x : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ (∑ x in s₂, f x) : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_add_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_add_comm_monoid β] theorem sum_lt_sum (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) : (∑ x in s, f x) < (∑ x in s, g x) := begin classical, rcases Hlt with ⟨i, hi, hlt⟩, rw [← insert_erase hi, sum_insert (not_mem_erase _ _), sum_insert (not_mem_erase _ _)], exact add_lt_add_of_lt_of_le hlt (sum_le_sum $ λ j hj, Hle j $ mem_of_mem_erase hj) end lemma sum_lt_sum_of_nonempty (hs : s.nonempty) (Hlt : ∀ x ∈ s, f x < g x) : (∑ x in s, f x) < (∑ x in s, g x) := begin apply sum_lt_sum, { intros i hi, apply le_of_lt (Hlt i hi) }, cases hs with i hi, exact ⟨i, hi, Hlt i hi⟩, end lemma sum_lt_sum_of_subset [decidable_eq α] (h : s₁ ⊆ s₂) {i : α} (hi : i ∈ s₂ \ s₁) (hpos : 0 < f i) (hnonneg : ∀ j ∈ s₂ \ s₁, 0 ≤ f j) : (∑ x in s₁, f x) < (∑ x in s₂, f x) := calc (∑ x in s₁, f x) < (∑ x in insert i s₁, f x) : begin simp only [mem_sdiff] at hi, rw sum_insert hi.2, exact lt_add_of_pos_left (∑ x in s₁, f x) hpos, end ... ≤ (∑ x in s₂, f x) : begin simp only [mem_sdiff] at hi, apply sum_le_sum_of_subset_of_nonneg, { simp [finset.insert_subset, h, hi.1] }, { assume x hx h'x, apply hnonneg x, simp [mem_insert, not_or_distrib] at h'x, rw mem_sdiff, simp [hx, h'x] } end end ordered_cancel_comm_monoid section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_add_comm_monoid β] theorem exists_lt_of_sum_lt (Hlt : (∑ x in s, f x) < ∑ x in s, g x) : ∃ i ∈ s, f i < g i := begin contrapose! Hlt with Hle, exact sum_le_sum Hle end theorem exists_le_of_sum_le (hs : s.nonempty) (Hle : (∑ x in s, f x) ≤ ∑ x in s, g x) : ∃ i ∈ s, f i ≤ g i := begin contrapose! Hle with Hlt, rcases hs with ⟨i, hi⟩, exact sum_lt_sum (λ i hi, le_of_lt (Hlt i hi)) ⟨i, hi, Hlt i hi⟩ end lemma exists_pos_of_sum_zero_of_exists_nonzero (f : α → β) (h₁ : ∑ e in s, f e = 0) (h₂ : ∃ x ∈ s, f x ≠ 0) : ∃ x ∈ s, 0 < f x := begin contrapose! h₁, obtain ⟨x, m, x_nz⟩ : ∃ x ∈ s, f x ≠ 0 := h₂, apply ne_of_lt, calc ∑ e in s, f e < ∑ e in s, 0 : sum_lt_sum h₁ ⟨x, m, lt_of_le_of_ne (h₁ x m) x_nz⟩ ... = 0 : by rw [finset.sum_const, nsmul_zero], end end linear_ordered_cancel_comm_monoid section linear_ordered_comm_ring variables [linear_ordered_comm_ring β] open_locale classical /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ (∏ x in s, f x) := prod_induction f (λ x, 0 ≤ x) (λ _ _ ha hb, mul_nonneg ha hb) zero_le_one h0 /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < (∏ x in s, f x) := prod_induction f (λ x, 0 < x) (λ _ _ ha hb, mul_pos ha hb) zero_lt_one h0 /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : (∏ x in s, f x) ≤ (∏ x in s, g x) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end lemma prod_le_one {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ 1) : (∏ x in s, f x) ≤ 1 := begin convert ← prod_le_prod h0 h1, exact finset.prod_const_one end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `linear_ordered_comm_ring`. -/ lemma prod_add_prod_le {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) (hg : ∀ i ∈ s, 0 ≤ g i) (hh : ∀ i ∈ s, 0 ≤ h i) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin simp_rw [← mul_prod_diff_singleton hi], refine le_trans _ (mul_le_mul_of_nonneg_right h2i _), { rw [right_distrib], apply add_le_add; apply mul_le_mul_of_nonneg_left; try { apply prod_le_prod }; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption }, { apply prod_nonneg, simp only [and_imp, mem_sdiff, mem_singleton], intros j h1j h2j, refine le_trans (hg j h1j) (hgf j h1j h2j) } end end linear_ordered_comm_ring section canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring β] lemma prod_le_prod' {s : finset α} {f g : α → β} (h : ∀ i ∈ s, f i ≤ g i) : (∏ x in s, f x) ≤ (∏ x in s, g x) := begin classical, induction s using finset.induction with a s has ih h, { simp }, { rw [finset.prod_insert has, finset.prod_insert has], apply canonically_ordered_semiring.mul_le_mul, { exact h _ (finset.mem_insert_self a s) }, { exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } } end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `canonically_ordered_comm_semiring`. -/ lemma prod_add_prod_le' {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin classical, simp_rw [← mul_prod_diff_singleton hi], refine le_trans _ (canonically_ordered_semiring.mul_le_mul_right' h2i _), rw [right_distrib], apply add_le_add; apply canonically_ordered_semiring.mul_le_mul_left'; apply prod_le_prod'; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption end end canonically_ordered_comm_semiring end finset namespace with_top open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top [canonically_ordered_comm_semiring β] [nontrivial β] [decidable_eq β] {s : finset α} {f : α → with_top β} (h : ∀ a ∈ s, f a < ⊤) : (∏ x in s, f x) < ⊤ := prod_induction f (λ a, a < ⊤) (λ a b, mul_lt_top) (coe_lt_top 1) h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top [ordered_add_comm_monoid β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → (∑ x in s, f x) < ⊤ := λ h, sum_induction f (λ a, a < ⊤) (by { simp_rw add_lt_top, tauto }) zero_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} : (∑ x in s, f x) < ⊤ ↔ (∀a∈s, f a < ⊤) := iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} : (∑ x in s, f x) = ⊤ ↔ (∃a∈s, f a = ⊤) := begin rw ← not_iff_not, push_neg, simp only [← lt_top_iff_ne_top], exact sum_lt_top_iff end end with_top
990b035d83979adc19819f97f891b899144bb35b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/combinatorics/simple_graph/degree_sum.lean
b31e89db0ce7e420f86b24f5a03bf551c950f5a0
[]
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
6,781
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kyle Miller -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.combinatorics.simple_graph.basic import Mathlib.algebra.big_operators.basic import Mathlib.data.nat.parity import Mathlib.data.zmod.parity import Mathlib.tactic.omega.default import Mathlib.PostPort universes u l namespace Mathlib /-! # Degree-sum formula and handshaking lemma The degree-sum formula is that the sum of the degrees of the vertices in a finite graph is equal to twice the number of edges. The handshaking lemma, a corollary, is that the number of odd-degree vertices is even. ## Main definitions - A `dart` is a directed edge, consisting of an ordered pair of adjacent vertices, thought of as being a directed edge. - `simple_graph.sum_degrees_eq_twice_card_edges` is the degree-sum formula. - `simple_graph.even_card_odd_degree_vertices` is the handshaking lemma. - `simple_graph.odd_card_odd_degree_vertices_ne` is that the number of odd-degree vertices different from a given odd-degree vertex is odd. - `simple_graph.exists_ne_odd_degree_of_exists_odd_degree` is that the existence of an odd-degree vertex implies the existence of another one. ## Implementation notes We give a combinatorial proof by using the facts that (1) the map from darts to vertices is such that each fiber has cardinality the degree of the corresponding vertex and that (2) the map from darts to edges is 2-to-1. ## Tags simple graphs, sums, degree-sum formula, handshaking lemma -/ namespace simple_graph /-- A dart is a directed edge, consisting of an ordered pair of adjacent vertices. -/ structure dart {V : Type u} (G : simple_graph V) where fst : V snd : V is_adj : adj G fst snd protected instance dart.fintype {V : Type u} (G : simple_graph V) [fintype V] [DecidableRel (adj G)] : fintype (dart G) := fintype.of_equiv (sigma fun (v : V) => ↥(neighbor_set G v)) (equiv.mk (fun (s : sigma fun (v : V) => ↥(neighbor_set G v)) => dart.mk (sigma.fst s) ↑(sigma.snd s) sorry) (fun (d : dart G) => sigma.mk (dart.fst d) { val := dart.snd d, property := dart.is_adj d }) sorry sorry) /-- The edge associated to the dart. -/ def dart.edge {V : Type u} {G : simple_graph V} (d : dart G) : sym2 V := quotient.mk (dart.fst d, dart.snd d) @[simp] theorem dart.edge_mem {V : Type u} {G : simple_graph V} (d : dart G) : dart.edge d ∈ edge_set G := dart.is_adj d /-- The dart with reversed orientation from a given dart. -/ def dart.rev {V : Type u} {G : simple_graph V} (d : dart G) : dart G := dart.mk (dart.snd d) (dart.fst d) sorry @[simp] theorem dart.rev_edge {V : Type u} {G : simple_graph V} (d : dart G) : dart.edge (dart.rev d) = dart.edge d := sym2.eq_swap @[simp] theorem dart.rev_rev {V : Type u} {G : simple_graph V} (d : dart G) : dart.rev (dart.rev d) = d := dart.ext (dart.rev (dart.rev d)) d rfl rfl @[simp] theorem dart.rev_involutive {V : Type u} {G : simple_graph V} : function.involutive dart.rev := dart.rev_rev theorem dart.rev_ne {V : Type u} {G : simple_graph V} (d : dart G) : dart.rev d ≠ d := sorry theorem dart_edge_eq_iff {V : Type u} {G : simple_graph V} (d₁ : dart G) (d₂ : dart G) : dart.edge d₁ = dart.edge d₂ ↔ d₁ = d₂ ∨ d₁ = dart.rev d₂ := sorry /-- For a given vertex `v`, this is the bijective map from the neighbor set at `v` to the darts `d` with `d.fst = v`. --/ def dart_of_neighbor_set {V : Type u} (G : simple_graph V) (v : V) (w : ↥(neighbor_set G v)) : dart G := dart.mk v ↑w sorry theorem dart_of_neighbor_set_injective {V : Type u} (G : simple_graph V) (v : V) : function.injective (dart_of_neighbor_set G v) := fun (e₁ e₂ : ↥(neighbor_set G v)) (h : dart_of_neighbor_set G v e₁ = dart_of_neighbor_set G v e₂) => dart.mk.inj_arrow h fun (h₁ : v = v) (h₂ : ↑e₁ = ↑e₂) => subtype.ext h₂ protected instance dart.inhabited {V : Type u} (G : simple_graph V) [Inhabited V] [Inhabited ↥(neighbor_set G Inhabited.default)] : Inhabited (dart G) := { default := dart_of_neighbor_set G Inhabited.default Inhabited.default } theorem dart_fst_fiber {V : Type u} (G : simple_graph V) [fintype V] [DecidableRel (adj G)] [DecidableEq V] (v : V) : finset.filter (fun (d : dart G) => dart.fst d = v) finset.univ = finset.image (dart_of_neighbor_set G v) finset.univ := sorry theorem dart_fst_fiber_card_eq_degree {V : Type u} (G : simple_graph V) [fintype V] [DecidableRel (adj G)] [DecidableEq V] (v : V) : finset.card (finset.filter (fun (d : dart G) => dart.fst d = v) finset.univ) = degree G v := sorry theorem dart_card_eq_sum_degrees {V : Type u} (G : simple_graph V) [fintype V] [DecidableRel (adj G)] : fintype.card (dart G) = finset.sum finset.univ fun (v : V) => degree G v := sorry theorem dart.edge_fiber {V : Type u} {G : simple_graph V} [fintype V] [DecidableRel (adj G)] [DecidableEq V] (d : dart G) : finset.filter (fun (d' : dart G) => dart.edge d' = dart.edge d) finset.univ = insert d (singleton (dart.rev d)) := sorry theorem dart_edge_fiber_card {V : Type u} (G : simple_graph V) [fintype V] [DecidableRel (adj G)] [DecidableEq V] (e : sym2 V) (h : e ∈ edge_set G) : finset.card (finset.filter (fun (d : dart G) => dart.edge d = e) finset.univ) = bit0 1 := sorry theorem dart_card_eq_twice_card_edges {V : Type u} (G : simple_graph V) [fintype V] [DecidableRel (adj G)] [DecidableEq V] : fintype.card (dart G) = bit0 1 * finset.card (edge_finset G) := sorry /-- The degree-sum formula. This is also known as the handshaking lemma, which might more specifically refer to `simple_graph.even_card_odd_degree_vertices`. -/ theorem sum_degrees_eq_twice_card_edges {V : Type u} (G : simple_graph V) [fintype V] [DecidableRel (adj G)] [DecidableEq V] : (finset.sum finset.univ fun (v : V) => degree G v) = bit0 1 * finset.card (edge_finset G) := Eq.trans (Eq.symm (dart_card_eq_sum_degrees G)) (dart_card_eq_twice_card_edges G) /-- The handshaking lemma. See also `simple_graph.sum_degrees_eq_twice_card_edges`. -/ theorem even_card_odd_degree_vertices {V : Type u} (G : simple_graph V) [fintype V] [DecidableRel (adj G)] : even (finset.card (finset.filter (fun (v : V) => odd (degree G v)) finset.univ)) := sorry theorem odd_card_odd_degree_vertices_ne {V : Type u} (G : simple_graph V) [fintype V] [DecidableEq V] [DecidableRel (adj G)] (v : V) (h : odd (degree G v)) : odd (finset.card (finset.filter (fun (w : V) => w ≠ v ∧ odd (degree G w)) finset.univ)) := sorry theorem exists_ne_odd_degree_of_exists_odd_degree {V : Type u} (G : simple_graph V) [fintype V] [DecidableRel (adj G)] (v : V) (h : odd (degree G v)) : ∃ (w : V), w ≠ v ∧ odd (degree G w) := sorry
d3526963e1303e79a4c8c2e80156fb77d2a0492b
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/data/rat/basic.lean
267f956ee5a5cdf0484e4f0e09d799eff5254b02
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
24,929
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.nat.gcd data.pnat.basic data.int.sqrt data.equiv.encodable algebra.group algebra.ordered_group algebra.group_power algebra.ordered_field tactic.norm_cast tactic.lift /-! # Basics for the Rational Numbers ## Summary We define a rational number `q` as a structure `{ num, denom, pos, cop }`, where - `num` is the numerator of `q`, - `denom` is the denominator of `q`, - `pos` is a proof that `denom > 0`, and - `cop` is a proof `num` and `denom` are coprime. We then define the expected (discrete) field structure on `ℚ` and prove basic lemmas about it. Moreoever, we provide the expected casts from `ℕ` and `ℤ` into `ℚ`, i.e. `(↑n : ℚ) = n / 1`. ## Main Definitions - `rat` is the structure encoding `ℚ`. - `rat.mk n d` constructs a rational number `q = n / d` from `n d : ℤ`. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom -/ /-- `rat`, or `ℚ`, is the type of rational numbers. It is defined as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and `d` are coprime. This representation is preferred to the quotient because without periodic reduction, the numerator and denominator can grow exponentially (for example, adding 1/2 to itself repeatedly). -/ structure rat := mk' :: (num : ℤ) (denom : ℕ) (pos : denom > 0) (cop : num.nat_abs.coprime denom) notation `ℚ` := rat namespace rat protected def repr : ℚ → string | ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else _root_.repr n ++ "/" ++ _root_.repr d instance : has_repr ℚ := ⟨rat.repr⟩ instance : has_to_string ℚ := ⟨rat.repr⟩ meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩ instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // d > 0 ∧ n.nat_abs.coprime d}) ⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩ /-- Embed an integer as a rational number -/ def of_int (n : ℤ) : ℚ := ⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩ instance : has_zero ℚ := ⟨of_int 0⟩ instance : has_one ℚ := ⟨of_int 1⟩ instance : inhabited ℚ := ⟨0⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/ def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ := let n' := n.nat_abs, g := n'.gcd d in ⟨n / g, d / g, begin apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2, simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _) end, begin have : int.nat_abs (n / ↑g) = n' / g, { cases int.nat_abs_eq n with e e; rw e, { refl }, rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl }, exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) }, rw this, exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos) end⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we define `n / 0 = 0` by convention. -/ def mk_nat (n : ℤ) (d : ℕ) : ℚ := if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩ /-- Form the quotient `n / d` where `n d : ℤ`. -/ def mk : ℤ → ℤ → ℚ | n (int.of_nat d) := mk_nat n d | n -[1+ d] := mk_pnat (-n) d.succ_pnat local infix ` /. `:70 := mk theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d := by change n /. d with dite _ _ _; simp [ne_of_gt h] theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl @[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl @[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 := by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl @[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 := by by_cases n = 0; simp [*, mk_nat] @[simp] theorem zero_mk (n) : 0 /. n = 0 := by cases n; simp [mk] private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a := int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b @[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 := begin constructor; intro h; [skip, {subst a, simp}], have : ∀ {a b}, mk_pnat a b = 0 → a = 0, { intros a b e, cases b with b h, injection e with e, apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e }, cases b with b; simp [mk, mk_nat] at h, { simp [mt (congr_arg int.of_nat) b0] at h, exact this h }, { apply neg_inj, simp [this h] } end theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0), a /. b = c /. d ↔ a * d = c * b := suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b, begin intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hb], all_goals { cases d with d d; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hd], all_goals { rw this, try {refl} } }, { change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b, constructor; intro h; apply neg_inj; simpa [left_distrib, neg_add_eq_iff_eq_add, eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h }, { change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ, constructor; intro h; apply neg_inj; simpa [left_distrib, eq_comm] using h }, { change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ, simp [left_distrib] } end, begin intros, simp [mk_pnat], constructor; intro h, { cases h with ha hb, have ha, { have dv := @gcd_abs_dvd_left, have := int.eq_mul_of_div_eq_right dv ha, rw ← int.mul_div_assoc _ dv at this, exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have hb, { have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b, have := nat.eq_mul_of_div_eq_right dv hb, rw ← nat.mul_div_assoc _ dv at this, exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, { refine int.coe_nat_ne_zero.2 (ne_of_gt _), apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption }, apply eq_of_mul_eq_mul_right m0, simpa [mul_comm, mul_left_comm] using congr (congr_arg (*) ha.symm) (congr_arg coe hb) }, { suffices : ∀ a c, a * d = c * b → a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d, { cases this a.nat_abs c.nat_abs (by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂, have hs := congr_arg int.sign h, simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb), int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs, conv in a { rw ← int.sign_mul_nat_abs a }, conv in c { rw ← int.sign_mul_nat_abs c }, rw [int.mul_div_assoc, int.mul_div_assoc], exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩, all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } }, intros a c h, suffices bd : b / a.gcd b = d / c.gcd d, { refine ⟨_, bd⟩, apply nat.eq_of_mul_eq_mul_left hb, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd, ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] }, suffices : ∀ {a c : ℕ} (b>0) (d>0), a * d = c * b → b / a.gcd b ≤ d / c.gcd d, { exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) }, intros a c b hb d hd h, have gb0 := nat.gcd_pos_of_pos_right a hb, have gd0 := nat.gcd_pos_of_pos_right c hd, apply nat.le_of_dvd, apply (nat.le_div_iff_mul_le _ _ gd0).2, simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _), apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left, refine ⟨c / c.gcd d, _⟩, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)], apply congr_arg (/ c.gcd d), rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] } end @[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) : (a * c) /. (b * c) = a /. b := begin by_cases b0 : b = 0, { subst b0, simp }, apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc] end @[simp] theorem num_denom : ∀ {a : ℚ}, a.num /. a.denom = a | ⟨n, d, h, (c:_=1)⟩ := show mk_nat n d = _, by simp [mk_nat, ne_of_gt h, mk_pnat, c] theorem num_denom' {n d h c} : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom.symm theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' @[elab_as_eliminator] theorem {u} num_denom_cases_on {C : ℚ → Sort u} : ∀ (a : ℚ) (H : ∀ n d, d > 0 → (int.nat_abs n).coprime d → C (n /. d)), C a | ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c @[elab_as_eliminator] theorem {u} num_denom_cases_on' {C : ℚ → Sort u} (a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a := num_denom_cases_on a $ λ n d h c, H n d $ ne_of_gt h theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := begin cases e : a /. b with n d h c, rw [rat.num_denom', rat.mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.dvd_of_dvd_mul_right _), have := congr_arg int.nat_abs e, simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this] end theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b := begin by_cases b0 : b = 0, {simp [b0]}, cases e : a /. b with n d h c, rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _), rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp end protected def add : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_add ℚ := ⟨rat.add⟩ theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ) (fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂}, f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂) (f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0) (a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0) (H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d), f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) : f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc, rw fv, have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁), have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂), exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc)) end @[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b + c /. d = (a * d + c * b) /. (b * d) := begin apply lift_binop_eq rat.add; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, calc (n₁ * d₂ + n₂ * d₁) * (b * d) = (n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm] ... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂] ... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm] end protected def neg : ℚ → ℚ | ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩ instance : has_neg ℚ := ⟨rat.neg⟩ @[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b := begin by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, show rat.mk' _ _ _ _ = _, rw num_denom', have d0 := ne_of_gt (int.coe_nat_lt.2 h₁), apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha, simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁] end protected def mul : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_mul ℚ := ⟨rat.mul⟩ @[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : (a /. b) * (c /. d) = (a * c) /. (b * d) := begin apply lift_binop_eq rat.mul; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, cc end protected def inv : ℚ → ℚ | ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩ | ⟨0, d, h, c⟩ := 0 | ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩ instance : has_inv ℚ := ⟨rat.inv⟩ @[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a := begin by_cases a0 : a = 0, { subst a0, simp, refl }, by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha, refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _, { cases n with n; [cases n with n, skip], { refl }, { change int.of_nat n.succ with (n+1:ℕ), unfold rat.inv, rw num_denom' }, { unfold rat.inv, rw num_denom', refl } }, have n0 : n ≠ 0, { refine mt (λ (n0 : n = 0), _) a0, subst n0, simp at ha, exact (mk_eq_zero b0).1 ha }, have d0 := ne_of_gt (int.coe_nat_lt.2 h), have ha := (mk_eq b0 d0).1 ha, apply (mk_eq n0 a0).2, cc end variables (a b c : ℚ) protected theorem add_zero : a + 0 = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem zero_add : 0 + a = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem add_comm : a + b = b + a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂, mul_comm] protected theorem add_assoc : a + b + c = a + (b + c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm] protected theorem add_left_neg : -a + a = 0 := num_denom_cases_on' a $ λ n d h, by simp [h] protected theorem mul_one : a * 1 = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem one_mul : 1 * a = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem mul_comm : a * b = b * a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂, mul_comm] protected theorem mul_assoc : a * b * c = a * (b * c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm] protected theorem add_mul : (a + b) * c = a * c + b * c := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero]; refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _; simp [mul_add, mul_comm, mul_assoc, mul_left_comm] protected theorem mul_add : a * (b + c) = a * b + a * c := by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a] protected theorem zero_ne_one : 0 ≠ (1:ℚ) := mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 := num_denom_cases_on' a $ λ n d h a0, have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0, by simp [h, n0, mul_comm]; exact eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0) protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h) instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance instance : discrete_field ℚ := { zero := 0, add := rat.add, neg := rat.neg, one := 1, mul := rat.mul, inv := rat.inv, zero_add := rat.zero_add, add_zero := rat.add_zero, add_comm := rat.add_comm, add_assoc := rat.add_assoc, add_left_neg := rat.add_left_neg, mul_one := rat.mul_one, one_mul := rat.one_mul, mul_comm := rat.mul_comm, mul_assoc := rat.mul_assoc, left_distrib := rat.mul_add, right_distrib := rat.add_mul, zero_ne_one := rat.zero_ne_one, mul_inv_cancel := rat.mul_inv_cancel, inv_mul_cancel := rat.inv_mul_cancel, has_decidable_eq := rat.decidable_eq, inv_zero := rfl } /- Extra instances to short-circuit type class resolution -/ instance : field ℚ := by apply_instance instance : division_ring ℚ := by apply_instance instance : integral_domain ℚ := by apply_instance -- TODO(Mario): this instance slows down data.real.basic --instance : domain ℚ := by apply_instance instance : nonzero_comm_ring ℚ := by apply_instance instance : comm_ring ℚ := by apply_instance --instance : ring ℚ := by apply_instance instance : comm_semiring ℚ := by apply_instance instance : semiring ℚ := by apply_instance instance : add_comm_group ℚ := by apply_instance instance : add_group ℚ := by apply_instance instance : add_comm_monoid ℚ := by apply_instance instance : add_monoid ℚ := by apply_instance instance : add_left_cancel_semigroup ℚ := by apply_instance instance : add_right_cancel_semigroup ℚ := by apply_instance instance : add_comm_semigroup ℚ := by apply_instance instance : add_semigroup ℚ := by apply_instance instance : comm_monoid ℚ := by apply_instance instance : monoid ℚ := by apply_instance instance : comm_semigroup ℚ := by apply_instance instance : semigroup ℚ := by apply_instance theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b - c /. d = (a * d - c * b) /. (b * d) := by simp [b0, d0] @[simp] lemma denom_neg_eq_denom : ∀ q : ℚ, (-q).denom = q.denom | ⟨_, d, _, _⟩ := rfl @[simp] lemma num_neg_eq_neg_num : ∀ q : ℚ, (-q).num = -(q.num) | ⟨n, _, _, _⟩ := rfl @[simp] lemma num_zero : rat.num 0 = 0 := rfl lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 := have q = q.num /. q.denom, from num_denom.symm, by simpa [hq] lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 := ⟨λ _, by simp *, zero_of_num_zero⟩ lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 := assume : q.num = 0, h $ zero_of_num_zero this @[simp] lemma num_one : (1 : ℚ).num = 1 := rfl @[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 := ne_of_gt q.pos lemma eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.denom = q.num * p.denom := begin conv_lhs { rw [←(@num_denom p), ←(@num_denom q)] }, exact rat.mk_eq (by exact_mod_cast p.denom_ne_zero) (by exact_mod_cast q.denom_ne_zero) end lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 := assume : n = 0, hq $ by simpa [this] using hqnd lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 := assume : d = 0, hq $ by simpa [this] using hqnd lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 := assume : n /. d = 0, h $ (mk_eq_zero hd).1 this lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) := have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa, have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa, suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom), by simpa using this, by simp [mul_def hq' hr', -num_denom] lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) := if hr : r.num = 0 then have hr' : r = 0, from zero_of_num_zero hr, by simp * else calc q / r = q * r⁻¹ : div_eq_mul_inv ... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by simp ... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def ... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.denom := have hq : q ≠ 0, from assume : q = 0, hn $ (rat.mk_eq_zero hd).1 (by cc), have q.num /. q.denom = n /. d, by rwa [num_denom], have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this, begin existsi n / q.num, have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end, split, { rw int.div_mul_cancel hqdn }, { apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left, {apply rat.num_ne_zero_of_ne_zero hq}, {simp [rat.denom_ne_zero]}, repeat {assumption} } end theorem mk_pnat_num (n : ℤ) (d : ℕ+) : (mk_pnat n d).num = n / nat.gcd n.nat_abs d := by cases d; refl theorem mk_pnat_denom (n : ℤ) (d : ℕ+) : (mk_pnat n d).denom = d / nat.gcd n.nat_abs d := by cases d; refl theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num = (q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom = (q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num := by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom := by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) lemma add_num_denom (q r : ℚ) : q + r = ((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) := have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3, have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3, by conv_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] }; simp [mul_comm] section casts theorem coe_int_eq_mk : ∀ (z : ℤ), ↑z = z /. 1 | (n : ℕ) := show (n:ℚ) = n /. 1, by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl] | -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin induction n with n IH, {refl}, show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1, rw [neg_add, IH], simpa [show -1 = (-1) /. 1, from rfl] end theorem mk_eq_div (n d : ℤ) : n /. d = ((n : ℚ) / d) := begin by_cases d0 : d = 0, {simp [d0, div_zero]}, simp [division_def, coe_int_eq_mk, mul_def one_ne_zero d0] end theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z := (coe_int_eq_mk z).trans (of_int_eq_mk z).symm @[simp, elim_cast] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n := by rw coe_int_eq_of_int; refl @[simp, elim_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 := by rw coe_int_eq_of_int; refl lemma coe_int_num_of_denom_eq_one {q : ℚ} (hq : q.denom = 1) : ↑(q.num) = q := by { conv_rhs { rw [←(@num_denom q), hq] }, rw [coe_int_eq_mk], refl } instance : can_lift ℚ ℤ := ⟨coe, λ q, q.denom = 1, λ q hq, ⟨q.num, coe_int_num_of_denom_eq_one hq⟩⟩ theorem coe_nat_eq_mk (n : ℕ) : ↑n = n /. 1 := by rw [← int.cast_coe_nat, coe_int_eq_mk] @[simp, elim_cast] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n := by rw [← int.cast_coe_nat, coe_int_num] @[simp, elim_cast] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 := by rw [← int.cast_coe_nat, coe_int_denom] end casts lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num := by { conv_lhs { rw ←(@num_denom q) }, cases q, simp [div_num_denom] } @[simp] lemma mul_own_denom_eq_num {q : ℚ} : q * q.denom = q.num := begin suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by { conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] }, have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos), rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)] end end rat
3924d9dd87bf45ff6da58372a08c2c0a9fd82ee0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/continued_fractions/terminated_stable.lean
86e0c340ce6f0d0762356cb36c34e8c3d875c565
[ "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,829
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 algebra.continued_fractions.translations /-! # Stabilisation of gcf Computations Under Termination > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Summary We show that the continuants and convergents of a gcf stabilise once the gcf terminates. -/ namespace generalized_continued_fraction open stream.seq as seq variables {K : Type*} {g : generalized_continued_fraction K} {n m : ℕ} /-- If a gcf terminated at position `n`, it also terminated at `m ≥ n`.-/ lemma terminated_stable (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.terminated_at m := g.s.terminated_stable n_le_m terminated_at_n variable [division_ring K] lemma continuants_aux_stable_step_of_terminated (terminated_at_n : g.terminated_at n) : g.continuants_aux (n + 2) = g.continuants_aux (n + 1) := by { rw [terminated_at_iff_s_none] at terminated_at_n, simp only [terminated_at_n, continuants_aux] } lemma continuants_aux_stable_of_terminated (n_lt_m : n < m) (terminated_at_n : g.terminated_at n) : g.continuants_aux m = g.continuants_aux (n + 1) := begin refine nat.le_induction rfl (λ k hnk hk, _) _ n_lt_m, rcases nat.exists_eq_add_of_lt hnk with ⟨k, rfl⟩, refine (continuants_aux_stable_step_of_terminated _).trans hk, exact terminated_stable (nat.le_add_right _ _) terminated_at_n end lemma convergents'_aux_stable_step_of_terminated {s : seq $ pair K} (terminated_at_n : s.terminated_at n) : convergents'_aux s (n + 1) = convergents'_aux s n := begin change s.nth n = none at terminated_at_n, induction n with n IH generalizing s, case nat.zero { simp only [convergents'_aux, terminated_at_n, seq.head] }, case nat.succ { cases s_head_eq : s.head with gp_head, case option.none { simp only [convergents'_aux, s_head_eq] }, case option.some { have : s.tail.terminated_at n, by simp only [seq.terminated_at, s.nth_tail, terminated_at_n], simp only [convergents'_aux, s_head_eq, (IH this)] } } end lemma convergents'_aux_stable_of_terminated {s : seq $ pair K} (n_le_m : n ≤ m) (terminated_at_n : s.terminated_at n) : convergents'_aux s m = convergents'_aux s n := begin induction n_le_m with m n_le_m IH, { refl }, { refine (convergents'_aux_stable_step_of_terminated _).trans IH, exact s.terminated_stable n_le_m terminated_at_n } end lemma continuants_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.continuants m = g.continuants n := by simp only [nth_cont_eq_succ_nth_cont_aux, (continuants_aux_stable_of_terminated (nat.pred_le_iff.elim_left n_le_m) terminated_at_n)] lemma numerators_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.numerators m = g.numerators n := by simp only [num_eq_conts_a, (continuants_stable_of_terminated n_le_m terminated_at_n)] lemma denominators_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.denominators m = g.denominators n := by simp only [denom_eq_conts_b, (continuants_stable_of_terminated n_le_m terminated_at_n)] lemma convergents_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.convergents m = g.convergents n := by simp only [convergents, (denominators_stable_of_terminated n_le_m terminated_at_n), (numerators_stable_of_terminated n_le_m terminated_at_n)] lemma convergents'_stable_of_terminated (n_le_m : n ≤ m) (terminated_at_n : g.terminated_at n) : g.convergents' m = g.convergents' n := by simp only [convergents', (convergents'_aux_stable_of_terminated n_le_m terminated_at_n)] end generalized_continued_fraction
3d8f217c5a46a77504d4ef121f7ddd550b8cb580
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/function/l1_space.lean
eb5066f28b7734655b963007901b23bfa7d15c15
[ "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
50,441
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.function.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, ∥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*} {m : measurable_space α} {μ ν : measure α} [measurable_space δ] 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, ∥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 {f g h : α → β} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) (hh : ae_strongly_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 : α, ∥(0 : β)∥₊ ∂μ = 0 := by simp lemma lintegral_nnnorm_add {f : α → β} {g : α → γ} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) : ∫⁻ a, ∥f a∥₊ + ∥g a∥₊ ∂μ = ∫⁻ a, ∥f a∥₊ ∂μ + ∫⁻ a, ∥g a∥₊ ∂μ := lintegral_add' hf.ennnorm hg.ennnorm lemma lintegral_nnnorm_neg {f : α → β} : ∫⁻ a, ∥(-f) a∥₊ ∂μ = ∫⁻ a, ∥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 {m : measurable_space α} (f : α → β) (μ : measure α . volume_tac) : Prop := ∫⁻ a, ∥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 < ∞ := by simp [has_finite_integral, lintegral_const, lt_top_iff_ne_top, or_iff_not_imp_left] lemma has_finite_integral_const [is_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 [is_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_rfl) 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_rfl 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_rfl @[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.ne end @[simp] lemma has_finite_integral_zero_measure {m : measurable_space α} (f : α → β) : has_finite_integral f (0 : measure α) := 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, (∥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) lemma has_finite_integral_to_real_of_lintegral_ne_top {f : α → ℝ≥0∞} (hf : ∫⁻ x, f x ∂μ ≠ ∞) : has_finite_integral (λ x, (f x).to_real) μ := begin have : ∀ x, (∥(f x).to_real∥₊ : ℝ≥0∞) = @coe ℝ≥0 ℝ≥0∞ _ (⟨(f x).to_real, ennreal.to_real_nonneg⟩ : ℝ≥0), { intro x, rw real.nnnorm_of_nonneg }, simp_rw [has_finite_integral, this], refine lt_of_le_of_lt (lintegral_mono (λ x, _)) (lt_top_iff_ne_top.2 hf), by_cases hfx : f x = ∞, { simp [hfx] }, { lift f x to ℝ≥0 using hfx with fx, simp [← h] } end lemma is_finite_measure_with_density_of_real {f : α → ℝ} (hfi : has_finite_integral f μ) : is_finite_measure (μ.with_density (λ x, ennreal.of_real $ f x)) := begin refine is_finite_measure_with_density ((lintegral_mono $ λ x, _).trans_lt hfi).ne, exact real.of_real_le_ennnorm (f x) end 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 {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (F_measurable : ∀ n, ae_strongly_measurable (F n) μ) (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) := have f_measurable : ae_strongly_measurable f μ := ae_strongly_measurable_of_tendsto_ae _ F_measurable h_lim, 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] with 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.ae_measurable }, -- 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_ne_top coe_ne_top bound_has_finite_integral.ne }, filter_upwards [h_bound 0] with _ h using 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, abs_eq_max_neg, le_total] 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 : α), ∥c • f a∥₊ ∂μ = ∫⁻ (a : α), (∥c∥₊) * ∥f a∥₊ ∂μ : by simp only [nnnorm_smul, ennreal.coe_mul] ... < ∞ : begin rw lintegral_const_mul', exacts [mul_lt_top coe_ne_top hfi.ne, 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 {α} {m : measurable_space α} (f : α → β) (μ : measure α . volume_tac) : Prop := ae_strongly_measurable f μ ∧ has_finite_integral f μ 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 integrable.ae_strongly_measurable {f : α → β} (hf : integrable f μ) : ae_strongly_measurable f μ := hf.1 lemma integrable.ae_measurable [measurable_space β] [borel_space β] {f : α → β} (hf : integrable f μ) : ae_measurable f μ := hf.ae_strongly_measurable.ae_measurable 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_strongly_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_strongly_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_strongly_measurable g μ) (h : ∀ᵐ a ∂μ, ∥f a∥ = ∥g a∥) : integrable g μ := ⟨hg, hf.has_finite_integral.congr' h⟩ lemma integrable_congr' {f : α → β} {g : α → γ} (hf : ae_strongly_measurable f μ) (hg : ae_strongly_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_strongly_measurable (λ (x : α), c) μ := ae_strongly_measurable_const, rw [integrable, and_iff_right this, has_finite_integral_const_iff] end lemma integrable_const [is_finite_measure μ] (c : β) : integrable (λ x : α, c) μ := integrable_const_iff.2 $ or.inr $ measure_lt_top _ _ lemma mem_ℒp.integrable_norm_rpow {f : α → β} {p : ℝ≥0∞} (hf : mem_ℒp f p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) : integrable (λ (x : α), ∥f x∥ ^ p.to_real) μ := begin rw ← mem_ℒp_one_iff_integrable, exact hf.norm_rpow hp_ne_zero hp_ne_top, end lemma mem_ℒp.integrable_norm_rpow' [is_finite_measure μ] {f : α → β} {p : ℝ≥0∞} (hf : mem_ℒp f p μ) : integrable (λ (x : α), ∥f x∥ ^ p.to_real) μ := begin by_cases h_zero : p = 0, { simp [h_zero, integrable_const] }, by_cases h_top : p = ∞, { simp [h_top, integrable_const] }, exact hf.integrable_norm_rpow h_zero h_top end lemma integrable.mono_measure {f : α → β} (h : integrable f ν) (hμ : μ ≤ ν) : integrable f μ := ⟨h.ae_strongly_measurable.mono_measure hμ, h.has_finite_integral.mono_measure hμ⟩ lemma integrable.of_measure_le_smul {μ' : measure α} (c : ℝ≥0∞) (hc : c ≠ ∞) (hμ'_le : μ' ≤ c • μ) {f : α → β} (hf : integrable f μ) : integrable f μ' := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.of_measure_le_smul c hc hμ'_le, } lemma integrable.add_measure {f : α → β} (hμ : integrable f μ) (hν : integrable f ν) : integrable f (μ + ν) := begin simp_rw ← mem_ℒp_one_iff_integrable at hμ hν ⊢, refine ⟨hμ.ae_strongly_measurable.add_measure hν.ae_strongly_measurable, _⟩, rw [snorm_one_add_measure, ennreal.add_lt_top], exact ⟨hμ.snorm_lt_top, hν.snorm_lt_top⟩, end lemma integrable.left_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f μ := by { rw ← mem_ℒp_one_iff_integrable at h ⊢, exact h.left_of_add_measure, } lemma integrable.right_of_add_measure {f : α → β} (h : integrable f (μ + ν)) : integrable f ν := by { rw ← mem_ℒp_one_iff_integrable at h ⊢, exact h.right_of_add_measure, } @[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⟩ @[simp] lemma integrable_zero_measure {m : measurable_space α} {f : α → β} : integrable f (0 : measure α) := ⟨ae_measurable_zero_measure f, has_finite_integral_zero_measure f⟩ theorem integrable_finset_sum_measure {ι} {m : measurable_space α} {f : α → β} {μ : ι → measure α} {s : finset ι} : integrable f (∑ i in s, μ i) ↔ ∀ i ∈ s, integrable f (μ i) := by induction s using finset.induction_on; simp [*] lemma integrable.smul_measure {f : α → β} (h : integrable f μ) {c : ℝ≥0∞} (hc : c ≠ ∞) : integrable f (c • μ) := by { rw ← mem_ℒp_one_iff_integrable at h ⊢, exact h.smul_measure hc, } lemma integrable_smul_measure {f : α → β} {c : ℝ≥0∞} (h₁ : c ≠ 0) (h₂ : c ≠ ∞) : integrable f (c • μ) ↔ integrable f μ := ⟨λ h, by simpa only [smul_smul, ennreal.inv_mul_cancel h₁ h₂, one_smul] using h.smul_measure (ennreal.inv_ne_top.2 h₁), λ h, h.smul_measure h₂⟩ lemma integrable.to_average {f : α → β} (h : integrable f μ) : integrable f ((μ univ)⁻¹ • μ) := begin rcases eq_or_ne μ 0 with rfl|hne, { rwa smul_zero }, { apply h.smul_measure, simpa } end lemma integrable_average [is_finite_measure μ] {f : α → β} : integrable f ((μ univ)⁻¹ • μ) ↔ integrable f μ := (eq_or_ne μ 0).by_cases (λ h, by simp [h]) $ λ h, integrable_smul_measure (ennreal.inv_ne_zero.2 $ measure_ne_top _ _) (ennreal.inv_ne_top.2 $ mt measure.measure_univ_eq_zero.1 h) lemma integrable_map_measure {f : α → δ} {g : δ → β} (hg : ae_strongly_measurable g (measure.map f μ)) (hf : ae_measurable f μ) : integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ := by { simp_rw ← mem_ℒp_one_iff_integrable, exact mem_ℒp_map_measure_iff hg hf, } lemma integrable.comp_ae_measurable {f : α → δ} {g : δ → β} (hg : integrable g (measure.map f μ)) (hf : ae_measurable f μ) : integrable (g ∘ f) μ := (integrable_map_measure hg.ae_strongly_measurable hf).mp hg lemma integrable.comp_measurable {f : α → δ} {g : δ → β} (hg : integrable g (measure.map f μ)) (hf : measurable f) : integrable (g ∘ f) μ := hg.comp_ae_measurable hf.ae_measurable lemma _root_.measurable_embedding.integrable_map_iff {f : α → δ} (hf : measurable_embedding f) {g : δ → β} : integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ := by { simp_rw ← mem_ℒp_one_iff_integrable, exact hf.mem_ℒp_map_measure_iff, } lemma integrable_map_equiv (f : α ≃ᵐ δ) (g : δ → β) : integrable g (measure.map f μ) ↔ integrable (g ∘ f) μ := by { simp_rw ← mem_ℒp_one_iff_integrable, exact f.mem_ℒp_map_measure_iff, } lemma measure_preserving.integrable_comp {ν : measure δ} {g : δ → β} {f : α → δ} (hf : measure_preserving f μ ν) (hg : ae_strongly_measurable g ν) : integrable (g ∘ f) μ ↔ integrable g ν := by { rw ← hf.map_eq at hg ⊢, exact (integrable_map_measure hg hf.measurable.ae_measurable).symm } lemma measure_preserving.integrable_comp_emb {f : α → δ} {ν} (h₁ : measure_preserving f μ ν) (h₂ : measurable_embedding f) {g : δ → β} : integrable (g ∘ f) μ ↔ integrable g ν := h₁.map_eq ▸ iff.symm h₂.integrable_map_iff lemma lintegral_edist_lt_top {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : ∫⁻ a, edist (f a) (g a) ∂μ < ∞ := lt_of_le_of_lt (lintegral_edist_triangle hf.ae_strongly_measurable hg.ae_strongly_measurable (ae_strongly_measurable_const : ae_strongly_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, ae_strongly_measurable_const] variables {α β μ} lemma integrable.add' {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f + g) μ := calc ∫⁻ a, ∥f a + g a∥₊ ∂μ ≤ ∫⁻ a, ∥f a∥₊ + ∥g a∥₊ ∂μ : lintegral_mono (λ a, by exact_mod_cast nnnorm_add_le _ _) ... = _ : lintegral_nnnorm_add hf.ae_strongly_measurable hg.ae_strongly_measurable ... < ∞ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩ lemma integrable.add {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : integrable (f + g) μ := ⟨hf.ae_strongly_measurable.add hg.ae_strongly_measurable, hf.add' hg⟩ lemma integrable_finset_sum' {ι} (s : finset ι) {f : ι → α → β} (hf : ∀ i ∈ s, integrable (f i) μ) : integrable (∑ i in s, f i) μ := finset.sum_induction f (λ g, integrable g μ) (λ _ _, integrable.add) (integrable_zero _ _ _) hf lemma integrable_finset_sum {ι} (s : finset ι) {f : ι → α → β} (hf : ∀ i ∈ s, integrable (f i) μ) : integrable (λ a, ∑ i in s, f i a) μ := by simpa only [← finset.sum_apply] using integrable_finset_sum' s hf lemma integrable.neg {f : α → β} (hf : integrable f μ) : integrable (-f) μ := ⟨hf.ae_strongly_measurable.neg, hf.has_finite_integral.neg⟩ @[simp] lemma integrable_neg_iff {f : α → β} : integrable (-f) μ ↔ integrable f μ := ⟨λ h, neg_neg f ▸ h.neg, integrable.neg⟩ lemma integrable.sub' {f g : α → β} (hf : integrable f μ) (hg : integrable g μ) : has_finite_integral (f - g) μ := calc ∫⁻ a, ∥f a - g a∥₊ ∂μ ≤ ∫⁻ a, ∥f a∥₊ + ∥-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_strongly_measurable hg.ae_strongly_measurable } ... < ∞ : add_lt_top.2 ⟨hf.has_finite_integral, hg.has_finite_integral⟩ lemma integrable.sub {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 {f : α → β} (hf : integrable f μ) : integrable (λa, ∥f a∥) μ := ⟨hf.ae_strongly_measurable.norm, hf.has_finite_integral.norm⟩ lemma integrable.abs {f : α → ℝ} (hf : integrable f μ) : integrable (λa, |f a|) μ := by simpa [← real.norm_eq_abs] using hf.norm lemma integrable_norm_iff {f : α → β} (hf : ae_strongly_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 {f₀ f₁ : α → β} {g : α → ℝ} (hf₁_m : ae_strongly_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 {f : α → β} {g : α → γ} (hf : integrable f μ) (hg : integrable g μ) : integrable (λ x, (f x, g x)) μ := ⟨hf.ae_strongly_measurable.prod_mk hg.ae_strongly_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.integrable {q : ℝ≥0∞} (hq1 : 1 ≤ q) {f : α → β} [is_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 {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_strongly_measurable.ae_measurable .real_to_nnreal.coe_nnreal_real.ae_strongly_measurable, _⟩, 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 lemma of_real_to_real_ae_eq {f : α → ℝ≥0∞} (hf : ∀ᵐ x ∂μ, f x < ∞) : (λ x, ennreal.of_real (f x).to_real) =ᵐ[μ] f := begin filter_upwards [hf], assume x hx, simp only [hx.ne, of_real_to_real, ne.def, not_false_iff], end lemma coe_to_nnreal_ae_eq {f : α → ℝ≥0∞} (hf : ∀ᵐ x ∂μ, f x < ∞) : (λ x, ((f x).to_nnreal : ℝ≥0∞)) =ᵐ[μ] f := begin filter_upwards [hf], assume x hx, simp only [hx.ne, ne.def, not_false_iff, coe_to_nnreal], end section variables {E : Type*} [normed_group E] [normed_space ℝ E] lemma integrable_with_density_iff_integrable_coe_smul {f : α → ℝ≥0} (hf : measurable f) {g : α → E} : integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, (f x : ℝ) • g x) μ := begin by_cases H : ae_strongly_measurable (λ (x : α), (f x : ℝ) • g x) μ, { simp only [integrable, ae_strongly_measurable_with_density_iff hf, has_finite_integral, H, true_and], rw lintegral_with_density_eq_lintegral_mul₀' hf.coe_nnreal_ennreal.ae_measurable, { congr', ext1 x, simp only [nnnorm_smul, nnreal.nnnorm_eq, coe_mul, pi.mul_apply] }, { rw ae_measurable_with_density_ennreal_iff hf, convert H.ennnorm, ext1 x, simp only [nnnorm_smul, nnreal.nnnorm_eq, coe_mul] } }, { simp only [integrable, ae_strongly_measurable_with_density_iff hf, H, false_and] } end lemma integrable_with_density_iff_integrable_smul {f : α → ℝ≥0} (hf : measurable f) {g : α → E} : integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, f x • g x) μ := integrable_with_density_iff_integrable_coe_smul hf lemma integrable_with_density_iff_integrable_smul' {f : α → ℝ≥0∞} (hf : measurable f) (hflt : ∀ᵐ x ∂μ, f x < ∞) {g : α → E} : integrable g (μ.with_density f) ↔ integrable (λ x, (f x).to_real • g x) μ := begin rw [← with_density_congr_ae (coe_to_nnreal_ae_eq hflt), integrable_with_density_iff_integrable_smul], { refl }, { exact hf.ennreal_to_nnreal }, end lemma integrable_with_density_iff_integrable_coe_smul₀ {f : α → ℝ≥0} (hf : ae_measurable f μ) {g : α → E} : integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, (f x : ℝ) • g x) μ := calc integrable g (μ.with_density (λ x, f x)) ↔ integrable g (μ.with_density (λ x, hf.mk f x)) : begin suffices : (λ x, (f x : ℝ≥0∞)) =ᵐ[μ] (λ x, hf.mk f x), by rw with_density_congr_ae this, filter_upwards [hf.ae_eq_mk] with x hx, simp [hx], end ... ↔ integrable (λ x, (hf.mk f x : ℝ) • g x) μ : integrable_with_density_iff_integrable_coe_smul hf.measurable_mk ... ↔ integrable (λ x, (f x : ℝ) • g x) μ : begin apply integrable_congr, filter_upwards [hf.ae_eq_mk] with x hx, simp [hx], end lemma integrable_with_density_iff_integrable_smul₀ {f : α → ℝ≥0} (hf : ae_measurable f μ) {g : α → E} : integrable g (μ.with_density (λ x, f x)) ↔ integrable (λ x, f x • g x) μ := integrable_with_density_iff_integrable_coe_smul₀ hf end lemma integrable_with_density_iff {f : α → ℝ≥0∞} (hf : measurable f) (hflt : ∀ᵐ x ∂μ, f x < ∞) {g : α → ℝ} : integrable g (μ.with_density f) ↔ integrable (λ x, g x * (f x).to_real) μ := begin have : (λ x, g x * (f x).to_real) = (λ x, (f x).to_real • g x), by simp [mul_comm], rw this, exact integrable_with_density_iff_integrable_smul' hf hflt, end section variables {E : Type*} [normed_group E] [normed_space ℝ E] lemma mem_ℒ1_smul_of_L1_with_density {f : α → ℝ≥0} (f_meas : measurable f) (u : Lp E 1 (μ.with_density (λ x, f x))) : mem_ℒp (λ x, f x • u x) 1 μ := mem_ℒp_one_iff_integrable.2 $ (integrable_with_density_iff_integrable_smul f_meas).1 $ mem_ℒp_one_iff_integrable.1 (Lp.mem_ℒp u) variable (μ) /-- The map `u ↦ f • u` is an isometry between the `L^1` spaces for `μ.with_density f` and `μ`. -/ noncomputable def with_density_smul_li {f : α → ℝ≥0} (f_meas : measurable f) : Lp E 1 (μ.with_density (λ x, f x)) →ₗᵢ[ℝ] Lp E 1 μ := { to_fun := λ u, (mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp _, map_add' := begin assume u v, ext1, filter_upwards [(mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp, (mem_ℒ1_smul_of_L1_with_density f_meas v).coe_fn_to_Lp, (mem_ℒ1_smul_of_L1_with_density f_meas (u + v)).coe_fn_to_Lp, Lp.coe_fn_add ((mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp _) ((mem_ℒ1_smul_of_L1_with_density f_meas v).to_Lp _), (ae_with_density_iff f_meas.coe_nnreal_ennreal).1 (Lp.coe_fn_add u v)], assume x hu hv huv h' h'', rw [huv, h', pi.add_apply, hu, hv], rcases eq_or_ne (f x) 0 with hx|hx, { simp only [hx, zero_smul, add_zero] }, { rw [h'' _, pi.add_apply, smul_add], simpa only [ne.def, ennreal.coe_eq_zero] using hx } end, map_smul' := begin assume r u, ext1, filter_upwards [(ae_with_density_iff f_meas.coe_nnreal_ennreal).1 (Lp.coe_fn_smul r u), (mem_ℒ1_smul_of_L1_with_density f_meas (r • u)).coe_fn_to_Lp, Lp.coe_fn_smul r ((mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp _), (mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp], assume x h h' h'' h''', rw [ring_hom.id_apply, h', h'', pi.smul_apply, h'''], rcases eq_or_ne (f x) 0 with hx|hx, { simp only [hx, zero_smul, smul_zero] }, { rw [h _, smul_comm, pi.smul_apply], simpa only [ne.def, ennreal.coe_eq_zero] using hx } end, norm_map' := begin assume u, simp only [snorm, linear_map.coe_mk, Lp.norm_to_Lp, one_ne_zero, ennreal.one_ne_top, ennreal.one_to_real, if_false, snorm', ennreal.rpow_one, _root_.div_one, Lp.norm_def], rw lintegral_with_density_eq_lintegral_mul_non_measurable _ f_meas.coe_nnreal_ennreal (filter.eventually_of_forall (λ x, ennreal.coe_lt_top)), congr' 1, apply lintegral_congr_ae, filter_upwards [(mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp] with x hx, rw [hx, pi.mul_apply], change ↑∥(f x : ℝ) • u x∥₊ = ↑(f x) * ↑∥u x∥₊, simp only [nnnorm_smul, nnreal.nnnorm_eq, ennreal.coe_mul], end } @[simp] lemma with_density_smul_li_apply {f : α → ℝ≥0} (f_meas : measurable f) (u : Lp E 1 (μ.with_density (λ x, f x))) : with_density_smul_li μ f_meas u = (mem_ℒ1_smul_of_L1_with_density f_meas u).to_Lp (λ x, f x • u x) := rfl end lemma mem_ℒ1_to_real_of_lintegral_ne_top {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) : mem_ℒp (λ x, (f x).to_real) 1 μ := begin rw [mem_ℒp, snorm_one_eq_lintegral_nnnorm], exact ⟨(ae_measurable.ennreal_to_real hfm).ae_strongly_measurable, has_finite_integral_to_real_of_lintegral_ne_top hfi⟩ end lemma integrable_to_real_of_lintegral_ne_top {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hfi : ∫⁻ x, f x ∂μ ≠ ∞) : integrable (λ x, (f x).to_real) μ := mem_ℒp_one_iff_integrable.1 $ mem_ℒ1_to_real_of_lintegral_ne_top hfm hfi section pos_part /-! ### Lemmas used for defining the positive part of a `L¹` function -/ lemma integrable.pos_part {f : α → ℝ} (hf : integrable f μ) : integrable (λ a, max (f a) 0) μ := ⟨(hf.ae_strongly_measurable.ae_measurable.max ae_measurable_const).ae_strongly_measurable, hf.has_finite_integral.max_zero⟩ lemma integrable.neg_part {f : α → ℝ} (hf : integrable f μ) : integrable (λ a, max (-f a) 0) μ := hf.neg.pos_part end pos_part section normed_space variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 β] lemma integrable.smul (c : 𝕜) {f : α → β} (hf : integrable f μ) : integrable (c • f) μ := ⟨hf.ae_strongly_measurable.const_smul c, hf.has_finite_integral.smul c⟩ lemma integrable_smul_iff {c : 𝕜} (hc : c ≠ 0) (f : α → β) : integrable (c • f) μ ↔ integrable f μ := and_congr (ae_strongly_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.const_mul' {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable ((λ (x : α), c) * f) μ := 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 _] lemma integrable.mul_const' {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (f * (λ (x : α), c)) μ := integrable.mul_const h c lemma integrable.div_const {f : α → ℝ} (h : integrable f μ) (c : ℝ) : integrable (λ x, f x / c) μ := by simp_rw [div_eq_mul_inv, h.mul_const] end normed_space section normed_space_over_complete_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] lemma integrable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : integrable (λ x, f x • c) μ ↔ integrable f μ := begin simp_rw [integrable, ae_strongly_measurable_smul_const_iff 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 is_R_or_C variables {𝕜 : Type*} [is_R_or_C 𝕜] {f : α → 𝕜} lemma integrable.of_real {f : α → ℝ} (hf : integrable f μ) : integrable (λ x, (f x : 𝕜)) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.of_real } lemma integrable.re_im_iff : integrable (λ x, is_R_or_C.re (f x)) μ ∧ integrable (λ x, is_R_or_C.im (f x)) μ ↔ integrable f μ := by { simp_rw ← mem_ℒp_one_iff_integrable, exact mem_ℒp_re_im_iff } lemma integrable.re (hf : integrable f μ) : integrable (λ x, is_R_or_C.re (f x)) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.re, } lemma integrable.im (hf : integrable f μ) : integrable (λ x, is_R_or_C.im (f x)) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.im, } end is_R_or_C section inner_product variables {𝕜 E : Type*} [is_R_or_C 𝕜] [inner_product_space 𝕜 E] {f : α → E} local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y lemma integrable.const_inner (c : E) (hf : integrable f μ) : integrable (λ x, ⟪c, f x⟫) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.const_inner c, } lemma integrable.inner_const (hf : integrable f μ) (c : E) : integrable (λ x, ⟪f x, c⟫) μ := by { rw ← mem_ℒp_one_iff_integrable at hf ⊢, exact hf.inner_const c, } end inner_product section trim variables {H : Type*} [normed_group H] {m0 : measurable_space α} {μ' : measure α} {f : α → H} lemma integrable.trim (hm : m ≤ m0) (hf_int : integrable f μ') (hf : strongly_measurable[m] f) : integrable f (μ'.trim hm) := begin refine ⟨hf.ae_strongly_measurable, _⟩, rw [has_finite_integral, lintegral_trim hm _], { exact hf_int.2, }, { exact @strongly_measurable.ennnorm _ m _ _ f hf }, end lemma integrable_of_integrable_trim (hm : m ≤ m0) (hf_int : integrable f (μ'.trim hm)) : integrable f μ' := begin obtain ⟨hf_meas_ae, hf⟩ := hf_int, refine ⟨ae_strongly_measurable_of_ae_strongly_measurable_trim hm hf_meas_ae, _⟩, rw has_finite_integral at hf ⊢, rwa lintegral_trim_ae hm _ at hf, exact ae_strongly_measurable.ennnorm hf_meas_ae end end trim section sigma_finite variables {E : Type*} {m0 : measurable_space α} [normed_group E] lemma integrable_of_forall_fin_meas_le' {μ : measure α} (hm : m ≤ m0) [sigma_finite (μ.trim hm)] (C : ℝ≥0∞) (hC : C < ∞) {f : α → E} (hf_meas : ae_strongly_measurable f μ) (hf : ∀ s, measurable_set[m] s → μ s ≠ ∞ → ∫⁻ x in s, ∥f x∥₊ ∂μ ≤ C) : integrable f μ := ⟨hf_meas, (lintegral_le_of_forall_fin_meas_le' hm C hf_meas.ennnorm hf).trans_lt hC⟩ lemma integrable_of_forall_fin_meas_le [sigma_finite μ] (C : ℝ≥0∞) (hC : C < ∞) {f : α → E} (hf_meas : ae_strongly_measurable f μ) (hf : ∀ s : set α, measurable_set s → μ s ≠ ∞ → ∫⁻ x in s, ∥f x∥₊ ∂μ ≤ C) : integrable f μ := @integrable_of_forall_fin_meas_le' _ _ _ _ _ _ _ (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_strongly_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 lemma integrable.neg {f : α →ₘ[μ] β} : integrable f → integrable (-f) := induction_on f $ λ f hfm hfi, (integrable_mk _).2 ((integrable_mk hfm).1 hfi).neg section 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 𝕜 β] 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 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 strongly_measurable_coe_fn (f : α →₁[μ] β) : strongly_measurable f := Lp.strongly_measurable f lemma measurable_coe_fn [measurable_space β] [borel_space β] (f : α →₁[μ] β) : measurable f := (Lp.strongly_measurable f).measurable lemma ae_strongly_measurable_coe_fn (f : α →₁[μ] β) : ae_strongly_measurable f μ := Lp.ae_strongly_measurable f lemma ae_measurable_coe_fn [measurable_space β] [borel_space β] (f : α →₁[μ] β) : ae_measurable f μ := (Lp.strongly_measurable f).measurable.ae_measurable 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, ∥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, (∥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] with _ ha, simp only [ha, pi.sub_apply], end lemma of_real_norm_eq_lintegral (f : α →₁[μ] β) : ennreal.of_real ∥f∥ = ∫⁻ x, (∥f x∥₊ : ℝ≥0∞) ∂μ := by { rw [norm_def, ennreal.of_real_to_real], exact ne_of_lt (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, (∥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] with _ ha, simp only [ha, pi.sub_apply], end end L1 namespace integrable /-- 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_strongly_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 𝕜 β] lemma to_L1_smul (f : α → β) (hf : integrable f μ) (k : 𝕜) : to_L1 (λ a, k • f a) (hf.smul k) = k • to_L1 f hf := rfl lemma to_L1_smul' (f : α → β) (hf : integrable f μ) (k : 𝕜) : to_L1 (k • f) (hf.smul k) = k • to_L1 f hf := rfl end integrable end measure_theory open measure_theory variables {E : Type*} [normed_group E] {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [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_strongly_measurable.apply_continuous_linear_map v) (eventually_of_forall $ λ a, (φ a).le_op_norm v) lemma continuous_linear_map.integrable_comp {φ : α → H} (L : H →L[𝕜] E) (φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ := ((integrable.norm φ_int).const_mul ∥L∥).mono' (L.continuous.comp_ae_strongly_measurable φ_int.ae_strongly_measurable) (eventually_of_forall $ λ a, L.le_op_norm (φ a))
89dbf5a1c8b8b34cc5161d8bf9c16874c6f1e586
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/bounds.lean
6d0286f9ff4362cf3d4a1a9c8f000c599bfd9bd5
[ "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
4,042
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import algebra.order.group.order_iso import algebra.order.monoid.order_dual import data.set.pointwise.basic import order.bounds.order_iso import order.conditionally_complete_lattice.basic /-! # Upper/lower bounds in ordered monoids and groups > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove a few facts like “`-s` is bounded above iff `s` is bounded below” (`bdd_above_neg`). -/ open function set open_locale pointwise section inv_neg variables {G : Type*} [group G] [preorder G] [covariant_class G G (*) (≤)] [covariant_class G G (swap (*)) (≤)] {s : set G} {a : G} @[simp, to_additive] lemma bdd_above_inv : bdd_above s⁻¹ ↔ bdd_below s := (order_iso.inv G).bdd_above_preimage @[simp, to_additive] lemma bdd_below_inv : bdd_below s⁻¹ ↔ bdd_above s := (order_iso.inv G).bdd_below_preimage @[to_additive] lemma bdd_above.inv (h : bdd_above s) : bdd_below s⁻¹ := bdd_below_inv.2 h @[to_additive] lemma bdd_below.inv (h : bdd_below s) : bdd_above s⁻¹ := bdd_above_inv.2 h @[simp, to_additive] lemma is_lub_inv : is_lub s⁻¹ a ↔ is_glb s a⁻¹ := (order_iso.inv G).is_lub_preimage @[to_additive] lemma is_lub_inv' : is_lub s⁻¹ a⁻¹ ↔ is_glb s a := (order_iso.inv G).is_lub_preimage' @[to_additive] lemma is_glb.inv (h : is_glb s a) : is_lub s⁻¹ a⁻¹ := is_lub_inv'.2 h @[simp, to_additive] lemma is_glb_inv : is_glb s⁻¹ a ↔ is_lub s a⁻¹ := (order_iso.inv G).is_glb_preimage @[to_additive] lemma is_glb_inv' : is_glb s⁻¹ a⁻¹ ↔ is_lub s a := (order_iso.inv G).is_glb_preimage' @[to_additive] lemma is_lub.inv (h : is_lub s a) : is_glb s⁻¹ a⁻¹ := is_glb_inv'.2 h end inv_neg section mul_add variables {M : Type*} [has_mul M] [preorder M] [covariant_class M M (*) (≤)] [covariant_class M M (swap (*)) (≤)] @[to_additive] lemma mul_mem_upper_bounds_mul {s t : set M} {a b : M} (ha : a ∈ upper_bounds s) (hb : b ∈ upper_bounds t) : a * b ∈ upper_bounds (s * t) := forall_image2_iff.2 $ λ x hx y hy, mul_le_mul' (ha hx) (hb hy) @[to_additive] lemma subset_upper_bounds_mul (s t : set M) : upper_bounds s * upper_bounds t ⊆ upper_bounds (s * t) := image2_subset_iff.2 $ λ x hx y hy, mul_mem_upper_bounds_mul hx hy @[to_additive] lemma mul_mem_lower_bounds_mul {s t : set M} {a b : M} (ha : a ∈ lower_bounds s) (hb : b ∈ lower_bounds t) : a * b ∈ lower_bounds (s * t) := @mul_mem_upper_bounds_mul Mᵒᵈ _ _ _ _ _ _ _ _ ha hb @[to_additive] lemma subset_lower_bounds_mul (s t : set M) : lower_bounds s * lower_bounds t ⊆ lower_bounds (s * t) := @subset_upper_bounds_mul Mᵒᵈ _ _ _ _ _ _ @[to_additive] lemma bdd_above.mul {s t : set M} (hs : bdd_above s) (ht : bdd_above t) : bdd_above (s * t) := (hs.mul ht).mono (subset_upper_bounds_mul s t) @[to_additive] lemma bdd_below.mul {s t : set M} (hs : bdd_below s) (ht : bdd_below t) : bdd_below (s * t) := (hs.mul ht).mono (subset_lower_bounds_mul s t) end mul_add section conditionally_complete_lattice section right variables {ι G : Type*} [group G] [conditionally_complete_lattice G] [covariant_class G G (function.swap (*)) (≤)] [nonempty ι] {f : ι → G} @[to_additive] lemma csupr_mul (hf : bdd_above (set.range f)) (a : G) : (⨆ i, f i) * a = ⨆ i, f i * a := (order_iso.mul_right a).map_csupr hf @[to_additive] lemma csupr_div (hf : bdd_above (set.range f)) (a : G) : (⨆ i, f i) / a = ⨆ i, f i / a := by simp only [div_eq_mul_inv, csupr_mul hf] end right section left variables {ι G : Type*} [group G] [conditionally_complete_lattice G] [covariant_class G G (*) (≤)] [nonempty ι] {f : ι → G} @[to_additive] lemma mul_csupr (hf : bdd_above (set.range f)) (a : G) : a * (⨆ i, f i) = ⨆ i, a * f i := (order_iso.mul_left a).map_csupr hf end left end conditionally_complete_lattice
48ad3545fe0029ed38ff714b7652c38092c923ec
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/ring/opposite.lean
e9d57dd7a7955e0fd2d212e3af1119eed239e893
[ "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
11,474
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 algebra.group_with_zero.basic import algebra.group.opposite import algebra.hom.ring /-! # Ring structures on the multiplicative opposite > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ universes u v variables (α : Type u) namespace mul_opposite instance [distrib α] : distrib αᵐᵒᵖ := { 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), .. mul_opposite.has_add α, .. mul_opposite.has_mul α } instance [mul_zero_class α] : mul_zero_class αᵐᵒᵖ := { 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 αᵐᵒᵖ := { .. mul_opposite.mul_zero_class α, .. mul_opposite.mul_one_class α } instance [semigroup_with_zero α] : semigroup_with_zero αᵐᵒᵖ := { .. mul_opposite.semigroup α, .. mul_opposite.mul_zero_class α } instance [monoid_with_zero α] : monoid_with_zero αᵐᵒᵖ := { .. mul_opposite.monoid α, .. mul_opposite.mul_zero_one_class α } instance [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring αᵐᵒᵖ := { .. mul_opposite.add_comm_monoid α, .. mul_opposite.mul_zero_class α, .. mul_opposite.distrib α } instance [non_unital_semiring α] : non_unital_semiring αᵐᵒᵖ := { .. mul_opposite.semigroup_with_zero α, .. mul_opposite.non_unital_non_assoc_semiring α } instance [non_assoc_semiring α] : non_assoc_semiring αᵐᵒᵖ := { .. mul_opposite.add_monoid_with_one α, .. mul_opposite.mul_zero_one_class α, .. mul_opposite.non_unital_non_assoc_semiring α } instance [semiring α] : semiring αᵐᵒᵖ := { .. mul_opposite.non_unital_semiring α, .. mul_opposite.non_assoc_semiring α, .. mul_opposite.monoid_with_zero α } instance [non_unital_comm_semiring α] : non_unital_comm_semiring αᵐᵒᵖ := { .. mul_opposite.non_unital_semiring α, .. mul_opposite.comm_semigroup α } instance [comm_semiring α] : comm_semiring αᵐᵒᵖ := { .. mul_opposite.semiring α, .. mul_opposite.comm_semigroup α } instance [non_unital_non_assoc_ring α] : non_unital_non_assoc_ring αᵐᵒᵖ := { .. mul_opposite.add_comm_group α, .. mul_opposite.mul_zero_class α, .. mul_opposite.distrib α} instance [non_unital_ring α] : non_unital_ring αᵐᵒᵖ := { .. mul_opposite.add_comm_group α, .. mul_opposite.semigroup_with_zero α, .. mul_opposite.distrib α} instance [non_assoc_ring α] : non_assoc_ring αᵐᵒᵖ := { .. mul_opposite.add_comm_group α, .. mul_opposite.mul_zero_one_class α, .. mul_opposite.distrib α, .. mul_opposite.add_group_with_one α } instance [ring α] : ring αᵐᵒᵖ := { .. mul_opposite.monoid α, .. mul_opposite.non_assoc_ring α } instance [non_unital_comm_ring α] : non_unital_comm_ring αᵐᵒᵖ := { .. mul_opposite.non_unital_ring α, .. mul_opposite.non_unital_comm_semiring α } instance [comm_ring α] : comm_ring αᵐᵒᵖ := { .. mul_opposite.ring α, .. mul_opposite.comm_semiring α } instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors αᵐᵒᵖ := { 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 [ring α] [is_domain α] : is_domain αᵐᵒᵖ := no_zero_divisors.to_is_domain _ instance [group_with_zero α] : group_with_zero αᵐᵒᵖ := { mul_inv_cancel := λ x hx, unop_injective $ inv_mul_cancel $ unop_injective.ne hx, inv_zero := unop_injective inv_zero, .. mul_opposite.monoid_with_zero α, .. mul_opposite.div_inv_monoid α, .. mul_opposite.nontrivial α } end mul_opposite namespace add_opposite instance [distrib α] : distrib αᵃᵒᵖ := { left_distrib := λ x y z, unop_injective $ @mul_add α _ _ _ x z y, right_distrib := λ x y z, unop_injective $ @add_mul α _ _ _ y x z, .. add_opposite.has_add α, .. @add_opposite.has_mul α _} instance [mul_zero_class α] : mul_zero_class αᵃᵒᵖ := { zero := 0, mul := (*), zero_mul := λ x, unop_injective $ zero_mul $ unop x, mul_zero := λ x, unop_injective $ mul_zero $ unop x } instance [mul_zero_one_class α] : mul_zero_one_class αᵃᵒᵖ := { .. add_opposite.mul_zero_class α, .. add_opposite.mul_one_class α } instance [semigroup_with_zero α] : semigroup_with_zero αᵃᵒᵖ := { .. add_opposite.semigroup α, .. add_opposite.mul_zero_class α } instance [monoid_with_zero α] : monoid_with_zero αᵃᵒᵖ := { .. add_opposite.monoid α, .. add_opposite.mul_zero_one_class α } instance [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring αᵃᵒᵖ := { .. add_opposite.add_comm_monoid α, .. add_opposite.mul_zero_class α, .. add_opposite.distrib α } instance [non_unital_semiring α] : non_unital_semiring αᵃᵒᵖ := { .. add_opposite.semigroup_with_zero α, .. add_opposite.non_unital_non_assoc_semiring α } instance [non_assoc_semiring α] : non_assoc_semiring αᵃᵒᵖ := { .. add_opposite.mul_zero_one_class α, .. add_opposite.non_unital_non_assoc_semiring α } instance [semiring α] : semiring αᵃᵒᵖ := { .. add_opposite.non_unital_semiring α, .. add_opposite.non_assoc_semiring α, .. add_opposite.monoid_with_zero α } instance [non_unital_comm_semiring α] : non_unital_comm_semiring αᵃᵒᵖ := { .. add_opposite.non_unital_semiring α, .. add_opposite.comm_semigroup α } instance [comm_semiring α] : comm_semiring αᵃᵒᵖ := { .. add_opposite.semiring α, .. add_opposite.comm_semigroup α } instance [non_unital_non_assoc_ring α] : non_unital_non_assoc_ring αᵃᵒᵖ := { .. add_opposite.add_comm_group α, .. add_opposite.mul_zero_class α, .. add_opposite.distrib α} instance [non_unital_ring α] : non_unital_ring αᵃᵒᵖ := { .. add_opposite.add_comm_group α, .. add_opposite.semigroup_with_zero α, .. add_opposite.distrib α} instance [non_assoc_ring α] : non_assoc_ring αᵃᵒᵖ := { .. add_opposite.add_comm_group α, .. add_opposite.mul_zero_one_class α, .. add_opposite.distrib α} instance [ring α] : ring αᵃᵒᵖ := { .. add_opposite.add_comm_group α, .. add_opposite.monoid α, .. add_opposite.semiring α } instance [non_unital_comm_ring α] : non_unital_comm_ring αᵃᵒᵖ := { .. add_opposite.non_unital_ring α, .. add_opposite.non_unital_comm_semiring α } instance [comm_ring α] : comm_ring αᵃᵒᵖ := { .. add_opposite.ring α, .. add_opposite.comm_semiring α } instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors αᵃᵒᵖ := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)), or.imp (λ hx, unop_injective hx) (λ hy, unop_injective hy) ((@eq_zero_or_eq_zero_of_mul_eq_zero α _ _ _ _ _) $ op_injective H) } instance [ring α] [is_domain α] : is_domain αᵃᵒᵖ := no_zero_divisors.to_is_domain _ instance [group_with_zero α] : group_with_zero αᵃᵒᵖ := { mul_inv_cancel := λ x hx, unop_injective $ mul_inv_cancel $ unop_injective.ne hx, inv_zero := unop_injective inv_zero, .. add_opposite.monoid_with_zero α, .. add_opposite.div_inv_monoid α, .. add_opposite.nontrivial α } end add_opposite open mul_opposite /-- A non-unital ring homomorphism `f : R →ₙ+* S` such that `f x` commutes with `f y` for all `x, y` defines a non-unital ring homomorphism to `Sᵐᵒᵖ`. -/ @[simps {fully_applied := ff}] def non_unital_ring_hom.to_opposite {R S : Type*} [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] (f : R →ₙ+* S) (hf : ∀ x y, commute (f x) (f y)) : R →ₙ+* Sᵐᵒᵖ := { to_fun := mul_opposite.op ∘ f, .. ((op_add_equiv : S ≃+ Sᵐᵒᵖ).to_add_monoid_hom.comp ↑f : R →+ Sᵐᵒᵖ), .. f.to_mul_hom.to_opposite hf } /-- A non-unital ring homomorphism `f : R →ₙ* S` such that `f x` commutes with `f y` for all `x, y` defines a non-unital ring homomorphism from `Rᵐᵒᵖ`. -/ @[simps {fully_applied := ff}] def non_unital_ring_hom.from_opposite {R S : Type*} [non_unital_non_assoc_semiring R] [non_unital_non_assoc_semiring S] (f : R →ₙ+* S) (hf : ∀ x y, commute (f x) (f y)) : Rᵐᵒᵖ →ₙ+* S := { to_fun := f ∘ mul_opposite.unop, .. (f.to_add_monoid_hom.comp (op_add_equiv : R ≃+ Rᵐᵒᵖ).symm.to_add_monoid_hom : Rᵐᵒᵖ →+ S), .. f.to_mul_hom.from_opposite hf } /-- A non-unital ring hom `α →ₙ+* β` can equivalently be viewed as a non-unital ring hom `αᵐᵒᵖ →+* βᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/ @[simps] def non_unital_ring_hom.op {α β} [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] : (α →ₙ+* β) ≃ (αᵐᵒᵖ →ₙ+* βᵐᵒᵖ) := { to_fun := λ f, { ..f.to_add_monoid_hom.mul_op, ..f.to_mul_hom.op }, inv_fun := λ f, { ..f.to_add_monoid_hom.mul_unop, ..f.to_mul_hom.unop }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of a non-unital ring hom `αᵐᵒᵖ →ₙ+* βᵐᵒᵖ`. Inverse to `non_unital_ring_hom.op`. -/ @[simp] def non_unital_ring_hom.unop {α β} [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] : (αᵐᵒᵖ →ₙ+* βᵐᵒᵖ) ≃ (α →ₙ+* β) := non_unital_ring_hom.op.symm /-- 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 := mul_opposite.op ∘ f, .. ((op_add_equiv : S ≃+ Sᵐᵒᵖ).to_add_monoid_hom.comp ↑f : R →+ Sᵐᵒᵖ), .. f.to_monoid_hom.to_opposite hf } /-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines a ring homomorphism from `Rᵐᵒᵖ`. -/ @[simps {fully_applied := ff}] def ring_hom.from_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S) (hf : ∀ x y, commute (f x) (f y)) : Rᵐᵒᵖ →+* S := { to_fun := f ∘ mul_opposite.unop, .. (f.to_add_monoid_hom.comp (op_add_equiv : R ≃+ Rᵐᵒᵖ).symm.to_add_monoid_hom : Rᵐᵒᵖ →+ S), .. f.to_monoid_hom.from_opposite hf } /-- A ring hom `α →+* β` can equivalently be viewed as a ring hom `αᵐᵒᵖ →+* βᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/ @[simps] def ring_hom.op {α β} [non_assoc_semiring α] [non_assoc_semiring β] : (α →+* β) ≃ (αᵐᵒᵖ →+* βᵐᵒᵖ) := { to_fun := λ f, { ..f.to_add_monoid_hom.mul_op, ..f.to_monoid_hom.op }, inv_fun := λ f, { ..f.to_add_monoid_hom.mul_unop, ..f.to_monoid_hom.unop }, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, simp } } /-- The 'unopposite' of a ring hom `αᵐᵒᵖ →+* βᵐᵒᵖ`. Inverse to `ring_hom.op`. -/ @[simp] def ring_hom.unop {α β} [non_assoc_semiring α] [non_assoc_semiring β] : (αᵐᵒᵖ →+* βᵐᵒᵖ) ≃ (α →+* β) := ring_hom.op.symm
6916ce94923a47af4b66dcbccfa6363a71ec0b91
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/sets_functions_and_relations/unnamed_256.lean
443ee19ae23c37806462c088e937e93c4db958a6
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
127
lean
import tactic variable {α : Type*} variables (s t u : set α) -- BEGIN example : s \ (t ∪ u) ⊆ s \ t \ u := sorry -- END
cf3715aceae06447aa9f3b635c9c7ffa3bd8b36e
3c9dc4ea6cc92e02634ef557110bde9eae393338
/src/Lean/Elab/BuiltinNotation.lean
0c01369f397858602fb81b992f7a5a9c498d7fdd
[ "Apache-2.0" ]
permissive
shingtaklam1324/lean4
3d7efe0c8743a4e33d3c6f4adbe1300df2e71492
351285a2e8ad0cef37af05851cfabf31edfb5970
refs/heads/master
1,676,827,679,740
1,610,462,623,000
1,610,552,340,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,692
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 Init.Data.ToString import Lean.Compiler.BorrowedAnnotation import Lean.Meta.KAbstract import Lean.Meta.Transform import Lean.Elab.Term import Lean.Elab.SyntheticMVars namespace Lean.Elab.Term open Meta @[builtinTermElab anonymousCtor] def elabAnonymousCtor : TermElab := fun stx expectedType? => match stx with | `(⟨$args,*⟩) => do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => let expectedType ← whnf expectedType matchConstInduct expectedType.getAppFn (fun _ => throwError! "invalid constructor ⟨...⟩, expected type must be an inductive type {indentExpr expectedType}") (fun ival us => do match ival.ctors with | [ctor] => let newStx ← `($(mkCIdentFrom stx ctor) $(args)*) withMacroExpansion stx newStx $ elabTerm newStx expectedType? | _ => throwError! "invalid constructor ⟨...⟩, expected type must be an inductive type with only one constructor {indentExpr expectedType}") | none => throwError "invalid constructor ⟨...⟩, expected type must be known" | _ => throwUnsupportedSyntax @[builtinTermElab borrowed] def elabBorrowed : TermElab := fun stx expectedType? => match stx with | `(@& $e) => return markBorrowed (← elabTerm e expectedType?) | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Term.show] def expandShow : Macro := fun stx => match stx with | `(show $type from $val) => let thisId := mkIdentFrom stx `this; `(let! $thisId : $type := $val; $thisId) | `(show $type by $tac:tacticSeq) => `(show $type from by $tac:tacticSeq) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.have] def expandHave : Macro := fun stx => let mkId (x? : Option Syntax) : Syntax := x?.getD <| mkIdentFrom stx `this match stx with | `(have $[$x :]? $type from $val $[;]? $body) => let x := mkId x; `(let! $x : $type := $val; $body) | `(have $[$x :]? $type := $val $[;]? $body) => let x := mkId x; `(let! $x : $type := $val; $body) | `(have $[$x :]? $type by $tac:tacticSeq $[;]? $body) => `(have $[$x :]? $type from by $tac:tacticSeq; $body) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.suffices] def expandSuffices : Macro | `(suffices $[$x :]? $type from $val $[;]? $body) => `(have $[$x :]? $type from $body; $val) | `(suffices $[$x :]? $type by $tac:tacticSeq $[;]? $body) => `(have $[$x :]? $type from $body; by $tac:tacticSeq) | _ => Macro.throwUnsupported private def elabParserMacroAux (prec : Syntax) (e : Syntax) : TermElabM Syntax := do let (some declName) ← getDeclName? | throwError "invalid `parser!` macro, it must be used in definitions" match extractMacroScopes declName with | { name := Name.str _ s _, scopes := scps, .. } => let kind := quote declName let s := quote s let p ← `(Lean.Parser.leadingNode $kind $prec $e) if scps == [] then -- TODO simplify the following quotation as soon as we have coercions `(OrElse.orElse (Lean.Parser.mkAntiquot $s (some $kind)) $p) else -- if the parser decl is hidden by hygiene, it doesn't make sense to provide an antiquotation kind `(OrElse.orElse (Lean.Parser.mkAntiquot $s none) $p) | _ => throwError "invalid `parser!` macro, unexpected declaration name" @[builtinTermElab «parser!»] def elabParserMacro : TermElab := adaptExpander fun stx => match stx with | `(parser! $e) => elabParserMacroAux (quote Parser.maxPrec) e | `(parser! : $prec $e) => elabParserMacroAux prec e | _ => throwUnsupportedSyntax private def elabTParserMacroAux (prec : Syntax) (e : Syntax) : TermElabM Syntax := do let declName? ← getDeclName? match declName? with | some declName => let kind := quote declName; `(Lean.Parser.trailingNode $kind $prec $e) | none => throwError "invalid `tparser!` macro, it must be used in definitions" @[builtinTermElab «tparser!»] def elabTParserMacro : TermElab := adaptExpander fun stx => match stx with | `(tparser! $e) => elabTParserMacroAux (quote Parser.maxPrec) e | `(tparser! : $prec $e) => elabTParserMacroAux prec e | _ => throwUnsupportedSyntax private def mkNativeReflAuxDecl (type val : Expr) : TermElabM Name := do let auxName ← mkAuxName `_nativeRefl let decl := Declaration.defnDecl { name := auxName, lparams := [], type := type, value := val, hints := ReducibilityHints.abbrev, safety := DefinitionSafety.safe } addDecl decl compileDecl decl pure auxName private def elabClosedTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let e ← elabTermAndSynthesize stx expectedType? if e.hasMVar then throwError! "invalid macro application, term contains metavariables{indentExpr e}" if e.hasFVar then throwError! "invalid macro application, term contains free variables{indentExpr e}" pure e @[builtinTermElab «nativeRefl»] def elabNativeRefl : TermElab := fun stx _ => do let arg := stx[1] let e ← elabClosedTerm arg none let type ← inferType e let type ← whnf type unless type.isConstOf `Bool || type.isConstOf `Nat do throwError! "invalid `nativeRefl!` macro application, term must have type `Nat` or `Bool`{indentExpr type}" let auxDeclName ← mkNativeReflAuxDecl type e let isBool := type.isConstOf `Bool let reduceValFn := if isBool then `Lean.reduceBool else `Lean.reduceNat let reduceThm := if isBool then `Lean.ofReduceBool else `Lean.ofReduceNat let aux := Lean.mkConst auxDeclName let reduceVal := mkApp (Lean.mkConst reduceValFn) aux let val? ← liftMetaM $ Meta.reduceNative? reduceVal match val? with | none => throwError! "failed to reduce term at `nativeRefl!` macro application{e}" | some val => let rflPrf ← mkEqRefl val let r := mkApp3 (Lean.mkConst reduceThm) aux val rflPrf let eq ← mkEq e val mkExpectedTypeHint r eq private def getPropToDecide (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | none => throwError "invalid macro, expected type is not available" | some expectedType => synthesizeSyntheticMVars let mut expectedType ← instantiateMVars expectedType if expectedType.hasFVar then expectedType ← zetaReduce expectedType if expectedType.hasFVar || expectedType.hasMVar then throwError! "expected type must not contain free or meta variables{indentExpr expectedType}" pure expectedType @[builtinTermElab «nativeDecide»] def elabNativeDecide : TermElab := fun stx expectedType? => do let p ← getPropToDecide expectedType? let d ← mkDecide p let auxDeclName ← mkNativeReflAuxDecl (Lean.mkConst `Bool) d let rflPrf ← mkEqRefl (toExpr true) let r := mkApp3 (Lean.mkConst `Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf mkExpectedTypeHint r p @[builtinTermElab Lean.Parser.Term.decide] def elabDecide : TermElab := fun stx expectedType? => do let p ← getPropToDecide expectedType? trace[Meta.debug]! "elabDecide: {p}" let d ← mkDecide p let d ← instantiateMVars d let s := d.appArg! -- get instance from `d` let rflPrf ← mkEqRefl (toExpr true) pure $ mkApp3 (Lean.mkConst `ofDecideEqTrue) p s rflPrf @[builtinTermElab panic] def elabPanic : TermElab := fun stx expectedType? => do let arg := stx[1] let pos ← getRefPosition let env ← getEnv let stxNew ← match (← getDeclName?) with | some declName => `(panicWithPosWithDecl $(quote (toString env.mainModule)) $(quote (toString declName)) $(quote pos.line) $(quote pos.column) $arg) | none => `(panicWithPos $(quote (toString env.mainModule)) $(quote pos.line) $(quote pos.column) $arg) withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? @[builtinMacro Lean.Parser.Term.unreachable] def expandUnreachable : Macro := fun stx => `(panic! "unreachable code has been reached") @[builtinMacro Lean.Parser.Term.assert] def expandAssert : Macro := fun stx => -- TODO: support for disabling runtime assertions let cond := stx[1] let body := stx[3] match cond.reprint with | some code => `(if $cond then $body else panic! ("assertion violation: " ++ $(quote code))) | none => `(if $cond then $body else panic! ("assertion violation")) @[builtinMacro Lean.Parser.Term.dbgTrace] def expandDbgTrace : Macro := fun stx => let arg := stx[1] let body := stx[3] if arg.getKind == interpolatedStrKind then `(dbgTrace (s! $arg) fun _ => $body) else `(dbgTrace (toString $arg) fun _ => $body) @[builtinMacro Lean.Parser.Term.«sorry»] def expandSorry : Macro := fun _ => `(sorryAx _ false) @[builtinTermElab emptyC] def expandEmptyC : TermElab := fun stx expectedType? => do let stxNew ← `(EmptyCollection.emptyCollection) withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? /-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/ partial def mkPairs (elems : Array Syntax) : MacroM Syntax := let rec loop (i : Nat) (acc : Syntax) := do if i > 0 then let i := i - 1 let elem := elems[i] let acc ← `(Prod.mk $elem $acc) loop i acc else pure acc loop (elems.size - 1) elems.back private partial def hasCDot : Syntax → Bool | Syntax.node k args => if k == `Lean.Parser.Term.paren then false else if k == `Lean.Parser.Term.cdot then true else args.any hasCDot | _ => false /-- Auxiliary function for expandind the `·` notation. The extra state `Array Syntax` contains the new binder names. If `stx` is a `·`, we create a fresh identifier, store in the extra state, and return it. Otherwise, we just return `stx`. -/ private partial def expandCDot : Syntax → StateT (Array Syntax) MacroM Syntax | stx@(Syntax.node k args) => if k == `Lean.Parser.Term.paren then pure stx else if k == `Lean.Parser.Term.cdot then withFreshMacroScope do let id ← `(a) modify fun s => s.push id; pure id else do let args ← args.mapM expandCDot pure $ Syntax.node k args | stx => pure stx /-- Return `some` if succeeded expanding `·` notation occurring in the given syntax. Otherwise, return `none`. Examples: - `· + 1` => `fun _a_1 => _a_1 + 1` - `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/ def expandCDot? (stx : Syntax) : MacroM (Option Syntax) := do if hasCDot stx then let (newStx, binders) ← (expandCDot stx).run #[]; `(fun $binders* => $newStx) else pure none /-- Try to expand `·` notation, and if successful elaborate result. This method is used to elaborate the Lean parentheses notation. Recall that in Lean the `·` notation must be surrounded by parentheses. We may change this is the future, but right now, here are valid examples - `(· + 1)` - `(f ⟨·, 1⟩ ·)` - `(· + ·)` - `(f · a b)` -/ private def elabCDot (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← liftMacroM <| expandCDot? stx) with | some stx' => withMacroExpansion stx stx' (elabTerm stx' expectedType?) | none => elabTerm stx expectedType? @[builtinTermElab paren] def elabParen : TermElab := fun stx expectedType? => do match stx with | `(()) => return Lean.mkConst `Unit.unit | `(($e : $type)) => let type ← withSynthesize (mayPostpone := true) $ elabType type let e ← elabCDot e type ensureHasType type e | `(($e)) => elabCDot e expectedType? | `(($e, $es,*)) => let pairs ← liftMacroM <| mkPairs (#[e] ++ es) withMacroExpansion stx pairs (elabCDot pairs expectedType?) | _ => throwError "unexpected parentheses notation" @[builtinTermElab subst] def elabSubst : TermElab := fun stx expectedType? => do let expectedType ← tryPostponeIfHasMVars expectedType? "invalid `▸` notation" match stx with | `($heq ▸ $h) => do let mut heq ← elabTerm heq none let heqType ← inferType heq let heqType ← instantiateMVars heqType match (← Meta.matchEq? heqType) with | none => throwError! "invalid `▸` notation, argument{indentExpr heq}\nhas type{indentExpr heqType}\nequality expected" | some (α, lhs, rhs) => let mut lhs := lhs let mut rhs := rhs let mkMotive (typeWithLooseBVar : Expr) := withLocalDeclD (← mkFreshUserName `x) α fun x => do mkLambdaFVars #[x] $ typeWithLooseBVar.instantiate1 x let mut expectedAbst ← kabstract expectedType rhs unless expectedAbst.hasLooseBVars do expectedAbst ← kabstract expectedType lhs unless expectedAbst.hasLooseBVars do throwError! "invalid `▸` notation, expected type{indentExpr expectedType}\ndoes contain equation left-hand-side nor right-hand-side{indentExpr heqType}" heq ← mkEqSymm heq (lhs, rhs) := (rhs, lhs) let hExpectedType := expectedAbst.instantiate1 lhs let h ← withRef h do let h ← elabTerm h hExpectedType try ensureHasType hExpectedType h catch ex => -- if `rhs` occurs in `hType`, we try to apply `heq` to `h` too let hType ← inferType h let hTypeAbst ← kabstract hType rhs unless hTypeAbst.hasLooseBVars do throw ex let hTypeNew := hTypeAbst.instantiate1 lhs unless (← isDefEq hExpectedType hTypeNew) do throw ex mkEqNDRec (← mkMotive hTypeAbst) h (← mkEqSymm heq) mkEqNDRec (← mkMotive expectedAbst) h heq | _ => throwUnsupportedSyntax @[builtinTermElab stateRefT] def elabStateRefT : TermElab := fun stx _ => do let σ ← elabType stx[1] let mut m := stx[2] if m.getKind == `Lean.Parser.Term.macroDollarArg then m := m[1] let m ← elabTerm m (← mkArrow (mkSort levelOne) (mkSort levelOne)) let ω ← mkFreshExprMVar (mkSort levelOne) let stWorld ← mkAppM `STWorld #[ω, m] discard <| mkInstMVar stWorld mkAppM `StateRefT' #[ω, σ, m] @[builtinTermElab noindex] def elabNoindex : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return DiscrTree.mkNoindexAnnotation e end Lean.Elab.Term
3bdc3cb9aa76c6623d121fb5f2192956b0af66f5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/adjoin/basic.lean
042265be90932fd1dc6e9bddae455bf9caba4acc
[ "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
15,759
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.operations import algebra.algebra.subalgebra.tower import linear_algebra.prod import linear_algebra.finsupp /-! # Adjoining elements to form subalgebras This file develops the basic theory of subalgebras of an R-algebra generated by a set of elements. A basic interface for `adjoin` is set up. ## Tags adjoin, algebra -/ universes u v w open_locale pointwise open submodule subsemiring variables {R : Type u} {A : Type v} {B : Type w} namespace algebra section semiring variables [comm_semiring R] [semiring A] [semiring B] variables [algebra R A] [algebra R B] {s t : set A} theorem subset_adjoin : s ⊆ adjoin R s := algebra.gc.le_u_l s theorem adjoin_le {S : subalgebra R A} (H : s ⊆ S) : adjoin R s ≤ S := algebra.gc.l_le H lemma adjoin_eq_Inf : adjoin R s = Inf {p | s ⊆ p} := le_antisymm (le_Inf (λ _ h, adjoin_le h)) (Inf_le subset_adjoin) theorem adjoin_le_iff {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ S:= algebra.gc _ _ theorem adjoin_mono (H : s ⊆ t) : adjoin R s ≤ adjoin R t := algebra.gc.monotone_l H theorem adjoin_eq_of_le (S : subalgebra R A) (h₁ : s ⊆ S) (h₂ : S ≤ adjoin R s) : adjoin R s = S := le_antisymm (adjoin_le h₁) h₂ theorem adjoin_eq (S : subalgebra R A) : adjoin R ↑S = S := adjoin_eq_of_le _ (set.subset.refl _) subset_adjoin lemma adjoin_Union {α : Type*} (s : α → set A) : adjoin R (set.Union s) = ⨆ (i : α), adjoin R (s i) := (@algebra.gc R A _ _ _).l_supr lemma adjoin_attach_bUnion [decidable_eq A] {α : Type*} {s : finset α} (f : s → finset A) : adjoin R (s.attach.bUnion f : set A) = ⨆ x, adjoin R (f x) := by simpa [adjoin_Union] @[elab_as_eliminator] theorem adjoin_induction {p : A → Prop} {x : A} (h : x ∈ adjoin R s) (Hs : ∀ x ∈ s, p x) (Halg : ∀ r, p (algebra_map R A r)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := let S : subalgebra R A := { carrier := p, mul_mem' := Hmul, add_mem' := Hadd, algebra_map_mem' := Halg } in adjoin_le (show s ≤ S, from Hs) h /-- Induction principle for the algebra generated by a set `s`: show that `p x y` holds for any `x y ∈ adjoin R s` given that that it holds for `x y ∈ s` and that it satisfies a number of natural properties. -/ @[elab_as_eliminator] lemma adjoin_induction₂ {p : A → A → Prop} {a b : A} (ha : a ∈ adjoin R s) (hb : b ∈ adjoin R s) (Hs : ∀ (x ∈ s) (y ∈ s), p x y) (Halg : ∀ r₁ r₂, p (algebra_map R A r₁) (algebra_map R A r₂)) (Halg_left : ∀ r (x ∈ s), p (algebra_map R A r) x) (Halg_right : ∀ r (x ∈ s), p x (algebra_map R A r)) (Hadd_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ + x₂) y) (Hadd_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ + y₂)) (Hmul_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ * x₂) y) (Hmul_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ * y₂)) : p a b := begin refine adjoin_induction hb _ (λ r, _) (Hadd_right a) (Hmul_right a), { exact adjoin_induction ha Hs Halg_left (λ x y Hx Hy z hz, Hadd_left x y z (Hx z hz) (Hy z hz)) (λ x y Hx Hy z hz, Hmul_left x y z (Hx z hz) (Hy z hz)) }, { exact adjoin_induction ha (Halg_right r) (λ r', Halg r' r) (λ x y, Hadd_left x y ((algebra_map R A) r)) (λ x y, Hmul_left x y ((algebra_map R A) r)) }, end /-- The difference with `algebra.adjoin_induction` is that this acts on the subtype. -/ lemma adjoin_induction' {p : adjoin R s → Prop} (Hs : ∀ x (h : x ∈ s), p ⟨x, subset_adjoin h⟩) (Halg : ∀ r, p (algebra_map R _ r)) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) (x : adjoin R s) : p x := subtype.rec_on x $ λ x hx, begin refine exists.elim _ (λ (hx : x ∈ adjoin R s) (hc : p ⟨x, hx⟩), hc), exact adjoin_induction hx (λ x hx, ⟨subset_adjoin hx, Hs x hx⟩) (λ r, ⟨subalgebra.algebra_map_mem _ r, Halg r⟩) (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨subalgebra.add_mem _ hx' hy', Hadd _ _ hx hy⟩) (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨subalgebra.mul_mem _ hx' hy', Hmul _ _ hx hy⟩), end @[simp] lemma adjoin_adjoin_coe_preimage {s : set A} : adjoin R ((coe : adjoin R s → A) ⁻¹' s) = ⊤ := begin refine eq_top_iff.2 (λ x, adjoin_induction' (λ a ha, _) (λ r, _) (λ _ _, _) (λ _ _, _) x), { exact subset_adjoin ha }, { exact subalgebra.algebra_map_mem _ r }, { exact subalgebra.add_mem _ }, { exact subalgebra.mul_mem _ } end lemma adjoin_union (s t : set A) : adjoin R (s ∪ t) = adjoin R s ⊔ adjoin R t := (algebra.gc : galois_connection _ (coe : subalgebra R A → set A)).l_sup variables (R A) @[simp] theorem adjoin_empty : adjoin R (∅ : set A) = ⊥ := show adjoin R ⊥ = ⊥, by { apply galois_connection.l_bot, exact algebra.gc } @[simp] theorem adjoin_univ : adjoin R (set.univ : set A) = ⊤ := eq_top_iff.2 $ λ x, subset_adjoin $ set.mem_univ _ variables (R) {A} (s) theorem adjoin_eq_span : (adjoin R s).to_submodule = span R (submonoid.closure s) := begin apply le_antisymm, { intros r hr, rcases subsemiring.mem_closure_iff_exists_list.1 hr with ⟨L, HL, rfl⟩, clear hr, induction L with hd tl ih, { exact zero_mem _ }, rw list.forall_mem_cons at HL, rw [list.map_cons, list.sum_cons], refine submodule.add_mem _ _ (ih HL.2), replace HL := HL.1, clear ih tl, suffices : ∃ z r (hr : r ∈ submonoid.closure s), has_smul.smul z r = list.prod hd, { rcases this with ⟨z, r, hr, hzr⟩, rw ← hzr, exact smul_mem _ _ (subset_span hr) }, induction hd with hd tl ih, { exact ⟨1, 1, (submonoid.closure s).one_mem', one_smul _ _⟩ }, rw list.forall_mem_cons at HL, rcases (ih HL.2) with ⟨z, r, hr, hzr⟩, rw [list.prod_cons, ← hzr], rcases HL.1 with ⟨hd, rfl⟩ | hs, { refine ⟨hd * z, r, hr, _⟩, rw [algebra.smul_def, algebra.smul_def, (algebra_map _ _).map_mul, _root_.mul_assoc] }, { exact ⟨z, hd * r, submonoid.mul_mem _ (submonoid.subset_closure hs) hr, (mul_smul_comm _ _ _).symm⟩ } }, refine span_le.2 _, change submonoid.closure s ≤ (adjoin R s).to_subsemiring.to_submonoid, exact submonoid.closure_le.2 subset_adjoin end lemma span_le_adjoin (s : set A) : span R s ≤ (adjoin R s).to_submodule := span_le.mpr subset_adjoin lemma adjoin_to_submodule_le {s : set A} {t : submodule R A} : (adjoin R s).to_submodule ≤ t ↔ ↑(submonoid.closure s) ⊆ (t : set A) := by rw [adjoin_eq_span, span_le] lemma adjoin_eq_span_of_subset {s : set A} (hs : ↑(submonoid.closure s) ⊆ (span R s : set A)) : (adjoin R s).to_submodule = span R s := le_antisymm ((adjoin_to_submodule_le R).mpr hs) (span_le_adjoin R s) @[simp] lemma adjoin_span {s : set A} : adjoin R (submodule.span R s : set A) = adjoin R s := le_antisymm (adjoin_le (span_le_adjoin _ _)) (adjoin_mono submodule.subset_span) lemma adjoin_image (f : A →ₐ[R] B) (s : set A) : adjoin R (f '' s) = (adjoin R s).map f := le_antisymm (adjoin_le $ set.image_subset _ subset_adjoin) $ subalgebra.map_le.2 $ adjoin_le $ set.image_subset_iff.1 subset_adjoin @[simp] lemma adjoin_insert_adjoin (x : A) : adjoin R (insert x ↑(adjoin R s)) = adjoin R (insert x s) := le_antisymm (adjoin_le (set.insert_subset.mpr ⟨subset_adjoin (set.mem_insert _ _), adjoin_mono (set.subset_insert _ _)⟩)) (algebra.adjoin_mono (set.insert_subset_insert algebra.subset_adjoin)) lemma adjoin_prod_le (s : set A) (t : set B) : adjoin R (s ×ˢ t) ≤ (adjoin R s).prod (adjoin R t) := adjoin_le $ set.prod_mono subset_adjoin subset_adjoin lemma mem_adjoin_of_map_mul {s} {x : A} {f : A →ₗ[R] B} (hf : ∀ a₁ a₂, f(a₁ * a₂) = f a₁ * f a₂) (h : x ∈ adjoin R s) : f x ∈ adjoin R (f '' (s ∪ {1})) := begin refine @adjoin_induction R A _ _ _ _ (λ a, f a ∈ adjoin R (f '' (s ∪ {1}))) x h (λ a ha, subset_adjoin ⟨a, ⟨set.subset_union_left _ _ ha, rfl⟩⟩) (λ r, _) (λ y z hy hz, by simpa [hy, hz] using subalgebra.add_mem _ hy hz) (λ y z hy hz, by simpa [hy, hz, hf y z] using subalgebra.mul_mem _ hy hz), have : f 1 ∈ adjoin R (f '' (s ∪ {1})) := subset_adjoin ⟨1, ⟨set.subset_union_right _ _ $ set.mem_singleton 1, rfl⟩⟩, replace this := subalgebra.smul_mem (adjoin R (f '' (s ∪ {1}))) this r, convert this, rw algebra_map_eq_smul_one, exact f.map_smul _ _ end lemma adjoin_inl_union_inr_eq_prod (s) (t) : adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})) = (adjoin R s).prod (adjoin R t) := begin apply le_antisymm, { simp only [adjoin_le_iff, set.insert_subset, subalgebra.zero_mem, subalgebra.one_mem, subset_adjoin, -- the rest comes from `squeeze_simp` set.union_subset_iff, linear_map.coe_inl, set.mk_preimage_prod_right, set.image_subset_iff, set_like.mem_coe, set.mk_preimage_prod_left, linear_map.coe_inr, and_self, set.union_singleton, subalgebra.coe_prod] }, { rintro ⟨a, b⟩ ⟨ha, hb⟩, let P := adjoin R (linear_map.inl R A B '' (s ∪ {1}) ∪ linear_map.inr R A B '' (t ∪ {1})), have Ha : (a, (0 : B)) ∈ adjoin R ((linear_map.inl R A B) '' (s ∪ {1})) := mem_adjoin_of_map_mul R (linear_map.inl_map_mul) ha, have Hb : ((0 : A), b) ∈ adjoin R ((linear_map.inr R A B) '' (t ∪ {1})) := mem_adjoin_of_map_mul R (linear_map.inr_map_mul) hb, replace Ha : (a, (0 : B)) ∈ P := adjoin_mono (set.subset_union_left _ _) Ha, replace Hb : ((0 : A), b) ∈ P := adjoin_mono (set.subset_union_right _ _) Hb, simpa using subalgebra.add_mem _ Ha Hb } end /-- If all elements of `s : set A` commute pairwise, then `adjoin R s` is a commutative semiring. -/ def adjoin_comm_semiring_of_comm {s : set A} (hcomm : ∀ (a ∈ s) (b ∈ s), a * b = b * a) : comm_semiring (adjoin R s) := { mul_comm := λ x y, begin ext, simp only [subalgebra.coe_mul], exact adjoin_induction₂ x.prop y.prop hcomm (λ _ _, by rw [commutes]) (λ r x hx, commutes r x) (λ r x hx, (commutes r x).symm) (λ _ _ _ h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂]) (λ _ _ _ h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂]) (λ x₁ x₂ y₁ h₁ h₂, by rw [mul_assoc, h₂, ←mul_assoc y₁, ←h₁, mul_assoc x₁]) (λ x₁ x₂ y₁ h₁ h₂, by rw [mul_assoc x₂, ←h₂, ←mul_assoc x₂, ←h₁, ←mul_assoc]) end, ..(adjoin R s).to_semiring } lemma adjoin_singleton_one : adjoin R ({1} : set A) = ⊥ := eq_bot_iff.2 $ adjoin_le $ set.singleton_subset_iff.2 $ set_like.mem_coe.2 $ one_mem _ lemma self_mem_adjoin_singleton (x : A) : x ∈ adjoin R ({x} : set A) := algebra.subset_adjoin (set.mem_singleton_iff.mpr rfl) end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] variables [algebra R A] {s t : set A} variables (R s t) theorem adjoin_union_eq_adjoin_adjoin : adjoin R (s ∪ t) = (adjoin (adjoin R s) t).restrict_scalars R := le_antisymm (closure_mono $ set.union_subset (set.range_subset_iff.2 $ λ r, or.inl ⟨algebra_map R (adjoin R s) r, rfl⟩) (set.union_subset_union_left _ $ λ x hxs, ⟨⟨_, subset_adjoin hxs⟩, rfl⟩)) (closure_le.2 $ set.union_subset (set.range_subset_iff.2 $ λ x, adjoin_mono (set.subset_union_left _ _) x.2) (set.subset.trans (set.subset_union_right _ _) subset_adjoin)) theorem adjoin_union_coe_submodule : (adjoin R (s ∪ t)).to_submodule = (adjoin R s).to_submodule * (adjoin R t).to_submodule := begin rw [adjoin_eq_span, adjoin_eq_span, adjoin_eq_span, span_mul_span], congr' 1 with z, simp [submonoid.closure_union, submonoid.mem_sup, set.mem_mul] end lemma adjoin_adjoin_of_tower [semiring B] [algebra R B] [algebra A B] [is_scalar_tower R A B] (s : set B) : adjoin A (adjoin R s : set B) = adjoin A s := begin apply le_antisymm (adjoin_le _), { exact adjoin_mono subset_adjoin }, { change adjoin R s ≤ (adjoin A s).restrict_scalars R, refine adjoin_le _, exact subset_adjoin } end variable {R} lemma pow_smul_mem_of_smul_subset_of_mem_adjoin [comm_semiring B] [algebra R B] [algebra A B] [is_scalar_tower R A B] (r : A) (s : set B) (B' : subalgebra R B) (hs : r • s ⊆ B') {x : B} (hx : x ∈ adjoin R s) (hr : algebra_map A B r ∈ B') : ∃ n₀ : ℕ, ∀ n ≥ n₀, r ^ n • x ∈ B' := begin change x ∈ (adjoin R s).to_submodule at hx, rw [adjoin_eq_span, finsupp.mem_span_iff_total] at hx, rcases hx with ⟨l, rfl : l.sum (λ (i : submonoid.closure s) (c : R), c • ↑i) = x⟩, choose n₁ n₂ using (λ x : submonoid.closure s, submonoid.pow_smul_mem_closure_smul r s x.prop), use l.support.sup n₁, intros n hn, rw finsupp.smul_sum, refine B'.to_submodule.sum_mem _, intros a ha, have : n ≥ n₁ a := le_trans (finset.le_sup ha) hn, dsimp only, rw [← tsub_add_cancel_of_le this, pow_add, ← smul_smul, ← is_scalar_tower.algebra_map_smul A (l a) (a : B), smul_smul (r ^ n₁ a), mul_comm, ← smul_smul, smul_def, map_pow, is_scalar_tower.algebra_map_smul], apply subalgebra.mul_mem _ (subalgebra.pow_mem _ hr _) _, refine subalgebra.smul_mem _ _ _, change _ ∈ B'.to_submonoid, rw ← submonoid.closure_eq B'.to_submonoid, apply submonoid.closure_mono hs (n₂ a), end lemma pow_smul_mem_adjoin_smul (r : R) (s : set A) {x : A} (hx : x ∈ adjoin R s) : ∃ n₀ : ℕ, ∀ n ≥ n₀, r ^ n • x ∈ adjoin R (r • s) := pow_smul_mem_of_smul_subset_of_mem_adjoin r s _ subset_adjoin hx (subalgebra.algebra_map_mem _ _) end comm_semiring section ring variables [comm_ring R] [ring A] variables [algebra R A] {s t : set A} variables {R s t} theorem adjoin_int (s : set R) : adjoin ℤ s = subalgebra_of_subring (subring.closure s) := le_antisymm (adjoin_le subring.subset_closure) (subring.closure_le.2 subset_adjoin : subring.closure s ≤ (adjoin ℤ s).to_subring) theorem mem_adjoin_iff {s : set A} {x : A} : x ∈ adjoin R s ↔ x ∈ subring.closure (set.range (algebra_map R A) ∪ s) := ⟨λ hx, subsemiring.closure_induction hx subring.subset_closure (subring.zero_mem _) (subring.one_mem _) (λ _ _, subring.add_mem _) ( λ _ _, subring.mul_mem _), suffices subring.closure (set.range ⇑(algebra_map R A) ∪ s) ≤ (adjoin R s).to_subring, from @this x, subring.closure_le.2 subsemiring.subset_closure⟩ theorem adjoin_eq_ring_closure (s : set A) : (adjoin R s).to_subring = subring.closure (set.range (algebra_map R A) ∪ s) := subring.ext $ λ x, mem_adjoin_iff variables (R) /-- If all elements of `s : set A` commute pairwise, then `adjoin R s` is a commutative ring. -/ def adjoin_comm_ring_of_comm {s : set A} (hcomm : ∀ (a ∈ s) (b ∈ s), a * b = b * a) : comm_ring (adjoin R s) := { ..(adjoin R s).to_ring, ..adjoin_comm_semiring_of_comm R hcomm } end ring end algebra open algebra subalgebra namespace alg_hom variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] lemma map_adjoin (φ : A →ₐ[R] B) (s : set A) : (adjoin R s).map φ = adjoin R (φ '' s) := (adjoin_image _ _ _).symm lemma adjoin_le_equalizer (φ₁ φ₂ : A →ₐ[R] B) {s : set A} (h : s.eq_on φ₁ φ₂) : adjoin R s ≤ φ₁.equalizer φ₂ := adjoin_le h lemma ext_of_adjoin_eq_top {s : set A} (h : adjoin R s = ⊤) ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (hs : s.eq_on φ₁ φ₂) : φ₁ = φ₂ := ext $ λ x, adjoin_le_equalizer φ₁ φ₂ hs $ h.symm ▸ trivial end alg_hom
2419c9dc2023b474ea0336df8e1e738fec9d59fd
00de0c30dd1b090ed139f65c82ea6deb48c3f4c2
/src/topology/algebra/module.lean
12b82e8e53025ca21e57cb38bafe3f716db0f04a
[ "Apache-2.0" ]
permissive
paulvanwamelen/mathlib
4b9c5c19eec71b475f3dd515cd8785f1c8515f26
79e296bdc9f83b9447dc1b81730d36f63a99f72d
refs/heads/master
1,667,766,172,625
1,590,239,595,000
1,590,239,595,000
266,392,625
0
0
Apache-2.0
1,590,257,277,000
1,590,257,277,000
null
UTF-8
Lean
false
false
35,993
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo, Yury Kudryashov -/ import topology.algebra.ring import ring_theory.algebra import linear_algebra.projection /-! # Theory of topological modules and continuous linear maps. We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`, as extensions of the corresponding algebraic classes where the algebraic operations are continuous. We also define continuous linear maps, as linear maps between topological modules which are continuous. The set of continuous linear maps between the topological `R`-modules `M` and `M₂` is denoted by `M →L[R] M₂`. Continuous linear equivalences are denoted by `M ≃L[R] M₂`. ## Implementation notes Topological vector spaces are defined as an `abbreviation` for topological modules, if the base ring is a field. This has as advantage that topological vector spaces are completely transparent for type class inference, which means that all instances for topological modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend topological vector spaces. The solution is to extend `topological_module` instead. -/ open filter open_locale topological_space universes u v w u' section prio set_option default_priority 100 -- see Note [default priority] /-- A topological semimodule, over a semiring which is also a topological space, is a semimodule in which scalar multiplication is continuous. In applications, R will be a topological semiring and M a topological additive semigroup, but this is not needed for the definition -/ class topological_semimodule (R : Type u) (M : Type v) [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] : Prop := (continuous_smul : continuous (λp : R × M, p.1 • p.2)) end prio section variables {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] lemma continuous_smul : continuous (λp:R×M, p.1 • p.2) := topological_semimodule.continuous_smul lemma continuous.smul {α : Type*} [topological_space α] {f : α → R} {g : α → M} (hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) := continuous_smul.comp (hf.prod_mk hg) lemma tendsto_smul {c : R} {x : M} : tendsto (λp:R×M, p.fst • p.snd) (𝓝 (c, x)) (𝓝 (c • x)) := continuous_smul.tendsto _ lemma filter.tendsto.smul {α : Type*} {l : filter α} {f : α → R} {g : α → M} {c : R} {x : M} (hf : tendsto f l (𝓝 c)) (hg : tendsto g l (𝓝 x)) : tendsto (λ a, f a • g a) l (𝓝 (c • x)) := tendsto_smul.comp (hf.prod_mk_nhds hg) end section prio set_option default_priority 100 -- see Note [default priority] /-- A topological module, over a ring which is also a topological space, is a module in which scalar multiplication is continuous. In applications, `R` will be a topological ring and `M` a topological additive group, but this is not needed for the definition -/ class topological_module (R : Type u) (M : Type v) [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] extends topological_semimodule R M : Prop /-- A topological vector space is a topological module over a field. -/ abbreviation topological_vector_space (R : Type u) (M : Type v) [field R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] := topological_module R M end prio section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] /-- Scalar multiplication by a unit is a homeomorphism from a topological module onto itself. -/ protected def homeomorph.smul_of_unit (a : units R) : M ≃ₜ M := { to_fun := λ x, (a : R) • x, inv_fun := λ x, ((a⁻¹ : units R) : R) • x, right_inv := λ x, calc (a : R) • ((a⁻¹ : units R) : R) • x = x : by rw [smul_smul, units.mul_inv, one_smul], left_inv := λ x, calc ((a⁻¹ : units R) : R) • (a : R) • x = x : by rw [smul_smul, units.inv_mul, one_smul], continuous_to_fun := continuous_const.smul continuous_id, continuous_inv_fun := continuous_const.smul continuous_id } lemma is_open_map_smul_of_unit (a : units R) : is_open_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_open_map lemma is_closed_map_smul_of_unit (a : units R) : is_closed_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_closed_map /-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then `⊤` is the only submodule of `M` with a nonempty interior. See also `submodule.eq_top_of_nonempty_interior` for a `normed_space` version. -/ lemma submodule.eq_top_of_nonempty_interior' [topological_add_monoid M] (h : nhds_within (0:R) {x | is_unit x} ≠ ⊥) (s : submodule R M) (hs : (interior (s:set M)).nonempty) : s = ⊤ := begin rcases hs with ⟨y, hy⟩, refine (submodule.eq_top_iff'.2 $ λ x, _), rw [mem_interior_iff_mem_nhds] at hy, have : tendsto (λ c:R, y + c • x) (nhds_within 0 {x | is_unit x}) (𝓝 (y + (0:R) • x)), from tendsto_const_nhds.add ((tendsto_nhds_within_of_tendsto_nhds tendsto_id).smul tendsto_const_nhds), rw [zero_smul, add_zero] at this, rcases nonempty_of_mem_sets h (inter_mem_sets (mem_map.1 (this hy)) self_mem_nhds_within) with ⟨_, hu, u, rfl⟩, have hy' : y ∈ ↑s := mem_of_nhds hy, exact (s.smul_mem_iff' _).1 ((s.add_mem_iff_right hy').1 hu) end end section variables {R : Type*} {M : Type*} {a : R} [field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] /-- Scalar multiplication by a non-zero field element is a homeomorphism from a topological vector space onto itself. -/ protected def homeomorph.smul_of_ne_zero (ha : a ≠ 0) : M ≃ₜ M := {.. homeomorph.smul_of_unit (units.mk0 a ha)} lemma is_open_map_smul_of_ne_zero (ha : a ≠ 0) : is_open_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_open_map lemma is_closed_map_smul_of_ne_zero (ha : a ≠ 0) : is_closed_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_closed_map end /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ structure continuous_linear_map (R : Type*) [ring R] (M : Type*) [topological_space M] [add_comm_group M] (M₂ : Type*) [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] extends linear_map R M M₂ := (cont : continuous to_fun) notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map R M M₂ /-- Continuous linear equivalences between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ @[nolint has_inhabited_instance] structure continuous_linear_equiv (R : Type*) [ring R] (M : Type*) [topological_space M] [add_comm_group M] (M₂ : Type*) [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] extends linear_equiv R M M₂ := (continuous_to_fun : continuous to_fun) (continuous_inv_fun : continuous inv_fun) notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv R M M₂ namespace continuous_linear_map section general_ring /- Properties that hold for non-necessarily commutative rings. -/ variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (M →L[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ /-- Coerce continuous linear maps to functions. -/ -- see Note [function coercion] instance to_fun : has_coe_to_fun $ M →L[R] M₂ := ⟨λ _, M → M₂, λ f, f⟩ protected lemma continuous (f : M →L[R] M₂) : continuous f := f.2 @[ext] theorem ext {f g : M →L[R] M₂} (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr' 1; ext x; apply h theorem ext_iff {f g : M →L[R] M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, by rw h, by ext⟩ variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M) -- make some straightforward lemmas available to `simp`. @[simp] lemma map_zero : f (0 : M) = 0 := (to_linear_map _).map_zero @[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _ @[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _ @[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _ @[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _ @[simp, norm_cast] lemma coe_coe : ((f : M →ₗ[R] M₂) : (M → M₂)) = (f : M → M₂) := rfl /-- The continuous map that is constantly zero. -/ instance: has_zero (M →L[R] M₂) := ⟨⟨0, continuous_const⟩⟩ instance : inhabited (M →L[R] M₂) := ⟨0⟩ @[simp] lemma zero_apply : (0 : M →L[R] M₂) x = 0 := rfl @[simp, norm_cast] lemma coe_zero : ((0 : M →L[R] M₂) : M →ₗ[R] M₂) = 0 := rfl /- no simp attribute on the next line as simp does not always simplify `0 x` to `0` when `0` is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ @[norm_cast] lemma coe_zero' : ((0 : M →L[R] M₂) : M → M₂) = 0 := rfl section variables (R M) /-- the identity map as a continuous linear map. -/ def id : M →L[R] M := ⟨linear_map.id, continuous_id⟩ end instance : has_one (M →L[R] M) := ⟨id R M⟩ lemma id_apply : id R M x = x := rfl @[simp, norm_cast] lemma coe_id : (id R M : M →ₗ[R] M) = linear_map.id := rfl @[simp, norm_cast] lemma coe_id' : (id R M : M → M) = _root_.id := rfl @[simp] lemma one_apply : (1 : M →L[R] M) x = x := rfl section add variables [topological_add_group M₂] instance : has_add (M →L[R] M₂) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ @[simp] lemma add_apply : (f + g) x = f x + g x := rfl @[simp, norm_cast] lemma coe_add : (((f + g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) + g := rfl @[norm_cast] lemma coe_add' : (((f + g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) + g := rfl instance : has_neg (M →L[R] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ @[simp] lemma neg_apply : (-f) x = - (f x) := rfl @[simp, norm_cast] lemma coe_neg : (((-f) : M →L[R] M₂) : M →ₗ[R] M₂) = -(f : M →ₗ[R] M₂) := rfl @[norm_cast] lemma coe_neg' : (((-f) : M →L[R] M₂) : M → M₂) = -(f : M → M₂) := rfl instance : add_comm_group (M →L[R] M₂) := by { refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; apply_rules [zero_add, add_assoc, add_zero, add_left_neg, add_comm] } lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl @[simp, norm_cast] lemma coe_sub : (((f - g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) - g := rfl @[simp, norm_cast] lemma coe_sub' : (((f - g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) - g := rfl lemma sum_apply {ι : Type*} (t : finset ι) (f : ι → M →L[R] M₂) (b : M) : t.sum f b = t.sum (λd, f d b) := begin haveI : is_add_group_hom (λ (g : M →L[R] M₂), g b) := { map_add := λ f g, continuous_linear_map.add_apply f g b }, exact (finset.sum_hom t (λ g : M →L[R] M₂, g b)).symm end end add @[simp] lemma sub_apply' (x : M) : ((f : M →ₗ[R] M₂) - g) x = f x - g x := rfl /-- Composition of bounded linear maps. -/ def comp (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : M →L[R] M₃ := ⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩ @[simp, norm_cast] lemma coe_comp : ((h.comp f) : (M →ₗ[R] M₃)) = (h : M₂ →ₗ[R] M₃).comp f := rfl @[simp, norm_cast] lemma coe_comp' : ((h.comp f) : (M → M₃)) = (h : M₂ → M₃) ∘ f := rfl @[simp] theorem comp_id : f.comp (id R M) = f := ext $ λ x, rfl @[simp] theorem id_comp : (id R M₂).comp f = f := ext $ λ x, rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →L[R] M) = 0 := by { ext, simp } @[simp] theorem zero_comp : (0 : M₂ →L[R] M₃).comp f = 0 := by { ext, simp } @[simp] lemma comp_add [topological_add_group M₂] [topological_add_group M₃] (g : M₂ →L[R] M₃) (f₁ f₂ : M →L[R] M₂) : g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ := by { ext, simp } @[simp] lemma add_comp [topological_add_group M₃] (g₁ g₂ : M₂ →L[R] M₃) (f : M →L[R] M₂) : (g₁ + g₂).comp f = g₁.comp f + g₂.comp f := by { ext, simp } theorem comp_assoc (h : M₃ →L[R] M₄) (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : (h.comp g).comp f = h.comp (g.comp f) := rfl instance : has_mul (M →L[R] M) := ⟨comp⟩ lemma mul_def (f g : M →L[R] M) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : M →L[R] M) : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (f g : M →L[R] M) (x : M) : (f * g) x = f (g x) := rfl instance [topological_add_group M] : ring (M →L[R] M) := { mul := (*), one := 1, mul_one := λ _, ext $ λ _, rfl, one_mul := λ _, ext $ λ _, rfl, mul_assoc := λ _ _ _, ext $ λ _, rfl, left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _, right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _, ..continuous_linear_map.add_comm_group } /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ protected def prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : M →L[R] (M₂ × M₃) := { cont := f₁.2.prod_mk f₂.2, ..f₁.to_linear_map.prod f₂.to_linear_map } @[simp, norm_cast] lemma coe_prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : (f₁.prod f₂ : M →ₗ[R] M₂ × M₃) = linear_map.prod f₁ f₂ := rfl @[simp, norm_cast] lemma prod_apply (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) (x : M) : f₁.prod f₂ x = (f₁ x, f₂ x) := rfl /-- Kernel of a continuous linear map. -/ def ker (f : M →L[R] M₂) : submodule R M := (f : M →ₗ[R] M₂).ker @[norm_cast] lemma ker_coe : (f : M →ₗ[R] M₂).ker = f.ker := rfl @[simp] lemma mem_ker {f : M →L[R] M₂} {x} : x ∈ f.ker ↔ f x = 0 := linear_map.mem_ker lemma is_closed_ker [t1_space M₂] : is_closed (f.ker : set M) := continuous_iff_is_closed.1 f.cont _ is_closed_singleton @[simp] lemma apply_ker (x : f.ker) : f x = 0 := mem_ker.1 x.2 /-- Range of a continuous linear map. -/ def range (f : M →L[R] M₂) : submodule R M₂ := (f : M →ₗ[R] M₂).range lemma range_coe : (f.range : set M₂) = set.range f := linear_map.range_coe _ lemma mem_range {f : M →L[R] M₂} {y} : y ∈ f.range ↔ ∃ x, f x = y := linear_map.mem_range /-- Restrict codomain of a continuous linear map. -/ def cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) : M →L[R] p := { cont := continuous_subtype_mk h f.continuous, to_linear_map := (f : M →ₗ[R] M₂).cod_restrict p h} @[norm_cast] lemma coe_cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) : (f.cod_restrict p h : M →ₗ[R] p) = (f : M →ₗ[R] M₂).cod_restrict p h := rfl @[simp] lemma coe_cod_restrict_apply (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) (x) : (f.cod_restrict p h x : M₂) = f x := rfl @[simp] lemma ker_cod_restrict (f : M →L[R] M₂) (p : submodule R M₂) (h : ∀ x, f x ∈ p) : ker (f.cod_restrict p h) = ker f := (f : M →ₗ[R] M₂).ker_cod_restrict p h /-- Embedding of a submodule into the ambient space as a continuous linear map. -/ def subtype_val (p : submodule R M) : p →L[R] M := { cont := continuous_subtype_val, to_linear_map := p.subtype } @[simp, norm_cast] lemma coe_subtype_val (p : submodule R M) : (subtype_val p : p →ₗ[R] M) = p.subtype := rfl @[simp, norm_cast] lemma subtype_val_apply (p : submodule R M) (x : p) : (subtype_val p : p → M) x = x := rfl variables (R M M₂) /-- `prod.fst` as a `continuous_linear_map`. -/ def fst : M × M₂ →L[R] M := { cont := continuous_fst, to_linear_map := linear_map.fst R M M₂ } /-- `prod.snd` as a `continuous_linear_map`. -/ def snd : M × M₂ →L[R] M₂ := { cont := continuous_snd, to_linear_map := linear_map.snd R M M₂ } variables {R M M₂} @[simp, norm_cast] lemma coe_fst : (fst R M M₂ : M × M₂ →ₗ[R] M) = linear_map.fst R M M₂ := rfl @[simp, norm_cast] lemma coe_fst' : (fst R M M₂ : M × M₂ → M) = prod.fst := rfl @[simp, norm_cast] lemma coe_snd : (snd R M M₂ : M × M₂ →ₗ[R] M₂) = linear_map.snd R M M₂ := rfl @[simp, norm_cast] lemma coe_snd' : (snd R M M₂ : M × M₂ → M₂) = prod.snd := rfl /-- `prod.map` of two continuous linear maps. -/ def prod_map (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : (M × M₃) →L[R] (M₂ × M₄) := (f₁.comp (fst R M M₃)).prod (f₂.comp (snd R M M₃)) @[simp, norm_cast] lemma coe_prod_map (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : (f₁.prod_map f₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = ((f₁ : M →ₗ[R] M₂).prod_map (f₂ : M₃ →ₗ[R] M₄)) := rfl @[simp, norm_cast] lemma coe_prod_map' (f₁ : M →L[R] M₂) (f₂ : M₃ →L[R] M₄) : ⇑(f₁.prod_map f₂) = prod.map f₁ f₂ := rfl /-- The continuous linear map given by `(x, y) ↦ f₁ x + f₂ y`. -/ def coprod [topological_add_monoid M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) : (M × M₂) →L[R] M₃ := ⟨linear_map.coprod f₁ f₂, (f₁.cont.comp continuous_fst).add (f₂.cont.comp continuous_snd)⟩ @[norm_cast, simp] lemma coe_coprod [topological_add_monoid M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) : (f₁.coprod f₂ : (M × M₂) →ₗ[R] M₃) = linear_map.coprod f₁ f₂ := rfl @[simp] lemma coprod_apply [topological_add_monoid M₃] (f₁ : M →L[R] M₃) (f₂ : M₂ →L[R] M₃) (x) : f₁.coprod f₂ x = f₁ x.1 + f₂ x.2 := rfl /-- Given a right inverse `f₂ : M₂ →L[R] M` to `f₁ : M →L[R] M₂`, `proj_ker_of_right_inverse f₁ f₂ h` is the projection `M →L[R] f₁.ker` along `f₂.range`. -/ def proj_ker_of_right_inverse [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : M →L[R] f₁.ker := (id R M - f₂.comp f₁).cod_restrict f₁.ker $ λ x, by simp [h (f₁ x)] @[simp] lemma coe_proj_ker_of_right_inverse_apply [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : (f₁.proj_ker_of_right_inverse f₂ h x : M) = x - f₂ (f₁ x) := rfl @[simp] lemma proj_ker_of_right_inverse_apply_idem [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : f₁.ker) : f₁.proj_ker_of_right_inverse f₂ h x = x := subtype.coe_ext.2 $ by simp @[simp] lemma proj_ker_of_right_inverse_comp_inv [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂) : f₁.proj_ker_of_right_inverse f₂ h (f₂ y) = 0 := subtype.coe_ext.2 $ by simp [h y] variables [topological_space R] [topological_module R M₂] /-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of `M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`) -/ def smul_right (c : M →L[R] R) (f : M₂) : M →L[R] M₂ := { cont := c.2.smul continuous_const, ..c.to_linear_map.smul_right f } @[simp] lemma smul_right_apply {c : M →L[R] R} {f : M₂} {x : M} : (smul_right c f : M → M₂) x = (c : M → R) x • f := rfl @[simp] lemma smul_right_one_one (c : R →L[R] M₂) : smul_right 1 ((c : R → M₂) 1) = c := by ext; simp [-continuous_linear_map.map_smul, (continuous_linear_map.map_smul _ _ _).symm] @[simp] lemma smul_right_one_eq_iff {f f' : M₂} : smul_right (1 : R →L[R] R) f = smul_right 1 f' ↔ f = f' := ⟨λ h, have (smul_right (1 : R →L[R] R) f : R → M₂) 1 = (smul_right (1 : R →L[R] R) f' : R → M₂) 1, by rw h, by simp at this; assumption, by cc⟩ lemma smul_right_comp [topological_module R R] {x : M₂} {c : R} : (smul_right 1 x : R →L[R] M₂).comp (smul_right 1 c : R →L[R] R) = smul_right 1 (c • x) := by { ext, simp [mul_smul] } lemma smul_right_one_pow [topological_add_group R] [topological_module R R] (c : R) (n : ℕ) : (smul_right 1 c : R →L[R] R)^n = smul_right 1 (c^n) := begin induction n with n ihn, { ext, simp }, { rw [pow_succ, ihn, mul_def, smul_right_comp, smul_eq_mul, pow_succ'] } end end general_ring section comm_ring variables {R : Type*} [comm_ring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] [topological_module R M₃] instance : has_scalar R (M →L[R] M₃) := ⟨λ c f, ⟨c • f, continuous_const.smul f.2⟩⟩ variables (c : R) (h : M₂ →L[R] M₃) (f g : M →L[R] M₂) (x y z : M) @[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl variable [topological_module R M₂] @[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl @[simp, norm_cast] lemma coe_apply : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • (f : M →ₗ[R] M₂) := rfl @[norm_cast] lemma coe_apply' : (((c • f) : M →L[R] M₂) : M → M₂) = c • (f : M → M₂) := rfl @[simp] lemma comp_smul : h.comp (c • f) = c • (h.comp f) := by { ext, simp } variable [topological_add_group M₂] instance : module R (M →L[R] M₂) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } instance : algebra R (M₂ →L[R] M₂) := algebra.of_semimodule' (λ c f, ext $ λ x, rfl) (λ c f, ext $ λ x, f.map_smul c x) end comm_ring end continuous_linear_map namespace continuous_linear_equiv variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] {M₄ : Type*} [topological_space M₄] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] /-- A continuous linear equivalence induces a continuous linear map. -/ def to_continuous_linear_map (e : M ≃L[R] M₂) : M →L[R] M₂ := { cont := e.continuous_to_fun, ..e.to_linear_equiv.to_linear_map } /-- Coerce continuous linear equivs to continuous linear maps. -/ instance : has_coe (M ≃L[R] M₂) (M →L[R] M₂) := ⟨to_continuous_linear_map⟩ /-- Coerce continuous linear equivs to maps. -/ -- see Note [function coercion] instance : has_coe_to_fun (M ≃L[R] M₂) := ⟨λ _, M → M₂, λ f, f⟩ @[simp] theorem coe_def_rev (e : M ≃L[R] M₂) : e.to_continuous_linear_map = e := rfl @[simp] theorem coe_apply (e : M ≃L[R] M₂) (b : M) : (e : M →L[R] M₂) b = e b := rfl @[norm_cast] lemma coe_coe (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) = e := rfl @[ext] lemma ext {f g : M ≃L[R] M₂} (h : (f : M → M₂) = g) : f = g := begin cases f; cases g, simp only [], ext x, induction h, refl end /-- A continuous linear equivalence induces a homeomorphism. -/ def to_homeomorph (e : M ≃L[R] M₂) : M ≃ₜ M₂ := { ..e } -- Make some straightforward lemmas available to `simp`. @[simp] lemma map_zero (e : M ≃L[R] M₂) : e (0 : M) = 0 := (e : M →L[R] M₂).map_zero @[simp] lemma map_add (e : M ≃L[R] M₂) (x y : M) : e (x + y) = e x + e y := (e : M →L[R] M₂).map_add x y @[simp] lemma map_sub (e : M ≃L[R] M₂) (x y : M) : e (x - y) = e x - e y := (e : M →L[R] M₂).map_sub x y @[simp] lemma map_smul (e : M ≃L[R] M₂) (c : R) (x : M) : e (c • x) = c • (e x) := (e : M →L[R] M₂).map_smul c x @[simp] lemma map_neg (e : M ≃L[R] M₂) (x : M) : e (-x) = -e x := (e : M →L[R] M₂).map_neg x @[simp] lemma map_eq_zero_iff (e : M ≃L[R] M₂) {x : M} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff protected lemma continuous (e : M ≃L[R] M₂) : continuous (e : M → M₂) := e.continuous_to_fun protected lemma continuous_on (e : M ≃L[R] M₂) {s : set M} : continuous_on (e : M → M₂) s := e.continuous.continuous_on protected lemma continuous_at (e : M ≃L[R] M₂) {x : M} : continuous_at (e : M → M₂) x := e.continuous.continuous_at protected lemma continuous_within_at (e : M ≃L[R] M₂) {s : set M} {x : M} : continuous_within_at (e : M → M₂) s x := e.continuous.continuous_within_at lemma comp_continuous_on_iff {α : Type*} [topological_space α] (e : M ≃L[R] M₂) (f : α → M) (s : set α) : continuous_on (e ∘ f) s ↔ continuous_on f s := e.to_homeomorph.comp_continuous_on_iff _ _ lemma comp_continuous_iff {α : Type*} [topological_space α] (e : M ≃L[R] M₂) (f : α → M) : continuous (e ∘ f) ↔ continuous f := e.to_homeomorph.comp_continuous_iff _ /-- An extensionality lemma for `R ≃L[R] M`. -/ lemma ext₁ [topological_space R] {f g : R ≃L[R] M} (h : f 1 = g 1) : f = g := ext $ funext $ λ x, mul_one x ▸ by rw [← smul_eq_mul, map_smul, h, map_smul] section variables (R M) /-- The identity map as a continuous linear equivalence. -/ @[refl] protected def refl : M ≃L[R] M := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. linear_equiv.refl R M } end @[simp, norm_cast] lemma coe_refl : (continuous_linear_equiv.refl R M : M →L[R] M) = continuous_linear_map.id R M := rfl @[simp, norm_cast] lemma coe_refl' : (continuous_linear_equiv.refl R M : M → M) = id := rfl /-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/ @[symm] protected def symm (e : M ≃L[R] M₂) : M₂ ≃L[R] M := { continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, .. e.to_linear_equiv.symm } @[simp] lemma symm_to_linear_equiv (e : M ≃L[R] M₂) : e.symm.to_linear_equiv = e.to_linear_equiv.symm := by { ext, refl } /-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/ @[trans] protected def trans (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : M ≃L[R] M₃ := { continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun, continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun, .. e₁.to_linear_equiv.trans e₂.to_linear_equiv } @[simp] lemma trans_to_linear_equiv (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := by { ext, refl } /-- Product of two continuous linear equivalences. The map comes from `equiv.prod_congr`. -/ def prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) : (M × M₃) ≃L[R] (M₂ × M₄) := { continuous_to_fun := e.continuous_to_fun.prod_map e'.continuous_to_fun, continuous_inv_fun := e.continuous_inv_fun.prod_map e'.continuous_inv_fun, .. e.to_linear_equiv.prod e'.to_linear_equiv } @[simp, norm_cast] lemma prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (x) : e.prod e' x = (e x.1, e' x.2) := rfl @[simp, norm_cast] lemma coe_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) : (e.prod e' : (M × M₃) →L[R] (M₂ × M₄)) = (e : M →L[R] M₂).prod_map (e' : M₃ →L[R] M₄) := rfl variables [topological_add_group M₄] /-- Equivalence given by a block lower diagonal matrix. `e` and `e'` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ def skew_prod (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) : (M × M₃) ≃L[R] M₂ × M₄ := { continuous_to_fun := (e.continuous_to_fun.comp continuous_fst).prod_mk ((e'.continuous_to_fun.comp continuous_snd).add $ f.continuous.comp continuous_fst), continuous_inv_fun := (e.continuous_inv_fun.comp continuous_fst).prod_mk (e'.continuous_inv_fun.comp $ continuous_snd.sub $ f.continuous.comp $ e.continuous_inv_fun.comp continuous_fst), .. e.to_linear_equiv.skew_prod e'.to_linear_equiv ↑f } @[simp] lemma skew_prod_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) : e.skew_prod e' f x = (e x.1, e' x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (e : M ≃L[R] M₂) (e' : M₃ ≃L[R] M₄) (f : M →L[R] M₄) (x) : (e.skew_prod e' f).symm x = (e.symm x.1, e'.symm (x.2 - f (e.symm x.1))) := rfl theorem bijective (e : M ≃L[R] M₂) : function.bijective e := e.to_linear_equiv.to_equiv.bijective theorem injective (e : M ≃L[R] M₂) : function.injective e := e.to_linear_equiv.to_equiv.injective theorem surjective (e : M ≃L[R] M₂) : function.surjective e := e.to_linear_equiv.to_equiv.surjective @[simp] theorem apply_symm_apply (e : M ≃L[R] M₂) (c : M₂) : e (e.symm c) = c := e.1.6 c @[simp] theorem symm_apply_apply (e : M ≃L[R] M₂) (b : M) : e.symm (e b) = b := e.1.5 b @[simp] theorem coe_comp_coe_symm (e : M ≃L[R] M₂) : (e : M →L[R] M₂).comp (e.symm : M₂ →L[R] M) = continuous_linear_map.id R M₂ := continuous_linear_map.ext e.apply_symm_apply @[simp] theorem coe_symm_comp_coe (e : M ≃L[R] M₂) : (e.symm : M₂ →L[R] M).comp (e : M →L[R] M₂) = continuous_linear_map.id R M := continuous_linear_map.ext e.symm_apply_apply lemma symm_comp_self (e : M ≃L[R] M₂) : (e.symm : M₂ → M) ∘ (e : M → M₂) = id := by{ ext x, exact symm_apply_apply e x } lemma self_comp_symm (e : M ≃L[R] M₂) : (e : M → M₂) ∘ (e.symm : M₂ → M) = id := by{ ext x, exact apply_symm_apply e x } @[simp] lemma symm_comp_self' (e : M ≃L[R] M₂) : ((e.symm : M₂ →L[R] M) : M₂ → M) ∘ ((e : M →L[R] M₂) : M → M₂) = id := symm_comp_self e @[simp] lemma self_comp_symm' (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) ∘ ((e.symm : M₂ →L[R] M) : M₂ → M) = id := self_comp_symm e @[simp] theorem symm_symm (e : M ≃L[R] M₂) : e.symm.symm = e := by { ext x, refl } theorem symm_symm_apply (e : M ≃L[R] M₂) (x : M) : e.symm.symm x = e x := rfl /-- Create a `continuous_linear_equiv` from two `continuous_linear_map`s that are inverse of each other. -/ def equiv_of_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h₁ : function.left_inverse f₂ f₁) (h₂ : function.right_inverse f₂ f₁) : M ≃L[R] M₂ := { to_fun := f₁, continuous_to_fun := f₁.continuous, inv_fun := f₂, continuous_inv_fun := f₂.continuous, left_inv := h₁, right_inv := h₂, .. f₁ } @[simp] lemma equiv_of_inverse_apply (f₁ : M →L[R] M₂) (f₂ h₁ h₂ x) : equiv_of_inverse f₁ f₂ h₁ h₂ x = f₁ x := rfl @[simp] lemma symm_equiv_of_inverse (f₁ : M →L[R] M₂) (f₂ h₁ h₂) : (equiv_of_inverse f₁ f₂ h₁ h₂).symm = equiv_of_inverse f₂ f₁ h₂ h₁ := rfl section variables (R) [topological_space R] [topological_module R R] /-- Continuous linear equivalences `R ≃L[R] R` are enumerated by `units R`. -/ def units_equiv_aut : units R ≃ (R ≃L[R] R) := { to_fun := λ u, equiv_of_inverse (continuous_linear_map.smul_right 1 ↑u) (continuous_linear_map.smul_right 1 ↑u⁻¹) (λ x, by simp) (λ x, by simp), inv_fun := λ e, ⟨e 1, e.symm 1, by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, symm_apply_apply], by rw [← smul_eq_mul, ← map_smul, smul_eq_mul, mul_one, apply_symm_apply]⟩, left_inv := λ u, units.ext $ by simp, right_inv := λ e, ext₁ $ by simp } variable {R} @[simp] lemma units_equiv_aut_apply (u : units R) (x : R) : units_equiv_aut R u x = x * u := rfl @[simp] lemma units_equiv_aut_apply_symm (u : units R) (x : R) : (units_equiv_aut R u).symm x = x * ↑u⁻¹ := rfl @[simp] lemma units_equiv_aut_symm_apply (e : R ≃L[R] R) : ↑((units_equiv_aut R).symm e) = e 1 := rfl end variables [topological_add_group M] open continuous_linear_map (id fst snd subtype_val mem_ker) /-- A pair of continuous linear maps such that `f₁ ∘ f₂ = id` generates a continuous linear equivalence `e` between `M` and `M₂ × f₁.ker` such that `(e x).2 = x` for `x ∈ f₁.ker`, `(e x).1 = f₁ x`, and `(e (f₂ y)).2 = 0`. The map is given by `e x = (f₁ x, x - f₂ (f₁ x))`. -/ def equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : M ≃L[R] M₂ × f₁.ker := equiv_of_inverse (f₁.prod (f₁.proj_ker_of_right_inverse f₂ h)) (f₂.coprod (subtype_val f₁.ker)) (λ x, by simp) (λ ⟨x, y⟩, by simp [h x]) @[simp] lemma fst_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : (equiv_of_right_inverse f₁ f₂ h x).1 = f₁ x := rfl @[simp] lemma snd_equiv_of_right_inverse (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (x : M) : ((equiv_of_right_inverse f₁ f₂ h x).2 : M) = x - f₂ (f₁ x) := rfl @[simp] lemma equiv_of_right_inverse_symm_apply (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) (y : M₂ × f₁.ker) : (equiv_of_right_inverse f₁ f₂ h).symm y = f₂ y.1 + y.2 := rfl end continuous_linear_equiv namespace submodule variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] [module R M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M₂] open continuous_linear_map /-- A submodule `p` is called *complemented* if there exists a continuous projection `M →ₗ[R] p`. -/ def closed_complemented (p : submodule R M) : Prop := ∃ f : M →L[R] p, ∀ x : p, f x = x lemma closed_complemented.has_closed_complement {p : submodule R M} [t1_space p] (h : closed_complemented p) : ∃ (q : submodule R M) (hq : is_closed (q : set M)), is_compl p q := exists.elim h $ λ f hf, ⟨f.ker, f.is_closed_ker, (f : M →ₗ[R] p).is_compl_of_proj hf⟩ protected lemma closed_complemented.is_closed [topological_add_group M] [t1_space M] {p : submodule R M} (h : closed_complemented p) : is_closed (p : set M) := begin rcases h with ⟨f, hf⟩, have : ker (id R M - (subtype_val p).comp f) = p := (f : M →ₗ[R] p).ker_id_sub_eq_of_proj hf, exact this ▸ (is_closed_ker _) end @[simp] lemma closed_complemented_bot : closed_complemented (⊥ : submodule R M) := ⟨0, λ x, by simp only [zero_apply, eq_zero_of_bot_submodule x]⟩ @[simp] lemma closed_complemented_top : closed_complemented (⊤ : submodule R M) := ⟨(id R M).cod_restrict ⊤ (λ x, trivial), λ x, subtype.coe_ext.2 $ by simp⟩ end submodule lemma continuous_linear_map.closed_complemented_ker_of_right_inverse {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] [topological_add_group M] (f₁ : M →L[R] M₂) (f₂ : M₂ →L[R] M) (h : function.right_inverse f₂ f₁) : f₁.ker.closed_complemented := ⟨f₁.proj_ker_of_right_inverse f₂ h, f₁.proj_ker_of_right_inverse_apply_idem f₂ h⟩
89691e0c13b9177485cdcefeba57a3eec4e0870a
10834b3de906c60d1989336d7506a00ee5e52c08
/library/init/meta/simp_tactic.lean
2aeaeff8a72d43f0cc367e5ad5f05392a74d53e1
[ "Apache-2.0" ]
permissive
Jack-Pumpkinhead/lean
16657b5ad7f5316f007842fa2426b7f91212eae8
81cabd7b5a8f789633639f5fba64b45d31e37259
refs/heads/master
1,621,358,983,310
1,585,070,616,000
1,585,070,616,000
251,335,905
0
0
Apache-2.0
1,585,579,683,000
1,585,579,682,000
null
UTF-8
Lean
false
false
26,857
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.tactic init.meta.attribute init.meta.constructor_tactic import init.meta.relation_tactics init.meta.occurrences import init.data.option.basic open tactic def simp.default_max_steps := 10000000 /-- Prefix the given `attr_name` with `"simp_attr"`. -/ meta constant mk_simp_attr_decl_name (attr_name : name) : name /-- Simp lemmas are used by the "simplifier" family of tactics. `simp_lemmas` is essentially a pair of tables `rb_map (expr_type × name) (priority_list simp_lemma)`. One of the tables is for congruences and one is for everything else. An individual simp lemma is: - A kind which can be `Refl`, `Simp` or `Congr`. - A pair of `expr`s `l ~> r`. The rb map is indexed by the name of `get_app_fn(l)`. - A proof that `l = r` or `l ↔ r`. - A list of the metavariables that must be filled before the proof can be applied. - A priority number -/ meta constant simp_lemmas : Type /-- Make a new table of simp lemmas -/ meta constant simp_lemmas.mk : simp_lemmas /-- Merge the simp_lemma tables. -/ meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas /-- Remove the given lemmas from the table. Use the names of the lemmas. -/ meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas /-- Makes the default simp_lemmas table which is composed of all lemmas tagged with `simp`. -/ meta constant simp_lemmas.mk_default : tactic simp_lemmas /-- Add a simplification lemma by an expression `p`. Some conditions on `p` must hold for it to be added, see list below. If your lemma is not being added, you can see the reasons by setting `set_option trace.simp_lemmas true`. - `p` must have the type `Π (h₁ : _) ... (hₙ : _), LHS ~ RHS` for some reflexive, transitive relation (usually `=`). - Any of the hypotheses `hᵢ` should either be present in `LHS` or otherwise a `Prop` or a typeclass instance. - `LHS` should not occur within `RHS`. - `LHS` should not occur within a hypothesis `hᵢ`. -/ meta constant simp_lemmas.add (s : simp_lemmas) (e : expr) (symm : bool := false) : tactic simp_lemmas /-- Add a simplification lemma by it's declaration name. See `simp_lemmas.add` for more information.-/ meta constant simp_lemmas.add_simp (s : simp_lemmas) (id : name) (symm : bool := false) : tactic simp_lemmas /-- Adds a congruence simp lemma to simp_lemmas. A congruence simp lemma is a lemma that breaks the simplification down into separate problems. For example, to simplify `a ∧ b` to `c ∧ d`, we should try to simp `a` to `c` and `b` to `d`. For examples of congruence simp lemmas look for lemmas with the `@[congr]` attribute. ```lean lemma if_simp_congr ... (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := ... lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := ... lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := ... ``` -/ meta constant simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas /-- Add expressions to a set of simp lemmas using `simp_lemmas.add`. This is the new version of `simp_lemmas.append`, which also allows you to set the `symm` flag. -/ meta def simp_lemmas.append_with_symm (s : simp_lemmas) (hs : list (expr × bool)) : tactic simp_lemmas := hs.mfoldl (λ s h, simp_lemmas.add s h.fst h.snd) s /-- Add expressions to a set of simp lemmas using `simp_lemmas.add`. This is the backwards-compatibility version of `simp_lemmas.append_with_symm`, and sets all `symm` flags to `ff`. -/ meta def simp_lemmas.append (s : simp_lemmas) (hs : list expr) : tactic simp_lemmas := hs.mfoldl (λ s h, simp_lemmas.add s h ff) s /-- `simp_lemmas.rewrite s e prove R` apply a simplification lemma from 's' - 'e' is the expression to be "simplified" - 'prove' is used to discharge proof obligations. - 'r' is the equivalence relation being used (e.g., 'eq', 'iff') - 'md' is the transparency; how aggresively should the simplifier perform reductions. Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ meta constant simp_lemmas.rewrite (s : simp_lemmas) (e : expr) (prove : tactic unit := failed) (r : name := `eq) (md := reducible) : tactic (expr × expr) meta constant simp_lemmas.rewrites (s : simp_lemmas) (e : expr) (prove : tactic unit := failed) (r : name := `eq) (md := reducible) : tactic $ list (expr × expr) /-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/ meta constant simp_lemmas.drewrite (s : simp_lemmas) (e : expr) (md := reducible) : tactic expr meta constant is_valid_simp_lemma_cnst : name → tactic bool meta constant is_valid_simp_lemma : expr → tactic bool meta constant simp_lemmas.pp : simp_lemmas → tactic format meta instance : has_to_tactic_format simp_lemmas := ⟨simp_lemmas.pp⟩ namespace tactic /- Remark: `transform` should not change the target. -/ /-- Revert a local constant, change its type using `transform`. -/ meta def revert_and_transform (transform : expr → tactic expr) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, t ← target, match t with | expr.pi n bi d b := do h_simp ← transform d, unsafe_change $ expr.pi n bi h_simp b | expr.elet n g e f := do h_simp ← transform g, unsafe_change $ expr.elet n h_simp e f | _ := fail "reverting hypothesis created neither a pi nor an elet expr (unreachable?)" end, intron num_reverted /-- `get_eqn_lemmas_for deps d` returns the automatically generated equational lemmas for definition d. If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/ meta constant get_eqn_lemmas_for : bool → name → tactic (list name) structure dsimp_config := (md := reducible) -- reduction mode: how aggressively constants are replaced with their definitions. (max_steps : nat := simp.default_max_steps) -- The maximum number of steps allowed before failing. (canonize_instances : bool := tt) -- [TODO] docs (single_pass : bool := ff) -- [TODO] Does this mean that _each_ simp-lemma can only be used once? (fail_if_unchanged := tt) -- Don't throw if simp didn't do anything. (eta := tt) -- allow eta-equivalence: `(λ x, F $ x) ↝ F` (zeta : bool := tt) -- do zeta-reductions: `let x : a := b in c ↝ c[x/b]`. (beta : bool := tt) -- do beta-reductions: `(λ x, E) $ (y) ↝ E[x/y]`. (proj : bool := tt) -- reduce projections: `⟨a,b⟩.1 ↝ a` [TODO] I think? (iota : bool := tt) -- reduce recursors for inductive datatypes: eg `nat.rec_on (succ n) Z R ↝ R n $ nat.rec_on n Z R` (unfold_reducible := ff) -- if tt, definitions with `reducible` transparency will be unfolded (delta-reduced) (memoize := tt) -- [TODO] what is being memoised? end tactic /-- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. The list `u` contains defintions to be delta-reduced, and projections to be reduced.-/ meta constant simp_lemmas.dsimplify (s : simp_lemmas) (u : list name := []) (e : expr) (cfg : tactic.dsimp_config := {}) : tactic expr namespace tactic /- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/ meta constant dsimplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) /- (pre a e) is invoked before visiting the children of subterm 'e', if it succeeds the result (new_a, new_e, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression that must be definitionally equal to 'e', - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → expr → tactic (α × expr × bool)) /- (post a e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → expr → tactic (α × expr × bool)) (e : expr) (cfg : dsimp_config := {}) : tactic (α × expr) meta def dsimplify (pre : expr → tactic (expr × bool)) (post : expr → tactic (expr × bool)) : expr → tactic expr := λ e, do (a, new_e) ← dsimplify_core () (λ u e, do r ← pre e, return (u, r)) (λ u e, do r ← post e, return (u, r)) e, return new_e meta def get_simp_lemmas_or_default : option simp_lemmas → tactic simp_lemmas | none := simp_lemmas.mk_default | (some s) := return s meta def dsimp_target (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit := do s ← get_simp_lemmas_or_default s, t ← target >>= instantiate_mvars, s.dsimplify u t cfg >>= unsafe_change meta def dsimp_hyp (h : expr) (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit := do s ← get_simp_lemmas_or_default s, revert_and_transform (λ e, s.dsimplify u e cfg) h /- Remark: we use transparency.instances by default to make sure that we can unfold projections of type classes. Example: (@has_add.add nat nat.has_add a b) -/ /-- Tries to unfold `e` if it is a constant or a constant application. Remark: this is not a recursive procedure. -/ meta constant dunfold_head (e : expr) (md := transparency.instances) : tactic expr structure dunfold_config extends dsimp_config := (md := transparency.instances) /- Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for performance reasons. -/ meta constant dunfold (cs : list name) (e : expr) (cfg : dunfold_config := {}) : tactic expr meta def dunfold_target (cs : list name) (cfg : dunfold_config := {}) : tactic unit := do t ← target, dunfold cs t cfg >>= unsafe_change meta def dunfold_hyp (cs : list name) (h : expr) (cfg : dunfold_config := {}) : tactic unit := revert_and_transform (λ e, dunfold cs e cfg) h structure delta_config := (max_steps := simp.default_max_steps) (visit_instances := tt) private meta def is_delta_target (e : expr) (cs : list name) : bool := cs.any (λ c, if e.is_app_of c then tt /- Exact match -/ else let f := e.get_app_fn in /- f is an auxiliary constant generated when compiling c -/ f.is_constant && f.const_name.is_internal && (f.const_name.get_prefix = c)) /-- Delta reduce the given constant names -/ meta def delta (cs : list name) (e : expr) (cfg : delta_config := {}) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (is_delta_target e cs), (expr.const f_name f_lvls) ← return e.get_app_fn, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, new_e ← head_beta (expr.mk_app new_f e.get_app_args), return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () (λ c e, failed) unfold e {max_steps := cfg.max_steps, canonize_instances := cfg.visit_instances}, return new_e meta def delta_target (cs : list name) (cfg : delta_config := {}) : tactic unit := do t ← target, delta cs t cfg >>= unsafe_change meta def delta_hyp (cs : list name) (h : expr) (cfg : delta_config := {}) :tactic unit := revert_and_transform (λ e, delta cs e cfg) h structure unfold_proj_config extends dsimp_config := (md := transparency.instances) /-- If `e` is a projection application, try to unfold it, otherwise fail. -/ meta constant unfold_proj (e : expr) (md := transparency.instances) : tactic expr meta def unfold_projs (e : expr) (cfg : unfold_proj_config := {}) : tactic expr := let unfold (changed : bool) (e : expr) : tactic (bool × expr × bool) := do new_e ← unfold_proj e cfg.md, return (tt, new_e, tt) in do (tt, new_e) ← dsimplify_core ff (λ c e, failed) unfold e cfg.to_dsimp_config | fail "no projections to unfold", return new_e meta def unfold_projs_target (cfg : unfold_proj_config := {}) : tactic unit := do t ← target, unfold_projs t cfg >>= unsafe_change meta def unfold_projs_hyp (h : expr) (cfg : unfold_proj_config := {}) : tactic unit := revert_and_transform (λ e, unfold_projs e cfg) h structure simp_config := (max_steps : nat := simp.default_max_steps) (contextual : bool := ff) -- [TODO] what does this mean? (lift_eq : bool := tt) (canonize_instances : bool := tt) (canonize_proofs : bool := ff) (use_axioms : bool := tt) (zeta : bool := tt) (beta : bool := tt) (eta : bool := tt) (proj : bool := tt) -- reduce projections (iota : bool := tt) (iota_eqn : bool := ff) -- reduce using all equation lemmas generated by equation/pattern-matching compiler (constructor_eq : bool := tt) (single_pass : bool := ff) (fail_if_unchanged := tt) (memoize := tt) /-- `simplify s e cfg r prove` simplify `e` using `s` using bottom-up traversal. `discharger` is a tactic for dischaging new subgoals created by the simplifier. If it fails, the simplifier tries to discharge the subgoal by simplifying it to `true`. The parameter `to_unfold` specifies definitions that should be delta-reduced, and projection applications that should be unfolded. -/ meta constant simplify (s : simp_lemmas) (to_unfold : list name := []) (e : expr) (cfg : simp_config := {}) (r : name := `eq) (discharger : tactic unit := failed) : tactic (expr × expr) meta def simp_target (s : simp_lemmas) (to_unfold : list name := []) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic unit := do t ← target, (new_t, pr) ← simplify s to_unfold t cfg `eq discharger, replace_target new_t pr meta def simp_hyp (s : simp_lemmas) (to_unfold : list name := []) (h : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic expr := do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"), htype ← infer_type h, (h_new_type, pr) ← simplify s to_unfold htype cfg `eq discharger, replace_hyp h h_new_type pr /-- `ext_simplify_core a c s discharger pre post r e`: - `a : α` - initial user data - `c : simp_config` - simp configuration options - `s : simp_lemmas` - the set of simp_lemmas to use. Remark: the simplification lemmas are not applied automatically like in the simplify tactic. The caller must use them at pre/post. - `discharger : α → tactic α` - tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user data. - `pre a s r p e` is invoked before visiting the children of subterm 'e'. + arguments: - `a` is the current user data - `s` is the updated set of lemmas if 'contextual' is `tt`, - `r` is the simplification relation being used, - `p` is the "parent" expression (if there is one). - `e` is the current subexpression in question. + if it succeeds the result is `(new_a, new_e, new_pr, flag)` where - `new_a` is the new value for the user data - `new_e` is a new expression s.t. `r e new_e` - `new_pr` is a proof for `e r new_e`, If it is none, the proof is assumed to be by reflexivity - `flag` if tt `new_e` children should be visited, and `post` invoked. - `(post a s r p e)` is invoked after visiting the children of subterm `e`, The output is similar to `(pre a r s p e)`, but the 'flag' indicates whether the new expression should be revisited or not. - `r` is the simplification relation. Usually `=` or `↔`. - `e` is the input expression to be simplified. The method returns `(a,e,pr)` where - `a` is the final user data - `e` is the new expression - `pr` is the proof that the given expression equals the input expression. -/ meta constant ext_simplify_core {α : Type} (a : α) (c : simp_config) (s : simp_lemmas) (discharger : α → tactic α) (pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) (post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) (r : name) : expr → tactic (α × expr × expr) private meta def is_equation : expr → bool | (expr.pi n bi d b) := is_equation b | e := match (expr.is_eq e) with (some a) := tt | none := ff end meta def collect_ctx_simps : tactic (list expr) := local_context section simp_intros meta def intro1_aux : bool → list name → tactic expr | ff _ := intro1 | tt (n::ns) := intro n | _ _ := failed structure simp_intros_config extends simp_config := (use_hyps := ff) meta def simp_intros_aux (cfg : simp_config) (use_hyps : bool) (to_unfold : list name) : simp_lemmas → bool → list name → tactic simp_lemmas | S tt [] := try (simp_target S to_unfold cfg) >> return S | S use_ns ns := do t ← target, if t.is_napp_of `not 1 then intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail else if t.is_arrow then do { d ← return t.binding_domain, (new_d, h_d_eq_new_d) ← simplify S to_unfold d cfg, h_d ← intro1_aux use_ns ns, h_new_d ← mk_eq_mp h_d_eq_new_d h_d, assertv_core h_d.local_pp_name new_d h_new_d, clear h_d, h_new ← intro1, new_S ← if use_hyps then mcond (is_prop new_d) (S.add h_new ff) (return S) else return S, simp_intros_aux new_S use_ns ns.tail } <|> -- failed to simplify... we just introduce and continue (intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail) else if t.is_pi || t.is_let then intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail else do new_t ← whnf t reducible, if new_t.is_pi then unsafe_change new_t >> simp_intros_aux S use_ns ns else try (simp_target S to_unfold cfg) >> mcond (expr.is_pi <$> target) (simp_intros_aux S use_ns ns) (if use_ns ∧ ¬ns.empty then failed else return S) meta def simp_intros (s : simp_lemmas) (to_unfold : list name := []) (ids : list name := []) (cfg : simp_intros_config := {}) : tactic unit := step $ simp_intros_aux cfg.to_simp_config cfg.use_hyps to_unfold s (bnot ids.empty) ids end simp_intros meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit := do (lhs, rhs) ← target >>= match_eq, (new_rhs, heq) ← simp_ext lhs, unify rhs new_rhs, exact heq /- Simp attribute support -/ meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (n::ns) := do S' ← S.add_simp n ff, to_simp_lemmas S' ns meta def mk_simp_attr (attr_name : name) (attr_deps : list name := []) : command := do let t := `(user_attribute simp_lemmas), let v := `({name := attr_name, descr := "simplifier attribute", cache_cfg := { mk_cache := λ ns, do { s ← tactic.to_simp_lemmas simp_lemmas.mk ns, s ← attr_deps.mfoldl (λ s attr_name, do ns ← attribute.get_instances attr_name, to_simp_lemmas s ns) s, return s }, dependencies := `reducibility :: attr_deps}} : user_attribute simp_lemmas), let n := mk_simp_attr_decl_name attr_name, add_decl (declaration.defn n [] t v reducibility_hints.abbrev ff), attribute.register n /-- ### Example usage: ```lean -- make a new simp attribute called "my_reduction" run_cmd mk_simp_attr `my_reduction -- Add "my_reduction" attributes to these if-reductions attribute [my_reduction] if_pos if_neg dif_pos dif_neg -- will return the simp_lemmas with the `my_reduction` attribute. #eval get_user_simp_lemmas `my_reduction ``` -/ meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas := if attr_name = `default then simp_lemmas.mk_default else get_attribute_cache_dyn (mk_simp_attr_decl_name attr_name) meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S.join S') R meta def join_user_simp_lemmas (no_dflt : bool) (attrs : list name) : tactic simp_lemmas := if no_dflt then join_user_simp_lemmas_core simp_lemmas.mk attrs else do s ← simp_lemmas.mk_default, join_user_simp_lemmas_core s attrs /-- Normalize numerical expression, returns a pair (n, pr) where n is the resultant numeral, and pr is a proof that the input argument is equal to n. -/ meta constant norm_num : expr → tactic (expr × expr) 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, tt)) (λ _ _ _ _ _, failed) `eq e meta def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_top_down () (λ _ e, do (new_e, pr) ← pre e, return ((), new_e, pr)) t cfg, replace_target new_target pr meta def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← post a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) `eq e meta def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_bottom_up () (λ _ e, do (new_e, pr) ← post e, return ((), new_e, pr)) t cfg, replace_target new_target pr private meta def remove_deps (s : name_set) (h : expr) : name_set := if s.empty then s else h.fold s (λ e o s, if e.is_local_constant then s.erase e.local_uniq_name else s) /- Return the list of hypothesis that are propositions and do not have forward dependencies. -/ meta def non_dep_prop_hyps : tactic (list expr) := do ctx ← local_context, s ← ctx.mfoldl (λ s h, do h_type ← infer_type h, let s := remove_deps s h_type, h_val ← head_zeta h, let s := if h_val =ₐ h then s else remove_deps s h_val, mcond (is_prop h_type) (return $ s.insert h.local_uniq_name) (return s)) mk_name_set, t ← target, let s := remove_deps s t, return $ ctx.filter (λ h, s.contains h.local_uniq_name) section simp_all meta structure simp_all_entry := (h : expr) -- hypothesis (new_type : expr) -- new type (pr : option expr) -- proof that type of h is equal to new_type (s : simp_lemmas) -- simplification lemmas for simplifying new_type private meta def update_simp_lemmas (es : list simp_all_entry) (h : expr) : tactic (list simp_all_entry) := es.mmap $ λ e, do new_s ← e.s.add h ff, return {s := new_s, ..e} /- Helper tactic for `init`. Remark: the following tactic is quadratic on the length of list expr (the list of non dependent propositions). We can make it more efficient as soon as we have an efficient simp_lemmas.erase. -/ private meta def init_aux : list expr → simp_lemmas → list simp_all_entry → tactic (simp_lemmas × list simp_all_entry) | [] s r := return (s, r) | (h::hs) s r := do new_r ← update_simp_lemmas r h, new_s ← s.add h ff, h_type ← infer_type h, init_aux hs new_s (⟨h, h_type, none, s⟩::new_r) private meta def init (s : simp_lemmas) (hs : list expr) : tactic (simp_lemmas × list simp_all_entry) := init_aux hs s [] private meta def add_new_hyps (es : list simp_all_entry) : tactic unit := es.mmap' $ λ e, match e.pr with | none := return () | some pr := assert e.h.local_pp_name e.new_type >> mk_eq_mp pr e.h >>= exact end private meta def clear_old_hyps (es : list simp_all_entry) : tactic unit := es.mmap' $ λ e, when (e.pr ≠ none) (try (clear e.h)) private meta def join_pr : option expr → expr → tactic expr | none pr₂ := return pr₂ | (some pr₁) pr₂ := mk_eq_trans pr₁ pr₂ private meta def loop (cfg : simp_config) (discharger : tactic unit) (to_unfold : list name) : list simp_all_entry → list simp_all_entry → simp_lemmas → bool → tactic unit | [] r s m := if m then loop r [] s ff else do add_new_hyps r, target_changed ← (simp_target s to_unfold cfg discharger >> return tt) <|> return ff, guard (cfg.fail_if_unchanged = ff ∨ target_changed ∨ r.any (λ e, e.pr ≠ none)) <|> fail "simp_all tactic failed to simplify", clear_old_hyps r | (e::es) r s m := do let ⟨h, h_type, h_pr, s'⟩ := e, (new_h_type, new_pr) ← simplify s' to_unfold h_type {fail_if_unchanged := ff, ..cfg} `eq discharger, if h_type =ₐ new_h_type then loop es (e::r) s m else do new_pr ← join_pr h_pr new_pr, new_fact_pr ← mk_eq_mp new_pr h, if new_h_type = `(false) then do tgt ← target, to_expr ``(@false.rec %%tgt %%new_fact_pr) >>= exact else do h0_type ← infer_type h, let new_fact_pr := mk_id_proof new_h_type new_fact_pr, new_es ← update_simp_lemmas es new_fact_pr, new_r ← update_simp_lemmas r new_fact_pr, let new_r := {new_type := new_h_type, pr := new_pr, ..e} :: new_r, new_s ← s.add new_fact_pr ff, loop new_es new_r new_s tt meta def simp_all (s : simp_lemmas) (to_unfold : list name) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic unit := do hs ← non_dep_prop_hyps, (s, es) ← init s hs, loop cfg discharger to_unfold es [] s ff end simp_all /- debugging support for algebraic normalizer -/ meta constant trace_algebra_info : expr → tactic unit end tactic export tactic (mk_simp_attr) run_cmd mk_simp_attr `norm [`simp]
53ef1dce8e70ad2ac6dac1f621ce8d61f9d02003
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/order/field/basic.lean
126e30e1cd3401d6001ad24835170ed32f8d40c7
[ "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
31,640
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn -/ import order.bounds.order_iso import algebra.field.basic import algebra.order.field.defs import algebra.group_power.order /-! # Lemmas about linear ordered (semi)fields > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open function order_dual variables {ι α β : Type*} section linear_ordered_semifield variables [linear_ordered_semifield α] {a b c d e : α} {m n : ℤ} /-- `equiv.mul_left₀` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_left₀ (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_left ha, ..equiv.mul_left₀ a ha.ne' } /-- `equiv.mul_right₀` as an order_iso. -/ @[simps {simp_rhs := tt}] def order_iso.mul_right₀ (a : α) (ha : 0 < a) : α ≃o α := { map_rel_iff' := λ _ _, mul_le_mul_right ha, ..equiv.mul_right₀ a ha.ne' } /-! ### Lemmas about pos, nonneg, nonpos, neg -/ @[simp] lemma inv_pos : 0 < a⁻¹ ↔ 0 < a := suffices ∀ a : α, 0 < a → 0 < a⁻¹, from ⟨λ h, inv_inv a ▸ this _ h, this a⟩, assume a ha, flip lt_of_mul_lt_mul_left ha.le $ by simp [ne_of_gt ha, zero_lt_one] alias inv_pos ↔ _ inv_pos_of_pos @[simp] lemma inv_nonneg : 0 ≤ a⁻¹ ↔ 0 ≤ a := by simp only [le_iff_eq_or_lt, inv_pos, zero_eq_inv] alias inv_nonneg ↔ _ inv_nonneg_of_nonneg @[simp] lemma inv_lt_zero : a⁻¹ < 0 ↔ a < 0 := by simp only [← not_le, inv_nonneg] @[simp] lemma inv_nonpos : a⁻¹ ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, inv_pos] lemma one_div_pos : 0 < 1 / a ↔ 0 < a := inv_eq_one_div a ▸ inv_pos lemma one_div_neg : 1 / a < 0 ↔ a < 0 := inv_eq_one_div a ▸ inv_lt_zero lemma one_div_nonneg : 0 ≤ 1 / a ↔ 0 ≤ a := inv_eq_one_div a ▸ inv_nonneg lemma one_div_nonpos : 1 / a ≤ 0 ↔ a ≤ 0 := inv_eq_one_div a ▸ inv_nonpos lemma div_pos (ha : 0 < a) (hb : 0 < b) : 0 < a / b := by { rw div_eq_mul_inv, exact mul_pos ha (inv_pos.2 hb) } lemma div_nonneg (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b := by { rw div_eq_mul_inv, exact mul_nonneg ha (inv_nonneg.2 hb) } lemma div_nonpos_of_nonpos_of_nonneg (ha : a ≤ 0) (hb : 0 ≤ b) : a / b ≤ 0 := by { rw div_eq_mul_inv, exact mul_nonpos_of_nonpos_of_nonneg ha (inv_nonneg.2 hb) } lemma div_nonpos_of_nonneg_of_nonpos (ha : 0 ≤ a) (hb : b ≤ 0) : a / b ≤ 0 := by { rw div_eq_mul_inv, exact mul_nonpos_of_nonneg_of_nonpos ha (inv_nonpos.2 hb) } lemma zpow_nonneg (ha : 0 ≤ a) : ∀ n : ℤ, 0 ≤ a ^ n | (n : ℕ) := by { rw zpow_coe_nat, exact pow_nonneg ha _ } | -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_nonneg.2 (pow_nonneg ha _) } lemma zpow_pos_of_pos (ha : 0 < a) : ∀ n : ℤ, 0 < a ^ n | (n : ℕ) := by { rw zpow_coe_nat, exact pow_pos ha _ } | -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_pos.2 (pow_pos ha _) } /-! ### Relating one division with another term. -/ lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc).symm ▸ mul_le_mul_of_nonneg_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc).symm ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b := by rw [mul_comm, le_div_iff hc] lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b := ⟨λ h, calc a = a / b * b : by rw (div_mul_cancel _ (ne_of_lt hb).symm) ... ≤ c * b : mul_le_mul_of_nonneg_right h hb.le, λ h, calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≤ (c * b) * (1 / b) : mul_le_mul_of_nonneg_right h (one_div_pos.2 hb).le ... = (c * b) / b : (div_eq_mul_one_div (c * b) b).symm ... = c : by refine (div_eq_iff (ne_of_gt hb)).mpr rfl⟩ lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c := by rw [mul_comm, div_le_iff hb] lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b := lt_iff_lt_of_le_iff_le $ div_le_iff hc lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b := by rw [mul_comm, lt_div_iff hc] lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c := lt_iff_lt_of_le_iff_le (le_div_iff hc) lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a := by rw [mul_comm, div_lt_iff hc] lemma inv_mul_le_iff (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_le_iff' h, end lemma inv_mul_le_iff' (h : 0 < b) : b⁻¹ * a ≤ c ↔ a ≤ c * b := by rw [inv_mul_le_iff h, mul_comm] lemma mul_inv_le_iff (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ b * c := by rw [mul_comm, inv_mul_le_iff h] lemma mul_inv_le_iff' (h : 0 < b) : a * b⁻¹ ≤ c ↔ a ≤ c * b := by rw [mul_comm, inv_mul_le_iff' h] lemma div_self_le_one (a : α) : a / a ≤ 1 := if h : a = 0 then by simp [h] else by simp [h] lemma inv_mul_lt_iff (h : 0 < b) : b⁻¹ * a < c ↔ a < b * c := begin rw [inv_eq_one_div, mul_comm, ← div_eq_mul_one_div], exact div_lt_iff' h, end lemma inv_mul_lt_iff' (h : 0 < b) : b⁻¹ * a < c ↔ a < c * b := by rw [inv_mul_lt_iff h, mul_comm] lemma mul_inv_lt_iff (h : 0 < b) : a * b⁻¹ < c ↔ a < b * c := by rw [mul_comm, inv_mul_lt_iff h] lemma mul_inv_lt_iff' (h : 0 < b) : a * b⁻¹ < c ↔ a < c * b := by rw [mul_comm, inv_mul_lt_iff' h] lemma inv_pos_le_iff_one_le_mul (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ b * a := by { rw [inv_eq_one_div], exact div_le_iff ha } lemma inv_pos_le_iff_one_le_mul' (ha : 0 < a) : a⁻¹ ≤ b ↔ 1 ≤ a * b := by { rw [inv_eq_one_div], exact div_le_iff' ha } lemma inv_pos_lt_iff_one_lt_mul (ha : 0 < a) : a⁻¹ < b ↔ 1 < b * a := by { rw [inv_eq_one_div], exact div_lt_iff ha } lemma inv_pos_lt_iff_one_lt_mul' (ha : 0 < a) : a⁻¹ < b ↔ 1 < a * b := by { rw [inv_eq_one_div], exact div_lt_iff' ha } /-- One direction of `div_le_iff` where `b` is allowed to be `0` (but `c` must be nonnegative) -/ lemma div_le_of_nonneg_of_le_mul (hb : 0 ≤ b) (hc : 0 ≤ c) (h : a ≤ c * b) : a / b ≤ c := by { rcases eq_or_lt_of_le hb with rfl|hb', simp [hc], rwa [div_le_iff hb'] } lemma div_le_one_of_le (h : a ≤ b) (hb : 0 ≤ b) : a / b ≤ 1 := div_le_of_nonneg_of_le_mul hb zero_le_one $ by rwa one_mul /-! ### Bi-implications of inequalities using inversions -/ lemma inv_le_inv_of_le (ha : 0 < a) (h : a ≤ b) : b⁻¹ ≤ a⁻¹ := by rwa [← one_div a, le_div_iff' ha, ← div_eq_mul_inv, div_le_iff (ha.trans_le h), one_mul] /-- See `inv_le_inv_of_le` for the implication from right-to-left with one fewer assumption. -/ lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff ha, ← div_eq_inv_mul, le_div_iff hb, one_mul] /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ ≤ b ↔ b⁻¹ ≤ a`. See also `inv_le_of_inv_le` for a one-sided implication with one fewer assumption. -/ lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv hb (inv_pos.2 ha), inv_inv] lemma inv_le_of_inv_le (ha : 0 < a) (h : a⁻¹ ≤ b) : b⁻¹ ≤ a := (inv_le ha ((inv_pos.2 ha).trans_le h)).1 h lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv (inv_pos.2 hb) ha, inv_inv] /-- See `inv_lt_inv_of_lt` for the implication from right-to-left with one fewer assumption. -/ lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv hb ha) lemma inv_lt_inv_of_lt (hb : 0 < b) (h : b < a) : a⁻¹ < b⁻¹ := (inv_lt_inv (hb.trans h) hb).2 h /-- In a linear ordered field, for positive `a` and `b` we have `a⁻¹ < b ↔ b⁻¹ < a`. See also `inv_lt_of_inv_lt` for a one-sided implication with one fewer assumption. -/ lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv hb ha) lemma inv_lt_of_inv_lt (ha : 0 < a) (h : a⁻¹ < b) : b⁻¹ < a := (inv_lt ha ((inv_pos.2 ha).trans h)).1 h lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le hb ha) lemma inv_lt_one (ha : 1 < a) : a⁻¹ < 1 := by rwa [inv_lt (zero_lt_one.trans ha) zero_lt_one, inv_one] lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ := by rwa [lt_inv zero_lt_one h₁, inv_one] lemma inv_le_one (ha : 1 ≤ a) : a⁻¹ ≤ 1 := by rwa [inv_le (zero_lt_one.trans_le ha) zero_lt_one, inv_one] lemma one_le_inv (h₁ : 0 < a) (h₂ : a ≤ 1) : 1 ≤ a⁻¹ := by rwa [le_inv zero_lt_one h₁, inv_one] lemma inv_lt_one_iff_of_pos (h₀ : 0 < a) : a⁻¹ < 1 ↔ 1 < a := ⟨λ h₁, inv_inv a ▸ one_lt_inv (inv_pos.2 h₀) h₁, inv_lt_one⟩ lemma inv_lt_one_iff : a⁻¹ < 1 ↔ a ≤ 0 ∨ 1 < a := begin cases le_or_lt a 0 with ha ha, { simp [ha, (inv_nonpos.2 ha).trans_lt zero_lt_one] }, { simp only [ha.not_le, false_or, inv_lt_one_iff_of_pos ha] } end lemma one_lt_inv_iff : 1 < a⁻¹ ↔ 0 < a ∧ a < 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans h), inv_inv a ▸ inv_lt_one h⟩, and_imp.2 one_lt_inv⟩ lemma inv_le_one_iff : a⁻¹ ≤ 1 ↔ a ≤ 0 ∨ 1 ≤ a := begin rcases em (a = 1) with (rfl|ha), { simp [le_rfl] }, { simp only [ne.le_iff_lt (ne.symm ha), ne.le_iff_lt (mt inv_eq_one.1 ha), inv_lt_one_iff] } end lemma one_le_inv_iff : 1 ≤ a⁻¹ ↔ 0 < a ∧ a ≤ 1 := ⟨λ h, ⟨inv_pos.1 (zero_lt_one.trans_le h), inv_inv a ▸ inv_le_one h⟩, and_imp.2 one_le_inv⟩ /-! ### Relating two divisions. -/ @[mono] lemma div_le_div_of_le (hc : 0 ≤ c) (h : a ≤ b) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 hc) end -- Not a `mono` lemma b/c `div_le_div` is strictly more general lemma div_le_div_of_le_left (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) : a / b ≤ a / c := begin rw [div_eq_mul_inv, div_eq_mul_inv], exact mul_le_mul_of_nonneg_left ((inv_le_inv (hc.trans_le h) hc).mpr h) ha end lemma div_le_div_of_le_of_nonneg (hab : a ≤ b) (hc : 0 ≤ c) : a / c ≤ b / c := div_le_div_of_le hc hab lemma div_lt_div_of_lt (hc : 0 < c) (h : a < b) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos.2 hc) end lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_lt hc, div_le_div_of_le $ hc.le⟩ lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b := lt_iff_lt_of_le_iff_le $ div_le_div_right hc lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b := by simp only [div_eq_mul_inv, mul_lt_mul_left ha, inv_lt_inv hb hc] lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb) lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b < c / d ↔ a * d < c * b := by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0] lemma div_le_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b ≤ c / d ↔ a * d ≤ c * b := by rw [le_div_iff d0, div_mul_eq_mul_div, div_le_iff b0] @[mono] lemma div_le_div (hc : 0 ≤ c) (hac : a ≤ c) (hd : 0 < d) (hbd : d ≤ b) : a / b ≤ c / d := by { rw div_le_div_iff (hd.trans_le hbd) hd, exact mul_le_mul hac hbd hd.le hc } lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans_le hbd) d0).2 (mul_lt_mul hac hbd d0 c0) lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (d0.trans hbd) d0).2 (mul_lt_mul' hac hbd d0.le c0) lemma div_lt_div_of_lt_left (hc : 0 < c) (hb : 0 < b) (h : b < a) : c / a < c / b := (div_lt_div_left hc (hb.trans h) hb).mpr h /-! ### Relating one division and involving `1` -/ lemma div_le_self (ha : 0 ≤ a) (hb : 1 ≤ b) : a / b ≤ a := by simpa only [div_one] using div_le_div_of_le_left ha zero_lt_one hb lemma div_lt_self (ha : 0 < a) (hb : 1 < b) : a / b < a := by simpa only [div_one] using div_lt_div_of_lt_left ha zero_lt_one hb lemma le_div_self (ha : 0 ≤ a) (hb₀ : 0 < b) (hb₁ : b ≤ 1) : a ≤ a / b := by simpa only [div_one] using div_le_div_of_le_left ha hb₀ hb₁ lemma one_le_div (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a := by rw [le_div_iff hb, one_mul] lemma div_le_one (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b := by rw [div_le_iff hb, one_mul] lemma one_lt_div (hb : 0 < b) : 1 < a / b ↔ b < a := by rw [lt_div_iff hb, one_mul] lemma div_lt_one (hb : 0 < b) : a / b < 1 ↔ a < b := by rw [div_lt_iff hb, one_mul] lemma one_div_le (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le ha hb lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt ha hb lemma le_one_div (ha : 0 < a) (hb : 0 < b) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv ha hb lemma lt_one_div (ha : 0 < a) (hb : 0 < b) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv ha hb /-! ### Relating two divisions, involving `1` -/ lemma one_div_le_one_div_of_le (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a := by simpa using inv_le_inv_of_le ha h lemma one_div_lt_one_div_of_lt (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := by rwa [lt_div_iff' ha, ← div_eq_mul_one_div, div_lt_one (ha.trans h)] lemma le_of_one_div_le_one_div (ha : 0 < a) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_lt ha) h lemma lt_of_one_div_lt_one_div (ha : 0 < a) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_le ha) h /-- For the single implications with fewer assumptions, see `one_div_le_one_div_of_le` and `le_of_one_div_le_one_div` -/ lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a := div_le_div_left zero_lt_one ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a := div_lt_div_left zero_lt_one ha hb lemma one_lt_one_div (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := by rwa [lt_one_div zero_lt_one h1, one_div_one] lemma one_le_one_div (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a := by rwa [le_one_div zero_lt_one h1, one_div_one] /-! ### Results about halving. The equalities also hold in semifields of characteristic `0`. -/ /- TODO: Unify `add_halves` and `add_halves'` into a single lemma about `division_semiring` + `char_zero` -/ lemma add_halves (a : α) : a / 2 + a / 2 = a := by rw [div_add_div_same, ← two_mul, mul_div_cancel_left a two_ne_zero] -- TODO: Generalize to `division_semiring` lemma add_self_div_two (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero] lemma half_pos (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one lemma div_two_lt_of_pos (h : 0 < a) : a / 2 < a := by { rw [div_lt_iff (zero_lt_two' α)], exact lt_mul_of_one_lt_right h one_lt_two } lemma half_lt_self : 0 < a → a / 2 < a := div_two_lt_of_pos lemma half_le_self (ha_nonneg : 0 ≤ a) : a / 2 ≤ a := begin by_cases h0 : a = 0, { simp [h0], }, { rw ← ne.def at h0, exact (half_lt_self (lt_of_le_of_ne ha_nonneg h0.symm)).le, }, end lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one lemma two_inv_lt_one : (2⁻¹ : α) < 1 := (one_div _).symm.trans_lt one_half_lt_one lemma left_lt_add_div_two : a < (a + b) / 2 ↔ a < b := by simp [lt_div_iff, mul_two] lemma add_div_two_lt_right : (a + b) / 2 < b ↔ a < b := by simp [div_lt_iff, mul_two] /-! ### Miscellaneous lemmas -/ lemma mul_le_mul_of_mul_div_le (h : a * (b / c) ≤ d) (hc : 0 < c) : b * a ≤ d * c := begin rw [← mul_div_assoc] at h, rwa [mul_comm b, ← div_le_iff hc], end lemma div_mul_le_div_mul_of_div_le_div (h : a / b ≤ c / d) (he : 0 ≤ e) : a / (b * e) ≤ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], exact mul_le_mul_of_nonneg_right h (one_div_nonneg.2 he) end lemma exists_pos_mul_lt {a : α} (h : 0 < a) (b : α) : ∃ c : α, 0 < c ∧ b * c < a := begin have : 0 < a / max (b + 1) 1, from div_pos h (lt_max_iff.2 (or.inr zero_lt_one)), refine ⟨a / max (b + 1) 1, this, _⟩, rw [← lt_div_iff this, div_div_cancel' h.ne'], exact lt_max_iff.2 (or.inl $ lt_add_one _) end lemma exists_pos_lt_mul {a : α} (h : 0 < a) (b : α) : ∃ c : α, 0 < c ∧ b < c * a := let ⟨c, hc₀, hc⟩ := exists_pos_mul_lt h b in ⟨c⁻¹, inv_pos.2 hc₀, by rwa [← div_eq_inv_mul, lt_div_iff hc₀]⟩ lemma monotone.div_const {β : Type*} [preorder β] {f : β → α} (hf : monotone f) {c : α} (hc : 0 ≤ c) : monotone (λ x, (f x) / c) := begin haveI := @linear_order.decidable_le α _, simpa only [div_eq_mul_inv] using (monotone_mul_right_of_nonneg (inv_nonneg.2 hc)).comp hf end lemma strict_mono.div_const {β : Type*} [preorder β] {f : β → α} (hf : strict_mono f) {c : α} (hc : 0 < c) : strict_mono (λ x, (f x) / c) := by simpa only [div_eq_mul_inv] using hf.mul_const (inv_pos.2 hc) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_densely_ordered : densely_ordered α := { dense := λ a₁ a₂ h, ⟨(a₁ + a₂) / 2, calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm ... < (a₁ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_left h _), calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt zero_lt_two (add_lt_add_right h _) ... = a₂ : add_self_div_two a₂⟩ } lemma min_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : min (a / c) (b / c) = (min a b) / c := eq.symm $ monotone.map_min (λ x y, div_le_div_of_le hc) lemma max_div_div_right {c : α} (hc : 0 ≤ c) (a b : α) : max (a / c) (b / c) = (max a b) / c := eq.symm $ monotone.map_max (λ x y, div_le_div_of_le hc) lemma one_div_strict_anti_on : strict_anti_on (λ x : α, 1 / x) (set.Ioi 0) := λ x x1 y y1 xy, (one_div_lt_one_div (set.mem_Ioi.mp y1) (set.mem_Ioi.mp x1)).mpr xy lemma one_div_pow_le_one_div_pow_of_le (a1 : 1 ≤ a) {m n : ℕ} (mn : m ≤ n) : 1 / a ^ n ≤ 1 / a ^ m := by refine (one_div_le_one_div _ _).mpr (pow_le_pow a1 mn); exact pow_pos (zero_lt_one.trans_le a1) _ lemma one_div_pow_lt_one_div_pow_of_lt (a1 : 1 < a) {m n : ℕ} (mn : m < n) : 1 / a ^ n < 1 / a ^ m := by refine (one_div_lt_one_div _ _).mpr (pow_lt_pow a1 mn); exact pow_pos (trans zero_lt_one a1) _ lemma one_div_pow_anti (a1 : 1 ≤ a) : antitone (λ n : ℕ, 1 / a ^ n) := λ m n, one_div_pow_le_one_div_pow_of_le a1 lemma one_div_pow_strict_anti (a1 : 1 < a) : strict_anti (λ n : ℕ, 1 / a ^ n) := λ m n, one_div_pow_lt_one_div_pow_of_lt a1 lemma inv_strict_anti_on : strict_anti_on (λ x : α, x⁻¹) (set.Ioi 0) := λ x hx y hy xy, (inv_lt_inv hy hx).2 xy lemma inv_pow_le_inv_pow_of_le (a1 : 1 ≤ a) {m n : ℕ} (mn : m ≤ n) : (a ^ n)⁻¹ ≤ (a ^ m)⁻¹ := by convert one_div_pow_le_one_div_pow_of_le a1 mn; simp lemma inv_pow_lt_inv_pow_of_lt (a1 : 1 < a) {m n : ℕ} (mn : m < n) : (a ^ n)⁻¹ < (a ^ m)⁻¹ := by convert one_div_pow_lt_one_div_pow_of_lt a1 mn; simp lemma inv_pow_anti (a1 : 1 ≤ a) : antitone (λ n : ℕ, (a ^ n)⁻¹) := λ m n, inv_pow_le_inv_pow_of_le a1 lemma inv_pow_strict_anti (a1 : 1 < a) : strict_anti (λ n : ℕ, (a ^ n)⁻¹) := λ m n, inv_pow_lt_inv_pow_of_lt a1 /-! ### Results about `is_lub` and `is_glb` -/ lemma is_glb.mul_left {s : set α} (ha : 0 ≤ a) (hs : is_glb s b) : is_glb ((λ b, a * b) '' s) (a * b) := begin rcases lt_or_eq_of_le ha with ha | rfl, { exact (order_iso.mul_left₀ _ ha).is_glb_image'.2 hs, }, { simp_rw zero_mul, rw hs.nonempty.image_const, exact is_glb_singleton }, end lemma is_glb.mul_right {s : set α} (ha : 0 ≤ a) (hs : is_glb s b) : is_glb ((λ b, b * a) '' s) (b * a) := by simpa [mul_comm] using hs.mul_left ha end linear_ordered_semifield section variables [linear_ordered_field α] {a b c d : α} {n : ℤ} /-! ### Lemmas about pos, nonneg, nonpos, neg -/ lemma div_pos_iff : 0 < a / b ↔ 0 < a ∧ 0 < b ∨ a < 0 ∧ b < 0 := by simp [division_def, mul_pos_iff] lemma div_neg_iff : a / b < 0 ↔ 0 < a ∧ b < 0 ∨ a < 0 ∧ 0 < b := by simp [division_def, mul_neg_iff] lemma div_nonneg_iff : 0 ≤ a / b ↔ 0 ≤ a ∧ 0 ≤ b ∨ a ≤ 0 ∧ b ≤ 0 := by simp [division_def, mul_nonneg_iff] lemma div_nonpos_iff : a / b ≤ 0 ↔ 0 ≤ a ∧ b ≤ 0 ∨ a ≤ 0 ∧ 0 ≤ b := by simp [division_def, mul_nonpos_iff] lemma div_nonneg_of_nonpos (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a / b := div_nonneg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_pos_of_neg_of_neg (ha : a < 0) (hb : b < 0) : 0 < a / b := div_pos_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a / b < 0 := div_neg_iff.2 $ or.inr ⟨ha, hb⟩ lemma div_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a / b < 0 := div_neg_iff.2 $ or.inl ⟨ha, hb⟩ /-! ### Relating one division with another term -/ lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b := ⟨λ h, div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h hc.le, λ h, calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (one_div_neg.2 hc).le ... = b / c : (div_eq_mul_one_div b c).symm⟩ lemma div_le_iff_of_neg' (hc : c < 0) : b / c ≤ a ↔ c * a ≤ b := by rw [mul_comm, div_le_iff_of_neg hc] lemma le_div_iff_of_neg (hc : c < 0) : a ≤ b / c ↔ b ≤ a * c := by rw [← neg_neg c, mul_neg, div_neg, le_neg, div_le_iff (neg_pos.2 hc), neg_mul] lemma le_div_iff_of_neg' (hc : c < 0) : a ≤ b / c ↔ b ≤ c * a := by rw [mul_comm, le_div_iff_of_neg hc] lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b := lt_iff_lt_of_le_iff_le $ le_div_iff_of_neg hc lemma div_lt_iff_of_neg' (hc : c < 0) : b / c < a ↔ c * a < b := by rw [mul_comm, div_lt_iff_of_neg hc] lemma lt_div_iff_of_neg (hc : c < 0) : a < b / c ↔ b < a * c := lt_iff_lt_of_le_iff_le $ div_le_iff_of_neg hc lemma lt_div_iff_of_neg' (hc : c < 0) : a < b / c ↔ b < c * a := by rw [mul_comm, lt_div_iff_of_neg hc] /-! ### Bi-implications of inequalities using inversions -/ lemma inv_le_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [← one_div, div_le_iff_of_neg ha, ← div_eq_inv_mul, div_le_iff_of_neg hb, one_mul] lemma inv_le_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv_of_neg hb (inv_lt_zero.2 ha), inv_inv] lemma le_inv_of_neg (ha : a < 0) (hb : b < 0) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv_of_neg (inv_lt_zero.2 hb) ha, inv_inv] lemma inv_lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv_of_neg hb ha) lemma inv_lt_of_neg (ha : a < 0) (hb : b < 0) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv_of_neg hb ha) lemma lt_inv_of_neg (ha : a < 0) (hb : b < 0) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le_of_neg hb ha) /-! ### Relating two divisions -/ lemma div_le_div_of_nonpos_of_le (hc : c ≤ 0) (h : b ≤ a) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (one_div_nonpos.2 hc) end lemma div_lt_div_of_neg_of_lt (hc : c < 0) (h : b < a) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg.2 hc) end lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a := ⟨le_imp_le_of_lt_imp_lt $ div_lt_div_of_neg_of_lt hc, div_le_div_of_nonpos_of_le $ hc.le⟩ lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a := lt_iff_lt_of_le_iff_le $ div_le_div_right_of_neg hc /-! ### Relating one division and involving `1` -/ lemma one_le_div_of_neg (hb : b < 0) : 1 ≤ a / b ↔ a ≤ b := by rw [le_div_iff_of_neg hb, one_mul] lemma div_le_one_of_neg (hb : b < 0) : a / b ≤ 1 ↔ b ≤ a := by rw [div_le_iff_of_neg hb, one_mul] lemma one_lt_div_of_neg (hb : b < 0) : 1 < a / b ↔ a < b := by rw [lt_div_iff_of_neg hb, one_mul] lemma div_lt_one_of_neg (hb : b < 0) : a / b < 1 ↔ b < a := by rw [div_lt_iff_of_neg hb, one_mul] lemma one_div_le_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ b ↔ 1 / b ≤ a := by simpa using inv_le_of_neg ha hb lemma one_div_lt_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < b ↔ 1 / b < a := by simpa using inv_lt_of_neg ha hb lemma le_one_div_of_neg (ha : a < 0) (hb : b < 0) : a ≤ 1 / b ↔ b ≤ 1 / a := by simpa using le_inv_of_neg ha hb lemma lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : a < 1 / b ↔ b < 1 / a := by simpa using lt_inv_of_neg ha hb lemma one_lt_div_iff : 1 < a / b ↔ 0 < b ∧ b < a ∨ b < 0 ∧ a < b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_lt_div_of_neg] }, { simp [lt_irrefl, zero_le_one] }, { simp [hb, hb.not_lt, one_lt_div] } end lemma one_le_div_iff : 1 ≤ a / b ↔ 0 < b ∧ b ≤ a ∨ b < 0 ∧ a ≤ b := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, one_le_div_of_neg] }, { simp [lt_irrefl, zero_lt_one.not_le, zero_lt_one] }, { simp [hb, hb.not_lt, one_le_div] } end lemma div_lt_one_iff : a / b < 1 ↔ 0 < b ∧ a < b ∨ b = 0 ∨ b < 0 ∧ b < a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_lt_one_of_neg] }, { simp [zero_lt_one], }, { simp [hb, hb.not_lt, div_lt_one, hb.ne.symm] } end lemma div_le_one_iff : a / b ≤ 1 ↔ 0 < b ∧ a ≤ b ∨ b = 0 ∨ b < 0 ∧ b ≤ a := begin rcases lt_trichotomy b 0 with (hb|rfl|hb), { simp [hb, hb.not_lt, hb.ne, div_le_one_of_neg] }, { simp [zero_le_one], }, { simp [hb, hb.not_lt, div_le_one, hb.ne.symm] } end /-! ### Relating two divisions, involving `1` -/ lemma one_div_le_one_div_of_neg_of_le (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a := by rwa [div_le_iff_of_neg' hb, ← div_eq_mul_one_div, div_le_one_of_neg (h.trans_lt hb)] lemma one_div_lt_one_div_of_neg_of_lt (hb : b < 0) (h : a < b) : 1 / b < 1 / a := by rwa [div_lt_iff_of_neg' hb, ← div_eq_mul_one_div, div_lt_one_of_neg (h.trans hb)] lemma le_of_neg_of_one_div_le_one_div (hb : b < 0) (h : 1 / a ≤ 1 / b) : b ≤ a := le_imp_le_of_lt_imp_lt (one_div_lt_one_div_of_neg_of_lt hb) h lemma lt_of_neg_of_one_div_lt_one_div (hb : b < 0) (h : 1 / a < 1 / b) : b < a := lt_imp_lt_of_le_imp_le (one_div_le_one_div_of_neg_of_le hb) h /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_neg_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_le_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a ≤ 1 / b ↔ b ≤ a := by simpa [one_div] using inv_le_inv_of_neg ha hb /-- For the single implications with fewer assumptions, see `one_div_lt_one_div_of_lt` and `lt_of_one_div_lt_one_div` -/ lemma one_div_lt_one_div_of_neg (ha : a < 0) (hb : b < 0) : 1 / a < 1 / b ↔ b < a := lt_iff_lt_of_le_iff_le (one_div_le_one_div_of_neg hb ha) lemma one_div_lt_neg_one (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_neg_of_lt h1 h2 lemma one_div_le_neg_one (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 := suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_neg_of_le h1 h2 /-! ### Results about halving -/ lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_sub_div_two_lt (h : a < b) : a + (b - a) / 2 < b := begin rwa [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg, ← lt_sub_iff_add_lt, sub_self_div_two, sub_self_div_two, div_lt_div_right (zero_lt_two' α)] end /-- An inequality involving `2`. -/ lemma sub_one_div_inv_le_two (a2 : 2 ≤ a) : (1 - 1 / a)⁻¹ ≤ 2 := begin -- Take inverses on both sides to obtain `2⁻¹ ≤ 1 - 1 / a` refine (inv_le_inv_of_le (inv_pos.2 $ zero_lt_two' α) _).trans_eq (inv_inv (2 : α)), -- move `1 / a` to the left and `1 - 1 / 2 = 1 / 2` to the right to obtain `1 / a ≤ ⅟ 2` refine (le_sub_iff_add_le.2 (_ : _ + 2⁻¹ = _ ).le).trans ((sub_le_sub_iff_left 1).2 _), { -- show 2⁻¹ + 2⁻¹ = 1 exact (two_mul _).symm.trans (mul_inv_cancel two_ne_zero) }, { -- take inverses on both sides and use the assumption `2 ≤ a`. exact (one_div a).le.trans (inv_le_inv_of_le zero_lt_two a2) } end /-! ### Results about `is_lub` and `is_glb` -/ -- TODO: Generalize to `linear_ordered_semifield` lemma is_lub.mul_left {s : set α} (ha : 0 ≤ a) (hs : is_lub s b) : is_lub ((λ b, a * b) '' s) (a * b) := begin rcases lt_or_eq_of_le ha with ha | rfl, { exact (order_iso.mul_left₀ _ ha).is_lub_image'.2 hs, }, { simp_rw zero_mul, rw hs.nonempty.image_const, exact is_lub_singleton }, end -- TODO: Generalize to `linear_ordered_semifield` lemma is_lub.mul_right {s : set α} (ha : 0 ≤ a) (hs : is_lub s b) : is_lub ((λ b, b * a) '' s) (b * a) := by simpa [mul_comm] using hs.mul_left ha /-! ### Miscellaneous lemmmas -/ lemma mul_sub_mul_div_mul_neg_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) < 0 ↔ a / c < b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_lt_zero] lemma mul_sub_mul_div_mul_nonpos_iff (hc : c ≠ 0) (hd : d ≠ 0) : (a * d - b * c) / (c * d) ≤ 0 ↔ a / c ≤ b / d := by rw [mul_comm b c, ← div_sub_div _ _ hc hd, sub_nonpos] alias mul_sub_mul_div_mul_neg_iff ↔ div_lt_div_of_mul_sub_mul_div_neg mul_sub_mul_div_mul_neg alias mul_sub_mul_div_mul_nonpos_iff ↔ div_le_div_of_mul_sub_mul_div_nonpos mul_sub_mul_div_mul_nonpos lemma exists_add_lt_and_pos_of_lt (h : b < a) : ∃ c, b + c < a ∧ 0 < c := ⟨(a - b) / 2, add_sub_div_two_lt h, div_pos (sub_pos_of_lt h) zero_lt_two⟩ lemma le_of_forall_sub_le (h : ∀ ε > 0, b - ε ≤ a) : b ≤ a := begin contrapose! h, simpa only [and_comm ((0 : α) < _), lt_sub_iff_add_lt, gt_iff_lt] using exists_add_lt_and_pos_of_lt h, end lemma mul_self_inj_of_nonneg (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b := mul_self_eq_mul_self_iff.trans $ or_iff_left_of_imp $ λ h, by { subst a, have : b = 0 := le_antisymm (neg_nonneg.1 a0) b0, rw [this, neg_zero] } lemma min_div_div_right_of_nonpos (hc : c ≤ 0) (a b : α) : min (a / c) (b / c) = (max a b) / c := eq.symm $ antitone.map_max $ λ x y, div_le_div_of_nonpos_of_le hc lemma max_div_div_right_of_nonpos (hc : c ≤ 0) (a b : α) : max (a / c) (b / c) = (min a b) / c := eq.symm $ antitone.map_min $ λ x y, div_le_div_of_nonpos_of_le hc lemma abs_inv (a : α) : |a⁻¹| = (|a|)⁻¹ := map_inv₀ (abs_hom : α →*₀ α) a lemma abs_div (a b : α) : |a / b| = |a| / |b| := map_div₀ (abs_hom : α →*₀ α) a b lemma abs_one_div (a : α) : |1 / a| = 1 / |a| := by rw [abs_div, abs_one] lemma pow_minus_two_nonneg : 0 ≤ a^(-2 : ℤ) := begin simp only [inv_nonneg, zpow_neg], change 0 ≤ a ^ ((2 : ℕ) : ℤ), rw zpow_coe_nat, apply sq_nonneg, end end
32629d84608005d84368552a9b517832eab977f4
c777c32c8e484e195053731103c5e52af26a25d1
/src/number_theory/liouville/liouville_with.lean
c05c8aeaa9979e036061a89ca4274f4f84104138
[ "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
14,807
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.special_functions.pow import number_theory.liouville.basic import topology.instances.irrational /-! # Liouville numbers with a given exponent We say that a real number `x` is a Liouville number with exponent `p : ℝ` if there exists a real number `C` such that for infinitely many denominators `n` there exists a numerator `m` such that `x ≠ m / n` and `|x - m / n| < C / n ^ p`. A number is a Liouville number in the sense of `liouville` if it is `liouville_with` any real exponent, see `forall_liouville_with_iff`. * If `p ≤ 1`, then this condition is trivial. * If `1 < p ≤ 2`, then this condition is equivalent to `irrational x`. The forward implication does not require `p ≤ 2` and is formalized as `liouville_with.irrational`; the other implication follows from approximations by continued fractions and is not formalized yet. * If `p > 2`, then this is a non-trivial condition on irrational numbers. In particular, [Thue–Siegel–Roth theorem](https://en.wikipedia.org/wiki/Roth's_theorem) states that such numbers must be transcendental. In this file we define the predicate `liouville_with` and prove some basic facts about this predicate. ## Tags Liouville number, irrational, irrationality exponent -/ open filter metric real set open_locale filter topology /-- We say that a real number `x` is a Liouville number with exponent `p : ℝ` if there exists a real number `C` such that for infinitely many denominators `n` there exists a numerator `m` such that `x ≠ m / n` and `|x - m / n| < C / n ^ p`. A number is a Liouville number in the sense of `liouville` if it is `liouville_with` any real exponent. -/ def liouville_with (p x : ℝ) : Prop := ∃ C, ∃ᶠ n : ℕ in at_top, ∃ m : ℤ, x ≠ m / n ∧ |x - m / n| < C / n ^ p /-- For `p = 1` (hence, for any `p ≤ 1`), the condition `liouville_with p x` is trivial. -/ lemma liouville_with_one (x : ℝ) : liouville_with 1 x := begin use 2, refine ((eventually_gt_at_top 0).mono $ λ n hn, _).frequently, have hn' : (0 : ℝ) < n, by simpa, have : x < ↑(⌊x * ↑n⌋ + 1) / ↑n, { rw [lt_div_iff hn', int.cast_add, int.cast_one], exact int.lt_floor_add_one _ }, refine ⟨⌊x * n⌋ + 1, this.ne, _⟩, rw [abs_sub_comm, abs_of_pos (sub_pos.2 this), rpow_one, sub_lt_iff_lt_add', add_div_eq_mul_add_div _ _ hn'.ne', div_lt_div_right hn'], simpa [bit0, ← add_assoc] using (int.floor_le (x * n)).trans_lt (lt_add_one _) end namespace liouville_with variables {p q x y : ℝ} {r : ℚ} {m : ℤ} {n : ℕ} /-- The constant `C` provided by the definition of `liouville_with` can be made positive. We also add `1 ≤ n` to the list of assumptions about the denominator. While it is equivalent to the original statement, the case `n = 0` breaks many arguments. -/ lemma exists_pos (h : liouville_with p x) : ∃ (C : ℝ) (h₀ : 0 < C), ∃ᶠ n : ℕ in at_top, 1 ≤ n ∧ ∃ m : ℤ, x ≠ m / n ∧ |x - m / n| < C / n ^ p := begin rcases h with ⟨C, hC⟩, refine ⟨max C 1, zero_lt_one.trans_le $ le_max_right _ _, _⟩, refine ((eventually_ge_at_top 1).and_frequently hC).mono _, rintro n ⟨hle, m, hne, hlt⟩, refine ⟨hle, m, hne, hlt.trans_le _⟩, exact div_le_div_of_le (rpow_nonneg_of_nonneg n.cast_nonneg _) (le_max_left _ _) end /-- If a number is Liouville with exponent `p`, then it is Liouville with any smaller exponent. -/ lemma mono (h : liouville_with p x) (hle : q ≤ p) : liouville_with q x := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨C, hC.mono _⟩, rintro n ⟨hn, m, hne, hlt⟩, refine ⟨m, hne, hlt.trans_le $ div_le_div_of_le_left hC₀.le _ _⟩, exacts [rpow_pos_of_pos (nat.cast_pos.2 hn) _, rpow_le_rpow_of_exponent_le (nat.one_le_cast.2 hn) hle] end /-- If `x` satisfies Liouville condition with exponent `p` and `q < p`, then `x` satisfies Liouville condition with exponent `q` and constant `1`. -/ lemma frequently_lt_rpow_neg (h : liouville_with p x) (hlt : q < p) : ∃ᶠ n : ℕ in at_top, ∃ m : ℤ, x ≠ m / n ∧ |x - m / n| < n ^ (-q) := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, have : ∀ᶠ n : ℕ in at_top, C < n ^ (p - q), by simpa only [(∘), neg_sub, one_div] using ((tendsto_rpow_at_top (sub_pos.2 hlt)).comp tendsto_coe_nat_at_top_at_top).eventually (eventually_gt_at_top C), refine (this.and_frequently hC).mono _, rintro n ⟨hnC, hn, m, hne, hlt⟩, replace hn : (0 : ℝ) < n := nat.cast_pos.2 hn, refine ⟨m, hne, hlt.trans $ (div_lt_iff $ rpow_pos_of_pos hn _).2 _⟩, rwa [mul_comm, ← rpow_add hn, ← sub_eq_add_neg] end /-- The product of a Liouville number and a nonzero rational number is again a Liouville number. -/ lemma mul_rat (h : liouville_with p x) (hr : r ≠ 0) : liouville_with p (x * r) := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨r.denom ^ p * (|r| * C), (tendsto_id.nsmul_at_top r.pos).frequently (hC.mono _)⟩, rintro n ⟨hn, m, hne, hlt⟩, have A : (↑(r.num * m) : ℝ) / ↑(r.denom • id n) = (m / n) * r, by simp [← div_mul_div_comm, ← r.cast_def, mul_comm], refine ⟨r.num * m, _, _⟩, { rw A, simp [hne, hr] }, { rw [A, ← sub_mul, abs_mul], simp only [smul_eq_mul, id.def, nat.cast_mul], refine (mul_lt_mul_of_pos_right hlt $ abs_pos.2 $ rat.cast_ne_zero.2 hr).trans_le _, rw [mul_rpow, mul_div_mul_left, mul_comm, mul_div_assoc], exacts [(rpow_pos_of_pos (nat.cast_pos.2 r.pos) _).ne', nat.cast_nonneg _, nat.cast_nonneg _] } end /-- The product `x * r`, `r : ℚ`, `r ≠ 0`, is a Liouville number with exponent `p` if and only if `x` satisfies the same condition. -/ lemma mul_rat_iff (hr : r ≠ 0) : liouville_with p (x * r) ↔ liouville_with p x := ⟨λ h, by simpa only [mul_assoc, ← rat.cast_mul, mul_inv_cancel hr, rat.cast_one, mul_one] using h.mul_rat (inv_ne_zero hr), λ h, h.mul_rat hr⟩ /-- The product `r * x`, `r : ℚ`, `r ≠ 0`, is a Liouville number with exponent `p` if and only if `x` satisfies the same condition. -/ lemma rat_mul_iff (hr : r ≠ 0) : liouville_with p (r * x) ↔ liouville_with p x := by rw [mul_comm, mul_rat_iff hr] lemma rat_mul (h : liouville_with p x) (hr : r ≠ 0) : liouville_with p (r * x) := (rat_mul_iff hr).2 h lemma mul_int_iff (hm : m ≠ 0) : liouville_with p (x * m) ↔ liouville_with p x := by rw [← rat.cast_coe_int, mul_rat_iff (int.cast_ne_zero.2 hm)] lemma mul_int (h : liouville_with p x) (hm : m ≠ 0) : liouville_with p (x * m) := (mul_int_iff hm).2 h lemma int_mul_iff (hm : m ≠ 0) : liouville_with p (m * x) ↔ liouville_with p x := by rw [mul_comm, mul_int_iff hm] lemma int_mul (h : liouville_with p x) (hm : m ≠ 0) : liouville_with p (m * x) := (int_mul_iff hm).2 h lemma mul_nat_iff (hn : n ≠ 0) : liouville_with p (x * n) ↔ liouville_with p x := by rw [← rat.cast_coe_nat, mul_rat_iff (nat.cast_ne_zero.2 hn)] lemma mul_nat (h : liouville_with p x) (hn : n ≠ 0) : liouville_with p (x * n) := (mul_nat_iff hn).2 h lemma nat_mul_iff (hn : n ≠ 0) : liouville_with p (n * x) ↔ liouville_with p x:= by rw [mul_comm, mul_nat_iff hn] lemma nat_mul (h : liouville_with p x) (hn : n ≠ 0) : liouville_with p (n * x) := by { rw mul_comm, exact h.mul_nat hn } lemma add_rat (h : liouville_with p x) (r : ℚ) : liouville_with p (x + r) := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨r.denom ^ p * C, (tendsto_id.nsmul_at_top r.pos).frequently (hC.mono _)⟩, rintro n ⟨hn, m, hne, hlt⟩, have hr : (0 : ℝ) < r.denom, from nat.cast_pos.2 r.pos, have hn' : (n : ℝ) ≠ 0, from nat.cast_ne_zero.2 (zero_lt_one.trans_le hn).ne', have : (↑(r.denom * m + r.num * n : ℤ) / ↑(r.denom • id n) : ℝ) = m / n + r, by simp [add_div, hr.ne', mul_div_mul_left, mul_div_mul_right, hn', ← rat.cast_def], refine ⟨r.denom * m + r.num * n, _⟩, rw [this, add_sub_add_right_eq_sub], refine ⟨by simpa, hlt.trans_le (le_of_eq _)⟩, have : (r.denom ^ p : ℝ) ≠ 0, from (rpow_pos_of_pos hr _).ne', simp [mul_rpow, nat.cast_nonneg, mul_div_mul_left, this] end @[simp] lemma add_rat_iff : liouville_with p (x + r) ↔ liouville_with p x := ⟨λ h, by simpa using h.add_rat (-r), λ h, h.add_rat r⟩ @[simp] lemma rat_add_iff : liouville_with p (r + x) ↔ liouville_with p x := by rw [add_comm, add_rat_iff] lemma rat_add (h : liouville_with p x) (r : ℚ) : liouville_with p (r + x) := add_comm x r ▸ h.add_rat r @[simp] lemma add_int_iff : liouville_with p (x + m) ↔ liouville_with p x := by rw [← rat.cast_coe_int m, add_rat_iff] @[simp] lemma int_add_iff : liouville_with p (m + x) ↔ liouville_with p x := by rw [add_comm, add_int_iff] @[simp] lemma add_nat_iff : liouville_with p (x + n) ↔ liouville_with p x := by rw [← rat.cast_coe_nat n, add_rat_iff] @[simp] lemma nat_add_iff : liouville_with p (n + x) ↔ liouville_with p x := by rw [add_comm, add_nat_iff] lemma add_int (h : liouville_with p x) (m : ℤ) : liouville_with p (x + m) := add_int_iff.2 h lemma int_add (h : liouville_with p x) (m : ℤ) : liouville_with p (m + x) := int_add_iff.2 h lemma add_nat (h : liouville_with p x) (n : ℕ) : liouville_with p (x + n) := h.add_int n lemma nat_add (h : liouville_with p x) (n : ℕ) : liouville_with p (n + x) := h.int_add n protected lemma neg (h : liouville_with p x) : liouville_with p (-x) := begin rcases h with ⟨C, hC⟩, refine ⟨C, hC.mono _⟩, rintro n ⟨m, hne, hlt⟩, use (-m), simp [neg_div, abs_sub_comm _ x, *] end @[simp] lemma neg_iff : liouville_with p (-x) ↔ liouville_with p x := ⟨λ h, neg_neg x ▸ h.neg, liouville_with.neg⟩ @[simp] lemma sub_rat_iff : liouville_with p (x - r) ↔ liouville_with p x := by rw [sub_eq_add_neg, ← rat.cast_neg, add_rat_iff] lemma sub_rat (h : liouville_with p x) (r : ℚ) : liouville_with p (x - r) := sub_rat_iff.2 h @[simp] lemma sub_int_iff : liouville_with p (x - m) ↔ liouville_with p x := by rw [← rat.cast_coe_int, sub_rat_iff] lemma sub_int (h : liouville_with p x) (m : ℤ) : liouville_with p (x - m) := sub_int_iff.2 h @[simp] lemma sub_nat_iff : liouville_with p (x - n) ↔ liouville_with p x := by rw [← rat.cast_coe_nat, sub_rat_iff] lemma sub_nat (h : liouville_with p x) (n : ℕ) : liouville_with p (x - n) := sub_nat_iff.2 h @[simp] lemma rat_sub_iff : liouville_with p (r - x) ↔ liouville_with p x := by simp [sub_eq_add_neg] lemma rat_sub (h : liouville_with p x) (r : ℚ) : liouville_with p (r - x) := rat_sub_iff.2 h @[simp] lemma int_sub_iff : liouville_with p (m - x) ↔ liouville_with p x := by simp [sub_eq_add_neg] lemma int_sub (h : liouville_with p x) (m : ℤ) : liouville_with p (m - x) := int_sub_iff.2 h @[simp] lemma nat_sub_iff : liouville_with p (n - x) ↔ liouville_with p x := by simp [sub_eq_add_neg] lemma nat_sub (h : liouville_with p x) (n : ℕ) : liouville_with p (n - x) := nat_sub_iff.2 h lemma ne_cast_int (h : liouville_with p x) (hp : 1 < p) (m : ℤ) : x ≠ m := begin rintro rfl, rename m M, rcases ((eventually_gt_at_top 0).and_frequently (h.frequently_lt_rpow_neg hp)).exists with ⟨n : ℕ, hn : 0 < n, m : ℤ, hne : (M : ℝ) ≠ m / n, hlt : |(M - m / n : ℝ)| < n ^ (-1 : ℝ)⟩, refine hlt.not_le _, have hn' : (0 : ℝ) < n, by simpa, rw [rpow_neg_one, ← one_div, sub_div' _ _ _ hn'.ne', abs_div, nat.abs_cast, div_le_div_right hn'], norm_cast, rw [← zero_add (1 : ℤ), int.add_one_le_iff, abs_pos, sub_ne_zero], rw [ne.def, eq_div_iff hn'.ne'] at hne, exact_mod_cast hne end /-- A number satisfying the Liouville condition with exponent `p > 1` is an irrational number. -/ protected lemma irrational (h : liouville_with p x) (hp : 1 < p) : irrational x := begin rintro ⟨r, rfl⟩, rcases eq_or_ne r 0 with (rfl|h0), { refine h.ne_cast_int hp 0 _, rw [rat.cast_zero, int.cast_zero] }, { refine (h.mul_rat (inv_ne_zero h0)).ne_cast_int hp 1 _, simp [rat.cast_ne_zero.2 h0] } end end liouville_with namespace liouville variables {x : ℝ} /-- If `x` is a Liouville number, then for any `n`, for infinitely many denominators `b` there exists a numerator `a` such that `x ≠ a / b` and `|x - a / b| < 1 / b ^ n`. -/ lemma frequently_exists_num (hx : liouville x) (n : ℕ) : ∃ᶠ b : ℕ in at_top, ∃ a : ℤ, x ≠ a / b ∧ |x - a / b| < 1 / b ^ n := begin refine not_not.1 (λ H, _), simp only [liouville, not_forall, not_exists, not_frequently, not_and, not_lt, eventually_at_top] at H, rcases H with ⟨N, hN⟩, have : ∀ b > (1 : ℕ), ∀ᶠ m : ℕ in at_top, ∀ a : ℤ, (1 / b ^ m : ℝ) ≤ |x - a / b|, { intros b hb, replace hb : (1 : ℝ) < b := nat.one_lt_cast.2 hb, have H : tendsto (λ m, 1 / b ^ m : ℕ → ℝ) at_top (𝓝 0), { simp only [one_div], exact tendsto_inv_at_top_zero.comp (tendsto_pow_at_top_at_top_of_one_lt hb) }, refine (H.eventually (hx.irrational.eventually_forall_le_dist_cast_div b)).mono _, exact λ m hm a, hm a }, have : ∀ᶠ m : ℕ in at_top, ∀ b < N, 1 < b → ∀ a : ℤ, (1 / b ^ m : ℝ) ≤ |x - a / b|, from (finite_lt_nat N).eventually_all.2 (λ b hb, eventually_imp_distrib_left.2 (this b)), rcases (this.and (eventually_ge_at_top n)).exists with ⟨m, hm, hnm⟩, rcases hx m with ⟨a, b, hb, hne, hlt⟩, lift b to ℕ using zero_le_one.trans hb.le, norm_cast at hb, push_cast at hne hlt, cases le_or_lt N b, { refine (hN b h a hne).not_lt (hlt.trans_le _), replace hb : (1 : ℝ) < b := nat.one_lt_cast.2 hb, have hb0 : (0 : ℝ) < b := zero_lt_one.trans hb, exact one_div_le_one_div_of_le (pow_pos hb0 _) (pow_le_pow hb.le hnm) }, { exact (hm b h hb _).not_lt hlt } end /-- A Liouville number is a Liouville number with any real exponent. -/ protected lemma liouville_with (hx : liouville x) (p : ℝ) : liouville_with p x := begin suffices : liouville_with ⌈p⌉₊ x, from this.mono (nat.le_ceil p), refine ⟨1, ((eventually_gt_at_top 1).and_frequently (hx.frequently_exists_num ⌈p⌉₊)).mono _⟩, rintro b ⟨hb, a, hne, hlt⟩, refine ⟨a, hne, _⟩, rwa rpow_nat_cast end end liouville /-- A number satisfies the Liouville condition with any exponent if and only if it is a Liouville number. -/ lemma forall_liouville_with_iff {x : ℝ} : (∀ p, liouville_with p x) ↔ liouville x := begin refine ⟨λ H n, _, liouville.liouville_with⟩, rcases ((eventually_gt_at_top 1).and_frequently ((H (n + 1)).frequently_lt_rpow_neg (lt_add_one n))).exists with ⟨b, hb, a, hne, hlt⟩, exact ⟨a, b, by exact_mod_cast hb, hne, by simpa [rpow_neg] using hlt⟩, end
31e90180c1a002f80a4f3a344e46829f2cbb4845
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/analysis/normed_space/basic.lean
6cd948e84282c90daf5112de67311b14123fdff2
[ "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
53,406
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import topology.instances.nnreal import topology.instances.complex import topology.algebra.module import topology.metric_space.antilipschitz /-! # Normed spaces -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space big_operators nnreal localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥`:1024 e:1 `∥`:1 := norm e /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ 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 } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { 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 rw sub_add_sub_cancel ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } 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, sub_zero] lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h := by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev] @[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg] @[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := dist_add_right _ _ _ /-- Triangle inequality for the norm. -/ lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ + g₂∥ ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂) lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := dist_neg_neg g₂ h₂ ▸ dist_add_add_le _ _ _ _ lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) : abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) := by simpa only [dist_add_left, dist_add_right, dist_comm h₂] using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂) @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } @[simp] lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥ ≤ ∑ a in s, ∥ f a ∥ := finset.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥∑ b in s, f b∥ ≤ ∑ b in s, n b := le_trans (norm_sum_le s f) (finset.sum_le_sum h) lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw[←dist_zero_right], exact dist_le_zero } lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ - g₂∥ ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma eq_of_norm_sub_eq_zero {u v : α} (h : ∥u - v∥ = 0) : u = v := begin apply eq_of_dist_eq_zero, rwa dist_eq_norm end lemma norm_le_insert (u v : α) : ∥v∥ ≤ ∥u∥ + ∥u - v∥ := calc ∥v∥ = ∥u - (u - v)∥ : by abel ... ≤ ∥u∥ + ∥u - v∥ : norm_sub_le u _ lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) : ∥h∥ ≤ ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H } lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) : ∥h∥ < ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H } theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε := metric.tendsto_nhds.trans $ by simp only [dist_zero_right] lemma normed_group.tendsto_nhds_nhds {f : α → β} {x : α} {y : β} : tendsto f (𝓝 x) (𝓝 y) ↔ ∀ ε > 0, ∃ δ > 0, ∀ x', ∥x' - x∥ < δ → ∥f x' - y∥ < ε := by simp_rw [metric.tendsto_nhds_nhds, dist_eq_norm] /-- A homomorphism `f` of normed groups is Lipschitz, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.lipschitz_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (nnreal.of_real C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma lipschitz_on_with_iff_norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} : lipschitz_on_with C f s ↔ ∀ (x ∈ s) (y ∈ s), ∥f x - f y∥ ≤ C * ∥x - y∥ := by simp only [lipschitz_on_with_iff_dist_le_mul, dist_eq_norm] lemma lipschitz_on_with.norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} (h : lipschitz_on_with C f s) {x y : α} (x_in : x ∈ s) (y_in : y ∈ s) : ∥f x - f y∥ ≤ C * ∥x - y∥ := lipschitz_on_with_iff_norm_sub_le.mp h x x_in y y_in /-- A homomorphism `f` of normed groups is continuous, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.continuous_of_bound (f :α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous section nnnorm /-- Version of the norm taking values in nonnegative reals. -/ 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 _ _ @[simp] 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_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h := nnreal.coe_le_coe.2 $ norm_add_le 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_coe.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ennreal) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂ lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le } lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α), nnnorm (∑ a in s, f a) ≤ ∑ a in s, nnnorm (f a) := finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le end nnnorm lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : nnreal} {f : α → β} (hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) := λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y lemma lipschitz_with.add {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x + g x) := λ x y, calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_add_add_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.sub {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β} (hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := hf.add hg.neg lemma antilipschitz_with.add_lipschitz_with {α : Type*} [metric_space α] {Kf : nnreal} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul], rw le_div_iff (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK), rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _) end /-- A submodule of a normed group is also a normed group, with the restriction of the norm. As all instances can be inferred from the submodule `s`, they are put as implicit instead of typeclasses. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.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 prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πi, π i) := { 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 _ _ } /-- The norm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by { simp only [(dist_zero_right _).symm, dist_pi_le_iff hr], refl } lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) := by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm] lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) := have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) := tendsto_iff_norm_tendsto_zero, by simpa /-- Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real function `g` which tends to `0`, then `f` tends to `0`. In this pair of lemmas (`squeeze_zero_norm'` and `squeeze_zero_norm`), following a convention of similar lemmas in `topology.metric_space.basic` and `topology.algebra.ordered`, the `'` version is phrased using "eventually" and the non-`'` version is phrased absolutely. -/ lemma squeeze_zero_norm' {f : γ → α} {g : γ → ℝ} {t₀ : filter γ} (h : ∀ᶠ n in t₀, ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := tendsto_zero_iff_norm_tendsto_zero.mpr (squeeze_zero' (eventually_of_forall (λ n, norm_nonneg _)) h h') /-- Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `g` which tends to `0`, then `f` tends to `0`. -/ lemma squeeze_zero_norm {f : γ → α} {g : γ → ℝ} {t₀ : filter γ} (h : ∀ (n:γ), ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero_norm' (eventually_of_forall h) h' 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 filter.tendsto.norm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto.comp continuous_norm.continuous_at h lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) := continuous_subtype_mk _ continuous_norm lemma filter.tendsto.nnnorm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) := tendsto.comp continuous_nnnorm.continuous_at h /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α} (h : tendsto (λ y, ∥f y∥) l at_top) (x : α) : ∀ᶠ y in l, f y ≠ x := begin have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)), refine this.mono (λ y hy hxy, _), subst x, exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy) end /-- A normed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ @[priority 100] -- see Note [lower instance priority] 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, sub_eq_add_neg]; abel ... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_sub_le _ _ ... < ε / 2 + ε / 2 : add_lt_add h.1 h.2 ... = ε : add_halves _ end @[priority 100] -- see Note [lower instance priority] instance normed_top_monoid : has_continuous_add α := by apply_instance -- short-circuit type class inference @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference end normed_group section normed_ring /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ 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) @[priority 100] -- see Note [lower instance priority] 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 : ℕ}, 0 < n → ∥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 _)) lemma eventually_norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ᶠ (n:ℕ) in at_top, ∥a ^ n∥ ≤ ∥a∥ ^ n := begin refine eventually_at_top.mpr ⟨1, _⟩, intros b h, exact norm_pow_le a (nat.succ_le_iff.mp h), end lemma units.norm_pos {α : Type*} [normed_ring α] [nontrivial α] (x : units α) : 0 < ∥(x:α)∥ := norm_pos_iff.mpr (units.ne_zero x) /-- In a normed ring, the left-multiplication `add_monoid_hom` is bounded. -/ lemma mul_left_bound {α : Type*} [normed_ring α] (x : α) : ∀ (y:α), ∥add_monoid_hom.mul_left x y∥ ≤ ∥x∥ * ∥y∥ := norm_mul_le x /-- In a normed ring, the right-multiplication `add_monoid_hom` is bounded. -/ lemma mul_right_bound {α : Type*} [normed_ring α] (x : α) : ∀ (y:α), ∥add_monoid_hom.mul_right x y∥ ≤ ∥x∥ * ∥y∥ := λ y, by {rw mul_comm, convert norm_mul_le y x} /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ 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 @[priority 100] -- see Note [lower instance priority] instance normed_ring_top_monoid [normed_ring α] : has_continuous_mul α := ⟨ 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_add_le }, { 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_norm.comp continuous_fst }, { 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 ⟩ /-- A normed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] 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 ⟩ /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type*) extends has_norm α, field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) @[priority 100] -- see Note [lower instance priority] instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α := { norm_mul := by finish [i.norm_mul'], ..i } namespace normed_field @[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, mul_left_cancel' (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 @[simp] lemma nnnorm_one [normed_field α] : nnnorm (1:α) = 1 := nnreal.eq $ by simp instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) := { map_one := norm_one, map_mul := 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 : β → α) : ∥∏ b in s, f b∥ = ∏ b in s, ∥f b∥ := eq.symm (s.prod_hom norm) @[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ := begin classical, by_cases hb : b = 0, {simp [hb]}, 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] @[simp] lemma nnnorm_inv {α : Type*} [normed_field α] (a : α) : nnnorm (a⁻¹) = (nnnorm a)⁻¹ := nnreal.eq $ by simp @[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ, ∥a^n∥ = ∥a∥^n | (n : ℕ) := norm_pow a n | -[1+ n] := by simp [fpow_neg_succ_of_nat] lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ := i.non_trivial lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], assume h, rw ← norm_eq_zero at h, rw h at hy, exact lt_irrefl _ (lt_trans zero_lt_one hy) }, { simp [inv_lt_one hy] } end lemma exists_lt_norm (α : Type*) [nondiscrete_normed_field α] (r : ℝ) : ∃ x : α, r < ∥x∥ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt (α : Type*) [nondiscrete_normed_field α] {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in ⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _}, by rwa norm_fpow⟩ @[instance] lemma punctured_nhds_ne_bot {α : Type*} [nondiscrete_normed_field α] (x : α) : ne_bot (𝓝[{x}ᶜ] x) := begin rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff], rintros ε ε0, rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩, refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩, rwa [dist_comm, dist_eq_norm, add_sub_cancel'], end @[instance] lemma nhds_within_is_unit_ne_bot {α : Type*} [nondiscrete_normed_field α] : ne_bot (𝓝[{x : α | is_unit x}] 0) := by simpa only [is_unit_iff_ne_zero] using punctured_nhds_ne_bot (0:α) lemma tendsto_inv [normed_field α] {r : α} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := begin refine (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, _), let δ := min (ε/2 * ∥r∥^2) (∥r∥/2), have norm_r_pos : 0 < ∥r∥ := norm_pos_iff.mpr r0, have A : 0 < ε / 2 * ∥r∥ ^ 2 := mul_pos (half_pos εpos) (pow_pos norm_r_pos 2), have δpos : 0 < δ, by simp [half_pos norm_r_pos, A], refine ⟨δ, δpos, λ x hx, _⟩, have rx : ∥r∥/2 ≤ ∥x∥ := calc ∥r∥/2 = ∥r∥ - ∥r∥/2 : by ring ... ≤ ∥r∥ - ∥r - x∥ : begin apply sub_le_sub (le_refl _), rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_right _ _) end ... ≤ ∥r - (r - x)∥ : norm_sub_norm_le r (r - x) ... = ∥x∥ : by simp [sub_sub_cancel], have norm_x_pos : 0 < ∥x∥ := lt_of_lt_of_le (half_pos norm_r_pos) rx, have : x⁻¹ - r⁻¹ = (r - x) * x⁻¹ * r⁻¹, by rw [sub_mul, sub_mul, mul_inv_cancel (norm_pos_iff.mp norm_x_pos), one_mul, mul_comm, ← mul_assoc, inv_mul_cancel r0, one_mul], calc dist x⁻¹ r⁻¹ = ∥x⁻¹ - r⁻¹∥ : dist_eq_norm _ _ ... ≤ ∥r-x∥ * ∥x∥⁻¹ * ∥r∥⁻¹ : by rw [this, norm_mul, norm_mul, norm_inv, norm_inv] ... ≤ (ε/2 * ∥r∥^2) * (2 * ∥r∥⁻¹) * (∥r∥⁻¹) : begin apply_rules [mul_le_mul, inv_nonneg.2, le_of_lt A, norm_nonneg, mul_nonneg, (inv_le_inv norm_x_pos norm_r_pos).2, le_refl], show ∥r - x∥ ≤ ε / 2 * ∥r∥ ^ 2, by { rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_left _ _) }, show ∥x∥⁻¹ ≤ 2 * ∥r∥⁻¹, { convert (inv_le_inv norm_x_pos (half_pos norm_r_pos)).2 rx, rw [inv_div, div_eq_inv_mul, mul_comm] }, show (0 : ℝ) ≤ 2, by norm_num end ... = ε * (∥r∥ * ∥r∥⁻¹)^2 : by { generalize : ∥r∥⁻¹ = u, ring } ... = ε : by { rw [mul_inv_cancel (ne.symm (ne_of_lt norm_r_pos))], simp } end lemma continuous_on_inv [normed_field α] : continuous_on (λ(x:α), x⁻¹) {x | x ≠ 0} := begin assume x hx, apply continuous_at.continuous_within_at, exact (tendsto_inv hx) end end normed_field instance : normed_field ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl, norm_mul' := abs_mul } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } /-- If a function converges to a nonzero value, its inverse converges to the inverse of this value. We use the name `tendsto.inv'` as `tendsto.inv` is already used in multiplicative topological groups. -/ lemma filter.tendsto.inv' [normed_field α] {l : filter β} {f : β → α} {y : α} (hy : y ≠ 0) (h : tendsto f l (𝓝 y)) : tendsto (λx, (f x)⁻¹) l (𝓝 y⁻¹) := (normed_field.tendsto_inv hy).comp h lemma filter.tendsto.div [normed_field α] {l : filter β} {f g : β → α} {x y : α} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (hy : y ≠ 0) : tendsto (λa, f a / g a) l (𝓝 (x / y)) := hf.mul (hg.inv' hy) lemma filter.tendsto.div_const [normed_field α] {l : filter β} {f : β → α} {x y : α} (hf : tendsto f l (𝓝 x)) : tendsto (λa, f a / y) l (𝓝 (x / y)) := by { simp only [div_eq_inv_mul], exact tendsto_const_nhds.mul hf } /-- Continuity at a point of the result of dividing two functions continuous at that point, where the denominator is nonzero. -/ lemma continuous_at.div [topological_space α] [normed_field β] {f : α → β} {g : α → β} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) (hnz : g x ≠ 0) : continuous_at (λ x, f x / g x) x := hf.div hg hnz namespace real lemma norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl @[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg @[simp] lemma nnnorm_coe_nat (n : ℕ) : nnnorm (n : ℝ) = n := nnreal.eq $ by simp @[simp] lemma norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@two_pos ℝ _) @[simp] lemma nnnorm_two : nnnorm (2:ℝ) = 2 := nnreal.eq $ by simp open_locale nnreal @[simp] lemma nnreal.norm_eq (x : ℝ≥0) : ∥(x : ℝ)∥ = x := by rw [real.norm_eq_abs, x.abs_eq] end real @[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)] @[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a := by simp only [nnnorm, norm_norm] instance : normed_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub] } @[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast section normed_space section prio set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[normed_space α β] : semimodule α β` -- to take precedence over `semiring.to_semimodule` as this leads to instance paths with better -- unification properties. -- see Note[vector space definition] for why we extend `semimodule`. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends semimodule α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) end prio variables [normed_field α] [normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) } lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin classical, by_cases h : s = 0, { simp [h] }, { refine le_antisymm (normed_space.norm_smul_le s x) _, calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h] ... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : _ ... = ∥s • x∥ : _, exact mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _), rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel, one_mul], rwa [ne.def, norm_eq_zero] } end lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x := nnreal.eq $ norm_smul s x lemma nndist_smul [normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = nnnorm s * nndist x y := nnreal.eq $ dist_smul s x y lemma norm_smul_of_nonneg [normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ∥t • x∥ = t * ∥x∥ := by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht] variables {E : Type*} {F : Type*} [normed_group E] [normed_space α E] [normed_group F] [normed_space α F] @[priority 100] -- see Note [lower instance priority] instance normed_space.topological_vector_space : topological_vector_space α E := begin refine { continuous_smul := continuous_iff_continuous_at.2 $ λ p, tendsto_iff_norm_tendsto_zero.2 _ }, refine squeeze_zero (λ _, norm_nonneg _) _ _, { exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ }, { intro q, rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul], exact norm_add_le _ _ }, { conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr, rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] }, exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul (continuous_snd.tendsto p).norm).add (tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) } end theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : closure (ball x r) = closed_ball x r := begin refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico (@zero_lt_one ℝ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, apply mul_lt_mul'; assumption } end theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, is_open_ball.interior_eq], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : interior (closed_ball x r) = ball x r := begin refine set.subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : interior (closed_ball x r) = ball x r := begin rcases lt_trichotomy r 0 with hr|rfl|hr, { simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] }, { suffices : x ∉ interior {x}, { rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff], intros y hy, obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy), exact this hy }, rw [← set.mem_compl_iff, ← closure_compl], rcases exists_ne (0 : E) with ⟨z, hz⟩, suffices : (λ c : ℝ, x + c • z) 0 ∈ closure ({x}ᶜ : set E), by simpa only [zero_smul, add_zero] using this, have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi], refine (continuous_const.add (continuous_id.smul continuous_const)).continuous_within_at.mem_closure this _, intros c hc, simp [smul_eq_zero, hz, ne_of_gt hc] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball] open normed_field /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos (norm_pos_iff.2 hx) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow], exact (div_le_iff εpos).1 (le_of_lt (hn.2)) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, mul_inv_rev', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance : normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg], -- TODO: without the next two lines Lean unfolds `≤` to `real.le` 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.semimodule } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ 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] } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } end normed_space section normed_algebra /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) @[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := normed_algebra.norm_algebra_map_eq _ variables (𝕜 : Type*) [normed_field 𝕜] variables (𝕜' : Type*) [normed_ring 𝕜'] @[priority 100] instance normed_algebra.to_normed_space [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := { norm_smul_le := λ s x, calc ∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl } ... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : normed_ring.norm_mul _ _ ... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq, ..h } instance normed_algebra.id : normed_algebra 𝕜 𝕜 := { norm_algebra_map_eq := by simp, .. algebra.id 𝕜} variables {𝕜'} [normed_algebra 𝕜 𝕜'] include 𝕜 @[simp] lemma normed_algebra.norm_one : ∥(1:𝕜')∥ = 1 := by simpa using (norm_algebra_map_eq 𝕜' (1:𝕜)) lemma normed_algebra.zero_ne_one : (0:𝕜') ≠ 1 := begin refine (norm_pos_iff.mp _).symm, rw @normed_algebra.norm_one 𝕜, norm_num, end lemma normed_algebra.to_nonzero : nontrivial 𝕜' := ⟨⟨0, 1, normed_algebra.zero_ne_one 𝕜⟩⟩ end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type*) [normed_group E] [normed_space 𝕜' E] /-- `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. The type synonym `semimodule.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default. -/ def normed_space.restrict_scalars' : normed_space 𝕜 E := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..semimodule.restrict_scalars' 𝕜 𝕜' E } instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_group E] : normed_group (semimodule.restrict_scalars 𝕜 𝕜' E) := I instance semimodule.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [normed_field 𝕜'] [normed_group E] [I : normed_space 𝕜' E] : normed_space 𝕜' (semimodule.restrict_scalars 𝕜 𝕜' E) := I instance : normed_space 𝕜 (semimodule.restrict_scalars 𝕜 𝕜' E) := (normed_space.restrict_scalars' 𝕜 𝕜' E : normed_space 𝕜 E) end restrict_scalars section summable open_locale classical open finset filter variables [normed_group α] [normed_group β] -- Applying a bounded homomorphism commutes with taking an (infinite) sum. lemma has_sum_of_bounded_monoid_hom_of_has_sum {f : ι → α} {φ : α →+ β} {x : α} (hf : has_sum f x) (C : ℝ) (hφ : ∀x, ∥φ x∥ ≤ C * ∥x∥) : has_sum (λ (b:ι), φ (f b)) (φ x) := begin unfold has_sum, convert (φ.continuous_of_bound C hφ).continuous_at.tendsto.comp hf, ext s, rw [function.comp_app, finset.sum_hom s φ], end lemma has_sum_of_bounded_monoid_hom_of_summable {f : ι → α} {φ : α →+ β} (hf : summable f) (C : ℝ) (hφ : ∀x, ∥φ x∥ ≤ C * ∥x∥) : has_sum (λ (b:ι), φ (f b)) (φ (∑'b, f b)) := has_sum_of_bounded_monoid_hom_of_has_sum hf.has_sum C hφ lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} : cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := begin simp only [cauchy_seq_finset_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 summable_iff_vanishing_norm [complete_space α] {f : ι → α} : summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm] lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) := cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in ⟨s, assume t ht, have ∥∑ i in t, g i∥ < ε := hs t ht, have nn : 0 ≤ ∑ i in t, g i := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : cauchy_seq (λ s : finset ι, ∑ a in s, f a) := cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥)) {s : γ → finset ι} {p : filter γ} [ne_bot p] (hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hs ha /-- If `∑' i, ∥f i∥` is summable, then `∥(∑' i, f i)∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑'i, f i)∥ ≤ (∑' i, ∥f i∥) := begin by_cases h : summable f, { have h₁ : tendsto (λs:finset ι, ∥∑ i in s, f i∥) at_top (𝓝 ∥(∑' i, f i)∥) := (continuous_norm.tendsto _).comp h.has_sum, have h₂ : tendsto (λs:finset ι, ∑ i in s, ∥f i∥) at_top (𝓝 (∑' i, ∥f i∥)) := hf.has_sum, exact le_of_tendsto_of_tendsto' h₁ h₂ (assume s, norm_sum_le _ _) }, { rw tsum_eq_zero_of_not_summable h, simp [tsum_nonneg] } end lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := ⟨λ h, h.tendsto_sum_nat, λ h, has_sum_of_subseq_of_summable hf tendsto_finset_range h⟩ /-- The direct comparison test for series: if the norm of `f` is bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded [complete_space α] {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h } /-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is summable, and for all `i`, `∥f i∥ ≤ g i`, then `∥(∑' i, f i)∥ ≤ (∑' i, g i)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma tsum_of_norm_bounded {f : ι → α} {g : ι → ℝ} {a : ℝ} (hg : has_sum g a) (h : ∀i, ∥f i∥ ≤ g i) : ∥(∑' (i:ι), f i)∥ ≤ a := begin have h' : summable (λ (i : ι), ∥f i∥), { let f' : ι → ℝ := λ i, ∥f i∥, have h'' : ∀ i, ∥f' i∥ ≤ g i, { intros i, convert h i, simp }, simpa [f'] using summable_of_norm_bounded g hg.summable h'' }, have h1 : ∥(∑' (i:ι), f i)∥ ≤ ∑' (i:ι), ∥f i∥ := by simpa using norm_tsum_le_tsum_norm h', have h2 := tsum_le_tsum h h' hg.summable, have h3 : a = ∑' (i:ι), g i := (has_sum.tsum_eq hg).symm, linarith end variable [complete_space α] /-- Variant of the direct comparison test for series: if the norm of `f` is eventually bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded_eventually {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀ᶠ i in cofinite, ∥f i∥ ≤ g i) : summable f := begin replace h := mem_cofinite.1 h, refine h.summable_compl_iff.mp _, refine summable_of_norm_bounded _ (h.summable_compl_iff.mpr hg) _, rintros ⟨a, h'⟩, simpa using h' end lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → nnreal) (hg : summable g) (h : ∀i, nnnorm (f i) ≤ g i) : summable f := summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i) lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f := summable_of_nnnorm_bounded _ hf (assume i, le_refl _) end summable
4779b31a64bf1ce45a3759a6e59accfba7a7cd71
4376c25f060c13471bb89cdb12aeac1d53e53876
/src/espaces-metriques/custom/topology.lean
c7a7225a936785d0b00c523448c17cfd82ff681a
[ "MIT" ]
permissive
RaitoBezarius/projet-maths-lean
8fa7df563d64c256561ab71893c523fc1424b85c
42356e980e021a20c3468f5ca1639fec01bb934f
refs/heads/master
1,613,002,128,339
1,589,289,282,000
1,589,289,282,000
244,431,534
0
1
MIT
1,584,312,574,000
1,583,169,883,000
TeX
UTF-8
Lean
false
false
498
lean
import .defs import .sequences open espace_metrique section topologie variables {X:Type} [espace_metrique X] -- Accumulation point of S def adhere_ens (S: set X) (l: X) := ∃ (x: ℕ → X), (∀ n, x n ∈ S) ∧ (converge x l) -- Limit point: l is an accumulation point of S \ { l } def point_limite (S: set X) (l: X) := adhere_ens (S \ {l}) l -- Completeness of the space. def complete (T: Type) [espace_metrique T] := ∀ x : ℕ → T, cauchy x → ∃ l : T, converge x l end topologie
ea753d46b90579b2f9dc9e1916629b89faf92ac2
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/category/Mon/basic.lean
1616d7095a67a8fb54fae5d8f078369d8ce94014
[ "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
7,406
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.concrete_category.bundled_hom import category_theory.concrete_category.reflects_isomorphisms import algebra.punit_instances /-! # Category instances for monoid, add_monoid, comm_monoid, and add_comm_monoid. We introduce the bundled categories: * `Mon` * `AddMon` * `CommMon` * `AddCommMon` along with the relevant forgetful functors between them. -/ universes u v open category_theory /-- The category of monoids and monoid morphisms. -/ @[to_additive AddMon] def Mon : Type (u+1) := bundled monoid /-- The category of additive monoids and monoid morphisms. -/ add_decl_doc AddMon namespace Mon @[to_additive] instance bundled_hom : bundled_hom @monoid_hom := ⟨@monoid_hom.to_fun, @monoid_hom.id, @monoid_hom.comp, @monoid_hom.coe_inj⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] Mon AddMon /-- Construct a bundled `Mon` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [monoid M] : Mon := bundled.of M /-- Construct a bundled `Mon` from the underlying type and typeclass. -/ add_decl_doc AddMon.of @[to_additive] instance : inhabited Mon := -- The default instance for `monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @group.to_monoid _ $ @comm_group.to_group _ punit.comm_group⟩ @[to_additive] instance (M : Mon) : monoid M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [monoid R] : (Mon.of R : Type u) = R := rfl end Mon /-- The category of commutative monoids and monoid morphisms. -/ @[to_additive AddCommMon] def CommMon : Type (u+1) := bundled comm_monoid /-- The category of additive commutative monoids and monoid morphisms. -/ add_decl_doc AddCommMon namespace CommMon @[to_additive] instance : bundled_hom.parent_projection comm_monoid.to_monoid := ⟨⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] CommMon AddCommMon /-- Construct a bundled `CommMon` from the underlying type and typeclass. -/ @[to_additive] def of (M : Type u) [comm_monoid M] : CommMon := bundled.of M /-- Construct a bundled `AddCommMon` from the underlying type and typeclass. -/ add_decl_doc AddCommMon.of @[to_additive] instance : inhabited CommMon := -- The default instance for `comm_monoid punit` is derived via `punit.comm_ring`, -- which breaks to_additive. ⟨@of punit $ @comm_group.to_comm_monoid _ punit.comm_group⟩ @[to_additive] instance (M : CommMon) : comm_monoid M := M.str @[simp, to_additive] lemma coe_of (R : Type u) [comm_monoid R] : (CommMon.of R : Type u) = R := rfl @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ CommMon Mon := bundled_hom.forget₂ _ _ end CommMon -- We verify that the coercions of morphisms to functions work correctly: example {R S : Mon} (f : R ⟶ S) : (R : Type) → (S : Type) := f example {R S : CommMon} (f : R ⟶ S) : (R : Type) → (S : Type) := f -- We verify that when constructing a morphism in `CommMon`, -- when we construct the `to_fun` field, the types are presented as `↥R`, -- rather than `R.α` or (as we used to have) `↥(bundled.map comm_monoid.to_monoid R)`. example (R : CommMon.{u}) : R ⟶ R := { to_fun := λ x, begin match_target (R : Type u), match_hyp x : (R : Type u), exact x * x end , map_one' := by simp, map_mul' := λ x y, begin rw [mul_assoc x y (x * y), ←mul_assoc y x y, mul_comm y x, mul_assoc, mul_assoc], end, } variables {X Y : Type u} section variables [monoid X] [monoid Y] /-- Build an isomorphism in the category `Mon` from a `mul_equiv` between `monoid`s. -/ @[to_additive add_equiv.to_AddMon_iso "Build an isomorphism in the category `AddMon` from an `add_equiv` between `add_monoid`s."] def mul_equiv.to_Mon_iso (e : X ≃* Y) : Mon.of X ≅ Mon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } @[simp, to_additive add_equiv.to_AddMon_iso_hom] lemma mul_equiv.to_Mon_iso_hom {e : X ≃* Y} : e.to_Mon_iso.hom = e.to_monoid_hom := rfl @[simp, to_additive add_equiv.to_AddMon_iso_inv] lemma mul_equiv.to_Mon_iso_inv {e : X ≃* Y} : e.to_Mon_iso.inv = e.symm.to_monoid_hom := rfl end section variables [comm_monoid X] [comm_monoid Y] /-- Build an isomorphism in the category `CommMon` from a `mul_equiv` between `comm_monoid`s. -/ @[to_additive add_equiv.to_AddCommMon_iso "Build an isomorphism in the category `AddCommMon` from an `add_equiv` between `add_comm_monoid`s."] def mul_equiv.to_CommMon_iso (e : X ≃* Y) : CommMon.of X ≅ CommMon.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } @[simp, to_additive add_equiv.to_AddCommMon_iso_hom] lemma mul_equiv.to_CommMon_iso_hom {e : X ≃* Y} : e.to_CommMon_iso.hom = e.to_monoid_hom := rfl @[simp, to_additive add_equiv.to_AddCommMon_iso_inv] lemma mul_equiv.to_CommMon_iso_inv {e : X ≃* Y} : e.to_CommMon_iso.inv = e.symm.to_monoid_hom := rfl end namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Mon`. -/ @[to_additive AddMon_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddMon`."] def Mon_iso_to_mul_equiv {X Y : Mon} (i : X ≅ Y) : X ≃* Y := i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id /-- Build a `mul_equiv` from an isomorphism in the category `CommMon`. -/ @[to_additive "Build an `add_equiv` from an isomorphism in the category `AddCommMon`."] def CommMon_iso_to_mul_equiv {X Y : CommMon} (i : X ≅ Y) : X ≃* Y := i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id end category_theory.iso /-- multiplicative equivalences between `monoid`s are the same as (isomorphic to) isomorphisms in `Mon` -/ @[to_additive add_equiv_iso_AddMon_iso "additive equivalences between `add_monoid`s are the same as (isomorphic to) isomorphisms in `AddMon`"] def mul_equiv_iso_Mon_iso {X Y : Type u} [monoid X] [monoid Y] : (X ≃* Y) ≅ (Mon.of X ≅ Mon.of Y) := { hom := λ e, e.to_Mon_iso, inv := λ i, i.Mon_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_monoid`s are the same as (isomorphic to) isomorphisms in `CommMon` -/ @[to_additive add_equiv_iso_AddCommMon_iso "additive equivalences between `add_comm_monoid`s are the same as (isomorphic to) isomorphisms in `AddCommMon`"] def mul_equiv_iso_CommMon_iso {X Y : Type u} [comm_monoid X] [comm_monoid Y] : (X ≃* Y) ≅ (CommMon.of X ≅ CommMon.of Y) := { hom := λ e, e.to_CommMon_iso, inv := λ i, i.CommMon_iso_to_mul_equiv, } @[to_additive] instance Mon.forget_reflects_isos : reflects_isomorphisms (forget Mon.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Mon).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact { ..e.to_Mon_iso }, end } @[to_additive] instance CommMon.forget_reflects_isos : reflects_isomorphisms (forget CommMon.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget CommMon).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact { ..e.to_CommMon_iso }, end } /-! Once we've shown that the forgetful functors to type reflect isomorphisms, we automatically obtain that the `forget₂` functors between our concrete categories reflect isomorphisms. -/ example : reflects_isomorphisms (forget₂ CommMon Mon) := by apply_instance
fd16bea1726f8f8519cb8bb76bedf1cf9a558a53
3268ab3a126f0fef71459fbf170dc38efe5d0506
/cohomology/serre.hlean
e6c6ab4adfc38835f02edc506d9a8ceb1d20a583
[ "Apache-2.0" ]
permissive
soraismus/Spectral
f043fed1a4e02ddfeba531769b2980eb817471f4
32512bf47db3a1b932856e7ed7c7830b1fc07ef0
refs/heads/master
1,585,628,705,579
1,538,609,948,000
1,538,609,974,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,309
hlean
import ..algebra.spectral_sequence ..spectrum.trunc .basic open eq spectrum trunc is_trunc pointed int EM algebra left_module fiber lift equiv is_equiv cohomology group sigma unit is_conn prod set_option pp.binder_types true /- Eilenberg MacLane spaces are the fibers of the Postnikov system of a type -/ namespace pointed definition postnikov_map [constructor] (A : Type*) (n : ℕ₋₂) : ptrunc (n.+1) A →* ptrunc n A := ptrunc.elim (n.+1) (ptr n A) definition ptrunc_functor_postnikov_map {A B : Type*} (n : ℕ₋₂) (f : A →* B) : ptrunc_functor n f ∘* postnikov_map A n ~* ptrunc.elim (n.+1) (!ptr ∘* f) := begin fapply phomotopy.mk, { intro x, induction x with a, reflexivity }, { reflexivity } end section open nat group definition pfiber_postnikov_map (A : Type*) (n : ℕ) : pfiber (postnikov_map A n) ≃* EM_type A (n+1) := begin symmetry, apply EM_type_pequiv, { symmetry, refine _ ⬝g ghomotopy_group_ptrunc (n+1) A, exact chain_complex.LES_isomorphism_of_trivial_cod _ _ (trivial_homotopy_group_of_is_trunc _ (self_lt_succ n)) (trivial_homotopy_group_of_is_trunc _ (le_succ _)) }, { apply is_conn_fun_trunc_elim, apply is_conn_fun_tr }, { have is_trunc (n+1) (ptrunc n.+1 A), from !is_trunc_trunc, have is_trunc ((n+1).+1) (ptrunc n A), by do 2 apply is_trunc_succ, apply is_trunc_trunc, exact is_trunc_pfiber _ _ _ _ } end end definition postnikov_map_natural {A B : Type*} (f : A →* B) (n : ℕ₋₂) : psquare (postnikov_map A n) (postnikov_map B n) (ptrunc_functor (n.+1) f) (ptrunc_functor n f) := !ptrunc_functor_postnikov_map ⬝* !ptrunc_elim_ptrunc_functor⁻¹* definition is_equiv_postnikov_map (A : Type*) {n k : ℕ₋₂} [HA : is_trunc k A] (H : k ≤ n) : is_equiv (postnikov_map A n) := begin apply is_equiv_of_equiv_of_homotopy (ptrunc_pequiv_ptrunc_of_is_trunc (trunc_index.le.step H) H HA), intro x, induction x, reflexivity end definition encode_ap1_gen_tr (n : ℕ₋₂) {A : Type*} {a a' : A} (p : a = a') : trunc.encode (ap1_gen tr idp idp p) = tr p :> trunc n (a = a') := by induction p; reflexivity definition ap1_postnikov_map (A : Type*) (n : ℕ₋₂) : psquare (Ω→ (postnikov_map A (n.+1))) (postnikov_map (Ω A) n) (loop_ptrunc_pequiv (n.+1) A) (loop_ptrunc_pequiv n A) := have psquare (postnikov_map (Ω A) n) (Ω→ (postnikov_map A (n.+1))) (loop_ptrunc_pequiv (n.+1) A)⁻¹ᵉ* (loop_ptrunc_pequiv n A)⁻¹ᵉ*, begin refine _ ⬝* !ap1_ptrunc_elim⁻¹*, apply pinv_left_phomotopy_of_phomotopy, fapply phomotopy.mk, { intro x, induction x with p, exact !encode_ap1_gen_tr⁻¹ }, { reflexivity } end, this⁻¹ᵛ* end pointed open pointed namespace spectrum definition postnikov_smap [constructor] (X : spectrum) (k : ℤ) : strunc k X →ₛ strunc (k - 1) X := strunc_elim (str (k - 1) X) (is_strunc_strunc_pred X k) definition postnikov_map_pred (A : Type*) (n : ℕ₋₂) : ptrunc n A →* ptrunc (trunc_index.pred n) A := begin cases n with n, exact !pid, exact postnikov_map A n end definition pfiber_postnikov_map_pred (A : Type*) (n : ℕ) : pfiber (postnikov_map_pred A n) ≃* EM_type A n := begin cases n with n, apply pfiber_pequiv_of_is_contr, apply is_contr_ptrunc_minus_one, exact pfiber_postnikov_map A n end definition pfiber_postnikov_map_pred' (A : spectrum) (n k l : ℤ) (p : n + k = l) : pfiber (postnikov_map_pred (A k) (maxm2 l)) ≃* EM_spectrum (πₛ[n] A) l := begin cases l with l l, { refine pfiber_postnikov_map_pred (A k) l ⬝e* _, exact EM_type_pequiv_EM A p }, { refine pequiv_of_is_contr _ _ _ _, apply is_contr_pfiber_pid, apply is_contr_EM_spectrum_neg } end definition psquare_postnikov_map_ptrunc_elim (A : Type*) {n k l : ℕ₋₂} (H : is_trunc n (ptrunc k A)) (p : n = l.+1) (q : k = l) : psquare (ptrunc.elim n (ptr k A)) (postnikov_map A l) (ptrunc_change_index p A) (ptrunc_change_index q A) := begin induction q, cases p, refine _ ⬝pv* pvrfl, apply ptrunc_elim_phomotopy2, reflexivity end definition postnikov_smap_postnikov_map (A : spectrum) (n k l : ℤ) (p : n + k = l) : psquare (postnikov_smap A n k) (postnikov_map_pred (A k) (maxm2 l)) (ptrunc_maxm2_change_int p (A k)) (ptrunc_maxm2_pred (A k) (ap pred p⁻¹ ⬝ add.right_comm n k (- 1))) := begin cases l with l, { cases l with l, apply phomotopy_of_is_contr_cod_pmap, apply is_contr_ptrunc_minus_one, refine psquare_postnikov_map_ptrunc_elim (A k) _ _ _ ⬝hp* _, exact ap maxm2 (add.right_comm n (- 1) k ⬝ ap pred p ⬝ !pred_succ), apply ptrunc_maxm2_pred_nat }, { apply phomotopy_of_is_contr_cod_pmap, apply is_trunc_trunc } end definition sfiber_postnikov_smap_pequiv (A : spectrum) (n : ℤ) (k : ℤ) : sfiber (postnikov_smap A n) k ≃* ssuspn n (EM_spectrum (πₛ[n] A)) k := proof pfiber_pequiv_of_square _ _ (postnikov_smap_postnikov_map A n k (n + k) idp) ⬝e* pfiber_postnikov_map_pred' A n k _ idp ⬝e* pequiv_ap (EM_spectrum (πₛ[n] A)) (add.comm n k) qed open exact_couple section atiyah_hirzebruch parameters {X : Type*} (Y : X → spectrum) (s₀ : ℤ) (H : Πx, is_strunc s₀ (Y x)) include H definition atiyah_hirzebruch_exact_couple : exact_couple rℤ Z2 := @exact_couple_sequence (λs, spi X (λx, strunc s (Y x))) (λs, spi_compose_left (λx, postnikov_smap (Y x) s)) -- include H definition atiyah_hirzebruch_ub ⦃s n : ℤ⦄ (Hs : s ≤ n - 1) : is_contr (πₛ[n] (spi X (λx, strunc s (Y x)))) := begin refine trivial_shomotopy_group_of_is_strunc _ _ (lt_of_le_sub_one Hs), apply is_strunc_spi, intro x, exact is_strunc_strunc _ _ end definition atiyah_hirzebruch_lb' ⦃s n : ℤ⦄ (Hs : s ≥ s₀ + 1) : is_equiv (spi_compose_left (λx, postnikov_smap (Y x) s) n) := begin refine is_equiv_of_equiv_of_homotopy (ppi_pequiv_right (λx, ptrunc_pequiv_ptrunc_of_is_trunc _ _ (H x n))) _, { intro x, apply maxm2_monotone, apply add_le_add_right, exact le.trans !le_add_one Hs }, { intro x, apply maxm2_monotone, apply add_le_add_right, exact le_sub_one_of_lt Hs }, intro f, apply eq_of_phomotopy, apply pmap_compose_ppi_phomotopy_left, intro x, fapply phomotopy.mk, { refine @trunc.rec _ _ _ _ _, { intro x, apply is_trunc_eq, assert H3 : maxm2 (s - 1 + n) ≤ (maxm2 (s + n)).+1, { refine trunc_index.le_succ (maxm2_monotone (le.trans (le_of_eq !add.right_comm) !sub_one_le)) }, exact @is_trunc_of_le _ _ _ H3 !is_trunc_trunc }, intro a, reflexivity }, reflexivity end definition atiyah_hirzebruch_lb ⦃s n : ℤ⦄ (Hs : s ≥ s₀ + 1) : is_equiv (πₛ→[n] (spi_compose_left (λx, postnikov_smap (Y x) s))) := begin apply is_equiv_homotopy_group_functor, apply atiyah_hirzebruch_lb', exact Hs end definition is_bounded_atiyah_hirzebruch : is_bounded atiyah_hirzebruch_exact_couple := is_bounded_sequence _ (λn, s₀) (λn, n - 1) atiyah_hirzebruch_lb atiyah_hirzebruch_ub definition atiyah_hirzebruch_convergence1 : (λn s, πₛ[n] (sfiber (spi_compose_left (λx, postnikov_smap (Y x) s)))) ⟹ᵍ (λn, πₛ[n] (spi X (λx, strunc s₀ (Y x)))) := convergent_exact_couple_sequence _ (λn, s₀) (λn, n - 1) atiyah_hirzebruch_lb atiyah_hirzebruch_ub definition atiyah_hirzebruch_convergence2 : (λn s, opH^-(n-s)[(x : X), πₛ[s] (Y x)]) ⟹ᵍ (λn, pH^n[(x : X), Y x]) := convergent_exact_couple_g_isomorphism (convergent_exact_couple_negate_abutment atiyah_hirzebruch_convergence1) begin intro n s, refine _ ⬝g (parametrized_cohomology_isomorphism_shomotopy_group_spi _ idp)⁻¹ᵍ, refine _ ⬝g !shomotopy_group_ssuspn, apply shomotopy_group_isomorphism_of_pequiv n, intro k, refine !pfiber_pppi_compose_left ⬝e* _, exact ppi_pequiv_right (λx, sfiber_postnikov_smap_pequiv (Y x) s k) end begin intro n, refine _ ⬝g (parametrized_cohomology_isomorphism_shomotopy_group_spi _ !neg_neg)⁻¹ᵍ, apply shomotopy_group_isomorphism_of_pequiv, intro k, exact ppi_pequiv_right (λx, ptrunc_pequiv (maxm2 (s₀ + k)) (Y x k)), end open prod.ops definition atiyah_hirzebruch_base_change [constructor] : agℤ ×ag agℤ ≃g agℤ ×ag agℤ := begin fapply group.isomorphism.mk, { fapply group.homomorphism.mk, exact (λpq, (-(pq.1 + pq.2), -pq.2)), intro pq pq', induction pq with p q, induction pq' with p' q', esimp, exact prod_eq (ap neg !add.comm4 ⬝ !neg_add) !neg_add }, { fapply adjointify, { exact (λns, (ns.2 - ns.1, -ns.2)) }, { intro ns, esimp, exact prod_eq (ap neg (!add.comm ⬝ !neg_add_cancel_left) ⬝ !neg_neg) !neg_neg }, { intro pq, esimp, exact prod_eq (ap (λx, _ + x) !neg_neg ⬝ !add.comm ⬝ !add_neg_cancel_right) !neg_neg }} end definition atiyah_hirzebruch_convergence : (λp q, opH^p[(x : X), πₛ[-q] (Y x)]) ⟹ᵍ (λn, pH^n[(x : X), Y x]) := begin note z := convergent_exact_couple_reindex atiyah_hirzebruch_convergence2 atiyah_hirzebruch_base_change, refine convergent_exact_couple_g_isomorphism z _ (by intro n; reflexivity), intro p q, apply parametrized_cohomology_change_int, esimp, refine !neg_neg_sub_neg ⬝ !add_neg_cancel_right end definition atiyah_hirzebruch_spectral_sequence : convergent_spectral_sequence_g (λp q, opH^p[(x : X), πₛ[-q] (Y x)]) (λn, pH^n[(x : X), Y x]) := begin apply convergent_spectral_sequence_of_exact_couple atiyah_hirzebruch_convergence, { intro n, exact add.comm (s₀ - -n) (-s₀) ⬝ !neg_add_cancel_left ⬝ !neg_neg }, { reflexivity } end /- to unfold a field of atiyah_hirzebruch_spectral_sequence: esimp [atiyah_hirzebruch_spectral_sequence, convergent_spectral_sequence_of_exact_couple, atiyah_hirzebruch_convergence, convergent_exact_couple_g_isomorphism, convergent_exact_couple_isomorphism, convergent_exact_couple_reindex, atiyah_hirzebruch_convergence2, convergent_exact_couple_negate_abutment, atiyah_hirzebruch_convergence1, convergent_exact_couple_sequence], -/ definition AHSS_deg_d (r : ℕ) : convergent_spectral_sequence.deg_d atiyah_hirzebruch_spectral_sequence r = (r + 2, -(r + 1)) := begin reflexivity end end atiyah_hirzebruch section unreduced_atiyah_hirzebruch definition unreduced_atiyah_hirzebruch_convergence {X : Type} (Y : X → spectrum) (s₀ : ℤ) (H : Πx, is_strunc s₀ (Y x)) : (λp q, uopH^p[(x : X), πₛ[-q] (Y x)]) ⟹ᵍ (λn, upH^n[(x : X), Y x]) := convergent_exact_couple_g_isomorphism (@atiyah_hirzebruch_convergence X₊ (add_point_spectrum Y) s₀ (is_strunc_add_point_spectrum H)) begin intro p q, refine _ ⬝g !uopH_isomorphism_opH⁻¹ᵍ, apply ordinary_parametrized_cohomology_isomorphism_right, intro x, apply shomotopy_group_add_point_spectrum end begin intro n, reflexivity end definition unreduced_atiyah_hirzebruch_spectral_sequence {X : Type} (Y : X → spectrum) (s₀ : ℤ) (H : Πx, is_strunc s₀ (Y x)) : convergent_spectral_sequence_g (λp q, uopH^p[(x : X), πₛ[-q] (Y x)]) (λn, upH^n[(x : X), Y x]) := begin apply convergent_spectral_sequence_of_exact_couple (unreduced_atiyah_hirzebruch_convergence Y s₀ H), { intro n, exact add.comm (s₀ - -n) (-s₀) ⬝ !neg_add_cancel_left ⬝ !neg_neg }, { reflexivity } end end unreduced_atiyah_hirzebruch section serre universe variable u variables {X B : Type.{u}} (b₀ : B) (F : B → Type) (f : X → B) (Y : spectrum) (s₀ : ℤ) (H : is_strunc s₀ Y) include H definition serre_convergence : (λp q, uopH^p[(b : B), uH^q[F b, Y]]) ⟹ᵍ (λn, uH^n[Σ(b : B), F b, Y]) := proof convergent_exact_couple_g_isomorphism (unreduced_atiyah_hirzebruch_convergence (λx, sp_ucotensor (F x) Y) s₀ (λx, is_strunc_sp_ucotensor s₀ (F x) H)) begin intro p q, refine unreduced_ordinary_parametrized_cohomology_isomorphism_right _ p, intro x, exact (unreduced_cohomology_isomorphism_shomotopy_group_sp_ucotensor _ _ !neg_neg)⁻¹ᵍ end begin intro n, refine unreduced_parametrized_cohomology_isomorphism_shomotopy_group_supi _ !neg_neg ⬝g _, refine _ ⬝g (unreduced_cohomology_isomorphism_shomotopy_group_sp_ucotensor _ _ !neg_neg)⁻¹ᵍ, apply shomotopy_group_isomorphism_of_pequiv, intro k, exact (sigma_pumap F (Y k))⁻¹ᵉ* end qed definition serre_spectral_sequence : convergent_spectral_sequence_g (λp q, uopH^p[(b : B), uH^q[F b, Y]]) (λn, uH^n[Σ(b : B), F b, Y]) := begin apply convergent_spectral_sequence_of_exact_couple (serre_convergence F Y s₀ H), { intro n, exact add.comm (s₀ - -n) (-s₀) ⬝ !neg_add_cancel_left ⬝ !neg_neg }, { reflexivity } end definition serre_convergence_map : (λp q, uopH^p[(b : B), uH^q[fiber f b, Y]]) ⟹ᵍ (λn, uH^n[X, Y]) := proof convergent_exact_couple_g_isomorphism (serre_convergence (fiber f) Y s₀ H) begin intro p q, reflexivity end begin intro n, apply unreduced_cohomology_isomorphism, exact !sigma_fiber_equiv⁻¹ᵉ end qed definition serre_spectral_sequence_map : convergent_spectral_sequence_g (λp q, uopH^p[(b : B), uH^q[fiber f b, Y]]) (λn, uH^n[X, Y]) := begin apply convergent_spectral_sequence_of_exact_couple (serre_convergence_map f Y s₀ H), { intro n, exact add.comm (s₀ - -n) (-s₀) ⬝ !neg_add_cancel_left ⬝ !neg_neg }, { reflexivity } end definition serre_convergence_of_is_conn (H2 : is_conn 1 B) : (λp q, uoH^p[B, uH^q[F b₀, Y]]) ⟹ᵍ (λn, uH^n[Σ(b : B), F b, Y]) := proof convergent_exact_couple_g_isomorphism (serre_convergence F Y s₀ H) begin intro p q, exact @uopH_isomorphism_uoH_of_is_conn (pointed.MK B b₀) _ _ H2 end begin intro n, reflexivity end qed definition serre_spectral_sequence_of_is_conn (H2 : is_conn 1 B) : convergent_spectral_sequence_g (λp q, uoH^p[B, uH^q[F b₀, Y]]) (λn, uH^n[Σ(b : B), F b, Y]) := begin apply convergent_spectral_sequence_of_exact_couple (serre_convergence_of_is_conn b₀ F Y s₀ H H2), { intro n, exact add.comm (s₀ - -n) (-s₀) ⬝ !neg_add_cancel_left ⬝ !neg_neg }, { reflexivity } end definition serre_convergence_map_of_is_conn (H2 : is_conn 1 B) : (λp q, uoH^p[B, uH^q[fiber f b₀, Y]]) ⟹ᵍ (λn, uH^n[X, Y]) := proof convergent_exact_couple_g_isomorphism (serre_convergence_of_is_conn b₀ (fiber f) Y s₀ H H2) begin intro p q, reflexivity end begin intro n, apply unreduced_cohomology_isomorphism, exact !sigma_fiber_equiv⁻¹ᵉ end qed definition serre_spectral_sequence_map_of_is_conn (H2 : is_conn 1 B) : convergent_spectral_sequence_g (λp q, uoH^p[B, uH^q[fiber f b₀, Y]]) (λn, uH^n[X, Y]) := begin apply convergent_spectral_sequence_of_exact_couple (serre_convergence_map_of_is_conn b₀ f Y s₀ H H2), { intro n, exact add.comm (s₀ - -n) (-s₀) ⬝ !neg_add_cancel_left ⬝ !neg_neg }, { reflexivity } end end serre end spectrum
0712035c8106ab13b6064d0817f613ae0dada0da
3c693e12637d1cf47effc09ab5e21700d1278e73
/src/topology/twitch.lean
1769ff6aed3d9449348f2a408ed3e74d268a7773
[]
no_license
ImperialCollegeLondon/Example-Lean-Projects
e731664ae046980921a69ccfeb2286674080c5bb
87b27ba616eaf03f3642000829a481a1932dd08e
refs/heads/master
1,685,399,670,721
1,623,092,696,000
1,623,092,696,000
275,571,570
19
1
null
1,593,361,524,000
1,593,344,124,000
Lean
UTF-8
Lean
false
false
13,103
lean
-- topological spaces from first princples! -- Turns out there's quite a lot to it, but it's all straightforward -- I'll start on the hour. I'll do a brief review of last week -- (the below file, -- https://github.com/ImperialCollegeLondon/Example-Lean-Projects/blob/master/src/topology/twitch.lean -- and then I'll start on the proof that the continuous image of compact is compact. import tactic -- remember : in Lean, `set X` means the type of subsets of X -- or, the type of "sets of elements of X" open set /-- The definition of a topological space -/ class topological_space (X : Type) := -- some subsets of X are called "open sets" (is_open : set X → Prop) -- X itself is open (is_open_univ : is_open univ) -- intersection of two open sets is open (is_open_inter : ∀ U V : set X, is_open U → is_open V → is_open (U ∩ V)) -- arbitrary union of open sets is open (is_open_sUnion : ∀ (𝒞 : set (set X)), (∀ U ∈ 𝒞, is_open U) → is_open (⋃₀ 𝒞)) -- what is an "arbitrary union of open sets"? -- I've set it up as a set of open sets -- but you might have an "indexed family of open sets" -- ie some type ι, and for all i ∈ ι an open set U_i -- and you want ⋃ U_i open namespace topological_space -- let X be a topological space variables {X : Type} [topological_space X] -- let's do indexed unions lemma is_open_Union {ι : Type} {f : ι → set X} (hf : ∀ i : ι, is_open (f i)) : is_open (⋃ i, f i) := begin apply is_open_sUnion, intros U hU, cases hU with i hi, dsimp at hi, rw ←hi, apply hf, end -- empty set is open lemma is_open_empty : is_open (∅ : set X) := begin let 𝒞 : set (set X) := ∅, have h𝒞 : ∀ U ∈ 𝒞, is_open U, { rintro U ⟨⟩, }, convert is_open_sUnion 𝒞 h𝒞, rw sUnion_empty, end -- finite intersection of open sets is open -- proof by induction on size of finite set lemma is_open_sInter {𝒞 : set (set X)} (h𝒞 : finite 𝒞) : (∀ U ∈ 𝒞, is_open U) → is_open ⋂₀ 𝒞 := begin apply finite.induction_on h𝒞, { -- base case, intros, convert is_open_univ, rw sInter_empty }, { -- inductive step -- going to use is_open_inter intro U, intro 𝒞, intro hU𝒞, intro h𝒞, intro h𝒞2, -- h says "assume both U and every element of 𝒞 is open" -- insert U 𝒞 means {U} ∪ 𝒞 intro h, rw sInter_insert, apply is_open_inter, { apply h, simp }, { apply h𝒞2, intros U hU, apply h, simp [hU] }}, end -- a variant of finite intersection of opens is open lemma is_open_bInter {I : Type} {F : set I} (hf : finite F) (U : I → set X) (hU : ∀ (i : I), is_open (U i)) : is_open (⋂ i ∈ F, U i) := begin rw bInter_eq_Inter, show is_open (⋂₀ set.range (λ x : F, U x)), apply is_open_sInter, { rw ←image_univ, apply finite.image, haveI := classical.choice hf, apply finite_univ }, finish, end def is_closed (C : set X) : Prop := is_open Cᶜ @[simp] lemma is_closed_iff (C : set X) : is_closed C ↔ is_open Cᶜ := iff.rfl -- clearly could spend all day proving facts about closed sets now lemma is_closed_empty : is_closed (∅ : set X) := begin simp [is_open_univ], end end topological_space -- next : continuous functions open topological_space variables {X : Type} [topological_space X] {Y : Type} [topological_space Y] /-- a function X → Y between topological spaces is continuous if the preimage of every open set is open -/ def continuous (f : X → Y) : Prop := ∀ U, is_open U → is_open (f⁻¹' U) theorem continuous_id : continuous (id : X → X) := begin intro U, intro hU, -- interesting question -- clearly id⁻¹' U = U -- But this is true *by definition*? -- another interesting question -- clearly id'' U = U (pushforward) -- but is this true *by definition*? -- THESE QUESTIONS ARE NOT MATHEMATICAL QUESTIONS -- They depend not on the specification, but on the *implementation* -- have h1 : U = id '' U, -- { --refl, -- fails! -- -- not true by definition -- ext x, -- split, -- intro h, -- unfold set.image, -- use x, -- this is why it's not true by definition -- split, assumption, refl, -- rintro ⟨y, hy1, rfl⟩, -- exact hy1, -- }, -- have h2 : U = id⁻¹' U, -- true by definition -- refl, exact hU, end variables {Z : Type} [topological_space Z] theorem continuous.comp {f : X → Y} {g : Y → Z} (hf : continuous f) (hg : continuous g) : continuous (g ∘ f) := begin intro U, intro hU, change is_open ((g ∘ f)⁻¹' U), change is_open (f⁻¹' (g⁻¹' U)), -- proving it backwards apply hf, apply hg, exact hU end -- term mode proof (same proof!) theorem continuous.comp' {f : X → Y} {g : Y → Z} (hf : continuous f) (hg : continuous g) : continuous (g ∘ f) := λ U hU, hf (g⁻¹' U) (hg _ hU) /-- a subset C of a top space X is compact if every open cover has a finite subcover -/ def compact (C : set X) : Prop := ∀ (ι : Type) (U : ι → set X) (hi : ∀ i : ι, is_open (U i)) (hC : C ⊆ ⋃i, U i), ∃ F : set ι, finite F ∧ C ⊆ ⋃ i ∈ F, U i -- this definition seems to me to be easier to work with def hausdorff (X : Type) [topological_space X] : Prop := ∀ x y : X, x ≠ y → ∃ U V : set X, is_open U ∧ is_open V ∧ x ∈ U ∧ y ∈ V ∧ U ∩ V = ∅ -- Theorem: continuous image of a compact set is compact theorem compact_map {f : X → Y} (hf : continuous f) {C : set X} (hC : compact C) : compact (f '' C) := begin -- suffices to prove that if f(C) is covered by open sets, it has a -- finite subcover intros I U hU hUC, -- hUC : f(C) ⊆ ⋃_{i ∈ I} Uᵢ -- So say we've covered f(C) by open sets -- Then C has a cover by open sets, namely Vᵢ := f⁻¹(Uᵢ), let V : I → set X := λ i, f⁻¹' (U i), -- Let's check that all the Vᵢ are open have hV : ∀ i : I, is_open (V i), { intro i, apply hf, apply hU }, -- Let's check that the Vᵢ cover C have hVC : C ⊆ ⋃ i, V i, { -- say x ∈ C, intro x, intro hx, -- then f(x) ∈ ⋃_i Uᵢ have hx2 : f x ∈ ⋃ i, U i, apply hUC, use [x, hx], -- f(x) ∈ ⋃_i Uᵢ, so ∃ i s.t. f(x) ∈ Uᵢ rw mem_Union at hx2 ⊢, cases hx2 with i hi, use i, exact hi }, -- but C is compact specialize hC I V hV hVC, -- so there exists a finite subcover of Vᵢ, rcases hC with ⟨F, hF, hFC⟩, -- I claim that corresponding Uᵢ will work use [F, hF], -- Let's check they cover f(C), rintros _ ⟨x, hx1, rfl⟩, specialize hFC hx1, rw mem_bUnion_iff at hFC ⊢, exact hFC, -- They do, so the cover of f(C) had a finite subcover :D end -- To prove that a compact subspace of a Hausdorff space is closed, -- we need the fact that a "locally open" set is open! -- So let's prove that first lemma open_iff_locally_open (V : set X) : is_open V ↔ ∀ x : X, x ∈ V → ∃ U : set X, x ∈ U ∧ is_open U ∧ U ⊆ V := ⟨λ hV x hx, ⟨V, hx, hV, subset.refl _⟩, λ h, begin let 𝒞 : set (set X) := {U : set X | is_open U ∧ U ⊆ V}, -- 𝒞 doesn't just contain the neighbourhoods of x for each x ∈ V -- 𝒞 contains more sets, e.g. the empty set! -- Clearly every set in 𝒞 is open, so their union is open convert is_open_sUnion 𝒞 _, swap, { intros U H, cases H, assumption}, -- It suffices to prove that V is the union of the elements of 𝒞 { ext x, split, -- let's prove inclusions in both directions { intro hx, rcases h x hx with ⟨U, hU1, hU2, hU3⟩, rw mem_sUnion, use U, use hU2, exact hU3, exact hU1 }, { -- easy way intro hx, rw mem_sUnion at hx, rcases hx with ⟨U, hUC, hxU⟩, cases hUC with h1 h2, apply h2 hxU }} end⟩ -- #exit -- begin -- split, -- { -- This way is easy. Say V is open. -- intro hV, -- -- say x ∈ V -- intros x hx, -- -- Want an open neighbourhood of x contained in V -- -- let's just use V :-) -- use V, -- use hx, -- use hV }, -- last goal V ⊆ V closed automatically by `refl`, -- { intro h, -- -- Reid Barton trick! -- let 𝒞 : set (set X) := {U : set X | is_open U ∧ U ⊆ V}, -- -- 𝒞 doesn't just contain the neighbourhoods of x for each x ∈ V -- -- 𝒞 contains more sets, e.g. the empty set! -- -- Clearly every set in 𝒞 is open, so their union is open -- convert is_open_sUnion 𝒞 _, -- swap, -- { tidy }, -- -- It suffices to prove that V is the union of the elements of 𝒞 -- { ext x, -- split, -- -- let's prove inclusions in both directions -- { intro hx, -- rcases h x hx with ⟨U, hU1, hU2, hU3⟩, -- rw mem_sUnion, -- use U, -- use hU2, -- exact hU3, -- exact hU1 }, -- { -- easy way -- intro hx, -- rw mem_sUnion at hx, -- rcases hx with ⟨U, hUC, hxU⟩, -- cases hUC with h1 h2, -- apply h2 hxU }}} -- end -- stream starts at 10am UK time (UTC+2) -- Goal today theorem is_closed_of_compact (hX : hausdorff X) {C : set X} (hC : compact C) : is_closed C := begin unfold is_closed, -- let's start with the maths proof -- We're going to prove that Cᶜ is open by showing it's locally open -- Let x ∈ Cᶜ i.e. x : X and x ∉ C -- If we can find an open subset U ⊆ Cᶜ with x ∈ U then we're done -- by the previous lemma rw open_iff_locally_open, intros x hx, rw mem_compl_iff at hx, -- Where do we find such U? -- Now is where we use compactness. -- We're going to cover C by a bunch of open sets -- Where do we get the open sets? -- We get them from Hausdorffness -- Let's regard x as fixed. -- Say y ∈ C (y is moving) -- Then x ≠ y because x ∉ C -- so by Hausdorff there exists opens U=U(y) and V=V(y) -- disjoint, with x ∈ V and y ∈ U -- In particular x ∉ U = U(y) -- The union of the U(y) covers C because y ∈ C was arbitrary and y ∈ U(y) -- So there's a finite subcover, U(y₁), U(y₂)...U(yₙ) of C -- Now take the intersection of the corresponding V(y)'s -- this is an open nhd of x -- and it's disjoint from the union of the U(y)'s so it's disjoint from C -- This V works! -- "issue" with the maths proof -- uses the axiom of choice! -- Grateful to Reid Barton and Andrej Bauer who independently showed -- me a "AC removal principle" -- which makes proofs look (a) a bit slicker -- and (b) a bit harder to remember (possibly). -- AC removal principle says "DON'T CHOOSE! USE ALL THE CHOICES!" -- in our actual proof we'll define a slightly different cover -- I is the set of pairs (V,U) of open subsets of X, with -- x ∈ V, and U ∩ V empty let I := {VU : set X × set X // x ∈ VU.1 ∧ is_open VU.1 ∧ is_open VU.2 ∧ VU.1 ∩ VU.2 = ∅}, -- We want to consider all the U's coming from pairs (V,U) in I let U : I → set X := λ VUH, VUH.1.2, -- send (V,U) to U -- My claim is that as i ranges through I, the U(i) are an open cover -- Let's first prove they're all open have hU1 : ∀ i : I, is_open (U i), { rintro ⟨⟨V, U⟩, _, _, h, _⟩, exact h }, -- now let's prove they cover C have hU2 : C ⊆ ⋃ i, U i, { intros y hy, /- def hausdorff (X : Type) [topological_space X] : Prop := ∀ x y : X, x ≠ y → ∃ U V : set X, is_open U ∧ is_open V ∧ x ∈ U ∧ y ∈ V ∧ U ∩ V = ∅ -/ have hxy : x ≠ y, { rintro rfl, contradiction }, -- now use that X is Hausdorff rcases hX x y hxy with ⟨V, U, hV, hU, hxV, hyU, hUV⟩, rw mem_Union, -- now let's give the term of type I use ⟨(V, U), ⟨hxV, hV, hU, hUV⟩⟩, exact hyU }, /- def compact (C : set X) : Prop := ∀ (ι : Type) (U : ι → set X) (hi : ∀ i : ι, is_open (U i)) (hC : C ⊆ ⋃i, U i), ∃ F : set ι, finite F ∧ C ⊆ ⋃ i ∈ F, U i -/ specialize hC I U hU1 hU2, rcases hC with ⟨F, hF, hFC⟩, -- now we have our finite subcover -- now let's create the open nhd of x let W := ⋂ i ∈ F, (i : I).1.1, use W, refine ⟨_, _, _⟩, { show x ∈ ⋂ (i : I) (H : i ∈ F), i.val.fst, rw mem_bInter_iff, rintro ⟨⟨V, U⟩, hxV, hV, hU, hUV⟩, intro hi, use hxV }, { -- we're missing a lemma here -- need a different kind of "finite intersection of opens is open" show is_open (⋂ (i : I) (H : i ∈ F), i.val.fst), apply is_open_bInter hF, rintro ⟨⟨V, U⟩, hxV, hV, hU, hUV⟩, exact hV, }, { rw subset_compl_comm, rw compl_Inter, refine set.subset.trans hFC _, apply Union_subset_Union, intro i, rw compl_Inter, apply Union_subset_Union, rintro hi, rcases i with ⟨⟨V, U⟩, hxV, hV, hU, hUV⟩, show U ⊆ Vᶜ, rw subset_compl_iff_disjoint, rw inter_comm, exact hUV }, end
bcecc60ec24e0345e3aea3de241ec6b8a768bd3e
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/Tactic/Rewrite.lean
cf135f2c9e16fd854b466dc45b8bc928fd6b8b4a
[ "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
2,480
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.Rewrite import Lean.Meta.Tactic.Replace import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Location import Lean.Elab.Tactic.Config namespace Lean.Elab.Tactic open Meta def rewriteTarget (stx : Syntax) (symm : Bool) (config : Rewrite.Config) : TacticM Unit := do Term.withSynthesize <| withMainContext do let e ← elabTerm stx none true let r ← rewrite (← getMainGoal) (← getMainTarget) e symm (config := config) let mvarId' ← replaceTargetEq (← getMainGoal) r.eNew r.eqProof replaceMainGoal (mvarId' :: r.mvarIds) def rewriteLocalDecl (stx : Syntax) (symm : Bool) (fvarId : FVarId) (config : Rewrite.Config) : TacticM Unit := do Term.withSynthesize <| withMainContext do let e ← elabTerm stx none true let localDecl ← getLocalDecl fvarId let rwResult ← rewrite (← getMainGoal) localDecl.type e symm (config := config) let replaceResult ← replaceLocalDecl (← getMainGoal) fvarId rwResult.eNew rwResult.eqProof replaceMainGoal (replaceResult.mvarId :: rwResult.mvarIds) def withRWRulesSeq (token : Syntax) (rwRulesSeqStx : Syntax) (x : (symm : Bool) → (term : Syntax) → TacticM Unit) : TacticM Unit := do let lbrak := rwRulesSeqStx[0] let rules := rwRulesSeqStx[1].getArgs let rbrak := rwRulesSeqStx[2] -- show initial state up to (incl.) `[` withTacticInfoContext (mkNullNode #[token, lbrak]) (pure ()) let numRules := (rules.size + 1) / 2 for i in [:numRules] do let rule := rules[i * 2] let sep := rules.getD (i * 2 + 1) Syntax.missing -- show rule state up to (incl.) next `,` withTacticInfoContext (mkNullNode #[rule, sep]) do -- show errors on rule withRef rule do let symm := !rule[0].isNone let term := rule[1] x symm term declare_config_elab elabRewriteConfig Rewrite.Config @[builtinTactic Lean.Parser.Tactic.rewriteSeq] def evalRewriteSeq : Tactic := fun stx => do let cfg ← elabRewriteConfig stx[1] let loc := expandOptLocation stx[3] withRWRulesSeq stx[0] stx[2] fun symm term => do withLocation loc (rewriteLocalDecl term symm · cfg) (rewriteTarget term symm cfg) (throwTacticEx `rewrite . "did not find instance of the pattern in the current goal") end Lean.Elab.Tactic
f0d35ae2d0d9253f14f6e2321909602855149884
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Meta/Injective.lean
e2abf546fe564791739e05760761cff78dbbe9d8
[ "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
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
6,725
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Transform import Lean.Meta.Tactic.Injection import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Refl import Lean.Meta.Tactic.Cases import Lean.Meta.Tactic.Subst import Lean.Meta.Tactic.Simp.Types import Lean.Meta.Tactic.Assumption namespace Lean.Meta private def mkAnd? (args : Array Expr) : Option Expr := Id.run do if args.isEmpty then return none else let mut result := args.back for arg in args.reverse[1:] do result := mkApp2 (mkConst ``And) arg result return result def elimOptParam (type : Expr) : CoreM Expr := do Core.transform type fun e => if e.isAppOfArity ``optParam 2 then return TransformStep.visit (e.getArg! 0) else return TransformStep.visit e private partial def mkInjectiveTheoremTypeCore? (ctorVal : ConstructorVal) (useEq : Bool) : MetaM (Option Expr) := do let us := ctorVal.levelParams.map mkLevelParam let type ← elimOptParam ctorVal.type forallBoundedTelescope type ctorVal.numParams fun params type => forallTelescope type fun args1 resultType => do let jp (args2 args2New : Array Expr) : MetaM (Option Expr) := do let lhs := mkAppN (mkAppN (mkConst ctorVal.name us) params) args1 let rhs := mkAppN (mkAppN (mkConst ctorVal.name us) params) args2 let eq ← mkEq lhs rhs let mut eqs := #[] for arg1 in args1, arg2 in args2 do let arg1Type ← inferType arg1 if !(← isProp arg1Type) && arg1 != arg2 then eqs := eqs.push (← mkEqHEq arg1 arg2) if let some andEqs := mkAnd? eqs then let result ← if useEq then mkEq eq andEqs else mkArrow eq andEqs mkForallFVars params (← mkForallFVars args1 (← mkForallFVars args2New result)) else return none let rec mkArgs2 (i : Nat) (type : Expr) (args2 args2New : Array Expr) : MetaM (Option Expr) := do if h : i < args1.size then match (← whnf type) with | Expr.forallE n d b _ => let arg1 := args1.get ⟨i, h⟩ if arg1.occurs resultType then mkArgs2 (i + 1) (b.instantiate1 arg1) (args2.push arg1) args2New else withLocalDecl n (if useEq then BinderInfo.default else BinderInfo.implicit) d fun arg2 => mkArgs2 (i + 1) (b.instantiate1 arg2) (args2.push arg2) (args2New.push arg2) | _ => throwError "unexpected constructor type for '{ctorVal.name}'" else jp args2 args2New if useEq then mkArgs2 0 type #[] #[] else withNewBinderInfos (params.map fun param => (param.fvarId!, BinderInfo.implicit)) <| withNewBinderInfos (args1.map fun arg1 => (arg1.fvarId!, BinderInfo.implicit)) <| mkArgs2 0 type #[] #[] private def mkInjectiveTheoremType? (ctorVal : ConstructorVal) : MetaM (Option Expr) := mkInjectiveTheoremTypeCore? ctorVal false private def injTheoremFailureHeader (ctorName : Name) : MessageData := m!"failed to prove injectivity theorem for constructor '{ctorName}', use 'set_option genInjectivity false' to disable the generation" private def throwInjectiveTheoremFailure {α} (ctorName : Name) (mvarId : MVarId) : MetaM α := throwError "{injTheoremFailureHeader ctorName}{indentD <| MessageData.ofGoal mvarId}" private def solveEqOfCtorEq (ctorName : Name) (mvarId : MVarId) (h : FVarId) : MetaM Unit := do match (← injection mvarId h) with | InjectionResult.solved => unreachable! | InjectionResult.subgoal mvarId .. => (← mvarId.splitAnd).forM fun mvarId => unless (← mvarId.assumptionCore) do throwInjectiveTheoremFailure ctorName mvarId private def mkInjectiveTheoremValue (ctorName : Name) (targetType : Expr) : MetaM Expr := forallTelescopeReducing targetType fun xs type => do let mvar ← mkFreshExprSyntheticOpaqueMVar type solveEqOfCtorEq ctorName mvar.mvarId! xs.back.fvarId! mkLambdaFVars xs mvar def mkInjectiveTheoremNameFor (ctorName : Name) : Name := ctorName ++ `inj private def mkInjectiveTheorem (ctorVal : ConstructorVal) : MetaM Unit := do let some type ← mkInjectiveTheoremType? ctorVal | return () let value ← mkInjectiveTheoremValue ctorVal.name type let name := mkInjectiveTheoremNameFor ctorVal.name addDecl <| Declaration.thmDecl { name levelParams := ctorVal.levelParams type := (← instantiateMVars type) value := (← instantiateMVars value) } def mkInjectiveEqTheoremNameFor (ctorName : Name) : Name := ctorName ++ `injEq private def mkInjectiveEqTheoremType? (ctorVal : ConstructorVal) : MetaM (Option Expr) := mkInjectiveTheoremTypeCore? ctorVal true private def mkInjectiveEqTheoremValue (ctorName : Name) (targetType : Expr) : MetaM Expr := do forallTelescopeReducing targetType fun xs type => do let mvar ← mkFreshExprSyntheticOpaqueMVar type let [mvarId₁, mvarId₂] ← mvar.mvarId!.apply (mkConst ``Eq.propIntro) | throwError "unexpected number of subgoals when proving injective theorem for constructor '{ctorName}'" let (h, mvarId₁) ← mvarId₁.intro1 let (_, mvarId₂) ← mvarId₂.intro1 solveEqOfCtorEq ctorName mvarId₁ h let mvarId₂ ← mvarId₂.casesAnd if let some mvarId₂ ← mvarId₂.substEqs then try mvarId₂.refl catch _ => throwError (injTheoremFailureHeader ctorName) mkLambdaFVars xs mvar private def mkInjectiveEqTheorem (ctorVal : ConstructorVal) : MetaM Unit := do let some type ← mkInjectiveEqTheoremType? ctorVal | return () let value ← mkInjectiveEqTheoremValue ctorVal.name type let name := mkInjectiveEqTheoremNameFor ctorVal.name addDecl <| Declaration.thmDecl { name levelParams := ctorVal.levelParams type := (← instantiateMVars type) value := (← instantiateMVars value) } addSimpTheorem (ext := simpExtension) name (post := true) (inv := false) AttributeKind.global (prio := eval_prio default) register_builtin_option genInjectivity : Bool := { defValue := true descr := "generate injectivity theorems for inductive datatype constructors" } def mkInjectiveTheorems (declName : Name) : MetaM Unit := do if (← getEnv).contains ``Eq.propIntro && genInjectivity.get (← getOptions) && !(← isInductivePredicate declName) then let info ← getConstInfoInduct declName unless info.isUnsafe do for ctor in info.ctors do let ctorVal ← getConstInfoCtor ctor if ctorVal.numFields > 0 then mkInjectiveTheorem ctorVal mkInjectiveEqTheorem ctorVal end Lean.Meta
654b6b1c6b72e72965b24bde64ced69677b2402a
f7315930643edc12e76c229a742d5446dad77097
/tests/lean/run/tactic9.lean
ce73ab2f34468fc70be4ec9f4b01a8d9efaffffc
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
175
lean
import logic open tactic theorem tst {A B : Prop} (H1 : A) (H2 : B) : ((fun x : Prop, x) A) ∧ B ∧ A := by apply and.intro; beta; assumption; apply and.intro; !assumption
de7ca06abc3b18b769a61825920dedca4bd08083
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/category/galois_connection.lean
35ab915fc0bfe36419f58df9335d7ef40d4c1aea
[ "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
1,454
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton -/ import category_theory.category.preorder import category_theory.adjunction.basic import order.galois_connection /-! # Galois connections between preorders are adjunctions. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. * `galois_connection.adjunction` is the adjunction associated to a galois connection. -/ universes u v section variables {X : Type u} {Y : Type v} [preorder X] [preorder Y] /-- A galois connection between preorders induces an adjunction between the associated categories. -/ def galois_connection.adjunction {l : X → Y} {u : Y → X} (gc : galois_connection l u) : gc.monotone_l.functor ⊣ gc.monotone_u.functor := category_theory.adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, ⟨λ f, (gc.le_u f.le).hom, λ f, (gc.l_le f.le).hom, by tidy, by tidy⟩ } end namespace category_theory variables {X : Type u} {Y : Type v} [preorder X] [preorder Y] /-- An adjunction between preorder categories induces a galois connection. -/ lemma adjunction.gc {L : X ⥤ Y} {R : Y ⥤ X} (adj : L ⊣ R) : galois_connection L.obj R.obj := λ x y, ⟨λ h, ((adj.hom_equiv x y).to_fun h.hom).le, λ h, ((adj.hom_equiv x y).inv_fun h.hom).le⟩ end category_theory
a4a47f49f9593b42dd52b64d705a1fba0ef8a9d3
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/cubical/squareover.hlean
e3d0484877b5732a1761fb0ca910ba4d73259fde
[ "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
15,645
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Squareovers -/ import .square open eq equiv is_equiv namespace eq -- we give the argument B explicitly, because Lean would find (λa, B a) by itself, which -- makes the type uglier (of course the two terms are definitionally equal) inductive squareover {A : Type} (B : A → Type) {a₀₀ : A} {b₀₀ : B a₀₀} : Π{a₂₀ a₀₂ a₂₂ : A} {p₁₀ : a₀₀ = a₂₀} {p₁₂ : a₀₂ = a₂₂} {p₀₁ : a₀₀ = a₀₂} {p₂₁ : a₂₀ = a₂₂} (s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁) {b₂₀ : B a₂₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} (q₁₀ : pathover B b₀₀ p₁₀ b₂₀) (q₁₂ : pathover B b₀₂ p₁₂ b₂₂) (q₀₁ : pathover B b₀₀ p₀₁ b₀₂) (q₂₁ : pathover B b₂₀ p₂₁ b₂₂), Type := idsquareo : squareover B ids idpo idpo idpo idpo variables {A A' : Type} {B : A → Type} {a a' a'' a₀₀ a₂₀ a₄₀ a₀₂ a₂₂ a₂₄ a₀₄ a₄₂ a₄₄ : A} /-a₀₀-/ {p₁₀ : a₀₀ = a₂₀} /-a₂₀-/ {p₃₀ : a₂₀ = a₄₀} /-a₄₀-/ {p₀₁ : a₀₀ = a₀₂} /-s₁₁-/ {p₂₁ : a₂₀ = a₂₂} /-s₃₁-/ {p₄₁ : a₄₀ = a₄₂} /-a₀₂-/ {p₁₂ : a₀₂ = a₂₂} /-a₂₂-/ {p₃₂ : a₂₂ = a₄₂} /-a₄₂-/ {p₀₃ : a₀₂ = a₀₄} /-s₁₃-/ {p₂₃ : a₂₂ = a₂₄} /-s₃₃-/ {p₄₃ : a₄₂ = a₄₄} /-a₀₄-/ {p₁₄ : a₀₄ = a₂₄} /-a₂₄-/ {p₃₄ : a₂₄ = a₄₄} /-a₄₄-/ {s₁₁ : square p₁₀ p₁₂ p₀₁ p₂₁} {s₃₁ : square p₃₀ p₃₂ p₂₁ p₄₁} {s₁₃ : square p₁₂ p₁₄ p₀₃ p₂₃} {s₃₃ : square p₃₂ p₃₄ p₂₃ p₄₃} {b₀₀ : B a₀₀} {b₂₀ : B a₂₀} {b₄₀ : B a₄₀} {b₀₂ : B a₀₂} {b₂₂ : B a₂₂} {b₄₂ : B a₄₂} {b₀₄ : B a₀₄} {b₂₄ : B a₂₄} {b₄₄ : B a₄₄} /-b₀₀-/ {q₁₀ : b₀₀ =[p₁₀] b₂₀} /-b₂₀-/ {q₃₀ : b₂₀ =[p₃₀] b₄₀} /-b₄₀-/ {q₀₁ : b₀₀ =[p₀₁] b₀₂} /-t₁₁-/ {q₂₁ : b₂₀ =[p₂₁] b₂₂} /-t₃₁-/ {q₄₁ : b₄₀ =[p₄₁] b₄₂} /-b₀₂-/ {q₁₂ : b₀₂ =[p₁₂] b₂₂} /-b₂₂-/ {q₃₂ : b₂₂ =[p₃₂] b₄₂} /-b₄₂-/ {q₀₃ : b₀₂ =[p₀₃] b₀₄} /-t₁₃-/ {q₂₃ : b₂₂ =[p₂₃] b₂₄} /-t₃₃-/ {q₄₃ : b₄₂ =[p₄₃] b₄₄} /-b₀₄-/ {q₁₄ : b₀₄ =[p₁₄] b₂₄} /-b₂₄-/ {q₃₄ : b₂₄ =[p₃₄] b₄₄} /-b₄₄-/ definition squareo := @squareover A B a₀₀ definition idsquareo [reducible] [constructor] (b₀₀ : B a₀₀) := @squareover.idsquareo A B a₀₀ b₀₀ definition idso [reducible] [constructor] := @squareover.idsquareo A B a₀₀ b₀₀ definition apds (f : Πa, B a) (s : square p₁₀ p₁₂ p₀₁ p₂₁) : squareover B s (apdo f p₁₀) (apdo f p₁₂) (apdo f p₀₁) (apdo f p₂₁) := square.rec_on s idso definition vrflo : squareover B vrfl q₁₀ q₁₀ idpo idpo := by induction q₁₀; exact idso definition hrflo : squareover B hrfl idpo idpo q₁₀ q₁₀ := by induction q₁₀; exact idso definition vdeg_squareover {p₁₀'} {s : p₁₀ = p₁₀'} {q₁₀' : b₀₀ =[p₁₀'] b₂₀} (r : change_path s q₁₀ = q₁₀') : squareover B (vdeg_square s) q₁₀ q₁₀' idpo idpo := by induction s; esimp at *; induction r; exact vrflo definition hdeg_squareover {p₀₁'} {s : p₀₁ = p₀₁'} {q₀₁' : b₀₀ =[p₀₁'] b₀₂} (r : change_path s q₀₁ = q₀₁') : squareover B (hdeg_square s) idpo idpo q₀₁ q₀₁' := by induction s; esimp at *; induction r; exact hrflo definition hconcato (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (t₃₁ : squareover B s₃₁ q₃₀ q₃₂ q₂₁ q₄₁) : squareover B (hconcat s₁₁ s₃₁) (q₁₀ ⬝o q₃₀) (q₁₂ ⬝o q₃₂) q₀₁ q₄₁ := by induction t₃₁; exact t₁₁ definition vconcato (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (t₁₃ : squareover B s₁₃ q₁₂ q₁₄ q₀₃ q₂₃) : squareover B (vconcat s₁₁ s₁₃) q₁₀ q₁₄ (q₀₁ ⬝o q₀₃) (q₂₁ ⬝o q₂₃) := by induction t₁₃; exact t₁₁ definition hinverseo (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (hinverse s₁₁) q₁₀⁻¹ᵒ q₁₂⁻¹ᵒ q₂₁ q₀₁ := by induction t₁₁; constructor definition vinverseo (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (vinverse s₁₁) q₁₂ q₁₀ q₀₁⁻¹ᵒ q₂₁⁻¹ᵒ := by induction t₁₁; constructor definition eq_vconcato {q : b₀₀ =[p₁₀] b₂₀} (r : q = q₁₀) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q q₁₂ q₀₁ q₂₁ := by induction r; exact t₁₁ definition vconcato_eq {q : b₀₂ =[p₁₂] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : q₁₂ = q) : squareover B s₁₁ q₁₀ q q₀₁ q₂₁ := by induction r; exact t₁₁ definition eq_hconcato {q : b₀₀ =[p₀₁] b₀₂} (r : q = q₀₁) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q q₂₁ := by induction r; exact t₁₁ definition hconcato_eq {q : b₂₀ =[p₂₁] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : q₂₁ = q) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q := by induction r; exact t₁₁ definition pathover_vconcato {p : a₀₀ = a₂₀} {sp : p = p₁₀} {q : b₀₀ =[p] b₂₀} (r : change_path sp q = q₁₀) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (sp ⬝pv s₁₁) q q₁₂ q₀₁ q₂₁ := by induction sp; induction r; exact t₁₁ definition vconcato_pathover {p : a₀₂ = a₂₂} {sp : p₁₂ = p} {q : b₀₂ =[p] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : change_path sp q₁₂ = q) : squareover B (s₁₁ ⬝vp sp) q₁₀ q q₀₁ q₂₁ := by induction sp; induction r; exact t₁₁ definition pathover_hconcato {p : a₀₀ = a₀₂} {sp : p = p₀₁} {q : b₀₀ =[p] b₀₂} (r : change_path sp q = q₀₁) (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B (sp ⬝ph s₁₁) q₁₀ q₁₂ q q₂₁ := by induction sp; induction r; exact t₁₁ definition hconcato_pathover {p : a₂₀ = a₂₂} {sp : p₂₁ = p} {q : b₂₀ =[p] b₂₂} (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) (r : change_path sp q₂₁ = q) : squareover B (s₁₁ ⬝hp sp) q₁₀ q₁₂ q₀₁ q := by induction sp; induction r; exact t₁₁ -- relating squareovers to squares definition square_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : square (!con_tr ⬝ ap (λa, p₂₁ ▸ a) (tr_eq_of_pathover q₁₀)) (tr_eq_of_pathover q₁₂) (ap (λq, q ▸ b₀₀) (eq_of_square s₁₁) ⬝ !con_tr ⬝ ap (λa, p₁₂ ▸ a) (tr_eq_of_pathover q₀₁)) (tr_eq_of_pathover q₂₁) := by induction t₁₁; esimp; constructor /- definition squareover_of_square (q : square (!con_tr ⬝ ap (λa, p₂₁ ▸ a) (tr_eq_of_pathover q₁₀)) (tr_eq_of_pathover q₁₂) (ap (λq, q ▸ b₀₀) (eq_of_square s₁₁) ⬝ !con_tr ⬝ ap (λa, p₁₂ ▸ a) (tr_eq_of_pathover q₀₁)) (tr_eq_of_pathover q₂₁)) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ := sorry -/ definition square_of_squareover_ids {b₀₀ b₀₂ b₂₀ b₂₂ : B a} {t : b₀₀ = b₂₀} {b : b₀₂ = b₂₂} {l : b₀₀ = b₀₂} {r : b₂₀ = b₂₂} (so : squareover B ids (pathover_idp_of_eq t) (pathover_idp_of_eq b) (pathover_idp_of_eq l) (pathover_idp_of_eq r)) : square t b l r := begin note H := square_of_squareover so, -- use apply ... in rewrite [▸* at H,+idp_con at H,+ap_id at H,↑pathover_idp_of_eq at H], rewrite [+to_right_inv !(pathover_equiv_tr_eq (refl a)) at H], exact H end definition squareover_ids_of_square {b₀₀ b₀₂ b₂₀ b₂₂ : B a} {t : b₀₀ = b₂₀} {b : b₀₂ = b₂₂} {l : b₀₀ = b₀₂} {r : b₂₀ = b₂₂} (q : square t b l r) : squareover B ids (pathover_idp_of_eq t) (pathover_idp_of_eq b) (pathover_idp_of_eq l) (pathover_idp_of_eq r) := square.rec_on q idso -- relating pathovers to squareovers definition pathover_of_squareover' (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ ⬝o q₂₁ =[eq_of_square s₁₁] q₀₁ ⬝o q₁₂ := by induction t₁₁; constructor definition pathover_of_squareover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} (t₁₁ : squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ ⬝o q₂₁ =[s] q₀₁ ⬝o q₁₂ := begin revert s t₁₁, refine equiv_rect' !square_equiv_eq⁻¹ᵉ (λa b, squareover B b _ _ _ _ → _) _, intro s, exact pathover_of_squareover' end definition squareover_of_pathover {s : p₁₀ ⬝ p₂₁ = p₀₁ ⬝ p₁₂} (r : q₁₀ ⬝o q₂₁ =[s] q₀₁ ⬝o q₁₂) : squareover B (square_of_eq s) q₁₀ q₁₂ q₀₁ q₂₁ := by induction q₁₂; esimp [concato] at r;induction r;induction q₂₁;induction q₁₀;constructor definition pathover_top_of_squareover (t₁₁ : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : q₁₀ =[eq_top_of_square s₁₁] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ := by induction t₁₁; constructor definition squareover_of_pathover_top {s : p₁₀ = p₀₁ ⬝ p₁₂ ⬝ p₂₁⁻¹} (r : q₁₀ =[s] q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ) : squareover B (square_of_eq_top s) q₁₀ q₁₂ q₀₁ q₂₁ := by induction q₂₁; induction q₁₂; esimp at r;induction r;induction q₁₀;constructor definition pathover_of_hdeg_squareover {p₀₁' : a₀₀ = a₀₂} {r : p₀₁ = p₀₁'} {q₀₁' : b₀₀ =[p₀₁'] b₀₂} (t : squareover B (hdeg_square r) idpo idpo q₀₁ q₀₁') : q₀₁ =[r] q₀₁' := by induction r; induction q₀₁'; exact (pathover_of_squareover' t)⁻¹ᵒ definition pathover_of_vdeg_squareover {p₁₀' : a₀₀ = a₂₀} {r : p₁₀ = p₁₀'} {q₁₀' : b₀₀ =[p₁₀'] b₂₀} (t : squareover B (vdeg_square r) q₁₀ q₁₀' idpo idpo) : q₁₀ =[r] q₁₀' := by induction r; induction q₁₀'; exact pathover_of_squareover' t definition squareover_of_eq_top (r : change_path (eq_top_of_square s₁₁) q₁₀ = q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ := begin induction s₁₁, revert q₁₂ q₁₀ r, eapply idp_rec_on q₂₁, clear q₂₁, intro q₁₂, eapply idp_rec_on q₁₂, clear q₁₂, esimp, intros, induction r, eapply idp_rec_on q₁₀, constructor end definition eq_top_of_squareover (r : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : change_path (eq_top_of_square s₁₁) q₁₀ = q₀₁ ⬝o q₁₂ ⬝o q₂₁⁻¹ᵒ := by induction r; reflexivity definition change_square {s₁₁'} (p : s₁₁ = s₁₁') (r : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁' q₁₀ q₁₂ q₀₁ q₂₁ := p ▸ r /- definition squareover_equiv_pathover (q₁₀ : b₀₀ =[p₁₀] b₂₀) (q₁₂ : b₀₂ =[p₁₂] b₂₂) (q₀₁ : b₀₀ =[p₀₁] b₀₂) (q₂₁ : b₂₀ =[p₂₁] b₂₂) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ q₂₁ ≃ q₁₀ ⬝o q₂₁ =[eq_of_square s₁₁] q₀₁ ⬝o q₁₂ := begin fapply equiv.MK, { exact pathover_of_squareover}, { intro r, rewrite [-to_left_inv !square_equiv_eq s₁₁], apply squareover_of_pathover, exact r}, { intro r, }, --need characterization of squareover lying over ids. { intro s, induction s, apply idp}, end -/ definition eq_of_vdeg_squareover {q₁₀' : b₀₀ =[p₁₀] b₂₀} (p : squareover B vrfl q₁₀ q₁₀' idpo idpo) : q₁₀ = q₁₀' := begin note H := square_of_squareover p, -- use apply ... in induction p₁₀, -- if needed we can remove this induction and use con_tr_idp in types/eq2 rewrite [▸* at H,idp_con at H,+ap_id at H], let H' := eq_of_vdeg_square H, exact eq_of_fn_eq_fn !pathover_equiv_tr_eq H' end -- definition vdeg_tr_squareover {q₁₂ : p₀₁ ▸ b₀₀ =[p₁₂] p₂₁ ▸ b₂₀} (r : q₁₀ =[_] q₁₂) -- : squareover B s₁₁ q₁₀ q₁₂ !pathover_tr !pathover_tr := -- by induction p;exact vrflo /- A version of eq_pathover where the type of the equality also varies -/ definition eq_pathover_dep {f g : Πa, B a} {p : a = a'} {q : f a = g a} {r : f a' = g a'} (s : squareover B hrfl (pathover_idp_of_eq q) (pathover_idp_of_eq r) (apdo f p) (apdo g p)) : q =[p] r := begin induction p, apply pathover_idp_of_eq, apply eq_of_vdeg_square, exact square_of_squareover_ids s end /- charcaterization of pathovers in pathovers -/ -- in this version the fibration (B) of the pathover does not depend on the variable (a) definition pathover_pathover {a' a₂' : A'} {p : a' = a₂'} {f g : A' → A} {b : Πa, B (f a)} {b₂ : Πa, B (g a)} {q : Π(a' : A'), f a' = g a'} (r : pathover B (b a') (q a') (b₂ a')) (r₂ : pathover B (b a₂') (q a₂') (b₂ a₂')) (s : squareover B (natural_square_tr q p) r r₂ (pathover_ap B f (apdo b p)) (pathover_ap B g (apdo b₂ p))) : pathover (λa, pathover B (b a) (q a) (b₂ a)) r p r₂ := begin induction p, esimp at s, apply pathover_idp_of_eq, apply eq_of_vdeg_squareover, exact s end definition squareover_change_path_left {p₀₁' : a₀₀ = a₀₂} (r : p₀₁' = p₀₁) {q₀₁ : b₀₀ =[p₀₁'] b₀₂} (t : squareover B (r ⬝ph s₁₁) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ (change_path r q₀₁) q₂₁ := by induction r; exact t definition squareover_change_path_right {p₂₁' : a₂₀ = a₂₂} (r : p₂₁' = p₂₁) {q₂₁ : b₂₀ =[p₂₁'] b₂₂} (t : squareover B (s₁₁ ⬝hp r⁻¹) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ (change_path r q₂₁) := by induction r; exact t definition squareover_change_path_right' {p₂₁' : a₂₀ = a₂₂} (r : p₂₁ = p₂₁') {q₂₁ : b₂₀ =[p₂₁'] b₂₂} (t : squareover B (s₁₁ ⬝hp r) q₁₀ q₁₂ q₀₁ q₂₁) : squareover B s₁₁ q₁₀ q₁₂ q₀₁ (change_path r⁻¹ q₂₁) := by induction r; exact t end eq
aa85769c8f7d21b48a7445795404ae8a62aab8ac
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/ctx.lean
4475e0e72229fd2ef43e15cdcfde51bf3440fb5b
[ "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
363
lean
import data.nat open nat inhabited constant N : Type.{1} constant a : N section s1 set_option pp.implicit true definition f (a b : nat) := a theorem nat_inhabited [instance] : inhabited nat := inhabited.mk zero definition to_N [coercion] (n : nat) : N := a infixl `$$`:65 := f end s1 theorem tst : inhabited nat constants n m : nat check n = a
ce137f6a1ed627ca5a2f5b19af3168a8973b93f7
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/algebraic_geometry/stalks.lean
3728a23be73d85a54f1a5e0bf0a4dcc89b0ad847
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
1,900
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebraic_geometry.presheafed_space import topology.Top.stalks /-! # Stalks for presheaved spaces This file lifts constructions of stalks and pushforwards of stalks to work with the category of presheafed spaces. -/ universes v u v' u' open category_theory open category_theory.limits category_theory.category category_theory.functor open algebraic_geometry open topological_space variables {C : Type u} [𝒞 : category.{v+1} C] [has_colimits.{v} C] include 𝒞 local attribute [tidy] tactic.op_induction' open Top.presheaf namespace algebraic_geometry.PresheafedSpace def stalk (X : PresheafedSpace.{v} C) (x : X) : C := X.𝒪.stalk x def stalk_map {X Y : PresheafedSpace.{v} C} (α : X ⟶ Y) (x : X) : Y.stalk (α x) ⟶ X.stalk x := (stalk_functor C (α x)).map (α.c) ≫ X.𝒪.stalk_pushforward C α x namespace stalk_map @[simp] lemma id (X : PresheafedSpace.{v} C) (x : X) : stalk_map (𝟙 X) x = 𝟙 (X.stalk x) := begin dsimp [stalk_map], simp only [stalk_pushforward.id], rw [←map_comp], convert (stalk_functor C x).map_id X.𝒪, tidy, end . @[simp] lemma comp {X Y Z : PresheafedSpace.{v} C} (α : X ⟶ Y) (β : Y ⟶ Z) (x : X) : stalk_map (α ≫ β) x = (stalk_map β (α x) : Z.stalk (β (α x)) ⟶ Y.stalk (α x)) ≫ (stalk_map α x : Y.stalk (α x) ⟶ X.stalk x) := begin dsimp [stalk_map, stalk_functor, stalk_pushforward], ext U, op_induction U, cases U, simp only [colim.ι_map_assoc, colimit.ι_pre_assoc, colimit.ι_pre, whisker_left.app, whisker_right.app, assoc, id_comp, map_id, map_comp], dsimp, simp only [map_id, assoc], -- FIXME Why doesn't simp do this: erw [id_comp, id_comp], end end stalk_map end algebraic_geometry.PresheafedSpace
268e74c7425253fe8a039dad3b8894f0ea2ec3f0
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/convex/cone/basic.lean
ca62b0911010ef52bf22850a1e32995f219d53b2
[ "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
37,191
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Frédéric Dupuis -/ import analysis.inner_product_space.projection /-! # Convex cones In a `𝕜`-module `E`, we define a convex cone as a set `s` such that `a • x + b • y ∈ s` whenever `x, y ∈ s` and `a, b > 0`. We prove that convex cones form a `complete_lattice`, and define their images (`convex_cone.map`) and preimages (`convex_cone.comap`) under linear maps. We define pointed, blunt, flat and salient cones, and prove the correspondence between convex cones and ordered modules. We define `convex.to_cone` to be the minimal cone that includes a given convex set. We define `set.inner_dual_cone` to be the cone consisting of all points `y` such that for all points `x` in a given set `0 ≤ ⟪ x, y ⟫`. ## Main statements We prove two extension theorems: * `riesz_extension`: [M. Riesz extension theorem](https://en.wikipedia.org/wiki/M._Riesz_extension_theorem) says that if `s` is a convex cone in a real vector space `E`, `p` is a submodule of `E` such that `p + s = E`, and `f` is a linear function `p → ℝ` which is nonnegative on `p ∩ s`, then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. * `exists_extension_of_le_sublinear`: Hahn-Banach theorem: if `N : E → ℝ` is a sublinear map, `f` is a linear map defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`, then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x` for all `x` We prove the following theorems: * `convex_cone.hyperplane_separation_of_nonempty_of_is_closed_of_nmem`: This variant of the [hyperplane separation theorem](https://en.wikipedia.org/wiki/Hyperplane_separation_theorem) states that given a nonempty, closed, convex cone `K` in a complete, real inner product space `H` and a point `b` disjoint from it, there is a vector `y` which separates `b` from `K` in the sense that for all points `x` in `K`, `0 ≤ ⟪x, y⟫_ℝ` and `⟪y, b⟫_ℝ < 0`. This is also a geometric interpretation of the [Farkas lemma](https://en.wikipedia.org/wiki/Farkas%27_lemma#Geometric_interpretation). * `convex_cone.inner_dual_cone_of_inner_dual_cone_eq_self`: The `inner_dual_cone` of the `inner_dual_cone` of a nonempty, closed, convex cone is itself. ## Implementation notes While `convex 𝕜` is a predicate on sets, `convex_cone 𝕜 E` is a bundled convex cone. ## References * https://en.wikipedia.org/wiki/Convex_cone * [Stephen P. Boyd and Lieven Vandenberghe, *Convex Optimization*][boydVandenberghe2004] * [Emo Welzl and Bernd Gärtner, *Cone Programming*][welzl_garter] -/ open set linear_map open_locale classical pointwise variables {𝕜 E F G : Type*} /-! ### Definition of `convex_cone` and basic properties -/ section definitions variables (𝕜 E) [ordered_semiring 𝕜] /-- A convex cone is a subset `s` of a `𝕜`-module such that `a • x + b • y ∈ s` whenever `a, b > 0` and `x, y ∈ s`. -/ structure convex_cone [add_comm_monoid E] [has_smul 𝕜 E] := (carrier : set E) (smul_mem' : ∀ ⦃c : 𝕜⦄, 0 < c → ∀ ⦃x : E⦄, x ∈ carrier → c • x ∈ carrier) (add_mem' : ∀ ⦃x⦄ (hx : x ∈ carrier) ⦃y⦄ (hy : y ∈ carrier), x + y ∈ carrier) end definitions variables {𝕜 E} namespace convex_cone section ordered_semiring variables [ordered_semiring 𝕜] [add_comm_monoid E] section has_smul variables [has_smul 𝕜 E] (S T : convex_cone 𝕜 E) instance : set_like (convex_cone 𝕜 E) E := { coe := carrier, coe_injective' := λ S T h, by cases S; cases T; congr' } @[simp] lemma coe_mk {s : set E} {h₁ h₂} : ↑(@mk 𝕜 _ _ _ _ s h₁ h₂) = s := rfl @[simp] lemma mem_mk {s : set E} {h₁ h₂ x} : x ∈ @mk 𝕜 _ _ _ _ s h₁ h₂ ↔ x ∈ s := iff.rfl /-- Two `convex_cone`s are equal if they have the same elements. -/ @[ext] theorem ext {S T : convex_cone 𝕜 E} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h lemma smul_mem {c : 𝕜} {x : E} (hc : 0 < c) (hx : x ∈ S) : c • x ∈ S := S.smul_mem' hc hx lemma add_mem ⦃x⦄ (hx : x ∈ S) ⦃y⦄ (hy : y ∈ S) : x + y ∈ S := S.add_mem' hx hy instance : add_mem_class (convex_cone 𝕜 E) E := { add_mem := λ c a b ha hb, add_mem c ha hb } instance : has_inf (convex_cone 𝕜 E) := ⟨λ S T, ⟨S ∩ T, λ c hc x hx, ⟨S.smul_mem hc hx.1, T.smul_mem hc hx.2⟩, λ x hx y hy, ⟨S.add_mem hx.1 hy.1, T.add_mem hx.2 hy.2⟩⟩⟩ @[simp] lemma coe_inf : ((S ⊓ T : convex_cone 𝕜 E) : set E) = ↑S ∩ ↑T := rfl lemma mem_inf {x} : x ∈ S ⊓ T ↔ x ∈ S ∧ x ∈ T := iff.rfl instance : has_Inf (convex_cone 𝕜 E) := ⟨λ S, ⟨⋂ s ∈ S, ↑s, λ c hc x hx, mem_bInter $ λ s hs, s.smul_mem hc $ mem_Inter₂.1 hx s hs, λ x hx y hy, mem_bInter $ λ s hs, s.add_mem (mem_Inter₂.1 hx s hs) (mem_Inter₂.1 hy s hs)⟩⟩ @[simp] lemma coe_Inf (S : set (convex_cone 𝕜 E)) : ↑(Inf S) = ⋂ s ∈ S, (s : set E) := rfl lemma mem_Inf {x : E} {S : set (convex_cone 𝕜 E)} : x ∈ Inf S ↔ ∀ s ∈ S, x ∈ s := mem_Inter₂ @[simp] lemma coe_infi {ι : Sort*} (f : ι → convex_cone 𝕜 E) : ↑(infi f) = ⋂ i, (f i : set E) := by simp [infi] lemma mem_infi {ι : Sort*} {x : E} {f : ι → convex_cone 𝕜 E} : x ∈ infi f ↔ ∀ i, x ∈ f i := mem_Inter₂.trans $ by simp variables (𝕜) instance : has_bot (convex_cone 𝕜 E) := ⟨⟨∅, λ c hc x, false.elim, λ x, false.elim⟩⟩ lemma mem_bot (x : E) : x ∈ (⊥ : convex_cone 𝕜 E) = false := rfl @[simp] lemma coe_bot : ↑(⊥ : convex_cone 𝕜 E) = (∅ : set E) := rfl instance : has_top (convex_cone 𝕜 E) := ⟨⟨univ, λ c hc x hx, mem_univ _, λ x hx y hy, mem_univ _⟩⟩ lemma mem_top (x : E) : x ∈ (⊤ : convex_cone 𝕜 E) := mem_univ x @[simp] lemma coe_top : ↑(⊤ : convex_cone 𝕜 E) = (univ : set E) := rfl instance : complete_lattice (convex_cone 𝕜 E) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x, false.elim, top := (⊤), le_top := λ S x hx, mem_top 𝕜 x, inf := (⊓), Inf := has_Inf.Inf, sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x}, Sup := λ s, Inf {T | ∀ S ∈ s, S ≤ T}, le_sup_left := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.1 hx, le_sup_right := λ a b, λ x hx, mem_Inf.2 $ λ s hs, hs.2 hx, sup_le := λ a b c ha hb x hx, mem_Inf.1 hx c ⟨ha, hb⟩, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, le_Sup := λ s p hs x hx, mem_Inf.2 $ λ t ht, ht p hs hx, Sup_le := λ s p hs x hx, mem_Inf.1 hx p hs, le_Inf := λ s a ha x hx, mem_Inf.2 $ λ t ht, ha t ht hx, Inf_le := λ s a ha x hx, mem_Inf.1 hx _ ha, .. set_like.partial_order } instance : inhabited (convex_cone 𝕜 E) := ⟨⊥⟩ end has_smul section module variables [module 𝕜 E] (S : convex_cone 𝕜 E) protected lemma convex : convex 𝕜 (S : set E) := convex_iff_forall_pos.2 $ λ x hx y hy a b ha hb _, S.add_mem (S.smul_mem ha hx) (S.smul_mem hb hy) end module end ordered_semiring section linear_ordered_field variables [linear_ordered_field 𝕜] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] [add_comm_monoid G] section mul_action variables [mul_action 𝕜 E] (S : convex_cone 𝕜 E) lemma smul_mem_iff {c : 𝕜} (hc : 0 < c) {x : E} : c • x ∈ S ↔ x ∈ S := ⟨λ h, inv_smul_smul₀ hc.ne' x ▸ S.smul_mem (inv_pos.2 hc) h, S.smul_mem hc⟩ end mul_action section module variables [module 𝕜 E] [module 𝕜 F] [module 𝕜 G] /-- The image of a convex cone under a `𝕜`-linear map is a convex cone. -/ def map (f : E →ₗ[𝕜] F) (S : convex_cone 𝕜 E) : convex_cone 𝕜 F := { carrier := f '' S, smul_mem' := λ c hc y ⟨x, hx, hy⟩, hy ▸ f.map_smul c x ▸ mem_image_of_mem f (S.smul_mem hc hx), add_mem' := λ y₁ ⟨x₁, hx₁, hy₁⟩ y₂ ⟨x₂, hx₂, hy₂⟩, hy₁ ▸ hy₂ ▸ f.map_add x₁ x₂ ▸ mem_image_of_mem f (S.add_mem hx₁ hx₂) } @[simp] lemma mem_map {f : E →ₗ[𝕜] F} {S : convex_cone 𝕜 E} {y : F} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex lemma map_map (g : F →ₗ[𝕜] G) (f : E →ₗ[𝕜] F) (S : convex_cone 𝕜 E) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ image_image g f S @[simp] lemma map_id (S : convex_cone 𝕜 E) : S.map linear_map.id = S := set_like.coe_injective $ image_id _ /-- The preimage of a convex cone under a `𝕜`-linear map is a convex cone. -/ def comap (f : E →ₗ[𝕜] F) (S : convex_cone 𝕜 F) : convex_cone 𝕜 E := { carrier := f ⁻¹' S, smul_mem' := λ c hc x hx, by { rw [mem_preimage, f.map_smul c], exact S.smul_mem hc hx }, add_mem' := λ x hx y hy, by { rw [mem_preimage, f.map_add], exact S.add_mem hx hy } } @[simp] lemma coe_comap (f : E →ₗ[𝕜] F) (S : convex_cone 𝕜 F) : (S.comap f : set E) = f ⁻¹' S := rfl @[simp] lemma comap_id (S : convex_cone 𝕜 E) : S.comap linear_map.id = S := set_like.coe_injective preimage_id lemma comap_comap (g : F →ₗ[𝕜] G) (f : E →ₗ[𝕜] F) (S : convex_cone 𝕜 G) : (S.comap g).comap f = S.comap (g.comp f) := set_like.coe_injective $ preimage_comp.symm @[simp] lemma mem_comap {f : E →ₗ[𝕜] F} {S : convex_cone 𝕜 F} {x : E} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl end module end add_comm_monoid section ordered_add_comm_group variables [ordered_add_comm_group E] [module 𝕜 E] /-- Constructs an ordered module given an `ordered_add_comm_group`, a cone, and a proof that the order relation is the one defined by the cone. -/ lemma to_ordered_smul (S : convex_cone 𝕜 E) (h : ∀ x y : E, x ≤ y ↔ y - x ∈ S) : ordered_smul 𝕜 E := ordered_smul.mk' begin intros x y z xy hz, rw [h (z • x) (z • y), ←smul_sub z y x], exact smul_mem S hz ((h x y).mp xy.le), end end ordered_add_comm_group end linear_ordered_field /-! ### Convex cones with extra properties -/ section ordered_semiring variables [ordered_semiring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [has_smul 𝕜 E] (S : convex_cone 𝕜 E) /-- A convex cone is pointed if it includes `0`. -/ def pointed (S : convex_cone 𝕜 E) : Prop := (0 : E) ∈ S /-- A convex cone is blunt if it doesn't include `0`. -/ def blunt (S : convex_cone 𝕜 E) : Prop := (0 : E) ∉ S lemma pointed_iff_not_blunt (S : convex_cone 𝕜 E) : S.pointed ↔ ¬S.blunt := ⟨λ h₁ h₂, h₂ h₁, not_not.mp⟩ lemma blunt_iff_not_pointed (S : convex_cone 𝕜 E) : S.blunt ↔ ¬S.pointed := by rw [pointed_iff_not_blunt, not_not] lemma pointed.mono {S T : convex_cone 𝕜 E} (h : S ≤ T) : S.pointed → T.pointed := @h _ lemma blunt.anti {S T : convex_cone 𝕜 E} (h : T ≤ S) : S.blunt → T.blunt := (∘ @@h) end add_comm_monoid section add_comm_group variables [add_comm_group E] [has_smul 𝕜 E] (S : convex_cone 𝕜 E) /-- A convex cone is flat if it contains some nonzero vector `x` and its opposite `-x`. -/ def flat : Prop := ∃ x ∈ S, x ≠ (0 : E) ∧ -x ∈ S /-- A convex cone is salient if it doesn't include `x` and `-x` for any nonzero `x`. -/ def salient : Prop := ∀ x ∈ S, x ≠ (0 : E) → -x ∉ S lemma salient_iff_not_flat (S : convex_cone 𝕜 E) : S.salient ↔ ¬S.flat := begin split, { rintros h₁ ⟨x, xs, H₁, H₂⟩, exact h₁ x xs H₁ H₂ }, { intro h, unfold flat at h, push_neg at h, exact h } end lemma flat.mono {S T : convex_cone 𝕜 E} (h : S ≤ T) : S.flat → T.flat | ⟨x, hxS, hx, hnxS⟩ := ⟨x, h hxS, hx, h hnxS⟩ lemma salient.anti {S T : convex_cone 𝕜 E} (h : T ≤ S) : S.salient → T.salient := λ hS x hxT hx hnT, hS x (h hxT) hx (h hnT) /-- A flat cone is always pointed (contains `0`). -/ lemma flat.pointed {S : convex_cone 𝕜 E} (hS : S.flat) : S.pointed := begin obtain ⟨x, hx, _, hxneg⟩ := hS, rw [pointed, ←add_neg_self x], exact add_mem S hx hxneg, end /-- A blunt cone (one not containing `0`) is always salient. -/ lemma blunt.salient {S : convex_cone 𝕜 E} : S.blunt → S.salient := begin rw [salient_iff_not_flat, blunt_iff_not_pointed], exact mt flat.pointed, end /-- A pointed convex cone defines a preorder. -/ def to_preorder (h₁ : S.pointed) : preorder E := { le := λ x y, y - x ∈ S, le_refl := λ x, by change x - x ∈ S; rw [sub_self x]; exact h₁, le_trans := λ x y z xy zy, by simpa using add_mem S zy xy } /-- A pointed and salient cone defines a partial order. -/ def to_partial_order (h₁ : S.pointed) (h₂ : S.salient) : partial_order E := { le_antisymm := begin intros a b ab ba, by_contradiction h, have h' : b - a ≠ 0 := λ h'', h (eq_of_sub_eq_zero h'').symm, have H := h₂ (b-a) ab h', rw neg_sub b a at H, exact H ba, end, ..to_preorder S h₁ } /-- A pointed and salient cone defines an `ordered_add_comm_group`. -/ def to_ordered_add_comm_group (h₁ : S.pointed) (h₂ : S.salient) : ordered_add_comm_group E := { add_le_add_left := begin intros a b hab c, change c + b - (c + a) ∈ S, rw add_sub_add_left_eq_sub, exact hab, end, ..to_partial_order S h₁ h₂, ..show add_comm_group E, by apply_instance } end add_comm_group section module variables [add_comm_monoid E] [module 𝕜 E] instance : has_zero (convex_cone 𝕜 E) := ⟨⟨0, λ _ _, by simp, λ _, by simp⟩⟩ @[simp] lemma mem_zero (x : E) : x ∈ (0 : convex_cone 𝕜 E) ↔ x = 0 := iff.rfl @[simp] lemma coe_zero : ((0 : convex_cone 𝕜 E) : set E) = 0 := rfl lemma pointed_zero : (0 : convex_cone 𝕜 E).pointed := by rw [pointed, mem_zero] instance : has_add (convex_cone 𝕜 E) := ⟨ λ K₁ K₂, { carrier := {z | ∃ (x y : E), x ∈ K₁ ∧ y ∈ K₂ ∧ x + y = z}, smul_mem' := begin rintro c hc _ ⟨x, y, hx, hy, rfl⟩, rw smul_add, use [c • x, c • y, K₁.smul_mem hc hx, K₂.smul_mem hc hy], end, add_mem' := begin rintro _ ⟨x₁, x₂, hx₁, hx₂, rfl⟩ y ⟨y₁, y₂, hy₁, hy₂, rfl⟩, use [x₁ + y₁, x₂ + y₂, K₁.add_mem hx₁ hy₁, K₂.add_mem hx₂ hy₂], abel, end } ⟩ @[simp] lemma mem_add {K₁ K₂ : convex_cone 𝕜 E} {a : E} : a ∈ K₁ + K₂ ↔ ∃ (x y : E), x ∈ K₁ ∧ y ∈ K₂ ∧ x + y = a := iff.rfl instance : add_zero_class (convex_cone 𝕜 E) := ⟨0, has_add.add, λ _, by {ext, simp}, λ _, by {ext, simp}⟩ instance : add_comm_semigroup (convex_cone 𝕜 E) := { add := has_add.add, add_assoc := λ _ _ _, set_like.coe_injective $ set.add_comm_semigroup.add_assoc _ _ _, add_comm := λ _ _, set_like.coe_injective $ set.add_comm_semigroup.add_comm _ _ } end module end ordered_semiring end convex_cone namespace submodule /-! ### Submodules are cones -/ section ordered_semiring variables [ordered_semiring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [module 𝕜 E] /-- Every submodule is trivially a convex cone. -/ def to_convex_cone (S : submodule 𝕜 E) : convex_cone 𝕜 E := { carrier := S, smul_mem' := λ c hc x hx, S.smul_mem c hx, add_mem' := λ x hx y hy, S.add_mem hx hy } @[simp] lemma coe_to_convex_cone (S : submodule 𝕜 E) : ↑S.to_convex_cone = (S : set E) := rfl @[simp] lemma mem_to_convex_cone {x : E} {S : submodule 𝕜 E} : x ∈ S.to_convex_cone ↔ x ∈ S := iff.rfl @[simp] lemma to_convex_cone_le_iff {S T : submodule 𝕜 E} : S.to_convex_cone ≤ T.to_convex_cone ↔ S ≤ T := iff.rfl @[simp] lemma to_convex_cone_bot : (⊥ : submodule 𝕜 E).to_convex_cone = 0 := rfl @[simp] lemma to_convex_cone_top : (⊤ : submodule 𝕜 E).to_convex_cone = ⊤ := rfl @[simp] lemma to_convex_cone_inf (S T : submodule 𝕜 E) : (S ⊓ T).to_convex_cone = S.to_convex_cone ⊓ T.to_convex_cone := rfl @[simp] lemma pointed_to_convex_cone (S : submodule 𝕜 E) : S.to_convex_cone.pointed := S.zero_mem end add_comm_monoid end ordered_semiring end submodule namespace convex_cone /-! ### Positive cone of an ordered module -/ section positive_cone variables (𝕜 E) [ordered_semiring 𝕜] [ordered_add_comm_group E] [module 𝕜 E] [ordered_smul 𝕜 E] /-- The positive cone is the convex cone formed by the set of nonnegative elements in an ordered module. -/ def positive : convex_cone 𝕜 E := { carrier := set.Ici 0, smul_mem' := λ c hc x (hx : _ ≤ _), smul_nonneg hc.le hx, add_mem' := λ x (hx : _ ≤ _) y (hy : _ ≤ _), add_nonneg hx hy } @[simp] lemma mem_positive {x : E} : x ∈ positive 𝕜 E ↔ 0 ≤ x := iff.rfl @[simp] lemma coe_positive : ↑(positive 𝕜 E) = set.Ici (0 : E) := rfl /-- The positive cone of an ordered module is always salient. -/ lemma salient_positive : salient (positive 𝕜 E) := λ x xs hx hx', lt_irrefl (0 : E) (calc 0 < x : lt_of_le_of_ne xs hx.symm ... ≤ x + (-x) : le_add_of_nonneg_right hx' ... = 0 : add_neg_self x) /-- The positive cone of an ordered module is always pointed. -/ lemma pointed_positive : pointed (positive 𝕜 E) := le_refl 0 /-- The cone of strictly positive elements. Note that this naming diverges from the mathlib convention of `pos` and `nonneg` due to "positive cone" (`convex_cone.positive`) being established terminology for the non-negative elements. -/ def strictly_positive : convex_cone 𝕜 E := { carrier := set.Ioi 0, smul_mem' := λ c hc x (hx : _ < _), smul_pos hc hx, add_mem' := λ x hx y hy, add_pos hx hy } @[simp] lemma mem_strictly_positive {x : E} : x ∈ strictly_positive 𝕜 E ↔ 0 < x := iff.rfl @[simp] lemma coe_strictly_positive : ↑(strictly_positive 𝕜 E) = set.Ioi (0 : E) := rfl lemma positive_le_strictly_positive : strictly_positive 𝕜 E ≤ positive 𝕜 E := λ x, le_of_lt /-- The strictly positive cone of an ordered module is always salient. -/ lemma salient_strictly_positive : salient (strictly_positive 𝕜 E) := (salient_positive 𝕜 E).anti $ positive_le_strictly_positive 𝕜 E /-- The strictly positive cone of an ordered module is always blunt. -/ lemma blunt_strictly_positive : blunt (strictly_positive 𝕜 E) := lt_irrefl 0 end positive_cone end convex_cone /-! ### Cone over a convex set -/ section cone_from_convex variables [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] namespace convex /-- The set of vectors proportional to those in a convex set forms a convex cone. -/ def to_cone (s : set E) (hs : convex 𝕜 s) : convex_cone 𝕜 E := begin apply convex_cone.mk (⋃ (c : 𝕜) (H : 0 < c), c • s); simp only [mem_Union, mem_smul_set], { rintros c c_pos _ ⟨c', c'_pos, x, hx, rfl⟩, exact ⟨c * c', mul_pos c_pos c'_pos, x, hx, (smul_smul _ _ _).symm⟩ }, { rintros _ ⟨cx, cx_pos, x, hx, rfl⟩ _ ⟨cy, cy_pos, y, hy, rfl⟩, have : 0 < cx + cy, from add_pos cx_pos cy_pos, refine ⟨_, this, _, convex_iff_div.1 hs hx hy cx_pos.le cy_pos.le this, _⟩, simp only [smul_add, smul_smul, mul_div_assoc', mul_div_cancel_left _ this.ne'] } end variables {s : set E} (hs : convex 𝕜 s) {x : E} lemma mem_to_cone : x ∈ hs.to_cone s ↔ ∃ (c : 𝕜), 0 < c ∧ ∃ y ∈ s, c • y = x := by simp only [to_cone, convex_cone.mem_mk, mem_Union, mem_smul_set, eq_comm, exists_prop] lemma mem_to_cone' : x ∈ hs.to_cone s ↔ ∃ (c : 𝕜), 0 < c ∧ c • x ∈ s := begin refine hs.mem_to_cone.trans ⟨_, _⟩, { rintros ⟨c, hc, y, hy, rfl⟩, exact ⟨c⁻¹, inv_pos.2 hc, by rwa [smul_smul, inv_mul_cancel hc.ne', one_smul]⟩ }, { rintros ⟨c, hc, hcx⟩, exact ⟨c⁻¹, inv_pos.2 hc, _, hcx, by rw [smul_smul, inv_mul_cancel hc.ne', one_smul]⟩ } end lemma subset_to_cone : s ⊆ hs.to_cone s := λ x hx, hs.mem_to_cone'.2 ⟨1, zero_lt_one, by rwa one_smul⟩ /-- `hs.to_cone s` is the least cone that includes `s`. -/ lemma to_cone_is_least : is_least { t : convex_cone 𝕜 E | s ⊆ t } (hs.to_cone s) := begin refine ⟨hs.subset_to_cone, λ t ht x hx, _⟩, rcases hs.mem_to_cone.1 hx with ⟨c, hc, y, hy, rfl⟩, exact t.smul_mem hc (ht hy) end lemma to_cone_eq_Inf : hs.to_cone s = Inf { t : convex_cone 𝕜 E | s ⊆ t } := hs.to_cone_is_least.is_glb.Inf_eq.symm end convex lemma convex_hull_to_cone_is_least (s : set E) : is_least {t : convex_cone 𝕜 E | s ⊆ t} ((convex_convex_hull 𝕜 s).to_cone _) := begin convert (convex_convex_hull 𝕜 s).to_cone_is_least, ext t, exact ⟨λ h, convex_hull_min h t.convex, (subset_convex_hull 𝕜 s).trans⟩, end lemma convex_hull_to_cone_eq_Inf (s : set E) : (convex_convex_hull 𝕜 s).to_cone _ = Inf {t : convex_cone 𝕜 E | s ⊆ t} := eq.symm $ is_glb.Inf_eq $ is_least.is_glb $ convex_hull_to_cone_is_least s end cone_from_convex /-! ### M. Riesz extension theorem Given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. We prove this theorem using Zorn's lemma. `riesz_extension.step` is the main part of the proof. It says that if the domain `p` of `f` is not the whole space, then `f` can be extended to a larger subspace `p ⊔ span ℝ {y}` without breaking the non-negativity condition. In `riesz_extension.exists_top` we use Zorn's lemma to prove that we can extend `f` to a linear map `g` on `⊤ : submodule E`. Mathematically this is the same as a linear map on `E` but in Lean `⊤ : submodule E` is isomorphic but is not equal to `E`. In `riesz_extension` we use this isomorphism to prove the theorem. -/ variables [add_comm_group E] [module ℝ E] namespace riesz_extension open submodule variables (s : convex_cone ℝ E) (f : E →ₗ.[ℝ] ℝ) /-- Induction step in M. Riesz extension theorem. Given a convex cone `s` in a vector space `E`, a partially defined linear map `f : f.domain → ℝ`, assume that `f` is nonnegative on `f.domain ∩ p` and `p + s = E`. If `f` is not defined on the whole `E`, then we can extend it to a larger submodule without breaking the non-negativity condition. -/ lemma step (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x) (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) (hdom : f.domain ≠ ⊤) : ∃ g, f < g ∧ ∀ x : g.domain, (x : E) ∈ s → 0 ≤ g x := begin obtain ⟨y, -, hy⟩ : ∃ (y : E) (h : y ∈ ⊤), y ∉ f.domain, { exact @set_like.exists_of_lt (submodule ℝ E) _ _ _ _ (lt_top_iff_ne_top.2 hdom) }, obtain ⟨c, le_c, c_le⟩ : ∃ c, (∀ x : f.domain, -(x:E) - y ∈ s → f x ≤ c) ∧ (∀ x : f.domain, (x:E) + y ∈ s → c ≤ f x), { set Sp := f '' {x : f.domain | (x:E) + y ∈ s}, set Sn := f '' {x : f.domain | -(x:E) - y ∈ s}, suffices : (upper_bounds Sn ∩ lower_bounds Sp).nonempty, by simpa only [set.nonempty, upper_bounds, lower_bounds, ball_image_iff] using this, refine exists_between_of_forall_le (nonempty.image f _) (nonempty.image f (dense y)) _, { rcases (dense (-y)) with ⟨x, hx⟩, rw [← neg_neg x, add_subgroup_class.coe_neg, ← sub_eq_add_neg] at hx, exact ⟨_, hx⟩ }, rintros a ⟨xn, hxn, rfl⟩ b ⟨xp, hxp, rfl⟩, have := s.add_mem hxp hxn, rw [add_assoc, add_sub_cancel'_right, ← sub_eq_add_neg, ← add_subgroup_class.coe_sub] at this, replace := nonneg _ this, rwa [f.map_sub, sub_nonneg] at this }, have hy' : y ≠ 0, from λ hy₀, hy (hy₀.symm ▸ zero_mem _), refine ⟨f.sup_span_singleton y (-c) hy, _, _⟩, { refine lt_iff_le_not_le.2 ⟨f.left_le_sup _ _, λ H, _⟩, replace H := linear_pmap.domain_mono.monotone H, rw [linear_pmap.domain_sup_span_singleton, sup_le_iff, span_le, singleton_subset_iff] at H, exact hy H.2 }, { rintros ⟨z, hz⟩ hzs, rcases mem_sup.1 hz with ⟨x, hx, y', hy', rfl⟩, rcases mem_span_singleton.1 hy' with ⟨r, rfl⟩, simp only [subtype.coe_mk] at hzs, erw [linear_pmap.sup_span_singleton_apply_mk _ _ _ _ _ hx, smul_neg, ← sub_eq_add_neg, sub_nonneg], rcases lt_trichotomy r 0 with hr|hr|hr, { have : -(r⁻¹ • x) - y ∈ s, by rwa [← s.smul_mem_iff (neg_pos.2 hr), smul_sub, smul_neg, neg_smul, neg_neg, smul_smul, mul_inv_cancel hr.ne, one_smul, sub_eq_add_neg, neg_smul, neg_neg], replace := le_c (r⁻¹ • ⟨x, hx⟩) this, rwa [← mul_le_mul_left (neg_pos.2 hr), neg_mul, neg_mul, neg_le_neg_iff, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel hr.ne, one_mul] at this }, { subst r, simp only [zero_smul, add_zero] at hzs ⊢, apply nonneg, exact hzs }, { have : r⁻¹ • x + y ∈ s, by rwa [← s.smul_mem_iff hr, smul_add, smul_smul, mul_inv_cancel hr.ne', one_smul], replace := c_le (r⁻¹ • ⟨x, hx⟩) this, rwa [← mul_le_mul_left hr, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel hr.ne', one_mul] at this } } end theorem exists_top (p : E →ₗ.[ℝ] ℝ) (hp_nonneg : ∀ x : p.domain, (x : E) ∈ s → 0 ≤ p x) (hp_dense : ∀ y, ∃ x : p.domain, (x : E) + y ∈ s) : ∃ q ≥ p, q.domain = ⊤ ∧ ∀ x : q.domain, (x : E) ∈ s → 0 ≤ q x := begin replace hp_nonneg : p ∈ { p | _ }, by { rw mem_set_of_eq, exact hp_nonneg }, obtain ⟨q, hqs, hpq, hq⟩ := zorn_nonempty_partial_order₀ _ _ _ hp_nonneg, { refine ⟨q, hpq, _, hqs⟩, contrapose! hq, rcases step s q hqs _ hq with ⟨r, hqr, hr⟩, { exact ⟨r, hr, hqr.le, hqr.ne'⟩ }, { exact λ y, let ⟨x, hx⟩ := hp_dense y in ⟨of_le hpq.left x, hx⟩ } }, { intros c hcs c_chain y hy, clear hp_nonneg hp_dense p, have cne : c.nonempty := ⟨y, hy⟩, refine ⟨linear_pmap.Sup c c_chain.directed_on, _, λ _, linear_pmap.le_Sup c_chain.directed_on⟩, rintros ⟨x, hx⟩ hxs, have hdir : directed_on (≤) (linear_pmap.domain '' c), from directed_on_image.2 (c_chain.directed_on.mono linear_pmap.domain_mono.monotone), rcases (mem_Sup_of_directed (cne.image _) hdir).1 hx with ⟨_, ⟨f, hfc, rfl⟩, hfx⟩, have : f ≤ linear_pmap.Sup c c_chain.directed_on, from linear_pmap.le_Sup _ hfc, convert ← hcs hfc ⟨x, hfx⟩ hxs, apply this.2, refl } end end riesz_extension /-- M. **Riesz extension theorem**: given a convex cone `s` in a vector space `E`, a submodule `p`, and a linear `f : p → ℝ`, assume that `f` is nonnegative on `p ∩ s` and `p + s = E`. Then there exists a globally defined linear function `g : E → ℝ` that agrees with `f` on `p`, and is nonnegative on `s`. -/ theorem riesz_extension (s : convex_cone ℝ E) (f : E →ₗ.[ℝ] ℝ) (nonneg : ∀ x : f.domain, (x : E) ∈ s → 0 ≤ f x) (dense : ∀ y, ∃ x : f.domain, (x : E) + y ∈ s) : ∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x ∈ s, 0 ≤ g x) := begin rcases riesz_extension.exists_top s f nonneg dense with ⟨⟨g_dom, g⟩, ⟨hpg, hfg⟩, htop, hgs⟩, clear hpg, refine ⟨g ∘ₗ ↑(linear_equiv.of_top _ htop).symm, _, _⟩; simp only [comp_apply, linear_equiv.coe_coe, linear_equiv.of_top_symm_apply], { exact λ x, (hfg (submodule.coe_mk _ _).symm).symm }, { exact λ x hx, hgs ⟨x, _⟩ hx } end /-- **Hahn-Banach theorem**: if `N : E → ℝ` is a sublinear map, `f` is a linear map defined on a subspace of `E`, and `f x ≤ N x` for all `x` in the domain of `f`, then `f` can be extended to the whole space to a linear map `g` such that `g x ≤ N x` for all `x`. -/ theorem exists_extension_of_le_sublinear (f : E →ₗ.[ℝ] ℝ) (N : E → ℝ) (N_hom : ∀ (c : ℝ), 0 < c → ∀ x, N (c • x) = c * N x) (N_add : ∀ x y, N (x + y) ≤ N x + N y) (hf : ∀ x : f.domain, f x ≤ N x) : ∃ g : E →ₗ[ℝ] ℝ, (∀ x : f.domain, g x = f x) ∧ (∀ x, g x ≤ N x) := begin let s : convex_cone ℝ (E × ℝ) := { carrier := {p : E × ℝ | N p.1 ≤ p.2 }, smul_mem' := λ c hc p hp, calc N (c • p.1) = c * N p.1 : N_hom c hc p.1 ... ≤ c * p.2 : mul_le_mul_of_nonneg_left hp hc.le, add_mem' := λ x hx y hy, (N_add _ _).trans (add_le_add hx hy) }, obtain ⟨g, g_eq, g_nonneg⟩ := riesz_extension s ((-f).coprod (linear_map.id.to_pmap ⊤)) _ _; try { simp only [linear_pmap.coprod_apply, to_pmap_apply, id_apply, linear_pmap.neg_apply, ← sub_eq_neg_add, sub_nonneg, subtype.coe_mk] at * }, replace g_eq : ∀ (x : f.domain) (y : ℝ), g (x, y) = y - f x, { intros x y, simpa only [subtype.coe_mk, subtype.coe_eta] using g_eq ⟨(x, y), ⟨x.2, trivial⟩⟩ }, { refine ⟨-g.comp (inl ℝ E ℝ), _, _⟩; simp only [neg_apply, inl_apply, comp_apply], { intro x, simp [g_eq x 0] }, { intro x, have A : (x, N x) = (x, 0) + (0, N x), by simp, have B := g_nonneg ⟨x, N x⟩ (le_refl (N x)), rw [A, map_add, ← neg_le_iff_add_nonneg'] at B, have C := g_eq 0 (N x), simp only [submodule.coe_zero, f.map_zero, sub_zero] at C, rwa ← C } }, { exact λ x hx, le_trans (hf _) hx }, { rintros ⟨x, y⟩, refine ⟨⟨(0, N x - y), ⟨f.domain.zero_mem, trivial⟩⟩, _⟩, simp only [convex_cone.mem_mk, mem_set_of_eq, subtype.coe_mk, prod.fst_add, prod.snd_add, zero_add, sub_add_cancel] } end /-! ### The dual cone -/ section dual variables {H : Type*} [normed_add_comm_group H] [inner_product_space ℝ H] (s t : set H) open_locale real_inner_product_space /-- The dual cone is the cone consisting of all points `y` such that for all points `x` in a given set `0 ≤ ⟪ x, y ⟫`. -/ def set.inner_dual_cone (s : set H) : convex_cone ℝ H := { carrier := { y | ∀ x ∈ s, 0 ≤ ⟪ x, y ⟫ }, smul_mem' := λ c hc y hy x hx, begin rw real_inner_smul_right, exact mul_nonneg hc.le (hy x hx) end, add_mem' := λ u hu v hv x hx, begin rw inner_add_right, exact add_nonneg (hu x hx) (hv x hx) end } @[simp] lemma mem_inner_dual_cone (y : H) (s : set H) : y ∈ s.inner_dual_cone ↔ ∀ x ∈ s, 0 ≤ ⟪ x, y ⟫ := iff.rfl @[simp] lemma inner_dual_cone_empty : (∅ : set H).inner_dual_cone = ⊤ := eq_top_iff.mpr $ λ x hy y, false.elim /-- Dual cone of the convex cone {0} is the total space. -/ @[simp] lemma inner_dual_cone_zero : (0 : set H).inner_dual_cone = ⊤ := eq_top_iff.mpr $ λ x hy y (hy : y = 0), hy.symm ▸ (inner_zero_left _).ge /-- Dual cone of the total space is the convex cone {0}. -/ @[simp] lemma inner_dual_cone_univ : (univ : set H).inner_dual_cone = 0 := begin suffices : ∀ x : H, x ∈ (univ : set H).inner_dual_cone → x = 0, { apply set_like.coe_injective, exact eq_singleton_iff_unique_mem.mpr ⟨λ x hx, (inner_zero_right _).ge, this⟩ }, exact λ x hx, by simpa [←real_inner_self_nonpos] using hx (-x) (mem_univ _), end lemma inner_dual_cone_le_inner_dual_cone (h : t ⊆ s) : s.inner_dual_cone ≤ t.inner_dual_cone := λ y hy x hx, hy x (h hx) lemma pointed_inner_dual_cone : s.inner_dual_cone.pointed := λ x hx, by rw inner_zero_right /-- The inner dual cone of a singleton is given by the preimage of the positive cone under the linear map `λ y, ⟪x, y⟫`. -/ lemma inner_dual_cone_singleton (x : H) : ({x} : set H).inner_dual_cone = (convex_cone.positive ℝ ℝ).comap (innerₛₗ ℝ x) := convex_cone.ext $ λ i, forall_eq lemma inner_dual_cone_union (s t : set H) : (s ∪ t).inner_dual_cone = s.inner_dual_cone ⊓ t.inner_dual_cone := le_antisymm (le_inf (λ x hx y hy, hx _ $ or.inl hy) (λ x hx y hy, hx _ $ or.inr hy)) (λ x hx y, or.rec (hx.1 _) (hx.2 _)) lemma inner_dual_cone_insert (x : H) (s : set H) : (insert x s).inner_dual_cone = set.inner_dual_cone {x} ⊓ s.inner_dual_cone := by rw [insert_eq, inner_dual_cone_union] lemma inner_dual_cone_Union {ι : Sort*} (f : ι → set H) : (⋃ i, f i).inner_dual_cone = ⨅ i, (f i).inner_dual_cone := begin refine le_antisymm (le_infi $ λ i x hx y hy, hx _ $ mem_Union_of_mem _ hy) _, intros x hx y hy, rw [convex_cone.mem_infi] at hx, obtain ⟨j, hj⟩ := mem_Union.mp hy, exact hx _ _ hj, end lemma inner_dual_cone_sUnion (S : set (set H)) : (⋃₀ S).inner_dual_cone = Inf (set.inner_dual_cone '' S) := by simp_rw [Inf_image, sUnion_eq_bUnion, inner_dual_cone_Union] /-- The dual cone of `s` equals the intersection of dual cones of the points in `s`. -/ lemma inner_dual_cone_eq_Inter_inner_dual_cone_singleton : (s.inner_dual_cone : set H) = ⋂ i : s, (({i} : set H).inner_dual_cone : set H) := by rw [←convex_cone.coe_infi, ←inner_dual_cone_Union, Union_of_singleton_coe] lemma is_closed_inner_dual_cone : is_closed (s.inner_dual_cone : set H) := begin -- reduce the problem to showing that dual cone of a singleton `{x}` is closed rw inner_dual_cone_eq_Inter_inner_dual_cone_singleton, apply is_closed_Inter, intros x, -- the dual cone of a singleton `{x}` is the preimage of `[0, ∞)` under `inner x` have h : ↑({x} : set H).inner_dual_cone = (inner x : H → ℝ) ⁻¹' set.Ici 0, { rw [inner_dual_cone_singleton, convex_cone.coe_comap, convex_cone.coe_positive, innerₛₗ_apply_coe] }, -- the preimage is closed as `inner x` is continuous and `[0, ∞)` is closed rw h, exact is_closed_Ici.preimage (by continuity), end lemma convex_cone.pointed_of_nonempty_of_is_closed (K : convex_cone ℝ H) (ne : (K : set H).nonempty) (hc : is_closed (K : set H)) : K.pointed := begin obtain ⟨x, hx⟩ := ne, let f : ℝ → H := (• x), -- f (0, ∞) is a subset of K have fI : f '' set.Ioi 0 ⊆ (K : set H), { rintro _ ⟨_, h, rfl⟩, exact K.smul_mem (set.mem_Ioi.1 h) hx }, -- closure of f (0, ∞) is a subset of K have clf : closure (f '' set.Ioi 0) ⊆ (K : set H) := hc.closure_subset_iff.2 fI, -- f is continuous at 0 from the right have fc : continuous_within_at f (set.Ioi (0 : ℝ)) 0 := (continuous_id.smul continuous_const).continuous_within_at, -- 0 belongs to the closure of the f (0, ∞) have mem₀ := fc.mem_closure_image (by rw [closure_Ioi (0 : ℝ), mem_Ici]), -- as 0 ∈ closure f (0, ∞) and closure f (0, ∞) ⊆ K, 0 ∈ K. have f₀ : f 0 = 0 := zero_smul ℝ x, simpa only [f₀, convex_cone.pointed, ← set_like.mem_coe] using mem_of_subset_of_mem clf mem₀, end section complete_space variables [complete_space H] /-- This is a stronger version of the Hahn-Banach separation theorem for closed convex cones. This is also the geometric interpretation of Farkas' lemma. -/ theorem convex_cone.hyperplane_separation_of_nonempty_of_is_closed_of_nmem (K : convex_cone ℝ H) (ne : (K : set H).nonempty) (hc : is_closed (K : set H)) {b : H} (disj : b ∉ K) : ∃ (y : H), (∀ x : H, x ∈ K → 0 ≤ ⟪x, y⟫_ℝ) ∧ ⟪y, b⟫_ℝ < 0 := begin -- let `z` be the point in `K` closest to `b` obtain ⟨z, hzK, infi⟩ := exists_norm_eq_infi_of_complete_convex ne hc.is_complete K.convex b, -- for any `w` in `K`, we have `⟪b - z, w - z⟫_ℝ ≤ 0` have hinner := (norm_eq_infi_iff_real_inner_le_zero K.convex hzK).1 infi, -- set `y := z - b` use z - b, split, { -- the rest of the proof is a straightforward calculation rintros x hxK, specialize hinner _ (K.add_mem hxK hzK), rwa [add_sub_cancel, real_inner_comm, ← neg_nonneg, neg_eq_neg_one_mul, ← real_inner_smul_right, neg_smul, one_smul, neg_sub] at hinner }, { -- as `K` is closed and non-empty, it is pointed have hinner₀ := hinner 0 (K.pointed_of_nonempty_of_is_closed ne hc), -- the rest of the proof is a straightforward calculation rw [zero_sub, inner_neg_right, right.neg_nonpos_iff] at hinner₀, have hbz : b - z ≠ 0 := by { rw sub_ne_zero, contrapose! hzK, rwa ← hzK }, rw [← neg_zero, lt_neg, ← neg_one_mul, ← real_inner_smul_left, smul_sub, neg_smul, one_smul, neg_smul, neg_sub_neg, one_smul], calc 0 < ⟪b - z, b - z⟫_ℝ : lt_of_not_le ((iff.not real_inner_self_nonpos).2 hbz) ... = ⟪b - z, b - z⟫_ℝ + 0 : (add_zero _).symm ... ≤ ⟪b - z, b - z⟫_ℝ + ⟪b - z, z⟫_ℝ : add_le_add rfl.ge hinner₀ ... = ⟪b - z, b - z + z⟫_ℝ : (inner_add_right _ _ _).symm ... = ⟪b - z, b⟫_ℝ : by rw sub_add_cancel }, end /-- The inner dual of inner dual of a non-empty, closed convex cone is itself. -/ theorem convex_cone.inner_dual_cone_of_inner_dual_cone_eq_self (K : convex_cone ℝ H) (ne : (K : set H).nonempty) (hc : is_closed (K : set H)) : ((K : set H).inner_dual_cone : set H).inner_dual_cone = K := begin ext x, split, { rw [mem_inner_dual_cone, ← set_like.mem_coe], contrapose!, exact K.hyperplane_separation_of_nonempty_of_is_closed_of_nmem ne hc }, { rintro hxK y h, specialize h x hxK, rwa real_inner_comm }, end end complete_space end dual
550c23e4ccdf65b8b15c110da1aae2443fc3a73d
82e44445c70db0f03e30d7be725775f122d72f3e
/src/measure_theory/vector_measure.lean
67e83d71f5a9b14a02460959a665190044fce94f
[ "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
22,611
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.integration /-! # Vector valued measures This file defines vector valued measures, which are σ-additive functions from a set to a add monoid `M` such that it maps the empty set and non-measurable sets to zero. In the case that `M = ℝ`, we called the vector measure a signed measure and write `signed_measure α`. Similarly, when `M = ℂ`, we call the measure a complex measure and write `complex_measure α`. ## Main definitions * `vector_measure` is a vector valued, σ-additive function that maps the empty and non-measurable set to zero. ## Implementation notes We require all non-measurable sets to be mapped to zero in order for the extensionality lemma to only compare the underlying functions for measurable sets. We use `has_sum` instead of `tsum` in the definition of vector measures in comparison to `measure` since this provides summablity. ## Tags vector measure, signed measure, complex measure -/ noncomputable theory open_locale classical big_operators nnreal ennreal namespace measure_theory variables {α β : Type*} [measurable_space α] /-- A vector measure on a measurable space `α` is a σ-additive `M`-valued function (for some `M` an add monoid) such that the empty set and non-measurable sets are mapped to zero. -/ structure vector_measure (α : Type*) [measurable_space α] (M : Type*) [add_comm_monoid M] [topological_space M] := (measure_of' : set α → M) (empty' : measure_of' ∅ = 0) (not_measurable' ⦃i : set α⦄ : ¬ measurable_set i → measure_of' i = 0) (m_Union' ⦃f : ℕ → set α⦄ : (∀ i, measurable_set (f i)) → pairwise (disjoint on f) → has_sum (λ i, measure_of' (f i)) (measure_of' (⋃ i, f i))) /-- A `signed_measure` is a `ℝ`-vector measure. -/ abbreviation signed_measure (α : Type*) [measurable_space α] := vector_measure α ℝ /-- A `complex_measure` is a `ℂ`-vector_measure. -/ abbreviation complex_measure (α : Type*) [measurable_space α] := vector_measure α ℂ open set measure_theory namespace vector_measure section variables {M : Type*} [add_comm_monoid M] [topological_space M] instance : has_coe_to_fun (vector_measure α M) := ⟨λ _, set α → M, vector_measure.measure_of'⟩ initialize_simps_projections vector_measure (measure_of' → apply) @[simp] lemma measure_of_eq_coe (v : vector_measure α M) : v.measure_of' = v := rfl @[simp] lemma empty (v : vector_measure α M) : v ∅ = 0 := v.empty' lemma not_measurable (v : vector_measure α M) {i : set α} (hi : ¬ measurable_set i) : v i = 0 := v.not_measurable' hi lemma m_Union (v : vector_measure α M) {f : ℕ → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : has_sum (λ i, v (f i)) (v (⋃ i, f i)) := v.m_Union' hf₁ hf₂ lemma of_disjoint_Union_nat [t2_space M] (v : vector_measure α M) {f : ℕ → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : v (⋃ i, f i) = ∑' i, v (f i) := (v.m_Union hf₁ hf₂).tsum_eq.symm lemma coe_injective : @function.injective (vector_measure α M) (set α → M) coe_fn := λ v w h, by { cases v, cases w, congr' } lemma ext_iff' (v w : vector_measure α M) : v = w ↔ ∀ i : set α, v i = w i := by rw [← coe_injective.eq_iff, function.funext_iff] lemma ext_iff (v w : vector_measure α M) : v = w ↔ ∀ i : set α, measurable_set i → v i = w i := begin split, { rintro rfl _ _, refl }, { rw ext_iff', intros h i, by_cases hi : measurable_set i, { exact h i hi }, { simp_rw [not_measurable _ hi] } } end @[ext] lemma ext {s t : vector_measure α M} (h : ∀ i : set α, measurable_set i → s i = t i) : s = t := (ext_iff s t).2 h variables [t2_space M] {v : vector_measure α M} {f : ℕ → set α} lemma has_sum_of_disjoint_Union [encodable β] {f : β → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : has_sum (λ i, v (f i)) (v (⋃ i, f i)) := begin set g := λ i : ℕ, ⋃ (b : β) (H : b ∈ encodable.decode₂ β i), f b with hg, have hg₁ : ∀ i, measurable_set (g i), { exact λ _, measurable_set.Union (λ b, measurable_set.Union_Prop $ λ _, hf₁ b) }, have hg₂ : pairwise (disjoint on g), { exact encodable.Union_decode₂_disjoint_on hf₂ }, have := v.of_disjoint_Union_nat hg₁ hg₂, rw [hg, encodable.Union_decode₂] at this, have hg₃ : (λ (i : β), v (f i)) = (λ i, v (g (encodable.encode i))), { ext, rw hg, simp only, congr, ext y, simp only [exists_prop, mem_Union, option.mem_def], split, { intro hy, refine ⟨x, (encodable.decode₂_is_partial_inv _ _).2 rfl, hy⟩ }, { rintro ⟨b, hb₁, hb₂⟩, rw (encodable.decode₂_is_partial_inv _ _) at hb₁, rwa ← encodable.encode_injective hb₁ } }, rw [summable.has_sum_iff, this, ← tsum_Union_decode₂], { exact v.empty }, { rw hg₃, change summable ((λ i, v (g i)) ∘ encodable.encode), rw function.injective.summable_iff encodable.encode_injective, { exact (v.m_Union hg₁ hg₂).summable }, { intros x hx, convert v.empty, simp only [Union_eq_empty, option.mem_def, not_exists, mem_range] at ⊢ hx, intros i hi, exact false.elim ((hx i) ((encodable.decode₂_is_partial_inv _ _).1 hi)) } } end lemma of_disjoint_Union [encodable β] {f : β → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : v (⋃ i, f i) = ∑' i, v (f i) := (has_sum_of_disjoint_Union hf₁ hf₂).tsum_eq.symm lemma of_union {A B : set α} (h : disjoint A B) (hA : measurable_set A) (hB : measurable_set B) : v (A ∪ B) = v A + v B := begin rw [union_eq_Union, of_disjoint_Union, tsum_fintype, fintype.sum_bool, cond, cond], exacts [λ b, bool.cases_on b hB hA, pairwise_disjoint_on_bool.2 h] end lemma of_add_of_diff {A B : set α} (hA : measurable_set A) (hB : measurable_set B) (h : A ⊆ B) : v A + v (B \ A) = v B := begin rw [← of_union disjoint_diff hA (hB.diff hA), union_diff_cancel h], apply_instance, end lemma of_diff {M : Type*} [add_comm_group M] [topological_space M] [t2_space M] {v : vector_measure α M} {A B : set α} (hA : measurable_set A) (hB : measurable_set B) (h : A ⊆ B) : v (B \ A) = v B - (v A) := begin rw [← of_add_of_diff hA hB h, add_sub_cancel'], apply_instance, end lemma of_Union_nonneg {M : Type*} [topological_space M] [ordered_add_comm_monoid M] [order_closed_topology M] {v : vector_measure α M} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) (hf₃ : ∀ i, 0 ≤ v (f i)) : 0 ≤ v (⋃ i, f i) := (v.of_disjoint_Union_nat hf₁ hf₂).symm ▸ tsum_nonneg hf₃ lemma of_Union_nonpos {M : Type*} [topological_space M] [ordered_add_comm_monoid M] [order_closed_topology M] {v : vector_measure α M} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) (hf₃ : ∀ i, v (f i) ≤ 0) : v (⋃ i, f i) ≤ 0 := (v.of_disjoint_Union_nat hf₁ hf₂).symm ▸ tsum_nonpos hf₃ lemma of_nonneg_disjoint_union_eq_zero {s : signed_measure α} {A B : set α} (h : disjoint A B) (hA₁ : measurable_set A) (hB₁ : measurable_set B) (hA₂ : 0 ≤ s A) (hB₂ : 0 ≤ s B) (hAB : s (A ∪ B) = 0) : s A = 0 := begin rw of_union h hA₁ hB₁ at hAB, linarith, apply_instance, end lemma of_nonpos_disjoint_union_eq_zero {s : signed_measure α} {A B : set α} (h : disjoint A B) (hA₁ : measurable_set A) (hB₁ : measurable_set B) (hA₂ : s A ≤ 0) (hB₂ : s B ≤ 0) (hAB : s (A ∪ B) = 0) : s A = 0 := begin rw of_union h hA₁ hB₁ at hAB, linarith, apply_instance, end end section add_comm_monoid variables {M : Type*} [add_comm_monoid M] [topological_space M] instance : has_zero (vector_measure α M) := ⟨⟨0, rfl, λ _ _, rfl, λ _ _ _, has_sum_zero⟩⟩ instance : inhabited (vector_measure α M) := ⟨0⟩ @[simp] lemma coe_zero : ⇑(0 : vector_measure α M) = 0 := rfl lemma zero_apply (i : set α) : (0 : vector_measure α M) i = 0 := rfl variables [has_continuous_add M] /-- The sum of two vector measure is a vector measure. -/ def add (v w : vector_measure α M) : vector_measure α M := { measure_of' := v + w, empty' := by simp, not_measurable' := λ _ hi, by simp [v.not_measurable hi, w.not_measurable hi], m_Union' := λ f hf₁ hf₂, has_sum.add (v.m_Union hf₁ hf₂) (w.m_Union hf₁ hf₂) } instance : has_add (vector_measure α M) := ⟨add⟩ @[simp] lemma coe_add (v w : vector_measure α M) : ⇑(v + w) = v + w := rfl lemma add_apply (v w : vector_measure α M) (i : set α) :(v + w) i = v i + w i := rfl instance : add_comm_monoid (vector_measure α M) := function.injective.add_comm_monoid _ coe_injective coe_zero coe_add /-- `coe_fn` is an `add_monoid_hom`. -/ @[simps] def coe_fn_add_monoid_hom : vector_measure α M →+ (set α → M) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } end add_comm_monoid section add_comm_group variables {M : Type*} [add_comm_group M] [topological_space M] variables [topological_add_group M] /-- The negative of a vector measure is a vector measure. -/ def neg (v : vector_measure α M) : vector_measure α M := { measure_of' := -v, empty' := by simp, not_measurable' := λ _ hi, by simp [v.not_measurable hi], m_Union' := λ f hf₁ hf₂, has_sum.neg $ v.m_Union hf₁ hf₂ } instance : has_neg (vector_measure α M) := ⟨neg⟩ @[simp] lemma coe_neg (v : vector_measure α M) : ⇑(-v) = - v := rfl lemma neg_apply (v : vector_measure α M) (i : set α) :(-v) i = - v i := rfl /-- The difference of two vector measure is a vector measure. -/ def sub (v w : vector_measure α M) : vector_measure α M := { measure_of' := v - w, empty' := by simp, not_measurable' := λ _ hi, by simp [v.not_measurable hi, w.not_measurable hi], m_Union' := λ f hf₁ hf₂, has_sum.sub (v.m_Union hf₁ hf₂) (w.m_Union hf₁ hf₂) } instance : has_sub (vector_measure α M) := ⟨sub⟩ @[simp] lemma coe_sub (v w : vector_measure α M) : ⇑(v - w) = v - w := rfl lemma sub_apply (v w : vector_measure α M) (i : set α) : (v - w) i = v i - w i := rfl instance : add_comm_group (vector_measure α M) := function.injective.add_comm_group _ coe_injective coe_zero coe_add coe_neg coe_sub end add_comm_group section distrib_mul_action variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [distrib_mul_action R M] variables [topological_space R] [has_continuous_smul R M] /-- Given a real number `r` and a signed measure `s`, `smul r s` is the signed measure corresponding to the function `r • s`. -/ def smul (r : R) (v : vector_measure α M) : vector_measure α M := { measure_of' := r • v, empty' := by rw [pi.smul_apply, empty, smul_zero], not_measurable' := λ _ hi, by rw [pi.smul_apply, v.not_measurable hi, smul_zero], m_Union' := λ _ hf₁ hf₂, has_sum.smul (v.m_Union hf₁ hf₂) } instance : has_scalar R (vector_measure α M) := ⟨smul⟩ @[simp] lemma coe_smul (r : R) (v : vector_measure α M) : ⇑(r • v) = r • v := rfl lemma smul_apply (r : R) (v : vector_measure α M) (i : set α) : (r • v) i = r • v i := rfl instance [has_continuous_add M] : distrib_mul_action R (vector_measure α M) := function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective coe_smul end distrib_mul_action section module variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [module R M] variables [topological_space R] [has_continuous_smul R M] instance [has_continuous_add M] : module R (vector_measure α M) := function.injective.module R coe_fn_add_monoid_hom coe_injective coe_smul end module end vector_measure namespace measure /-- A finite measure coerced into a real function is a signed measure. -/ @[simps] def to_signed_measure (μ : measure α) [hμ : finite_measure μ] : signed_measure α := { measure_of' := λ i : set α, if measurable_set i then (μ.measure_of i).to_real else 0, empty' := by simp [μ.empty], not_measurable' := λ _ hi, if_neg hi, m_Union' := begin intros _ hf₁ hf₂, rw [μ.m_Union hf₁ hf₂, ennreal.tsum_to_real_eq, if_pos (measurable_set.Union hf₁), summable.has_sum_iff], { congr, ext n, rw if_pos (hf₁ n) }, { refine @summable_of_nonneg_of_le _ (ennreal.to_real ∘ μ ∘ f) _ _ _ _, { intro, split_ifs, exacts [ennreal.to_real_nonneg, le_refl _] }, { intro, split_ifs, exacts [le_refl _, ennreal.to_real_nonneg] }, exact summable_measure_to_real hf₁ hf₂ }, { intros a ha, apply ne_of_lt hμ.measure_univ_lt_top, rw [eq_top_iff, ← ha, outer_measure.measure_of_eq_coe, coe_to_outer_measure], exact measure_mono (set.subset_univ _) } end } lemma to_signed_measure_apply_measurable {μ : measure α} [finite_measure μ] {i : set α} (hi : measurable_set i) : μ.to_signed_measure i = (μ i).to_real := if_pos hi @[simp] lemma to_signed_measure_zero : (0 : measure α).to_signed_measure = 0 := by { ext i hi, simp } @[simp] lemma to_signed_measure_add (μ ν : measure α) [finite_measure μ] [finite_measure ν] : (μ + ν).to_signed_measure = μ.to_signed_measure + ν.to_signed_measure := begin ext i hi, rw [to_signed_measure_apply_measurable hi, add_apply, ennreal.to_real_add (ne_of_lt (measure_lt_top _ _ )) (ne_of_lt (measure_lt_top _ _)), vector_measure.add_apply, to_signed_measure_apply_measurable hi, to_signed_measure_apply_measurable hi], all_goals { apply_instance } end @[simp] lemma to_signed_measure_smul (μ : measure α) [finite_measure μ] (r : ℝ≥0) : (r • μ).to_signed_measure = r • μ.to_signed_measure := begin ext i hi, rw [to_signed_measure_apply_measurable hi, vector_measure.smul_apply, to_signed_measure_apply_measurable hi, coe_nnreal_smul, pi.smul_apply, ennreal.to_real_smul], end /-- A measure is a vector measure over `ℝ≥0∞`. -/ @[simps] def to_ennreal_vector_measure (μ : measure α) : vector_measure α ℝ≥0∞ := { measure_of' := λ i : set α, if measurable_set i then μ i else 0, empty' := by simp [μ.empty], not_measurable' := λ _ hi, if_neg hi, m_Union' := λ _ hf₁ hf₂, begin rw summable.has_sum_iff ennreal.summable, { rw [if_pos (measurable_set.Union hf₁), measure_theory.measure_Union hf₂ hf₁], exact tsum_congr (λ n, if_pos (hf₁ n)) }, end } lemma to_ennreal_vector_measure_apply_measurable {μ : measure α} {i : set α} (hi : measurable_set i) : μ.to_ennreal_vector_measure i = μ i := if_pos hi @[simp] lemma to_ennreal_vector_measure_zero : (0 : measure α).to_ennreal_vector_measure = 0 := by { ext i hi, simp } @[simp] lemma to_ennreal_vector_measure_add (μ ν : measure α) : (μ + ν).to_ennreal_vector_measure = μ.to_ennreal_vector_measure + ν.to_ennreal_vector_measure := begin refine measure_theory.vector_measure.ext (λ i hi, _), rw [to_ennreal_vector_measure_apply_measurable hi, add_apply, vector_measure.add_apply, to_ennreal_vector_measure_apply_measurable hi, to_ennreal_vector_measure_apply_measurable hi] end /-- Given two finite measures `μ, ν`, `sub_to_signed_measure μ ν` is the signed measure corresponding to the function `μ - ν`. -/ def sub_to_signed_measure (μ ν : measure α) [hμ : finite_measure μ] [hν : finite_measure ν] : signed_measure α := μ.to_signed_measure - ν.to_signed_measure lemma sub_to_signed_measure_apply {μ ν : measure α} [finite_measure μ] [finite_measure ν] {i : set α} (hi : measurable_set i) : μ.sub_to_signed_measure ν i = (μ i).to_real - (ν i).to_real := begin rw [sub_to_signed_measure, vector_measure.sub_apply, to_signed_measure_apply_measurable hi, measure.to_signed_measure_apply_measurable hi, sub_eq_add_neg] end end measure namespace vector_measure variables [measurable_space β] section variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {v : vector_measure α M} /-- The pushforward of a vector measure along a function. -/ def map (v : vector_measure α M) (f : α → β) : vector_measure β M := if hf : measurable f then { measure_of' := λ s, if measurable_set s then v (f ⁻¹' s) else 0, empty' := by simp, not_measurable' := λ i hi, if_neg hi, m_Union' := begin intros g hg₁ hg₂, convert v.m_Union (λ i, hf (hg₁ i)) (λ i j hij x hx, hg₂ i j hij hx), { ext i, rw if_pos (hg₁ i) }, { rw [preimage_Union, if_pos (measurable_set.Union hg₁)] } end } else 0 lemma map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) : v.map f s = v (f ⁻¹' s) := by { rw [map, dif_pos hf], exact if_pos hs } @[simp] lemma map_id : v.map id = v := ext (λ i hi, by rw [map_apply measurable_id hi, preimage_id]) @[simp] lemma map_zero (f : α → β) : (0 : vector_measure α M).map f = 0 := begin by_cases hf : measurable f, { ext i hi, rw [map_apply hf hi, zero_apply, zero_apply] }, { exact dif_neg hf } end /-- The restriction of a vector measure on some set. -/ def restrict (v : vector_measure α M) (i : set α) : vector_measure α M := if hi : measurable_set i then { measure_of' := λ s, if measurable_set s then v (s ∩ i) else 0, empty' := by simp, not_measurable' := λ i hi, if_neg hi, m_Union' := begin intros f hf₁ hf₂, convert v.m_Union (λ n, (hf₁ n).inter hi) (hf₂.mono $ λ i j, disjoint.mono inf_le_left inf_le_left), { ext n, rw if_pos (hf₁ n) }, { rw [Union_inter, if_pos (measurable_set.Union hf₁)] } end } else 0 lemma restrict_apply {i : set α} (hi : measurable_set i) {j : set α} (hj : measurable_set j) : v.restrict i j = v (j ∩ i) := by { rw [restrict, dif_pos hi], exact if_pos hj } lemma restrict_eq_self {i : set α} (hi : measurable_set i) {j : set α} (hj : measurable_set j) (hij : j ⊆ i) : v.restrict i j = v j := by rw [restrict_apply hi hj, inter_eq_left_iff_subset.2 hij] @[simp] lemma restrict_empty : v.restrict ∅ = 0 := ext (λ i hi, by rw [restrict_apply measurable_set.empty hi, inter_empty, v.empty, zero_apply]) @[simp] lemma restrict_univ : v.restrict univ = v := ext (λ i hi, by rw [restrict_apply measurable_set.univ hi, inter_univ]) @[simp] lemma restrict_zero {i : set α} : (0 : vector_measure α M).restrict i = 0 := begin by_cases hi : measurable_set i, { ext j hj, rw [restrict_apply hi hj], refl }, { exact dif_neg hi } end section has_continuous_add variables [has_continuous_add M] lemma map_add (v w : vector_measure α M) (f : α → β) : (v + w).map f = v.map f + w.map f := begin by_cases hf : measurable f, { ext i hi, simp [map_apply hf hi] }, { simp [map, dif_neg hf] } end /-- `vector_measure.map` as an additive monoid homomorphism. -/ @[simps] def map_gm (f : α → β) : vector_measure α M →+ vector_measure β M := { to_fun := λ v, v.map f, map_zero' := map_zero f, map_add' := λ _ _, map_add _ _ f } lemma restrict_add (v w : vector_measure α M) (i : set α) : (v + w).restrict i = v.restrict i + w.restrict i := begin by_cases hi : measurable_set i, { ext j hj, simp [restrict_apply hi hj] }, { simp [restrict, dif_neg hi] } end /--`vector_measure.restrict` as an additive monoid homomorphism. -/ @[simps] def restrict_gm (i : set α) : vector_measure α M →+ vector_measure α M := { to_fun := λ v, v.restrict i, map_zero' := restrict_zero, map_add' := λ _ _, restrict_add _ _ i } end has_continuous_add end section variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [distrib_mul_action R M] variables [topological_space R] [has_continuous_smul R M] @[simp] lemma map_smul {v : vector_measure α M} {f : α → β} (c : R) : (c • v).map f = c • v.map f := begin by_cases hf : measurable f, { ext i hi, simp [map_apply hf hi] }, { simp only [map, dif_neg hf], -- `smul_zero` does not work since we do not require `has_continuous_add` ext i hi, simp } end @[simp] lemma restrict_smul {v :vector_measure α M} {i : set α} (c : R) : (c • v).restrict i = c • v.restrict i := begin by_cases hi : measurable_set i, { ext j hj, simp [restrict_apply hi hj] }, { simp only [restrict, dif_neg hi], -- `smul_zero` does not work since we do not require `has_continuous_add` ext j hj, simp } end end section variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [module R M] variables [topological_space R] [has_continuous_smul R M] [has_continuous_add M] /-- `vector_measure.map` as a linear map. -/ @[simps] def mapₗ (f : α → β) : vector_measure α M →ₗ[R] vector_measure β M := { to_fun := λ v, v.map f, map_add' := λ _ _, map_add _ _ f, map_smul' := λ _ _, map_smul _ } /-- `vector_measure.restrict` as an additive monoid homomorphism. -/ @[simps] def restrictₗ (i : set α) : vector_measure α M →ₗ[R] vector_measure α M := { to_fun := λ v, v.restrict i, map_add' := λ _ _, restrict_add _ _ i, map_smul' := λ _ _, restrict_smul _ } end section variables {M : Type*} [topological_space M] [add_comm_monoid M] [partial_order M] /-- Vector measures over a partially ordered monoid is partially ordered. This definition is consistent with `measure.partial_order`. -/ instance : partial_order (vector_measure α M) := { le := λ v w, ∀ i, measurable_set i → v i ≤ w i, le_refl := λ v i hi, le_refl _, le_trans := λ u v w h₁ h₂ i hi, le_trans (h₁ i hi) (h₂ i hi), le_antisymm := λ v w h₁ h₂, ext (λ i hi, le_antisymm (h₁ i hi) (h₂ i hi)) } variables {u v w : vector_measure α M} lemma le_iff : v ≤ w ↔ ∀ i, measurable_set i → v i ≤ w i := iff.rfl lemma le_iff' : v ≤ w ↔ ∀ i, v i ≤ w i := begin refine ⟨λ h i, _, λ h i hi, h i⟩, by_cases hi : measurable_set i, { exact h i hi }, { rw [v.not_measurable hi, w.not_measurable hi] } end end section variables {M : Type*} [topological_space M] [add_comm_monoid M] [partial_order M] [covariant_class M M (+) (≤)] [has_continuous_add M] instance covariant_add_le : covariant_class (vector_measure α M) (vector_measure α M) (+) (≤) := ⟨λ u v w h i hi, add_le_add_left (h i hi) _⟩ end end vector_measure end measure_theory
074723260b81b659ff75edd04a429fde5bee129e
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/data/set/disjointed.lean
6d68970672bb2e878f8e89ebfc768abb070e90e4
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,733
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 Disjointed sets -/ import data.set.lattice data.nat.basic open set classical lattice local attribute [instance] decidable_inhabited prop_decidable universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {s t u : set α} def pairwise {α : Type*} (p : α → α → Prop) := ∀i j, i ≠ j → p i j namespace set def disjointed (f : ℕ → set α) (n : ℕ) : set α := f n ∩ (⋂i<n, - f i) lemma disjoint_disjointed {f : ℕ → set α} : pairwise (disjoint on disjointed f) := assume i j h, have ∀i j, i < j → disjointed f i ∩ disjointed f j = ∅, from assume i j hij, eq_empty_of_forall_not_mem $ assume x h, have x ∈ f i, from h.left.left, have x ∈ (⋂i<j, - f i), from h.right.right, have x ∉ f i, begin simp at this; exact this _ hij end, absurd ‹x ∈ f i› this, show disjointed f i ∩ disjointed f j = ∅, from (ne_iff_lt_or_gt.mp h).elim (this i j) begin rw [inter_comm], exact this j i end lemma disjointed_Union {f : ℕ → set α} : (⋃n, disjointed f n) = (⋃n, f n) := subset.antisymm (Union_subset_Union $ assume i, inter_subset_left _ _) $ assume x h, have ∃n, x ∈ f n, from (mem_Union_eq _ _).mp h, have hn : ∀ (i : ℕ), i < nat.find this → x ∉ f i, from assume i, nat.find_min this, (mem_Union_eq _ _).mpr ⟨nat.find this, nat.find_spec this, by simp; assumption⟩ lemma disjointed_induct {f : ℕ → set α} {n : ℕ} {p : set α → Prop} (h₁ : p (f n)) (h₂ : ∀t i, p t → p (t - f i)) : p (disjointed f n) := have ∀n t, p t → p (t ∩ (⋂i<n, - f i)), begin intro n, induction n, case nat.zero { have h : (⋂ (i : ℕ) (H : i < 0), -f i) = univ, { apply eq_univ_of_forall, simp [mem_Inter, nat.not_lt_zero] }, simp [h, inter_univ] }, case nat.succ n ih { intro t, have h : (⨅i (H : i < n.succ), -f i) = (⨅i (H : i < n), -f i) ⊓ - f n, by simp [nat.lt_succ_iff_lt_or_eq, infi_or, infi_inf_eq, inf_comm], change (⋂ (i : ℕ) (H : i < n.succ), -f i) = (⋂ (i : ℕ) (H : i < n), -f i) ∩ - f n at h, rw [h, ←inter_assoc], exact assume ht, h₂ _ _ (ih _ ht) } end, this _ _ h₁ lemma disjointed_of_mono {f : ℕ → set α} {n : ℕ} (hf : monotone f) : disjointed f (n + 1) = f (n + 1) \ f n := have (⋂i (h : i < n + 1), -f i) = - f n, from le_antisymm (infi_le_of_le n $ infi_le_of_le (nat.lt_succ_self _) $ subset.refl _) (le_infi $ assume i, le_infi $ assume hi, neg_le_neg $ hf $ nat.le_of_succ_le_succ hi), by simp [disjointed, this, sdiff_eq] end set
4b51bec769e9111db198147e147c8e2d5f4f9c3e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/param_binder_update2.lean
862c293e9ba3919a18481c82082555ee3bb3f67a
[ "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
372
lean
section parameters {A : Type} {B : Type} definition foo1 (a : A) (b : B) := a parameters (B) {A} -- Should not change the order of the parameters definition foo2 (a : A) (b : B) := a parameters {B} (A) definition foo3 (a : A) (b : B) := a parameters (A) (B) definition foo4 (a : A) (b : B) := a end check @foo1 check @foo2 check @foo3 check @foo4
bce43aa5efcc866a71b0d8e90a49200b35dc8973
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/data/set/finite.lean
1cbd5dc740c642cbadf3a31a6d11df4d861cb27b
[ "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
26,324
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 data.fintype.basic /-! # Finite sets This file defines predicates `finite : set α → Prop` and `infinite : set α → Prop` and proves some basic facts about finite sets. -/ open set function universes u v w x variables {α : Type u} {β : Type v} {ι : Sort w} {γ : Type x} namespace set /-- A set is finite if the subtype is a fintype, i.e. there is a list that enumerates its members. -/ def finite (s : set α) : Prop := nonempty (fintype s) /-- A set is infinite if it is not finite. -/ def infinite (s : set α) : Prop := ¬ finite s /-- The subtype corresponding to a finite set is a finite type. Note that because `finite` isn't a typeclass, this will not fire if it is made into an instance -/ noncomputable def finite.fintype {s : set α} (h : finite s) : fintype s := classical.choice h /-- Get a finset from a finite set -/ noncomputable def finite.to_finset {s : set α} (h : finite s) : finset α := @set.to_finset _ _ h.fintype @[simp] theorem finite.mem_to_finset {s : set α} {h : finite s} {a : α} : a ∈ h.to_finset ↔ a ∈ s := @mem_to_finset _ _ h.fintype _ @[simp] theorem finite.to_finset.nonempty {s : set α} (h : finite s) : h.to_finset.nonempty ↔ s.nonempty := show (∃ x, x ∈ h.to_finset) ↔ (∃ x, x ∈ s), from exists_congr (λ _, finite.mem_to_finset) @[simp] lemma finite.coe_to_finset {α} {s : set α} (h : finite s) : ↑h.to_finset = s := @set.coe_to_finset _ s h.fintype theorem finite.exists_finset {s : set α} : finite s → ∃ s' : finset α, ∀ a : α, a ∈ s' ↔ a ∈ s | ⟨h⟩ := by exactI ⟨to_finset s, λ _, mem_to_finset⟩ theorem finite.exists_finset_coe {s : set α} (hs : finite s) : ∃ s' : finset α, ↑s' = s := ⟨hs.to_finset, hs.coe_to_finset⟩ /-- Finite sets can be lifted to finsets. -/ instance : can_lift (set α) (finset α) := { coe := coe, cond := finite, prf := λ s hs, hs.exists_finset_coe } theorem finite_mem_finset (s : finset α) : finite {a | a ∈ s} := ⟨fintype.of_finset s (λ _, iff.rfl)⟩ theorem finite.of_fintype [fintype α] (s : set α) : finite s := by classical; exact ⟨set_fintype s⟩ theorem exists_finite_iff_finset {p : set α → Prop} : (∃ s, finite s ∧ p s) ↔ ∃ s : finset α, p ↑s := ⟨λ ⟨s, hs, hps⟩, ⟨hs.to_finset, hs.coe_to_finset.symm ▸ hps⟩, λ ⟨s, hs⟩, ⟨↑s, finite_mem_finset s, hs⟩⟩ /-- Membership of a subset of a finite type is decidable. Using this as an instance leads to potential loops with `subtype.fintype` under certain decidability assumptions, so it should only be declared a local instance. -/ def decidable_mem_of_fintype [decidable_eq α] (s : set α) [fintype s] (a) : decidable (a ∈ s) := decidable_of_iff _ mem_to_finset instance fintype_empty : fintype (∅ : set α) := fintype.of_finset ∅ $ by simp theorem empty_card : fintype.card (∅ : set α) = 0 := rfl @[simp] theorem empty_card' {h : fintype.{u} (∅ : set α)} : @fintype.card (∅ : set α) h = 0 := eq.trans (by congr) empty_card @[simp] theorem finite_empty : @finite α ∅ := ⟨set.fintype_empty⟩ instance finite.inhabited : inhabited {s : set α // finite s} := ⟨⟨∅, finite_empty⟩⟩ /-- A `fintype` structure on `insert a s`. -/ def fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : fintype (insert a s : set α) := fintype.of_finset ⟨a ::ₘ s.to_finset.1, multiset.nodup_cons_of_nodup (by simp [h]) s.to_finset.2⟩ $ by simp theorem card_fintype_insert' {a : α} (s : set α) [fintype s] (h : a ∉ s) : @fintype.card _ (fintype_insert' s h) = fintype.card s + 1 := by rw [fintype_insert', fintype.card_of_finset]; simp [finset.card, to_finset]; refl @[simp] theorem card_insert {a : α} (s : set α) [fintype s] (h : a ∉ s) {d : fintype.{u} (insert a s : set α)} : @fintype.card _ d = fintype.card s + 1 := by rw ← card_fintype_insert' s h; congr lemma card_image_of_inj_on {s : set α} [fintype s] {f : α → β} [fintype (f '' s)] (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : fintype.card (f '' s) = fintype.card s := by haveI := classical.prop_decidable; exact calc fintype.card (f '' s) = (s.to_finset.image f).card : fintype.card_of_finset' _ (by simp) ... = s.to_finset.card : finset.card_image_of_inj_on (λ x hx y hy hxy, H x (mem_to_finset.1 hx) y (mem_to_finset.1 hy) hxy) ... = fintype.card s : (fintype.card_of_finset' _ (λ a, mem_to_finset)).symm lemma card_image_of_injective (s : set α) [fintype s] {f : α → β} [fintype (f '' s)] (H : function.injective f) : fintype.card (f '' s) = fintype.card s := card_image_of_inj_on $ λ _ _ _ _ h, H h section local attribute [instance] decidable_mem_of_fintype instance fintype_insert [decidable_eq α] (a : α) (s : set α) [fintype s] : fintype (insert a s : set α) := if h : a ∈ s then by rwa [insert_eq, union_eq_self_of_subset_left (singleton_subset_iff.2 h)] else fintype_insert' _ h end @[simp] theorem finite.insert (a : α) {s : set α} : finite s → finite (insert a s) | ⟨h⟩ := ⟨@set.fintype_insert _ (classical.dec_eq α) _ _ h⟩ lemma to_finset_insert [decidable_eq α] {a : α} {s : set α} (hs : finite s) : (hs.insert a).to_finset = insert a hs.to_finset := finset.ext $ by simp @[elab_as_eliminator] theorem finite.induction_on {C : set α → Prop} {s : set α} (h : finite s) (H0 : C ∅) (H1 : ∀ {a s}, a ∉ s → finite s → C s → C (insert a s)) : C s := let ⟨t⟩ := h in by exactI match s.to_finset, @mem_to_finset _ s _ with | ⟨l, nd⟩, al := begin change ∀ a, a ∈ l ↔ a ∈ s at al, clear _let_match _match t h, revert s nd al, refine multiset.induction_on l _ (λ a l IH, _); intros s nd al, { rw show s = ∅, from eq_empty_iff_forall_not_mem.2 (by simpa using al), exact H0 }, { rw ← show insert a {x | x ∈ l} = s, from set.ext (by simpa using al), cases multiset.nodup_cons.1 nd with m nd', refine H1 _ ⟨finset.subtype.fintype ⟨l, nd'⟩⟩ (IH nd' (λ _, iff.rfl)), exact m } end end @[elab_as_eliminator] theorem finite.dinduction_on {C : ∀s:set α, finite s → Prop} {s : set α} (h : finite s) (H0 : C ∅ finite_empty) (H1 : ∀ {a s}, a ∉ s → ∀h:finite s, C s h → C (insert a s) (h.insert a)) : C s h := have ∀h:finite s, C s h, from finite.induction_on h (assume h, H0) (assume a s has hs ih h, H1 has hs (ih _)), this h instance fintype_singleton (a : α) : fintype ({a} : set α) := unique.fintype @[simp] theorem card_singleton (a : α) : fintype.card ({a} : set α) = 1 := fintype.card_of_subsingleton _ @[simp] theorem finite_singleton (a : α) : finite ({a} : set α) := ⟨set.fintype_singleton _⟩ instance fintype_pure : ∀ a : α, fintype (pure a : set α) := set.fintype_singleton theorem finite_pure (a : α) : finite (pure a : set α) := ⟨set.fintype_pure a⟩ instance fintype_univ [fintype α] : fintype (@univ α) := fintype.of_equiv α $ (equiv.set.univ α).symm theorem finite_univ [fintype α] : finite (@univ α) := ⟨set.fintype_univ⟩ theorem infinite_univ_iff : (@univ α).infinite ↔ _root_.infinite α := ⟨λ h₁, ⟨λ h₂, h₁ $ @finite_univ α h₂⟩, λ ⟨h₁⟩ ⟨h₂⟩, h₁ $ @fintype.of_equiv _ _ h₂ $ equiv.set.univ _⟩ theorem infinite_univ [h : _root_.infinite α] : infinite (@univ α) := infinite_univ_iff.2 h theorem infinite_coe_iff {s : set α} : _root_.infinite s ↔ infinite s := ⟨λ ⟨h₁⟩ h₂, h₁ h₂.some, λ h₁, ⟨λ h₂, h₁ ⟨h₂⟩⟩⟩ theorem infinite.to_subtype {s : set α} (h : infinite s) : _root_.infinite s := infinite_coe_iff.2 h /-- Embedding of `ℕ` into an infinite set. -/ noncomputable def infinite.nat_embedding (s : set α) (h : infinite s) : ℕ ↪ s := by { haveI := h.to_subtype, exact infinite.nat_embedding s } lemma infinite.exists_subset_card_eq {s : set α} (hs : infinite s) (n : ℕ) : ∃ t : finset α, ↑t ⊆ s ∧ t.card = n := ⟨((finset.range n).map (hs.nat_embedding _)).map (embedding.subtype _), by simp⟩ instance fintype_union [decidable_eq α] (s t : set α) [fintype s] [fintype t] : fintype (s ∪ t : set α) := fintype.of_finset (s.to_finset ∪ t.to_finset) $ by simp theorem finite.union {s t : set α} : finite s → finite t → finite (s ∪ t) | ⟨hs⟩ ⟨ht⟩ := ⟨@set.fintype_union _ (classical.dec_eq α) _ _ hs ht⟩ instance fintype_sep (s : set α) (p : α → Prop) [fintype s] [decidable_pred p] : fintype ({a ∈ s | p a} : set α) := fintype.of_finset (s.to_finset.filter p) $ by simp instance fintype_inter (s t : set α) [fintype s] [decidable_pred t] : fintype (s ∩ t : set α) := set.fintype_sep s t /-- A `fintype` structure on a set defines a `fintype` structure on its subset. -/ def fintype_subset (s : set α) {t : set α} [fintype s] [decidable_pred t] (h : t ⊆ s) : fintype t := by rw ← inter_eq_self_of_subset_right h; apply_instance theorem finite.subset {s : set α} : finite s → ∀ {t : set α}, t ⊆ s → finite t | ⟨hs⟩ t h := ⟨@set.fintype_subset _ _ _ hs (classical.dec_pred t) h⟩ theorem infinite_mono {s t : set α} (h : s ⊆ t) : infinite s → infinite t := mt (λ ht, ht.subset h) instance fintype_image [decidable_eq β] (s : set α) (f : α → β) [fintype s] : fintype (f '' s) := fintype.of_finset (s.to_finset.image f) $ by simp instance fintype_range [decidable_eq β] (f : α → β) [fintype α] : fintype (range f) := fintype.of_finset (finset.univ.image f) $ by simp [range] theorem finite_range (f : α → β) [fintype α] : finite (range f) := by haveI := classical.dec_eq β; exact ⟨by apply_instance⟩ theorem finite.image {s : set α} (f : α → β) : finite s → finite (f '' s) | ⟨h⟩ := ⟨@set.fintype_image _ _ (classical.dec_eq β) _ _ h⟩ theorem infinite_of_infinite_image (f : α → β) {s : set α} (hs : (f '' s).infinite) : s.infinite := mt (finite.image f) hs lemma finite.dependent_image {s : set α} (hs : finite s) {F : Π i ∈ s, β} {t : set β} (H : ∀ y ∈ t, ∃ x (hx : x ∈ s), y = F x hx) : set.finite t := begin let G : s → β := λ x, F x.1 x.2, have A : t ⊆ set.range G, { assume y hy, rcases H y hy with ⟨x, hx, xy⟩, refine ⟨⟨x, hx⟩, xy.symm⟩ }, letI : fintype s := finite.fintype hs, exact (finite_range G).subset A end instance fintype_map {α β} [decidable_eq β] : ∀ (s : set α) (f : α → β) [fintype s], fintype (f <$> s) := set.fintype_image theorem finite.map {α β} {s : set α} : ∀ (f : α → β), finite s → finite (f <$> s) := finite.image /-- If a function `f` has a partial inverse and sends a set `s` to a set with `[fintype]` instance, then `s` has a `fintype` structure as well. -/ def fintype_of_fintype_image (s : set α) {f : α → β} {g} (I : is_partial_inv f g) [fintype (f '' s)] : fintype s := fintype.of_finset ⟨_, @multiset.nodup_filter_map β α g _ (@injective_of_partial_inv_right _ _ f g I) (f '' s).to_finset.2⟩ $ λ a, begin suffices : (∃ b x, f x = b ∧ g b = some a ∧ x ∈ s) ↔ a ∈ s, by simpa [exists_and_distrib_left.symm, and.comm, and.left_comm, and.assoc], rw exists_swap, suffices : (∃ x, x ∈ s ∧ g (f x) = some a) ↔ a ∈ s, {simpa [and.comm, and.left_comm, and.assoc]}, simp [I _, (injective_of_partial_inv I).eq_iff] end theorem finite_of_finite_image {s : set α} {f : α → β} (hi : set.inj_on f s) : finite (f '' s) → finite s | ⟨h⟩ := ⟨@fintype.of_injective _ _ h (λa:s, ⟨f a.1, mem_image_of_mem f a.2⟩) $ assume a b eq, subtype.eq $ hi a.2 b.2 $ subtype.ext_iff_val.1 eq⟩ theorem finite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : finite (f '' s) ↔ finite s := ⟨finite_of_finite_image hi, finite.image _⟩ theorem infinite_image_iff {s : set α} {f : α → β} (hi : inj_on f s) : infinite (f '' s) ↔ infinite s := not_congr $ finite_image_iff hi theorem infinite_of_inj_on_maps_to {s : set α} {t : set β} {f : α → β} (hi : inj_on f s) (hm : maps_to f s t) (hs : infinite s) : infinite t := infinite_mono (maps_to'.mp hm) $ (infinite_image_iff hi).2 hs theorem infinite_range_of_injective [_root_.infinite α] {f : α → β} (hi : injective f) : infinite (range f) := by { rw [←image_univ, infinite_image_iff (inj_on_of_injective hi _)], exact infinite_univ } theorem infinite_of_injective_forall_mem [_root_.infinite α] {s : set β} {f : α → β} (hi : injective f) (hf : ∀ x : α, f x ∈ s) : infinite s := by { rw ←range_subset_iff at hf, exact infinite_mono hf (infinite_range_of_injective hi) } theorem finite.preimage {s : set β} {f : α → β} (I : set.inj_on f (f⁻¹' s)) (h : finite s) : finite (f ⁻¹' s) := finite_of_finite_image I (h.subset (image_preimage_subset f s)) theorem finite.preimage_embedding {s : set β} (f : α ↪ β) (h : s.finite) : (f ⁻¹' s).finite := finite.preimage (λ _ _ _ _ h', f.injective h') h instance fintype_Union [decidable_eq α] {ι : Type*} [fintype ι] (f : ι → set α) [∀ i, fintype (f i)] : fintype (⋃ i, f i) := fintype.of_finset (finset.univ.bind (λ i, (f i).to_finset)) $ by simp theorem finite_Union {ι : Type*} [fintype ι] {f : ι → set α} (H : ∀i, finite (f i)) : finite (⋃ i, f i) := ⟨@set.fintype_Union _ (classical.dec_eq α) _ _ _ (λ i, finite.fintype (H i))⟩ /-- A union of sets with `fintype` structure over a set with `fintype` structure has a `fintype` structure. -/ def fintype_bUnion [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) (H : ∀ i ∈ s, fintype (f i)) : fintype (⋃ i ∈ s, f i) := by rw bUnion_eq_Union; exact @set.fintype_Union _ _ _ _ _ (by rintro ⟨i, hi⟩; exact H i hi) instance fintype_bUnion' [decidable_eq α] {ι : Type*} {s : set ι} [fintype s] (f : ι → set α) [H : ∀ i, fintype (f i)] : fintype (⋃ i ∈ s, f i) := fintype_bUnion _ (λ i _, H i) theorem finite.sUnion {s : set (set α)} (h : finite s) (H : ∀t∈s, finite t) : finite (⋃₀ s) := by rw sUnion_eq_Union; haveI := finite.fintype h; apply finite_Union; simpa using H theorem finite.bUnion {α} {ι : Type*} {s : set ι} {f : Π i ∈ s, set α} : finite s → (∀ i ∈ s, finite (f i ‹_›)) → finite (⋃ i∈s, f i ‹_›) | ⟨hs⟩ h := by rw [bUnion_eq_Union]; exactI finite_Union (λ i, h _ _) instance fintype_lt_nat (n : ℕ) : fintype {i | i < n} := fintype.of_finset (finset.range n) $ by simp instance fintype_le_nat (n : ℕ) : fintype {i | i ≤ n} := by simpa [nat.lt_succ_iff] using set.fintype_lt_nat (n+1) lemma finite_le_nat (n : ℕ) : finite {i | i ≤ n} := ⟨set.fintype_le_nat _⟩ lemma finite_lt_nat (n : ℕ) : finite {i | i < n} := ⟨set.fintype_lt_nat _⟩ instance fintype_prod (s : set α) (t : set β) [fintype s] [fintype t] : fintype (set.prod s t) := fintype.of_finset (s.to_finset.product t.to_finset) $ by simp lemma finite.prod {s : set α} {t : set β} : finite s → finite t → finite (set.prod s t) | ⟨hs⟩ ⟨ht⟩ := by exactI ⟨set.fintype_prod s t⟩ /-- `image2 f s t` is finitype if `s` and `t` are. -/ instance fintype_image2 [decidable_eq γ] (f : α → β → γ) (s : set α) (t : set β) [hs : fintype s] [ht : fintype t] : fintype (image2 f s t : set γ) := by { rw ← image_prod, apply set.fintype_image } lemma finite.image2 (f : α → β → γ) {s : set α} {t : set β} (hs : finite s) (ht : finite t) : finite (image2 f s t) := by { rw ← image_prod, exact (hs.prod ht).image _ } /-- If `s : set α` is a set with `fintype` instance and `f : α → set β` is a function such that each `f a`, `a ∈ s`, has a `fintype` structure, then `s >>= f` has a `fintype` structure. -/ def fintype_bind {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) (H : ∀ a ∈ s, fintype (f a)) : fintype (s >>= f) := set.fintype_bUnion _ H instance fintype_bind' {α β} [decidable_eq β] (s : set α) [fintype s] (f : α → set β) [H : ∀ a, fintype (f a)] : fintype (s >>= f) := fintype_bind _ _ (λ i _, H i) theorem finite_bind {α β} {s : set α} {f : α → set β} : finite s → (∀ a ∈ s, finite (f a)) → finite (s >>= f) | ⟨hs⟩ H := ⟨@fintype_bind _ _ (classical.dec_eq β) _ hs _ (λ a ha, (H a ha).fintype)⟩ instance fintype_seq {α β : Type u} [decidable_eq β] (f : set (α → β)) (s : set α) [fintype f] [fintype s] : fintype (f <*> s) := by rw seq_eq_bind_map; apply set.fintype_bind' theorem finite.seq {α β : Type u} {f : set (α → β)} {s : set α} : finite f → finite s → finite (f <*> s) | ⟨hf⟩ ⟨hs⟩ := by { haveI := classical.dec_eq β, exactI ⟨set.fintype_seq _ _⟩ } /-- There are finitely many subsets of a given finite set -/ lemma finite.finite_subsets {α : Type u} {a : set α} (h : finite a) : finite {b | b ⊆ a} := begin -- we just need to translate the result, already known for finsets, -- to the language of finite sets let s : set (set α) := coe '' (↑(finset.powerset (finite.to_finset h)) : set (finset α)), have : finite s := (finite_mem_finset _).image _, apply this.subset, refine λ b hb, ⟨(h.subset hb).to_finset, _, finite.coe_to_finset _⟩, simpa [finset.subset_iff] end lemma exists_min_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f a ≤ f b | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using (finite.to_finset h1).exists_min_image f ⟨x, finite.mem_to_finset.2 hx⟩ lemma exists_max_image [linear_order β] (s : set α) (f : α → β) (h1 : finite s) : s.nonempty → ∃ a ∈ s, ∀ b ∈ s, f b ≤ f a | ⟨x, hx⟩ := by simpa only [exists_prop, finite.mem_to_finset] using (finite.to_finset h1).exists_max_image f ⟨x, finite.mem_to_finset.2 hx⟩ end set namespace finset variables [decidable_eq β] variables {s : finset α} lemma finite_to_set (s : finset α) : set.finite (↑s : set α) := set.finite_mem_finset s @[simp] lemma coe_bind {f : α → finset β} : ↑(s.bind f) = (⋃x ∈ (↑s : set α), ↑(f x) : set β) := by simp [set.ext_iff] @[simp] lemma finite_to_set_to_finset {α : Type*} (s : finset α) : (finite_to_set s).to_finset = s := by { ext, rw [set.finite.mem_to_finset, mem_coe] } end finset namespace set lemma finite_subset_Union {s : set α} (hs : finite s) {ι} {t : ι → set α} (h : s ⊆ ⋃ i, t i) : ∃ I : set ι, finite I ∧ s ⊆ ⋃ i ∈ I, t i := begin casesI hs, choose f hf using show ∀ x : s, ∃ i, x.1 ∈ t i, {simpa [subset_def] using h}, refine ⟨range f, finite_range f, _⟩, rintro x hx, simp, exact ⟨x, ⟨hx, hf _⟩⟩, end lemma eq_finite_Union_of_finite_subset_Union {ι} {s : ι → set α} {t : set α} (tfin : finite t) (h : t ⊆ ⋃ i, s i) : ∃ I : set ι, (finite I) ∧ ∃ σ : {i | i ∈ I} → set α, (∀ i, finite (σ i)) ∧ (∀ i, σ i ⊆ s i) ∧ t = ⋃ i, σ i := let ⟨I, Ifin, hI⟩ := finite_subset_Union tfin h in ⟨I, Ifin, λ x, s x ∩ t, λ i, tfin.subset (inter_subset_right _ _), λ i, inter_subset_left _ _, begin ext x, rw mem_Union, split, { intro x_in, rcases mem_Union.mp (hI x_in) with ⟨i, _, ⟨hi, rfl⟩, H⟩, use [i, hi, H, x_in] }, { rintros ⟨i, hi, H⟩, exact H } end⟩ /-- An increasing union distributes over finite intersection. -/ lemma Union_Inter_of_monotone {ι ι' α : Type*} [fintype ι] [linear_order ι'] [nonempty ι'] {s : ι → ι' → set α} (hs : ∀ i, monotone (s i)) : (⋃ j : ι', ⋂ i : ι, s i j) = ⋂ i : ι, ⋃ j : ι', s i j := begin ext x, refine ⟨λ hx, Union_Inter_subset hx, λ hx, _⟩, simp only [mem_Inter, mem_Union, mem_Inter] at hx ⊢, choose j hj using hx, obtain ⟨j₀⟩ := show nonempty ι', by apply_instance, refine ⟨finset.univ.fold max j₀ j, λ i, hs i _ (hj i)⟩, rw [finset.fold_op_rel_iff_or (@le_max_iff _ _)], exact or.inr ⟨i, finset.mem_univ i, le_rfl⟩ end instance nat.fintype_Iio (n : ℕ) : fintype (Iio n) := fintype.of_finset (finset.range n) $ by simp /-- If `P` is some relation between terms of `γ` and sets in `γ`, such that every finite set `t : set γ` has some `c : γ` related to it, then there is a recursively defined sequence `u` in `γ` so `u n` is related to the image of `{0, 1, ..., n-1}` under `u`. (We use this later to show sequentially compact sets are totally bounded.) -/ lemma seq_of_forall_finite_exists {γ : Type*} {P : γ → set γ → Prop} (h : ∀ t, finite t → ∃ c, P c t) : ∃ u : ℕ → γ, ∀ n, P (u n) (u '' Iio n) := ⟨λ n, @nat.strong_rec_on' (λ _, γ) n $ λ n ih, classical.some $ h (range $ λ m : Iio n, ih m.1 m.2) (finite_range _), λ n, begin classical, refine nat.strong_rec_on' n (λ n ih, _), rw nat.strong_rec_on_beta', convert classical.some_spec (h _ _), ext x, split, { rintros ⟨m, hmn, rfl⟩, exact ⟨⟨m, hmn⟩, rfl⟩ }, { rintros ⟨⟨m, hmn⟩, rfl⟩, exact ⟨m, hmn, rfl⟩ } end⟩ lemma finite_range_ite {p : α → Prop} [decidable_pred p] {f g : α → β} (hf : finite (range f)) (hg : finite (range g)) : finite (range (λ x, if p x then f x else g x)) := (hf.union hg).subset range_ite_subset lemma finite_range_const {c : β} : finite (range (λ x : α, c)) := (finite_singleton c).subset range_const_subset lemma range_find_greatest_subset {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ}: range (λ x, nat.find_greatest (P x) b) ⊆ ↑(finset.range (b + 1)) := by { rw range_subset_iff, assume x, simp [nat.lt_succ_iff, nat.find_greatest_le] } lemma finite_range_find_greatest {P : α → ℕ → Prop} [∀ x, decidable_pred (P x)] {b : ℕ} : finite (range (λ x, nat.find_greatest (P x) b)) := (finset.range (b + 1)).finite_to_set.subset range_find_greatest_subset lemma card_lt_card {s t : set α} [fintype s] [fintype t] (h : s ⊂ t) : fintype.card s < fintype.card t := begin rw [← s.coe_to_finset, ← t.coe_to_finset, finset.coe_ssubset] at h, rw [fintype.card_of_finset' _ (λ x, mem_to_finset), fintype.card_of_finset' _ (λ x, mem_to_finset)], exact finset.card_lt_card h, end lemma card_le_of_subset {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) : fintype.card s ≤ fintype.card t := calc fintype.card s = s.to_finset.card : fintype.card_of_finset' _ (by simp) ... ≤ t.to_finset.card : finset.card_le_of_subset (λ x hx, by simp [set.subset_def, *] at *) ... = fintype.card t : eq.symm (fintype.card_of_finset' _ (by simp)) lemma eq_of_subset_of_card_le {s t : set α} [fintype s] [fintype t] (hsub : s ⊆ t) (hcard : fintype.card t ≤ fintype.card s) : s = t := (eq_or_ssubset_of_subset hsub).elim id (λ h, absurd hcard $ not_le_of_lt $ card_lt_card h) lemma card_range_of_injective [fintype α] {f : α → β} (hf : injective f) [fintype (range f)] : fintype.card (range f) = fintype.card α := eq.symm $ fintype.card_congr $ equiv.set.range f hf lemma finite.exists_maximal_wrt [partial_order β] (f : α → β) (s : set α) (h : set.finite s) : s.nonempty → ∃a∈s, ∀a'∈s, f a ≤ f a' → f a = f a' := begin classical, refine h.induction_on _ _, { assume h, exact absurd h empty_not_nonempty }, assume a s his _ ih _, cases s.eq_empty_or_nonempty with h h, { use a, simp [h] }, rcases ih h with ⟨b, hb, ih⟩, by_cases f b ≤ f a, { refine ⟨a, set.mem_insert _ _, assume c hc hac, le_antisymm hac _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { refl }, { rwa [← ih c hcs (le_trans h hac)] } }, { refine ⟨b, set.mem_insert_of_mem _ hb, assume c hc hbc, _⟩, rcases set.mem_insert_iff.1 hc with rfl | hcs, { exact (h hbc).elim }, { exact ih c hcs hbc } } end lemma finite.card_to_finset {s : set α} [fintype s] (h : s.finite) : h.to_finset.card = fintype.card s := by { rw [← finset.card_attach, finset.attach_eq_univ, ← fintype.card], congr' 2, funext, rw set.finite.mem_to_finset } section local attribute [instance, priority 1] classical.prop_decidable lemma to_finset_inter {α : Type*} [fintype α] (s t : set α) : (s ∩ t).to_finset = s.to_finset ∩ t.to_finset := by ext; simp end section variables [semilattice_sup α] [nonempty α] {s : set α} /--A finite set is bounded above.-/ protected lemma finite.bdd_above (hs : finite s) : bdd_above s := finite.induction_on hs bdd_above_empty $ λ a s _ _ h, h.insert a /--A finite union of sets which are all bounded above is still bounded above.-/ lemma finite.bdd_above_bUnion {I : set β} {S : β → set α} (H : finite I) : (bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) := finite.induction_on H (by simp only [bUnion_empty, bdd_above_empty, ball_empty_iff]) (λ a s ha _ hs, by simp only [bUnion_insert, ball_insert_iff, bdd_above_union, hs]) end section variables [semilattice_inf α] [nonempty α] {s : set α} /--A finite set is bounded below.-/ protected lemma finite.bdd_below (hs : finite s) : bdd_below s := @finite.bdd_above (order_dual α) _ _ _ hs /--A finite union of sets which are all bounded below is still bounded below.-/ lemma finite.bdd_below_bUnion {I : set β} {S : β → set α} (H : finite I) : (bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) := @finite.bdd_above_bUnion (order_dual α) _ _ _ _ _ H end end set namespace finset /-- A finset is bounded above. -/ protected lemma bdd_above [semilattice_sup α] [nonempty α] (s : finset α) : bdd_above (↑s : set α) := s.finite_to_set.bdd_above /-- A finset is bounded below. -/ protected lemma bdd_below [semilattice_inf α] [nonempty α] (s : finset α) : bdd_below (↑s : set α) := s.finite_to_set.bdd_below end finset lemma fintype.exists_max [fintype α] [nonempty α] {β : Type*} [linear_order β] (f : α → β) : ∃ x₀ : α, ∀ x, f x ≤ f x₀ := begin rcases set.finite_univ.exists_maximal_wrt f _ univ_nonempty with ⟨x, _, hx⟩, exact ⟨x, λ y, (le_total (f x) (f y)).elim (λ h, ge_of_eq $ hx _ trivial h) id⟩ end
1a94f851ead7157eafc60d41b6a0c33ebbc2c215
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/set_theory/cardinal.lean
8b2c46c9a6d7fba2c4b753bca570d5b33f6dd7f7
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
59,292
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, Floris van Doorn -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card import data.nat.enat /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. ## Main definitions * `cardinal` the type of cardinal numbers (in a given universe). * `cardinal.mk α` or `#α` is the cardinality of `α`. The notation `#` lives in the locale `cardinal`. * There is an instance that `cardinal` forms a `canonically_ordered_comm_semiring`. * Addition `c₁ + c₂` is defined by `cardinal.add_def α β : #α + #β = #(α ⊕ β)`. * Multiplication `c₁ * c₂` is defined by `cardinal.mul_def : #α * #β = #(α * β)`. * The order `c₁ ≤ c₂` is defined by `cardinal.le_def α β : #α ≤ #β ↔ nonempty (α ↪ β)`. * Exponentiation `c₁ ^ c₂` is defined by `cardinal.power_def α β : #α ^ #β = #(β → α)`. * `cardinal.omega` or `ω` the cardinality of `ℕ`. This definition is universe polymorphic: `cardinal.omega.{u} : cardinal.{u}` (contrast with `ℕ : Type`, which lives in a specific universe). In some cases the universe level has to be given explicitly. * `cardinal.min (I : nonempty ι) (c : ι → cardinal)` is the minimal cardinal in the range of `c`. * `cardinal.succ c` is the successor cardinal, the smallest cardinal larger than `c`. * `cardinal.sum` is the sum of a collection of cardinals. * `cardinal.sup` is the supremum of a collection of cardinals. * `cardinal.powerlt c₁ c₂` or `c₁ ^< c₂` is defined as `sup_{γ < β} α^γ`. ## Main Statements * Cantor's theorem: `cardinal.cantor c : c < 2 ^ c`. * König's theorem: `cardinal.sum_lt_prod` ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. The operation `cardinal.lift` lifts cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/cardinal_ordinal.lean`. * There is an instance `has_pow cardinal`, but this will only fire if Lean already knows that both the base and the exponent live in the same universe. As a workaround, you can add ``` local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow ``` to a file. This notation will work even if Lean doesn't know yet that the base and the exponent live in the same universe (but no exponents in other types can be used). ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega, Cantor's theorem, König's theorem, Konig's theorem -/ open function set open_locale classical universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal instance can_lift_cardinal_Type : can_lift cardinal.{u} (Type u) := ⟨mk, λ c, true, λ c _, quot.induction_on c $ λ α, ⟨α, rfl⟩⟩ @[elab_as_eliminator] lemma induction_on {p : cardinal → Prop} (c : cardinal) (h : ∀ α, p (#α)) : p c := quotient.induction_on c h @[elab_as_eliminator] lemma induction_on₂ {p : cardinal → cardinal → Prop} (c₁ : cardinal) (c₂ : cardinal) (h : ∀ α β, p (#α) (#β)) : p c₁ c₂ := quotient.induction_on₂ c₁ c₂ h @[elab_as_eliminator] lemma induction_on₃ {p : cardinal → cardinal → cardinal → Prop} (c₁ : cardinal) (c₂ : cardinal) (c₃ : cardinal) (h : ∀ α β γ, p (#α) (#β) (#γ)) : p c₁ c₂ c₃ := quotient.induction_on₃ c₁ c₂ c₃ h protected lemma eq : #α = #β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (#α) := rfl @[simp] theorem mk_out (c : cardinal) : #(c.out) = c := quotient.out_eq _ /-- The representative of the cardinal of a type is equivalent ot the original type. -/ noncomputable def out_mk_equiv {α : Type v} : (#α).out ≃ α := nonempty.some $ cardinal.eq.mp (by simp) lemma mk_congr (e : α ≃ β) : # α = # β := quot.sound ⟨e⟩ alias mk_congr ← equiv.cardinal_eq /-- Lift a function between `Type*`s to a function between `cardinal`s. -/ def map (f : Type u → Type v) (hf : ∀ α β, α ≃ β → f α ≃ f β) : cardinal.{u} → cardinal.{v} := quotient.map f (λ α β ⟨e⟩, ⟨hf α β e⟩) @[simp] lemma map_mk (f : Type u → Type v) (hf : ∀ α β, α ≃ β → f α ≃ f β) (α : Type u) : map f hf (#α) = #(f α) := rfl /-- Lift a binary operation `Type* → Type* → Type*` to a binary operation on `cardinal`s. -/ def map₂ (f : Type u → Type v → Type w) (hf : ∀ α β γ δ, α ≃ β → γ ≃ δ → f α γ ≃ f β δ) : cardinal.{u} → cardinal.{v} → cardinal.{w} := quotient.map₂ f $ λ α β ⟨e₁⟩ γ δ ⟨e₂⟩, ⟨hf α β γ δ e₁ e₂⟩ /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{v} → cardinal.{max v u}` -/ def lift (c : cardinal.{v}) : cardinal.{max v u} := map ulift (λ α β e, equiv.ulift.trans $ e.trans equiv.ulift.symm) c @[simp] theorem mk_ulift (α) : #(ulift.{v u} α) = lift.{v} (#α) := rfl theorem lift_umax : lift.{(max u v) u} = lift.{v u} := funext $ λ a, induction_on a $ λ α, (equiv.ulift.trans equiv.ulift.symm).cardinal_eq theorem lift_umax' : lift.{(max v u) u} = lift.{v u} := lift_umax theorem lift_id' (a : cardinal.{max u v}) : lift.{u} a = a := induction_on a $ λ α, mk_congr equiv.ulift @[simp] theorem lift_id (a : cardinal) : lift.{u u} a = a := lift_id'.{u u} a @[simp] theorem lift_uzero (a : cardinal.{u}) : lift.{0} a = a := lift_id'.{0 u} a @[simp] theorem lift_lift (a : cardinal) : lift.{w} (lift.{v} a) = lift.{(max v w)} a := induction_on a $ λ α, (equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm).cardinal_eq /-- We define the order on cardinal numbers by `#α ≤ #β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem le_def (α β : Type u) : #α ≤ #β ↔ nonempty (α ↪ β) := iff.rfl theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : #α ≤ #β := ⟨⟨f, hf⟩⟩ theorem _root_.function.embedding.cardinal_le {α β : Type u} (f : α ↪ β) : #α ≤ #β := ⟨f⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : #β ≤ #α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ #α ↔ ∃ p : set α, #p = c := ⟨induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, (equiv.of_injective f hf).cardinal_eq.symm⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } instance : preorder cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩ } instance : partial_order cardinal.{u} := { le_antisymm := by { rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩, exact quotient.sound (e₁.antisymm e₂) }, .. cardinal.preorder } theorem lift_mk_le {α : Type u} {β : Type v} : lift.{(max v w)} (#α) ≤ lift.{(max u w)} (#β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ /-- A variant of `cardinal.lift_mk_le` with specialized universes. Because Lean often can not realize it should use this specialization itself, we provide this statement separately so you don't have to solve the specialization problem either. -/ theorem lift_mk_le' {α : Type u} {β : Type v} : lift.{v} (#α) ≤ lift.{u} (#β) ↔ nonempty (α ↪ β) := lift_mk_le.{u v 0} theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{(max v w)} (#α) = lift.{(max u w)} (#β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ /-- A variant of `cardinal.lift_mk_eq` with specialized universes. Because Lean often can not realize it should use this specialization itself, we provide this statement separately so you don't have to solve the specialization problem either. -/ theorem lift_mk_eq' {α : Type u} {β : Type v} : lift.{v} (#α) = lift.{u} (#β) ↔ nonempty (α ≃ β) := lift_mk_eq.{u v 0} @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := induction_on₂ a b $ λ α β, by { rw ← lift_umax, exact lift_mk_le } /-- `cardinal.lift` as an `order_embedding`. -/ @[simps { fully_applied := ff }] def lift_order_embedding : cardinal.{v} ↪o cardinal.{max v u} := order_embedding.of_map_le_iff lift (λ _ _, lift_le) @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := lift_order_embedding.injective.eq_iff @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := lift_order_embedding.lt_iff_lt instance : has_zero cardinal.{u} := ⟨#pempty⟩ instance : inhabited cardinal.{u} := ⟨0⟩ @[simp] lemma mk_eq_zero (α : Type u) [is_empty α] : #α = 0 := (equiv.equiv_pempty α).cardinal_eq @[simp] theorem lift_zero : lift 0 = 0 := mk_congr (equiv.equiv_pempty _) lemma mk_eq_zero_iff {α : Type u} : #α = 0 ↔ is_empty α := ⟨λ e, let ⟨h⟩ := quotient.exact e in h.is_empty, @mk_eq_zero α⟩ theorem mk_ne_zero_iff {α : Type u} : #α ≠ 0 ↔ nonempty α := (not_iff_not.2 mk_eq_zero_iff).trans not_is_empty_iff @[simp] lemma mk_ne_zero (α : Type u) [nonempty α] : #α ≠ 0 := mk_ne_zero_iff.2 ‹_› instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nontrivial cardinal.{u} := ⟨⟨1, 0, mk_ne_zero _⟩⟩ @[simp] lemma mk_eq_one (α : Type u) [unique α] : #α = 1 := mk_congr equiv_punit_of_unique theorem le_one_iff_subsingleton {α : Type u} : #α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨map₂ sum $ λ α β γ δ, equiv.sum_congr⟩ theorem add_def (α β : Type u) : #α + #β = #(α ⊕ β) := rfl @[simp] lemma mk_sum (α : Type u) (β : Type v) : #(α ⊕ β) = lift.{v u} (#α) + lift.{u v} (#β) := mk_congr ((equiv.ulift).symm.sum_congr (equiv.ulift).symm) @[simp] theorem mk_option {α : Type u} : #(option α) = #α + 1 := (equiv.option_equiv_sum_punit α).cardinal_eq @[simp] lemma mk_psum (α : Type u) (β : Type v) : #(psum α β) = lift.{v} (#α) + lift.{u} (#β) := (mk_congr (equiv.psum_equiv_sum α β)).trans (mk_sum α β) instance : has_mul cardinal.{u} := ⟨map₂ prod $ λ α β γ δ, equiv.prod_congr⟩ theorem mul_def (α β : Type u) : #α * #β = #(α × β) := rfl @[simp] lemma mk_prod (α : Type u) (β : Type v) : #(α × β) = lift.{v u} (#α) * lift.{u v} (#β) := mk_congr (equiv.ulift.symm.prod_congr (equiv.ulift).symm) protected theorem add_comm (a b : cardinal.{u}) : a + b = b + a := induction_on₂ a b $ λ α β, mk_congr (equiv.sum_comm α β) protected theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := induction_on₂ a b $ λ α β, mk_congr (equiv.prod_comm α β) protected theorem zero_add (a : cardinal.{u}) : 0 + a = a := induction_on a $ λ α, mk_congr (equiv.empty_sum pempty α) protected theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := induction_on a $ λ α, mk_congr (equiv.pempty_prod α) protected theorem one_mul (a : cardinal.{u}) : 1 * a = a := induction_on a $ λ α, mk_congr (equiv.punit_prod α) protected theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := induction_on₃ a b c $ λ α β γ, mk_congr (equiv.prod_sum_distrib α β γ) protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : cardinal.{u}} : a * b = 0 → a = 0 ∨ b = 0 := begin induction a using cardinal.induction_on with α, induction b using cardinal.induction_on with β, simp only [mul_def, mk_eq_zero_iff, is_empty_prod], exact id end /-- The cardinal exponential. `#α ^ #β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := map₂ (λ α β : Type u, β → α) (λ α β γ δ e₁ e₂, e₂.arrow_congr e₁) a b instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow local infixr ` ^ℕ `:80 := @has_pow.pow cardinal ℕ monoid.has_pow theorem power_def (α β) : #α ^ #β = #(β → α) := rfl theorem mk_arrow (α : Type u) (β : Type v) : #(α → β) = lift.{u} (#β) ^ lift.{v} (#α) := mk_congr (equiv.ulift.symm.arrow_congr equiv.ulift.symm) @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := induction_on₂ a b $ λ α β, mk_congr (equiv.ulift.trans (equiv.ulift.arrow_congr equiv.ulift).symm) @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := induction_on a $ assume α, (equiv.pempty_arrow_equiv_punit α).cardinal_eq @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := induction_on a $ assume α, (equiv.punit_arrow_equiv α).cardinal_eq theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := induction_on₃ a b c $ assume α β γ, (equiv.sum_arrow_equiv_prod_arrow β γ α).cardinal_eq instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := cardinal.zero_add, add_zero := assume a, by rw [cardinal.add_comm a 0, cardinal.zero_add a], add_assoc := λa b c, induction_on₃ a b c $ assume α β γ, mk_congr (equiv.sum_assoc α β γ), add_comm := cardinal.add_comm, zero_mul := cardinal.zero_mul, mul_zero := assume a, by rw [cardinal.mul_comm a 0, cardinal.zero_mul a], one_mul := cardinal.one_mul, mul_one := assume a, by rw [cardinal.mul_comm a 1, cardinal.one_mul a], mul_assoc := λa b c, induction_on₃ a b c $ assume α β γ, mk_congr (equiv.prod_assoc α β γ), mul_comm := cardinal.mul_comm, left_distrib := cardinal.left_distrib, right_distrib := assume a b c, by rw [cardinal.mul_comm (a + b) c, cardinal.left_distrib c a b, cardinal.mul_comm c a, cardinal.mul_comm c b], npow := λ n c, c ^ n, npow_zero' := @power_zero, npow_succ' := λ n c, by rw [nat.cast_succ, power_add, power_one, cardinal.mul_comm] } @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := induction_on a $ assume α, (equiv.arrow_punit_equiv_punit α).cardinal_eq @[simp] theorem mk_bool : #bool = 2 := mk_congr equiv.bool_equiv_punit_sum_punit @[simp] theorem mk_Prop : #(Prop) = 2 := equiv.Prop_equiv_bool.cardinal_eq.trans mk_bool @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := induction_on a $ assume α heq, mk_eq_zero_iff.2 $ is_empty_pi.2 $ let ⟨a⟩ := mk_ne_zero_iff.1 heq in ⟨a, pempty.is_empty⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := induction_on₂ a b $ λ α β h, let ⟨a⟩ := mk_ne_zero_iff.1 h in mk_ne_zero_iff.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := induction_on₃ a b c $ assume α β γ, (equiv.arrow_prod_equiv_prod_arrow α β γ).cardinal_eq theorem power_mul {a b c : cardinal} : a ^ (b * c) = (a ^ b) ^ c := by rw [mul_comm b c]; from (induction_on₃ a b c $ assume α β γ, mk_congr (equiv.curry γ β α)) @[simp] lemma pow_cast_right (κ : cardinal.{u}) (n : ℕ) : (κ ^ (↑n : cardinal.{u})) = κ ^ℕ n := rfl @[simp] theorem lift_one : lift 1 = 1 := mk_congr (equiv.ulift.trans equiv.punit_equiv_punit) @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := induction_on₂ a b $ λ α β, mk_congr (equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm) @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := induction_on₂ a b $ λ α β, mk_congr (equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm) @[simp] theorem lift_bit0 (a : cardinal) : lift (bit0 a) = bit0 (lift a) := lift_add a a @[simp] theorem lift_bit1 (a : cardinal) : lift (bit1 a) = bit1 (lift a) := by simp [bit1] theorem lift_two : lift.{u v} 2 = 2 := by simp @[simp] theorem mk_set {α : Type u} : #(set α) = 2 ^ #α := by simp [set, mk_arrow] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp section order_properties open sum protected theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_is_empty⟩ protected theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩ protected theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := cardinal.add_le_add (le_refl _) protected theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from (equiv.sum_congr (equiv.of_injective f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨#↥(range f)ᶜ, mk_congr this.symm⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ cardinal.add_le_add_left _ (cardinal.zero_le _)⟩ instance : order_bot cardinal.{u} := { bot := 0, bot_le := cardinal.zero_le, ..cardinal.partial_order } instance : canonically_ordered_comm_semiring cardinal.{u} := { add_le_add_left := λ a b h c, cardinal.add_le_add_left _ h, le_iff_exists_add := @cardinal.le_iff_exists_add, eq_zero_or_eq_zero_of_mul_eq_zero := @cardinal.eq_zero_or_eq_zero_of_mul_eq_zero, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.partial_order } @[simp] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := mk_ne_zero_iff.1 hα in ⟨@embedding.arrow_congr_left _ _ _ ⟨a⟩ e⟩ /-- **Cantor's theorem** -/ theorem cantor (a : cardinal.{u}) : a < 2 ^ a := begin induction a using cardinal.induction_on with α, rw [← mk_set], refine ⟨⟨⟨singleton, λ a b, singleton_eq_singleton_iff.1⟩⟩, _⟩, rintro ⟨⟨f, hf⟩⟩, exact cantor_injective f hf end instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.partial_order } noncomputable instance : linear_order cardinal.{u} := { le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total, decidable_le := classical.dec_rel _, .. cardinal.partial_order } noncomputable instance : canonically_linear_ordered_add_monoid cardinal.{u} := { .. (infer_instance : canonically_ordered_add_monoid cardinal.{u}), .. cardinal.linear_order } -- short-circuit type class inference noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance theorem one_lt_iff_nontrivial {α : Type u} : 1 < #α ↔ nontrivial α := by rw [← not_le, le_one_iff_subsingleton, ← not_nontrivial_iff_subsingleton, not_not] theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_right e⟩ end order_properties /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.min_injective _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.min_injective _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ @[simp] theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal.{u}) : c + 1 ≤ succ c := begin refine le_min.2 (λ b, _), rcases ⟨b, c⟩ with ⟨⟨⟨β⟩, hlt⟩, ⟨γ⟩⟩, cases hlt.le with f, have : ¬ surjective f := λ hn, hlt.not_le (mk_le_of_surjective hn), simp only [surjective, not_forall] at this, rcases this with ⟨b, hb⟩, calc #γ + 1 = #(option γ) : mk_option.symm ... ≤ #β : (f.option_elim b hb).cardinal_le end lemma succ_pos (c : cardinal) : 0 < succ c := by simp lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := (succ_pos _).ne' /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem mk_sigma {ι} (f : ι → Type*) : #(Σ i, f i) = sum (λ i, #(f i)) := mk_congr $ equiv.sigma_congr_right $ λ i, out_mk_equiv.symm @[simp] theorem sum_const (ι : Type u) (a : cardinal.{v}) : sum (λ i : ι, a) = lift.{v} (#ι) * lift.{u} a := induction_on a $ λ α, mk_congr $ calc (Σ i : ι, quotient.out (#α)) ≃ ι × quotient.out (#α) : equiv.sigma_equiv_prod _ _ ... ≃ ulift ι × ulift α : equiv.ulift.symm.prod_congr (out_mk_equiv.trans equiv.ulift.symm) theorem sum_const' (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = #ι * a := by simp theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨(embedding.refl _).sigma_map $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ #ι * sup.{u u} f := by rw ← sum_const'; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} [is_empty ι] : sup f = 0 := by { rw [← nonpos_iff_eq_zero, sup_le], exact is_empty_elim } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := #(Π i, (f i).out) @[simp] theorem mk_pi {ι : Type u} (α : ι → Type v) : #(Π i, α i) = prod (λ i, #(α i)) := mk_congr $ equiv.Pi_congr_right $ λ i, out_mk_equiv.symm @[simp] theorem prod_const (ι : Type u) (a : cardinal.{v}) : prod (λ i : ι, a) = lift.{u} a ^ lift.{v} (#ι) := induction_on a $ λ α, mk_congr $ equiv.Pi_congr equiv.ulift.symm $ λ i, out_mk_equiv.trans equiv.ulift.symm theorem prod_const' (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ #ι := induction_on a $ λ α, (mk_pi _).symm theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ @[simp] theorem prod_eq_zero {ι} (f : ι → cardinal.{u}) : prod f = 0 ↔ ∃ i, f i = 0 := by { lift f to ι → Type u using λ _, trivial, simp only [mk_eq_zero_iff, ← mk_pi, is_empty_pi] } theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := by simp [prod_eq_zero] @[simp] theorem lift_prod {ι : Type u} (c : ι → cardinal.{v}) : lift.{w} (prod c) = prod (λ i, lift.{w} (c i)) := begin lift c to ι → Type v using λ _, trivial, simp only [← mk_pi, ← mk_ulift], exact mk_congr (equiv.ulift.trans $ equiv.Pi_congr_right $ λ i, equiv.ulift.symm) end @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := induction_on₂ a b $ λ α β, by rw [← lift_id (#β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨#(set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{(max v w)} a = lift.{(max u w)} b ↔ lift.{v} a = lift.{u} b := calc lift.{(max v w)} a = lift.{(max u w)} b ↔ lift.{w} (lift.{v} a) = lift.{w} (lift.{u} b) : by simp ... ↔ lift.{v} a = lift.{u} b : lift_inj protected lemma le_sup_iff {ι : Type v} {f : ι → cardinal.{max v w}} {c : cardinal} : (c ≤ sup f) ↔ (∀ b, (∀ i, f i ≤ b) → c ≤ b) := ⟨λ h b hb, le_trans h (sup_le.mpr hb), λ h, h _ $ λ i, le_sup f i⟩ /-- The lift of a supremum is the supremum of the lifts. -/ lemma lift_sup {ι : Type v} (f : ι → cardinal.{max v w}) : lift.{u} (sup.{v w} f) = sup.{v (max u w)} (λ i : ι, lift.{u} (f i)) := begin apply le_antisymm, { rw [cardinal.le_sup_iff], intros c hc, by_contra h, obtain ⟨d, rfl⟩ := cardinal.lift_down (not_le.mp h).le, simp only [lift_le, sup_le] at h hc, exact h hc }, { simp only [cardinal.sup_le, lift_le, le_sup, implies_true_iff] } end /-- To prove that the lift of a supremum is bounded by some cardinal `t`, it suffices to show that the lift of each cardinal is bounded by `t`. -/ lemma lift_sup_le {ι : Type v} (f : ι → cardinal.{max v w}) (t : cardinal.{max u v w}) (w : ∀ i, lift.{u} (f i) ≤ t) : lift.{u} (sup f) ≤ t := by { rw lift_sup, exact sup_le.mpr w, } @[simp] lemma lift_sup_le_iff {ι : Type v} (f : ι → cardinal.{max v w}) (t : cardinal.{max u v w}) : lift.{u} (sup f) ≤ t ↔ ∀ i, lift.{u} (f i) ≤ t := ⟨λ h i, (lift_le.mpr (le_sup f i)).trans h, λ h, lift_sup_le f t h⟩ universes v' w' /-- To prove an inequality between the lifts to a common universe of two different supremums, it suffices to show that the lift of each cardinal from the smaller supremum if bounded by the lift of some cardinal from the larger supremum. -/ lemma lift_sup_le_lift_sup {ι : Type v} {ι' : Type v'} (f : ι → cardinal.{max v w}) (f' : ι' → cardinal.{max v' w'}) (g : ι → ι') (h : ∀ i, lift.{(max v' w')} (f i) ≤ lift.{(max v w)} (f' (g i))) : lift.{(max v' w')} (sup f) ≤ lift.{(max v w)} (sup f') := begin apply lift_sup_le.{(max v' w')} f, intro i, apply le_trans (h i), simp only [lift_le], apply le_sup, end /-- A variant of `lift_sup_le_lift_sup` with universes specialized via `w = v` and `w' = v'`. This is sometimes necessary to avoid universe unification issues. -/ lemma lift_sup_le_lift_sup' {ι : Type v} {ι' : Type v'} (f : ι → cardinal.{v}) (f' : ι' → cardinal.{v'}) (g : ι → ι') (h : ∀ i, lift.{v'} (f i) ≤ lift.{v} (f' (g i))) : lift.{v'} (sup.{v v} f) ≤ lift.{v} (sup.{v' v'} f') := lift_sup_le_lift_sup f f' g h /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (#ℕ) localized "notation `ω` := cardinal.omega" in cardinal lemma mk_nat : #ℕ = ω := (lift_id _).symm theorem omega_ne_zero : ω ≠ 0 := mk_ne_zero _ theorem omega_pos : 0 < ω := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift ω = ω := lift_lift _ @[simp] theorem omega_le_lift {c : cardinal.{u}} : ω ≤ lift.{v} c ↔ ω ≤ c := by rw [← lift_omega, lift_le] @[simp] theorem lift_le_omega {c : cardinal.{u}} : lift.{v} c ≤ ω ↔ c ≤ ω := by rw [← lift_omega, lift_le] /- properties about the cast from nat -/ @[simp] theorem mk_fin : ∀ (n : ℕ), #(fin n) = n | 0 := mk_eq_zero _ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (#(fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : #α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (#α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ #α := begin rw (_ : (s.card : cardinal) = #s), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [pow_succ', power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, by simpa only [fintype.card_fin] using fintype.card_le_of_injective f hf, λ h, ⟨(fin.cast_le h).to_embedding⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] instance : char_zero cardinal := ⟨strict_mono.injective $ λ m n, nat_cast_lt.2⟩ theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := nat.cast_inj lemma nat_cast_injective : injective (coe : ℕ → cardinal) := nat.cast_injective @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) : # α ≤ n := begin refine lt_succ.1 (lt_of_not_ge $ λ hn, _), rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn, cases hn with f, refine not_lt_of_le (H $ finset.univ.map f) _, rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin], exact n.lt_succ_self end theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < ω := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨coe, λ a b, fin.ext⟩⟩ @[simp] theorem one_lt_omega : 1 < ω := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < ω ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, contrapose! h', haveI := infinite.to_subtype h', exact ⟨infinite.nat_embedding S⟩ end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : ω ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : #α < ω ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : #S < ω ↔ finite S := lt_omega_iff_fintype.trans finite_def.symm instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < ω, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < ω) (hb : b < ω) : a + b < ω := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < ω ↔ a < ω ∧ b < ω := ⟨λ h, ⟨lt_of_le_of_lt (self_le_add_right _ _) h, lt_of_le_of_lt (self_le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ lemma omega_le_add_iff {a b : cardinal} : ω ≤ a + b ↔ ω ≤ a ∨ ω ≤ b := by simp only [← not_lt, add_lt_omega_iff, not_and_distrib] theorem mul_lt_omega {a b : cardinal} (ha : a < ω) (hb : b < ω) : a * b < ω := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < ω ↔ a = 0 ∨ b = 0 ∨ a < ω ∧ b < ω := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (mul_le_mul' (le_refl a) hb) h }, { rw [← one_mul b], refine lt_of_le_of_lt (mul_le_mul' ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < ω ↔ a < ω ∧ b < ω := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < ω) (hb : b < ω) : a ^ b < ω := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_unique {α : Type*} : #α = 1 ↔ subsingleton α ∧ nonempty α := calc #α = 1 ↔ #α ≤ 1 ∧ ¬#α < 1 : eq_iff_le_not_lt ... ↔ subsingleton α ∧ nonempty α : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, mk_ne_zero_iff] end theorem infinite_iff {α : Type u} : infinite α ↔ ω ≤ #α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_iff, is_empty_fintype] @[simp] lemma omega_le_mk (α : Type u) [infinite α] : ω ≤ #α := infinite_iff.1 ‹_› lemma encodable_iff {α : Type u} : nonempty (encodable α) ↔ #α ≤ ω := ⟨λ ⟨h⟩, ⟨(@encodable.encode' α h).trans equiv.ulift.symm.to_embedding⟩, λ ⟨h⟩, ⟨encodable.of_inj _ (h.trans equiv.ulift.to_embedding).injective⟩⟩ @[simp] lemma mk_le_omega [encodable α] : #α ≤ ω := encodable_iff.1 ⟨‹_›⟩ lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ #α = ω := ⟨λ ⟨h⟩, mk_congr ((@denumerable.eqv α h).trans equiv.ulift.symm), λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ @[simp] lemma mk_denumerable (α : Type u) [denumerable α] : #α = ω := denumerable_iff.1 ⟨‹_›⟩ @[simp] lemma mk_set_le_omega (s : set α) : #s ≤ ω ↔ countable s := begin rw [countable_iff_exists_injective], split, { rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ }, { rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩ } end @[simp] lemma omega_add_omega : ω + ω = ω := mk_denumerable _ lemma omega_mul_omega : ω * ω = ω := mk_denumerable _ @[simp] lemma add_le_omega {c₁ c₂ : cardinal} : c₁ + c₂ ≤ ω ↔ c₁ ≤ ω ∧ c₂ ≤ ω := ⟨λ h, ⟨le_self_add.trans h, le_add_self.trans h⟩, λ h, omega_add_omega ▸ add_le_add h.1 h.2⟩ /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to 0. -/ noncomputable def to_nat : zero_hom cardinal ℕ := ⟨λ c, if h : c < omega.{v} then classical.some (lt_omega.1 h) else 0, begin have h : 0 < ω := nat_lt_omega 0, rw [dif_pos h, ← cardinal.nat_cast_inj, ← classical.some_spec (lt_omega.1 h), nat.cast_zero], end⟩ lemma to_nat_apply_of_lt_omega {c : cardinal} (h : c < ω) : c.to_nat = classical.some (lt_omega.1 h) := dif_pos h @[simp] lemma to_nat_apply_of_omega_le {c : cardinal} (h : ω ≤ c) : c.to_nat = 0 := dif_neg (not_lt_of_le h) @[simp] lemma cast_to_nat_of_lt_omega {c : cardinal} (h : c < ω) : ↑c.to_nat = c := by rw [to_nat_apply_of_lt_omega h, ← classical.some_spec (lt_omega.1 h)] @[simp] lemma cast_to_nat_of_omega_le {c : cardinal} (h : ω ≤ c) : ↑c.to_nat = (0 : cardinal) := by rw [to_nat_apply_of_omega_le h, nat.cast_zero] @[simp] lemma to_nat_cast (n : ℕ) : cardinal.to_nat n = n := begin rw [to_nat_apply_of_lt_omega (nat_lt_omega n), ← nat_cast_inj], exact (classical.some_spec (lt_omega.1 (nat_lt_omega n))).symm, end /-- `to_nat` has a right-inverse: coercion. -/ lemma to_nat_right_inverse : function.right_inverse (coe : ℕ → cardinal) to_nat := to_nat_cast lemma to_nat_surjective : surjective to_nat := to_nat_right_inverse.surjective @[simp] lemma mk_to_nat_of_infinite [h : infinite α] : (#α).to_nat = 0 := dif_neg (not_lt_of_le (infinite_iff.1 h)) @[simp] lemma mk_to_nat_eq_card [fintype α] : (#α).to_nat = fintype.card α := by simp [fintype_card] @[simp] lemma zero_to_nat : to_nat 0 = 0 := by rw [← to_nat_cast 0, nat.cast_zero] @[simp] lemma one_to_nat : to_nat 1 = 1 := by rw [← to_nat_cast 1, nat.cast_one] @[simp] lemma to_nat_eq_one {c : cardinal} : to_nat c = 1 ↔ c = 1 := ⟨λ h, (cast_to_nat_of_lt_omega (lt_of_not_ge (one_ne_zero ∘ h.symm.trans ∘ to_nat_apply_of_omega_le))).symm.trans ((congr_arg coe h).trans nat.cast_one), λ h, (congr_arg to_nat h).trans one_to_nat⟩ lemma to_nat_eq_one_iff_unique {α : Type*} : (#α).to_nat = 1 ↔ subsingleton α ∧ nonempty α := to_nat_eq_one.trans eq_one_iff_unique @[simp] lemma to_nat_lift (c : cardinal.{v}) : (lift.{u v} c).to_nat = c.to_nat := begin apply nat_cast_injective, cases lt_or_ge c ω with hc hc, { rw [cast_to_nat_of_lt_omega, ←lift_nat_cast, cast_to_nat_of_lt_omega hc], rwa [←lift_omega, lift_lt] }, { rw [cast_to_nat_of_omega_le, ←lift_nat_cast, cast_to_nat_of_omega_le hc, lift_zero], rwa [←lift_omega, lift_le] }, end lemma to_nat_congr {β : Type v} (e : α ≃ β) : (#α).to_nat = (#β).to_nat := by rw [←to_nat_lift, lift_mk_eq.mpr ⟨e⟩, to_nat_lift] @[simp] lemma to_nat_mul (x y : cardinal) : (x * y).to_nat = x.to_nat * y.to_nat := begin by_cases hx1 : x = 0, { rw [comm_semiring.mul_comm, hx1, mul_zero, zero_to_nat, nat.zero_mul] }, by_cases hy1 : y = 0, { rw [hy1, zero_to_nat, mul_zero, mul_zero, zero_to_nat] }, refine nat_cast_injective (eq.trans _ (nat.cast_mul _ _).symm), cases lt_or_ge x ω with hx2 hx2, { cases lt_or_ge y ω with hy2 hy2, { rw [cast_to_nat_of_lt_omega, cast_to_nat_of_lt_omega hx2, cast_to_nat_of_lt_omega hy2], exact mul_lt_omega hx2 hy2 }, { rw [cast_to_nat_of_omega_le hy2, mul_zero, cast_to_nat_of_omega_le], exact not_lt.mp (mt (mul_lt_omega_iff_of_ne_zero hx1 hy1).mp (λ h, not_lt.mpr hy2 h.2)) } }, { rw [cast_to_nat_of_omega_le hx2, zero_mul, cast_to_nat_of_omega_le], exact not_lt.mp (mt (mul_lt_omega_iff_of_ne_zero hx1 hy1).mp (λ h, not_lt.mpr hx2 h.1)) }, end @[simp] lemma to_nat_add_of_lt_omega {a : cardinal.{u}} {b : cardinal.{v}} (ha : a < ω) (hb : b < ω) : ((lift.{v u} a) + (lift.{u v} b)).to_nat = a.to_nat + b.to_nat := begin apply cardinal.nat_cast_injective, replace ha : (lift.{v u} a) < ω := by { rw [← lift_omega], exact lift_lt.2 ha }, replace hb : (lift.{u v} b) < ω := by { rw [← lift_omega], exact lift_lt.2 hb }, rw [nat.cast_add, ← to_nat_lift.{v u} a, ← to_nat_lift.{u v} b, cast_to_nat_of_lt_omega ha, cast_to_nat_of_lt_omega hb, cast_to_nat_of_lt_omega (add_lt_omega ha hb)] end /-- This function sends finite cardinals to the corresponding natural, and infinite cardinals to `⊤`. -/ noncomputable def to_enat : cardinal →+ enat := { to_fun := λ c, if c < omega.{v} then c.to_nat else ⊤, map_zero' := by simp [if_pos (lt_trans zero_lt_one one_lt_omega)], map_add' := λ x y, begin by_cases hx : x < ω, { obtain ⟨x0, rfl⟩ := lt_omega.1 hx, by_cases hy : y < ω, { obtain ⟨y0, rfl⟩ := lt_omega.1 hy, simp only [add_lt_omega hx hy, hx, hy, to_nat_cast, if_true], rw [← nat.cast_add, to_nat_cast, nat.cast_add] }, { rw [if_neg hy, if_neg, enat.add_top], contrapose! hy, apply lt_of_le_of_lt le_add_self hy } }, { rw [if_neg hx, if_neg, enat.top_add], contrapose! hx, apply lt_of_le_of_lt le_self_add hx }, end } @[simp] lemma to_enat_apply_of_lt_omega {c : cardinal} (h : c < ω) : c.to_enat = c.to_nat := if_pos h @[simp] lemma to_enat_apply_of_omega_le {c : cardinal} (h : ω ≤ c) : c.to_enat = ⊤ := if_neg (not_lt_of_le h) @[simp] lemma to_enat_cast (n : ℕ) : cardinal.to_enat n = n := by rw [to_enat_apply_of_lt_omega (nat_lt_omega n), to_nat_cast] @[simp] lemma mk_to_enat_of_infinite [h : infinite α] : (#α).to_enat = ⊤ := to_enat_apply_of_omega_le (infinite_iff.1 h) lemma to_enat_surjective : surjective to_enat := begin intro x, exact enat.cases_on x ⟨ω, to_enat_apply_of_omega_le (le_refl ω)⟩ (λ n, ⟨n, to_enat_cast n⟩), end @[simp] lemma mk_to_enat_eq_coe_card [fintype α] : (#α).to_enat = fintype.card α := by simp [fintype_card] lemma mk_int : #ℤ = ω := mk_denumerable ℤ lemma mk_pnat : #ℕ+ = ω := mk_denumerable ℕ+ lemma two_le_iff : (2 : cardinal) ≤ #α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ #α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- **König's theorem** -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin haveI : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ mk_ne_zero_iff.1 _⟩, rw mk_out, exact (H i).ne_bot }, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : #empty = 0 := mk_eq_zero _ @[simp] theorem mk_pempty : #pempty = 0 := mk_eq_zero _ @[simp] theorem mk_punit : #punit = 1 := mk_eq_one punit theorem mk_unit : #unit = 1 := mk_punit @[simp] theorem mk_singleton {α : Type u} (x : α) : #({x} : set α) = 1 := mk_eq_one _ @[simp] theorem mk_plift_true : #(plift true) = 1 := mk_eq_one _ @[simp] theorem mk_plift_false : #(plift false) = 0 := mk_eq_zero _ @[simp] theorem mk_vector (α : Type u) (n : ℕ) : #(vector α n) = (#α) ^ℕ n := (mk_congr (equiv.vector_equiv_fin α n)).trans $ by simp theorem mk_list_eq_sum_pow (α : Type u) : #(list α) = sum (λ n : ℕ, (#α) ^ℕ n) := calc #(list α) = #(Σ n, vector α n) : mk_congr (equiv.sigma_preimage_equiv list.length).symm ... = sum (λ n : ℕ, (#α) ^ℕ n) : by simp theorem mk_quot_le {α : Type u} {r : α → α → Prop} : #(quot r) ≤ #α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : #(quotient s) ≤ #α := mk_quot_le theorem mk_subtype_le {α : Type u} (p : α → Prop) : #(subtype p) ≤ #α := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : #(subtype p) ≤ #(subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : #(∅ : set α) = 0 := mk_eq_zero _ lemma mk_emptyc_iff {α : Type u} {s : set α} : #s = 0 ↔ s = ∅ := begin split, { intro h, rw mk_eq_zero_iff at h, exact eq_empty_iff_forall_not_mem.2 (λ x hx, h.elim' ⟨x, hx⟩) }, { rintro rfl, exact mk_emptyc _ } end @[simp] theorem mk_univ {α : Type u} : #(@univ α) = #α := mk_congr (equiv.set.univ α) theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : #(f '' s) ≤ #s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{u} (#(f '' s)) ≤ lift.{v} (#s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : #(range f) ≤ #α := mk_le_of_surjective surjective_onto_range theorem mk_range_le_lift {α : Type u} {β : Type v} {f : α → β} : lift.{u} (#(range f)) ≤ lift.{v} (#α) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_range⟩ lemma mk_range_eq (f : α → β) (h : injective f) : #(range f) = #α := mk_congr ((equiv.of_injective f h).symm) lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{u} (#(range f)) = lift.{v} (#α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.of_injective f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{(max u w)} (# (range f)) = lift.{(max v w)} (# α) := lift_mk_eq.mpr ⟨(equiv.of_injective f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : #(f '' s) = #s := mk_congr ((equiv.set.image f s hf).symm) theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : #(⋃ i, f i) ≤ sum (λ i, #(f i)) := calc #(⋃ i, f i) ≤ #(Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, #(f i)) : mk_sigma _ theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : #(⋃ i, f i) = sum (λ i, #(f i)) := calc #(⋃ i, f i) = #(Σ i, f i) : mk_congr (set.Union_eq_sigma_of_disjoint h) ... = sum (λi, #(f i)) : mk_sigma _ lemma mk_Union_le {α ι : Type u} (f : ι → set α) : #(⋃ i, f i) ≤ #ι * cardinal.sup.{u u} (λ i, #(f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : #(⋃₀ A) ≤ #A * cardinal.sup.{u u} (λ s : A, #s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : #(⋃(x ∈ s), A x) ≤ #s * cardinal.sup.{u u} (λ x : s, #(A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = #s := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : #(↑s : set α) < ω := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_eq_nat_iff_finset {α} {s : set α} {n : ℕ} : #s = n ↔ ∃ t : finset α, (t : set α) = s ∧ t.card = n := begin split, { intro h, have : # s < omega, by { rw h, exact nat_lt_omega n }, refine ⟨(lt_omega_iff_finite.1 this).to_finset, finite.coe_to_finset _, nat_cast_inj.1 _⟩, rwa [finset_card, finite.coe_sort_to_finset] }, { rintro ⟨t, rfl, rfl⟩, exact finset_card.symm } end theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : #(S ∪ T : set α) + #(S ∩ T : set α) = #S + #T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ lemma mk_union_le {α : Type u} (S T : set α) : #(S ∪ T : set α) ≤ #S + #T := @mk_union_add_mk_inter α S T ▸ self_le_add_right (#(S ∪ T : set α)) (#(S ∩ T : set α)) theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : #(S ∪ T : set α) = #S + #T := quot.sound ⟨equiv.set.union H⟩ theorem mk_insert {α : Type u} {s : set α} {a : α} (h : a ∉ s) : #(insert a s : set α) = #s + 1 := by { rw [← union_singleton, mk_union_of_disjoint, mk_singleton], simpa } lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α := mk_congr (equiv.set.sum_compl s) lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : #s ≤ #t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : #{x // p x} ≤ #{x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set α) : #s ≤ #α := mk_subtype_le s lemma mk_union_le_omega {α} {P Q : set α} : #((P ∪ Q : set α)) ≤ ω ↔ #P ≤ ω ∧ #Q ≤ ω := by simp lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{u} (#(f '' s)) = lift.{v} (#s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{u} (#(f '' s)) = lift.{v} (#s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : #(f '' s) = #s := mk_congr ((equiv.set.image_of_inj_on f s h).symm) lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : #{a : α // p (e a)} = #{b : β // p b} := mk_congr (equiv.subtype_equiv_of_subtype e) lemma mk_sep (s : set α) (t : α → Prop) : #({ x ∈ s | t x } : set α) = #{ x : s | t x.1 } := mk_congr (equiv.set.sep s t) lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{v} (#(f ⁻¹' s)) ≤ lift.{u} (#s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{u} (#s) ≤ lift.{v} (#(f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{v} (#(f ⁻¹' s)) = lift.{u} (#s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : #(f ⁻¹' s) ≤ #s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : #s ≤ #(f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : #(f ⁻¹' s) = #s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{u} (#t) ≤ lift.{v} (#({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : #t ≤ #({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ #s ↔ ∃ p : set α, p ⊆ s ∧ #p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // #s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // #s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // #s < c'}), #s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : #↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := begin convert sup_eq_zero, exact subtype.is_empty_of_false (λ x, (zero_le _).not_lt), end end cardinal
0c15eccf44cf93c7f68b5a6099d5fce1f35a26a1
1a61aba1b67cddccce19532a9596efe44be4285f
/library/data/nat/gcd.lean
f3e07ca5ce2fb21366d407abd524af80cd508a4c
[ "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
15,555
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 Definitions and properties of gcd, lcm, and coprime. -/ import .div open eq.ops well_founded decidable prod namespace nat /- gcd -/ private definition pair_nat.lt : nat × nat → nat × nat → Prop := measure pr₂ private definition pair_nat.lt.wf : well_founded pair_nat.lt := intro_k (measure.wf pr₂) 20 -- we use intro_k to be able to execute gcd efficiently in the kernel local attribute pair_nat.lt.wf [instance] -- instance will not be saved in .olean local infixl `≺`:50 := pair_nat.lt private definition gcd.lt.dec (x y₁ : nat) : (succ y₁, x mod succ y₁) ≺ (x, succ y₁) := !mod_lt (succ_pos y₁) definition gcd.F : Π (p₁ : nat × nat), (Π p₂ : nat × nat, p₂ ≺ p₁ → nat) → nat | (x, 0) f := x | (x, succ y) f := f (succ y, x mod succ y) !gcd.lt.dec definition gcd (x y : nat) := fix gcd.F (x, y) theorem gcd_zero_right (x : nat) : gcd x 0 = x := rfl theorem gcd_succ (x y : nat) : gcd x (succ y) = gcd (succ y) (x mod succ y) := well_founded.fix_eq gcd.F (x, succ y) theorem gcd_one_right (n : ℕ) : gcd n 1 = 1 := calc gcd n 1 = gcd 1 (n mod 1) : gcd_succ ... = gcd 1 0 : mod_one theorem gcd_def (x : ℕ) : Π (y : ℕ), gcd x y = if y = 0 then x else gcd y (x mod y) | 0 := !gcd_zero_right | (succ y) := !gcd_succ ⬝ (if_neg !succ_ne_zero)⁻¹ theorem gcd_self : Π (n : ℕ), gcd n n = n | 0 := rfl | (succ n₁) := calc gcd (succ n₁) (succ n₁) = gcd (succ n₁) (succ n₁ mod succ n₁) : gcd_succ ... = gcd (succ n₁) 0 : mod_self theorem gcd_zero_left : Π (n : ℕ), gcd 0 n = n | 0 := rfl | (succ n₁) := calc gcd 0 (succ n₁) = gcd (succ n₁) (0 mod succ n₁) : gcd_succ ... = gcd (succ n₁) 0 : zero_mod theorem gcd_of_pos (m : ℕ) {n : ℕ} (H : n > 0) : gcd m n = gcd n (m mod n) := gcd_def m n ⬝ if_neg (ne_zero_of_pos H) theorem gcd_rec (m n : ℕ) : gcd m n = gcd n (m mod n) := by_cases_zero_pos n (calc m = gcd 0 m : gcd_zero_left ... = gcd 0 (m mod 0) : mod_zero) (take n, assume H : 0 < n, gcd_of_pos m H) theorem gcd.induction {P : ℕ → ℕ → Prop} (m n : ℕ) (H0 : ∀m, P m 0) (H1 : ∀m n, 0 < n → P n (m mod n) → P m n) : P m n := induction (m, n) (prod.rec (λm, nat.rec (λ IH, H0 m) (λ n₁ v (IH : ∀p₂, p₂ ≺ (m, succ n₁) → P (pr₁ p₂) (pr₂ p₂)), H1 m (succ n₁) !succ_pos (IH _ !gcd.lt.dec)))) theorem gcd_dvd (m n : ℕ) : (gcd m n ∣ m) ∧ (gcd m n ∣ n) := gcd.induction m n (take m, and.intro (!one_mul ▸ !dvd_mul_left) !dvd_zero) (take m n (npos : 0 < n), and.rec (assume (IH₁ : gcd n (m mod n) ∣ n) (IH₂ : gcd n (m mod n) ∣ (m mod n)), have H : (gcd n (m mod n) ∣ (m div n * n + m mod n)), from dvd_add (dvd.trans IH₁ !dvd_mul_left) IH₂, have H1 : (gcd n (m mod n) ∣ m), from !eq_div_mul_add_mod⁻¹ ▸ H, show (gcd m n ∣ m) ∧ (gcd m n ∣ n), from !gcd_rec⁻¹ ▸ (and.intro H1 IH₁))) theorem gcd_dvd_left (m n : ℕ) : gcd m n ∣ m := and.left !gcd_dvd theorem gcd_dvd_right (m n : ℕ) : gcd m n ∣ n := and.right !gcd_dvd theorem dvd_gcd {m n k : ℕ} : k ∣ m → k ∣ n → k ∣ gcd m n := gcd.induction m n (take m, imp.intro) (take m n (npos : n > 0) (IH : k ∣ n → k ∣ m mod n → k ∣ gcd n (m mod n)) (H1 : k ∣ m) (H2 : k ∣ n), have H3 : k ∣ m div n * n + m mod n, from !eq_div_mul_add_mod ▸ H1, have H4 : k ∣ m mod n, from dvd_of_dvd_add_left H3 (dvd.trans H2 !dvd_mul_left), !gcd_rec⁻¹ ▸ IH H2 H4) theorem gcd.comm (m n : ℕ) : gcd m n = gcd n m := dvd.antisymm (dvd_gcd !gcd_dvd_right !gcd_dvd_left) (dvd_gcd !gcd_dvd_right !gcd_dvd_left) theorem gcd.assoc (m n k : ℕ) : gcd (gcd m n) k = gcd m (gcd n k) := dvd.antisymm (dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_left) (dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_right) !gcd_dvd_right)) (dvd_gcd (dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !gcd_dvd_left)) (dvd.trans !gcd_dvd_right !gcd_dvd_right)) theorem gcd_one_left (m : ℕ) : gcd 1 m = 1 := !gcd.comm ⬝ !gcd_one_right theorem gcd_mul_left (m n k : ℕ) : gcd (m * n) (m * k) = m * gcd n k := gcd.induction n k (take n, calc gcd (m * n) (m * 0) = gcd (m * n) 0 : mul_zero) (take n k, assume H : 0 < k, assume IH : gcd (m * k) (m * (n mod k)) = m * gcd k (n mod k), calc gcd (m * n) (m * k) = gcd (m * k) (m * n mod (m * k)) : !gcd_rec ... = gcd (m * k) (m * (n mod k)) : mul_mod_mul_left ... = m * gcd k (n mod k) : IH ... = m * gcd n k : !gcd_rec) theorem gcd_mul_right (m n k : ℕ) : gcd (m * n) (k * n) = gcd m k * n := calc gcd (m * n) (k * n) = gcd (n * m) (k * n) : mul.comm ... = gcd (n * m) (n * k) : mul.comm ... = n * gcd m k : gcd_mul_left ... = gcd m k * n : mul.comm theorem gcd_pos_of_pos_left {m : ℕ} (n : ℕ) (mpos : m > 0) : gcd m n > 0 := pos_of_dvd_of_pos !gcd_dvd_left mpos theorem gcd_pos_of_pos_right (m : ℕ) {n : ℕ} (npos : n > 0) : gcd m n > 0 := pos_of_dvd_of_pos !gcd_dvd_right npos theorem eq_zero_of_gcd_eq_zero_left {m n : ℕ} (H : gcd m n = 0) : m = 0 := or.elim (eq_zero_or_pos m) (assume H1, H1) (assume H1 : m > 0, absurd H⁻¹ (ne_of_lt (!gcd_pos_of_pos_left H1))) theorem eq_zero_of_gcd_eq_zero_right {m n : ℕ} (H : gcd m n = 0) : n = 0 := eq_zero_of_gcd_eq_zero_left (!gcd.comm ▸ H) theorem gcd_div {m n k : ℕ} (H1 : k ∣ m) (H2 : k ∣ n) : gcd (m div k) (n div k) = gcd m n div k := or.elim (eq_zero_or_pos k) (assume H3 : k = 0, by subst k; rewrite *div_zero) (assume H3 : k > 0, (div_eq_of_eq_mul_left H3 (calc gcd m n = gcd m (n div k * k) : div_mul_cancel H2 ... = gcd (m div k * k) (n div k * k) : div_mul_cancel H1 ... = gcd (m div k) (n div k) * k : gcd_mul_right))⁻¹) theorem gcd_dvd_gcd_mul_left (m n k : ℕ) : gcd m n ∣ gcd (k * m) n := dvd_gcd (dvd.trans !gcd_dvd_left !dvd_mul_left) !gcd_dvd_right theorem gcd_dvd_gcd_mul_right (m n k : ℕ) : gcd m n ∣ gcd (m * k) n := !mul.comm ▸ !gcd_dvd_gcd_mul_left theorem gcd_dvd_gcd_mul_left_right (m n k : ℕ) : gcd m n ∣ gcd m (k * n) := dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !dvd_mul_left) theorem gcd_dvd_gcd_mul_right_right (m n k : ℕ) : gcd m n ∣ gcd m (n * k) := !mul.comm ▸ !gcd_dvd_gcd_mul_left_right /- lcm -/ definition lcm (m n : ℕ) : ℕ := m * n div (gcd m n) theorem lcm.comm (m n : ℕ) : lcm m n = lcm n m := calc lcm m n = m * n div gcd m n : rfl ... = n * m div gcd m n : mul.comm ... = n * m div gcd n m : gcd.comm ... = lcm n m : rfl theorem lcm_zero_left (m : ℕ) : lcm 0 m = 0 := calc lcm 0 m = 0 * m div gcd 0 m : rfl ... = 0 div gcd 0 m : zero_mul ... = 0 : zero_div theorem lcm_zero_right (m : ℕ) : lcm m 0 = 0 := !lcm.comm ▸ !lcm_zero_left theorem lcm_one_left (m : ℕ) : lcm 1 m = m := calc lcm 1 m = 1 * m div gcd 1 m : rfl ... = m div gcd 1 m : one_mul ... = m div 1 : gcd_one_left ... = m : div_one theorem lcm_one_right (m : ℕ) : lcm m 1 = m := !lcm.comm ▸ !lcm_one_left theorem lcm_self (m : ℕ) : lcm m m = m := have H : m * m div m = m, from by_cases_zero_pos m !div_zero (take m, assume H1 : m > 0, !mul_div_cancel H1), calc lcm m m = m * m div gcd m m : rfl ... = m * m div m : gcd_self ... = m : H theorem dvd_lcm_left (m n : ℕ) : m ∣ lcm m n := have H : lcm m n = m * (n div gcd m n), from mul_div_assoc _ !gcd_dvd_right, dvd.intro H⁻¹ theorem dvd_lcm_right (m n : ℕ) : n ∣ lcm m n := !lcm.comm ▸ !dvd_lcm_left theorem gcd_mul_lcm (m n : ℕ) : gcd m n * lcm m n = m * n := eq.symm (eq_mul_of_div_eq_right (dvd.trans !gcd_dvd_left !dvd_mul_right) rfl) theorem lcm_dvd {m n k : ℕ} (H1 : m ∣ k) (H2 : n ∣ k) : lcm m n ∣ k := or.elim (eq_zero_or_pos k) (assume kzero : k = 0, !kzero⁻¹ ▸ !dvd_zero) (assume kpos : k > 0, have mpos : m > 0, from pos_of_dvd_of_pos H1 kpos, have npos : n > 0, from pos_of_dvd_of_pos H2 kpos, have gcd_pos : gcd m n > 0, from !gcd_pos_of_pos_left mpos, obtain p (km : k = m * p), from exists_eq_mul_right_of_dvd H1, obtain q (kn : k = n * q), from exists_eq_mul_right_of_dvd H2, have ppos : p > 0, from pos_of_mul_pos_left (km ▸ kpos), have qpos : q > 0, from pos_of_mul_pos_left (kn ▸ kpos), have H3 : p * q * (m * n * gcd p q) = p * q * (gcd m n * k), from calc p * q * (m * n * gcd p q) = m * p * (n * q * gcd p q) : by rewrite [*mul.assoc, *mul.left_comm q, mul.left_comm p] ... = k * (k * gcd p q) : by rewrite [-kn, -km] ... = k * gcd (k * p) (k * q) : by rewrite gcd_mul_left ... = k * gcd (n * q * p) (m * p * q) : by rewrite [-kn, -km] ... = k * (gcd n m * (p * q)) : by rewrite [*mul.assoc, mul.comm q, gcd_mul_right] ... = p * q * (gcd m n * k) : by rewrite [mul.comm, mul.comm (gcd n m), gcd.comm, *mul.assoc], have H4 : m * n * gcd p q = gcd m n * k, from !eq_of_mul_eq_mul_left (mul_pos ppos qpos) H3, have H5 : gcd m n * (lcm m n * gcd p q) = gcd m n * k, from !mul.assoc ▸ !gcd_mul_lcm⁻¹ ▸ H4, have H6 : lcm m n * gcd p q = k, from !eq_of_mul_eq_mul_left gcd_pos H5, dvd.intro H6) theorem lcm.assoc (m n k : ℕ) : lcm (lcm m n) k = lcm m (lcm n k) := dvd.antisymm (lcm_dvd (lcm_dvd !dvd_lcm_left (dvd.trans !dvd_lcm_left !dvd_lcm_right)) (dvd.trans !dvd_lcm_right !dvd_lcm_right)) (lcm_dvd (dvd.trans !dvd_lcm_left !dvd_lcm_left) (lcm_dvd (dvd.trans !dvd_lcm_right !dvd_lcm_left) !dvd_lcm_right)) /- coprime -/ definition coprime [reducible] (m n : ℕ) : Prop := gcd m n = 1 theorem coprime_swap {m n : ℕ} (H : coprime n m) : coprime m n := !gcd.comm ▸ H theorem dvd_of_coprime_of_dvd_mul_right {m n k : ℕ} (H1 : coprime k n) (H2 : k ∣ m * n) : k ∣ m := have H3 : gcd (m * k) (m * n) = m, from calc gcd (m * k) (m * n) = m * gcd k n : gcd_mul_left ... = m * 1 : H1 ... = m : mul_one, have H4 : (k ∣ gcd (m * k) (m * n)), from dvd_gcd !dvd_mul_left H2, H3 ▸ H4 theorem dvd_of_coprime_of_dvd_mul_left {m n k : ℕ} (H1 : coprime k m) (H2 : k ∣ m * n) : k ∣ n := dvd_of_coprime_of_dvd_mul_right H1 (!mul.comm ▸ H2) theorem gcd_mul_left_cancel_of_coprime {k : ℕ} (m : ℕ) {n : ℕ} (H : coprime k n) : gcd (k * m) n = gcd m n := have H1 : coprime (gcd (k * m) n) k, from calc gcd (gcd (k * m) n) k = gcd (k * gcd 1 m) n : by rewrite [-gcd_mul_left, mul_one, gcd.comm, gcd.assoc] ... = 1 : by rewrite [gcd_one_left, mul_one, ↑coprime at H, H], dvd.antisymm (dvd_gcd (dvd_of_coprime_of_dvd_mul_left H1 !gcd_dvd_left) !gcd_dvd_right) (dvd_gcd (dvd.trans !gcd_dvd_left !dvd_mul_left) !gcd_dvd_right) theorem gcd_mul_right_cancel_of_coprime (m : ℕ) {k n : ℕ} (H : coprime k n) : gcd (m * k) n = gcd m n := !mul.comm ▸ !gcd_mul_left_cancel_of_coprime H theorem gcd_mul_left_cancel_of_coprime_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (k * n) = gcd m n := !gcd.comm ▸ !gcd.comm ▸ !gcd_mul_left_cancel_of_coprime H theorem gcd_mul_right_cancel_of_coprime_right {k m : ℕ} (n : ℕ) (H : coprime k m) : gcd m (n * k) = gcd m n := !gcd.comm ▸ !gcd.comm ▸ !gcd_mul_right_cancel_of_coprime H theorem coprime_div_gcd_div_gcd {m n : ℕ} (H : gcd m n > 0) : coprime (m div gcd m n) (n div gcd m n) := calc gcd (m div gcd m n) (n div gcd m n) = gcd m n div gcd m n : gcd_div !gcd_dvd_left !gcd_dvd_right ... = 1 : div_self H theorem not_coprime_of_dvd_of_dvd {m n d : ℕ} (dgt1 : d > 1) (Hm : d ∣ m) (Hn : d ∣ n) : ¬ coprime m n := assume co : coprime m n, assert d ∣ gcd m n, from dvd_gcd Hm Hn, have d ∣ 1, by rewrite [↑coprime at co, co at this]; apply this, have d ≤ 1, from le_of_dvd dec_trivial this, show false, from not_lt_of_ge `d ≤ 1` `d > 1` theorem exists_coprime {m n : ℕ} (H : gcd m n > 0) : exists m' n', coprime m' n' ∧ m = m' * gcd m n ∧ n = n' * gcd m n := have H1 : m = (m div gcd m n) * gcd m n, from (div_mul_cancel !gcd_dvd_left)⁻¹, have H2 : n = (n div gcd m n) * gcd m n, from (div_mul_cancel !gcd_dvd_right)⁻¹, exists.intro _ (exists.intro _ (and.intro (coprime_div_gcd_div_gcd H) (and.intro H1 H2))) theorem coprime_mul {m n k : ℕ} (H1 : coprime m k) (H2 : coprime n k) : coprime (m * n) k := calc gcd (m * n) k = gcd n k : !gcd_mul_left_cancel_of_coprime H1 ... = 1 : H2 theorem coprime_mul_right {k m n : ℕ} (H1 : coprime k m) (H2 : coprime k n) : coprime k (m * n) := coprime_swap (coprime_mul (coprime_swap H1) (coprime_swap H2)) theorem coprime_of_coprime_mul_left {k m n : ℕ} (H : coprime (k * m) n) : coprime m n := have H1 : (gcd m n ∣ gcd (k * m) n), from !gcd_dvd_gcd_mul_left, eq_one_of_dvd_one (H ▸ H1) theorem coprime_of_coprime_mul_right {k m n : ℕ} (H : coprime (m * k) n) : coprime m n := coprime_of_coprime_mul_left (!mul.comm ▸ H) theorem coprime_of_coprime_mul_left_right {k m n : ℕ} (H : coprime m (k * n)) : coprime m n := coprime_swap (coprime_of_coprime_mul_left (coprime_swap H)) theorem coprime_of_coprime_mul_right_right {k m n : ℕ} (H : coprime m (n * k)) : coprime m n := coprime_of_coprime_mul_left_right (!mul.comm ▸ H) theorem comprime_one_left : ∀ n, coprime 1 n := λ n, !gcd_one_left theorem comprime_one_right : ∀ n, coprime n 1 := λ n, !gcd_one_right theorem exists_eq_prod_and_dvd_and_dvd {m n k} (H : k ∣ m * n) : ∃ m' n', k = m' * n' ∧ m' ∣ m ∧ n' ∣ n := or.elim (eq_zero_or_pos (gcd k m)) (assume H1 : gcd k m = 0, have H2 : k = 0, from eq_zero_of_gcd_eq_zero_left H1, have H3 : m = 0, from eq_zero_of_gcd_eq_zero_right H1, have H4 : k = 0 * n, from H2 ⬝ !zero_mul⁻¹, have H5 : 0 ∣ m, from H3⁻¹ ▸ !dvd.refl, have H6 : n ∣ n, from !dvd.refl, exists.intro _ (exists.intro _ (and.intro H4 (and.intro H5 H6)))) (assume H1 : gcd k m > 0, have H2 : gcd k m ∣ k, from !gcd_dvd_left, have H3 : k div gcd k m ∣ (m * n) div gcd k m, from div_dvd_div H2 H, have H4 : (m * n) div gcd k m = (m div gcd k m) * n, from calc m * n div gcd k m = n * m div gcd k m : mul.comm ... = n * (m div gcd k m) : !mul_div_assoc !gcd_dvd_right ... = m div gcd k m * n : mul.comm, have H5 : k div gcd k m ∣ (m div gcd k m) * n, from H4 ▸ H3, have H6 : coprime (k div gcd k m) (m div gcd k m), from coprime_div_gcd_div_gcd H1, have H7 : k div gcd k m ∣ n, from dvd_of_coprime_of_dvd_mul_left H6 H5, have H8 : k = gcd k m * (k div gcd k m), from (mul_div_cancel' H2)⁻¹, exists.intro _ (exists.intro _ (and.intro H8 (and.intro !gcd_dvd_right H7)))) end nat
a2abd2a8a9f24a309be96ef05eb403159a37687f
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/measurable_space.lean
8f41f84ede036ceddfc522a504781715f2167a90
[ "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
62,806
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 algebra.indicator_function import data.tprod import group_theory.coset import logic.equiv.fin import measure_theory.measurable_space_def import measure_theory.tactic import order.filter.lift /-! # Measurable spaces and measurable functions This file provides properties of measurable spaces and the functions and isomorphisms between them. The definition of a measurable space is in `measure_theory.measurable_space_def`. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. A function `f : α → β` induces a Galois connection between the lattices of σ-algebras on `α` and `β`. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. We say that a filter `f` is measurably generated if every set `s ∈ f` includes a measurable set `t ∈ f`. This property is useful, e.g., to extract a measurable witness of `filter.eventually`. ## Notation * We write `α ≃ᵐ β` for measurable equivalences between the measurable spaces `α` and `β`. This should not be confused with `≃ₘ` which is used for diffeomorphisms between manifolds. ## Implementation notes Measurability of a function `f : α → β` between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, σ-algebra, measurable function, measurable equivalence, dynkin system, π-λ theorem, π-system -/ open set encodable function equiv open_locale filter measure_theory variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α} namespace measurable_space section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measurable space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { measurable_set' := λ s, m.measurable_set' $ f ⁻¹' s, measurable_set_empty := m.measurable_set_empty, measurable_set_compl := assume s hs, m.measurable_set_compl _ hs, measurable_set_Union := assume f hf, by { rw preimage_Union, exact m.measurable_set_Union _ hf }} @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measurable space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { measurable_set' := λ s, ∃s', m.measurable_set' s' ∧ f ⁻¹' s' = s, measurable_set_empty := ⟨∅, m.measurable_set_empty, rfl⟩, measurable_set_compl := assume s ⟨s', h₁, h₂⟩, ⟨s'ᶜ, m.measurable_set_compl _ h₁, h₂ ▸ rfl⟩, measurable_set_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃ i, s' i, m.measurable_set_Union _ (λ i, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥ : measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} : (⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤ : measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors @[mono] lemma generate_from_mono {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (comap_le_iff_le_map.2 $ generate_from_le $ assume t hts, generate_measurable.basic _ $ mem_image_of_mem _ $ hts) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) end measurable_space section measurable_functions open measurable_space lemma measurable_iff_le_map {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂ ≤ m₁.map f := iff.rfl alias measurable_iff_le_map ↔ measurable.le_map measurable.of_le_map lemma measurable_iff_comap_le {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂.comap f ≤ m₁ := comap_le_iff_le_map.symm alias measurable_iff_comap_le ↔ measurable.comap_le measurable.of_comap_le lemma measurable.mono {ma ma' : measurable_space α} {mb mb' : measurable_space β} {f : α → β} (hf : @measurable α β ma mb f) (ha : ma ≤ ma') (hb : mb' ≤ mb) : @measurable α β ma' mb' f := λ t ht, ha _ $ hf $ hb _ ht @[measurability] lemma measurable_from_top [measurable_space β] {f : α → β} : measurable[⊤] f := λ s hs, trivial lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀ t ∈ s, measurable_set (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := measurable.of_le_map $ generate_from_le h variables {f g : α → β} section typeclass_measurable_space variables [measurable_space α] [measurable_space β] [measurable_space γ] @[nontriviality, measurability] lemma subsingleton.measurable [subsingleton α] : measurable f := λ s hs, @subsingleton.measurable_set α _ _ _ @[nontriviality, measurability] lemma measurable_of_subsingleton_codomain [subsingleton β] (f : α → β) : measurable f := λ s hs, subsingleton.set_cases measurable_set.empty measurable_set.univ s @[to_additive] lemma measurable_one [has_one α] : measurable (1 : β → α) := @measurable_const _ _ _ _ 1 lemma measurable_of_empty [is_empty α] (f : α → β) : measurable f := subsingleton.measurable lemma measurable_of_empty_codomain [is_empty β] (f : α → β) : measurable f := by { haveI := function.is_empty f, exact measurable_of_empty f } /-- A version of `measurable_const` that assumes `f x = f y` for all `x, y`. This version works for functions between empty types. -/ lemma measurable_const' {f : β → α} (hf : ∀ x y, f x = f y) : measurable f := begin casesI is_empty_or_nonempty β, { exact measurable_of_empty f }, { convert measurable_const, exact funext (λ x, hf x h.some) } end lemma measurable_of_fintype [fintype α] [measurable_singleton_class α] (f : α → β) : measurable f := λ s hs, (finite.of_fintype (f ⁻¹' s)).measurable_set end typeclass_measurable_space variables {m : measurable_space α} include m @[measurability] lemma measurable.iterate {f : α → α} (hf : measurable f) : ∀ n, measurable (f^[n]) | 0 := measurable_id | (n+1) := (measurable.iterate n).comp hf variables {mβ : measurable_space β} include mβ @[measurability] lemma measurable_set_preimage {t : set β} (hf : measurable f) (ht : measurable_set t) : measurable_set (f ⁻¹' t) := hf ht @[measurability] lemma measurable.piecewise {_ : decidable_pred (∈ s)} (hs : measurable_set s) (hf : measurable f) (hg : measurable g) : measurable (piecewise s f g) := begin intros t ht, rw piecewise_preimage, exact hs.ite (hf ht) (hg ht) end /-- this is slightly different from `measurable.piecewise`. It can be used to show `measurable (ite (x=0) 0 1)` by `exact measurable.ite (measurable_set_singleton 0) measurable_const measurable_const`, but replacing `measurable.ite` by `measurable.piecewise` in that example proof does not work. -/ lemma measurable.ite {p : α → Prop} {_ : decidable_pred p} (hp : measurable_set {a : α | p a}) (hf : measurable f) (hg : measurable g) : measurable (λ x, ite (p x) (f x) (g x)) := measurable.piecewise hp hf hg @[measurability] lemma measurable.indicator [has_zero β] (hf : measurable f) (hs : measurable_set s) : measurable (s.indicator f) := hf.piecewise hs measurable_const @[measurability, to_additive] lemma measurable_set_mul_support [has_one β] [measurable_singleton_class β] (hf : measurable f) : measurable_set (mul_support f) := hf (measurable_set_singleton 1).compl /-- If a function coincides with a measurable function outside of a countable set, it is measurable. -/ lemma measurable.measurable_of_countable_ne [measurable_singleton_class α] (hf : measurable f) (h : countable {x | f x ≠ g x}) : measurable g := begin assume t ht, have : g ⁻¹' t = (g ⁻¹' t ∩ {x | f x = g x}ᶜ) ∪ (g ⁻¹' t ∩ {x | f x = g x}), by simp [← inter_union_distrib_left], rw this, apply measurable_set.union (h.mono (inter_subset_right _ _)).measurable_set, have : g ⁻¹' t ∩ {x : α | f x = g x} = f ⁻¹' t ∩ {x : α | f x = g x}, by { ext x, simp {contextual := tt} }, rw this, exact (hf ht).inter h.measurable_set.of_compl, end end measurable_functions section constructions instance : measurable_space empty := ⊤ instance : measurable_space punit := ⊤ -- this also works for `unit` instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ instance : measurable_space ℚ := ⊤ instance : measurable_singleton_class empty := ⟨λ _, trivial⟩ instance : measurable_singleton_class punit := ⟨λ _, trivial⟩ instance : measurable_singleton_class bool := ⟨λ _, trivial⟩ instance : measurable_singleton_class ℕ := ⟨λ _, trivial⟩ instance : measurable_singleton_class ℤ := ⟨λ _, trivial⟩ instance : measurable_singleton_class ℚ := ⟨λ _, trivial⟩ lemma measurable_to_encodable [measurable_space α] [encodable α] [measurable_space β] {f : β → α} (h : ∀ y, measurable_set (f ⁻¹' {f y})) : measurable f := begin assume s hs, rw [← bUnion_preimage_singleton], refine measurable_set.Union (λ y, measurable_set.Union_Prop $ λ hy, _), by_cases hyf : y ∈ range f, { rcases hyf with ⟨y, rfl⟩, apply h }, { simp only [preimage_singleton_eq_empty.2 hyf, measurable_set.empty] } end @[measurability] lemma measurable_unit [measurable_space α] (f : unit → α) : measurable f := measurable_from_top section nat variables [measurable_space α] @[measurability] lemma measurable_from_nat {f : ℕ → α} : measurable f := measurable_from_top lemma measurable_to_nat {f : α → ℕ} : (∀ y, measurable_set (f ⁻¹' {f y})) → measurable f := measurable_to_encodable lemma measurable_find_greatest' {p : α → ℕ → Prop} [∀ x, decidable_pred (p x)] {N : ℕ} (hN : ∀ k ≤ N, measurable_set {x | nat.find_greatest (p x) N = k}) : measurable (λ x, nat.find_greatest (p x) N) := measurable_to_nat $ λ x, hN _ N.find_greatest_le lemma measurable_find_greatest {p : α → ℕ → Prop} [∀ x, decidable_pred (p x)] {N} (hN : ∀ k ≤ N, measurable_set {x | p x k}) : measurable (λ x, nat.find_greatest (p x) N) := begin refine measurable_find_greatest' (λ k hk, _), simp only [nat.find_greatest_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [measurable_set.inter, measurable_set.const, measurable_set.Inter, measurable_set.Inter_Prop, measurable_set.compl, hN]; try { intros } } end lemma measurable_find {p : α → ℕ → Prop} [∀ x, decidable_pred (p x)] (hp : ∀ x, ∃ N, p x N) (hm : ∀ k, measurable_set {x | p x k}) : measurable (λ x, nat.find (hp x)) := begin refine measurable_to_nat (λ x, _), rw [preimage_find_eq_disjointed], exact measurable_set.disjointed hm _ end end nat section quotient variables [measurable_space α] [measurable_space β] instance {α} {r : α → α → Prop} [m : measurable_space α] : measurable_space (quot r) := m.map (quot.mk r) instance {α} {s : setoid α} [m : measurable_space α] : measurable_space (quotient s) := m.map quotient.mk' @[to_additive] instance _root_.quotient_group.measurable_space {G} [group G] [measurable_space G] (S : subgroup G) : measurable_space (G ⧸ S) := quotient.measurable_space lemma measurable_set_quotient {s : setoid α} {t : set (quotient s)} : measurable_set t ↔ measurable_set (quotient.mk' ⁻¹' t) := iff.rfl lemma measurable_from_quotient {s : setoid α} {f : quotient s → β} : measurable f ↔ measurable (f ∘ quotient.mk') := iff.rfl @[measurability] lemma measurable_quotient_mk [s : setoid α] : measurable (quotient.mk : α → quotient s) := λ s, id @[measurability] lemma measurable_quotient_mk' {s : setoid α} : measurable (quotient.mk' : α → quotient s) := λ s, id @[measurability] lemma measurable_quot_mk {r : α → α → Prop} : measurable (quot.mk r) := λ s, id @[to_additive] lemma quotient_group.measurable_coe {G} [group G] [measurable_space G] {S : subgroup G} : measurable (coe : G → G ⧸ S) := measurable_quotient_mk' attribute [measurability] quotient_group.measurable_coe quotient_add_group.measurable_coe @[to_additive] lemma quotient_group.measurable_from_quotient {G} [group G] [measurable_space G] {S : subgroup G} {f : G ⧸ S → α} : measurable f ↔ measurable (f ∘ (coe : G → G ⧸ S)) := measurable_from_quotient end quotient section subtype instance {α} {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap (coe : _ → α) section variables [measurable_space α] @[measurability] lemma measurable_subtype_coe {p : α → Prop} : measurable (coe : subtype p → α) := measurable_space.le_map_comap instance {p : α → Prop} [measurable_singleton_class α] : measurable_singleton_class (subtype p) := { measurable_set_singleton := λ x, begin have : measurable_set {(x : α)} := measurable_set_singleton _, convert @measurable_subtype_coe α _ p _ this, ext y, simp [subtype.ext_iff], end } end variables {m : measurable_space α} {mβ : measurable_space β} include m lemma measurable_set.subtype_image {s : set α} {t : set s} (hs : measurable_set s) : measurable_set t → measurable_set ((coe : s → α) '' t) | ⟨u, (hu : measurable_set u), (eq : coe ⁻¹' u = t)⟩ := begin rw [← eq, subtype.image_preimage_coe], exact hu.inter hs end include mβ @[measurability] lemma measurable.subtype_coe {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λ a : α, (f a : β)) := measurable_subtype_coe.comp hf @[measurability] lemma measurable.subtype_mk {p : β → Prop} {f : α → β} (hf : measurable f) {h : ∀ x, p (f x)} : measurable (λ x, (⟨f x, h x⟩ : subtype p)) := λ t ⟨s, hs⟩, hs.2 ▸ by simp only [← preimage_comp, (∘), subtype.coe_mk, hf hs.1] lemma measurable_of_measurable_union_cover {f : α → β} (s t : set α) (hs : measurable_set s) (ht : measurable_set t) (h : univ ⊆ s ∪ t) (hc : measurable (λ a : s, f a)) (hd : measurable (λ a : t, f a)) : measurable f := begin intros u hu, convert (hs.subtype_image (hc hu)).union (ht.subtype_image (hd hu)), change f ⁻¹' u = coe '' (coe ⁻¹' (f ⁻¹' u) : set s) ∪ coe '' (coe ⁻¹' (f ⁻¹' u) : set t), rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, subtype.range_coe, subtype.range_coe, ← inter_distrib_left, univ_subset_iff.1 h, inter_univ], end lemma measurable_of_restrict_of_restrict_compl {f : α → β} {s : set α} (hs : measurable_set s) (h₁ : measurable (s.restrict f)) (h₂ : measurable (sᶜ.restrict f)) : measurable f := measurable_of_measurable_union_cover s sᶜ hs hs.compl (union_compl_self s).ge h₁ h₂ lemma measurable.dite [∀ x, decidable (x ∈ s)] {f : s → β} (hf : measurable f) {g : sᶜ → β} (hg : measurable g) (hs : measurable_set s) : measurable (λ x, if hx : x ∈ s then f ⟨x, hx⟩ else g ⟨x, hx⟩) := measurable_of_restrict_of_restrict_compl hs (by simpa) (by simpa) lemma measurable_of_measurable_on_compl_finite [measurable_singleton_class α] {f : α → β} (s : set α) (hs : finite s) (hf : measurable (sᶜ.restrict f)) : measurable f := begin letI : fintype s := finite.fintype hs, exact measurable_of_restrict_of_restrict_compl hs.measurable_set (measurable_of_fintype _) hf end lemma measurable_of_measurable_on_compl_singleton [measurable_singleton_class α] {f : α → β} (a : α) (hf : measurable ({x | x ≠ a}.restrict f)) : measurable f := measurable_of_measurable_on_compl_finite {a} (finite_singleton a) hf end subtype section prod /-- A `measurable_space` structure on the product of two measurable spaces. -/ def measurable_space.prod {α β} (m₁ : measurable_space α) (m₂ : measurable_space β) : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd instance {α β} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.prod m₂ @[measurability] lemma measurable_fst {ma : measurable_space α} {mb : measurable_space β} : measurable (prod.fst : α × β → α) := measurable.of_comap_le le_sup_left @[measurability] lemma measurable_snd {ma : measurable_space α} {mb : measurable_space β} : measurable (prod.snd : α × β → β) := measurable.of_comap_le le_sup_right variables {m : measurable_space α} {mβ : measurable_space β} {mγ : measurable_space γ} include m mβ mγ lemma measurable.fst {f : α → β × γ} (hf : measurable f) : measurable (λ a : α, (f a).1) := measurable_fst.comp hf lemma measurable.snd {f : α → β × γ} (hf : measurable f) : measurable (λ a : α, (f a).2) := measurable_snd.comp hf @[measurability] lemma measurable.prod {f : α → β × γ} (hf₁ : measurable (λ a, (f a).1)) (hf₂ : measurable (λ a, (f a).2)) : measurable f := measurable.of_le_map $ sup_le (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₁ }) (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₂ }) lemma measurable.prod_mk {β γ} {mβ : measurable_space β} {mγ : measurable_space γ} {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λ a : α, (f a, g a)) := measurable.prod hf hg lemma measurable.prod_map [measurable_space δ] {f : α → β} {g : γ → δ} (hf : measurable f) (hg : measurable g) : measurable (prod.map f g) := (hf.comp measurable_fst).prod_mk (hg.comp measurable_snd) omit mγ lemma measurable_prod_mk_left {x : α} : measurable (@prod.mk _ β x) := measurable_const.prod_mk measurable_id lemma measurable_prod_mk_right {y : β} : measurable (λ x : α, (x, y)) := measurable_id.prod_mk measurable_const include mγ lemma measurable.of_uncurry_left {f : α → β → γ} (hf : measurable (uncurry f)) {x : α} : measurable (f x) := hf.comp measurable_prod_mk_left lemma measurable.of_uncurry_right {f : α → β → γ} (hf : measurable (uncurry f)) {y : β} : measurable (λ x, f x y) := hf.comp measurable_prod_mk_right lemma measurable_prod {f : α → β × γ} : measurable f ↔ measurable (λ a, (f a).1) ∧ measurable (λ a, (f a).2) := ⟨λ hf, ⟨measurable_fst.comp hf, measurable_snd.comp hf⟩, λ h, measurable.prod h.1 h.2⟩ omit mγ @[measurability] lemma measurable_swap : measurable (prod.swap : α × β → β × α) := measurable.prod measurable_snd measurable_fst lemma measurable_swap_iff {mγ : measurable_space γ} {f : α × β → γ} : measurable (f ∘ prod.swap) ↔ measurable f := ⟨λ hf, by { convert hf.comp measurable_swap, ext ⟨x, y⟩, refl }, λ hf, hf.comp measurable_swap⟩ @[measurability] lemma measurable_set.prod {s : set α} {t : set β} (hs : measurable_set s) (ht : measurable_set t) : measurable_set (s ×ˢ t) := measurable_set.inter (measurable_fst hs) (measurable_snd ht) lemma measurable_set_prod_of_nonempty {s : set α} {t : set β} (h : (s ×ˢ t : set _).nonempty) : measurable_set (s ×ˢ t) ↔ measurable_set s ∧ measurable_set t := begin rcases h with ⟨⟨x, y⟩, hx, hy⟩, refine ⟨λ hst, _, λ h, h.1.prod h.2⟩, have : measurable_set ((λ x, (x, y)) ⁻¹' s ×ˢ t) := measurable_prod_mk_right hst, have : measurable_set (prod.mk x ⁻¹' s ×ˢ t) := measurable_prod_mk_left hst, simp * at * end lemma measurable_set_prod {s : set α} {t : set β} : measurable_set (s ×ˢ t) ↔ (measurable_set s ∧ measurable_set t) ∨ s = ∅ ∨ t = ∅ := begin cases (s ×ˢ t : set _).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.mp h] }, { simp [←not_nonempty_iff_eq_empty, prod_nonempty_iff.mp h, measurable_set_prod_of_nonempty h] } end lemma measurable_set_swap_iff {s : set (α × β)} : measurable_set (prod.swap ⁻¹' s) ↔ measurable_set s := ⟨λ hs, by { convert measurable_swap hs, ext ⟨x, y⟩, refl }, λ hs, measurable_swap hs⟩ lemma measurable_from_prod_encodable [encodable β] [measurable_singleton_class β] {mγ : measurable_space γ} {f : α × β → γ} (hf : ∀ y, measurable (λ x, f (x, y))) : measurable f := begin intros s hs, have : f ⁻¹' s = ⋃ y, ((λ x, f (x, y)) ⁻¹' s) ×ˢ ({y} : set β), { ext1 ⟨x, y⟩, simp [and_assoc, and.left_comm] }, rw this, exact measurable_set.Union (λ y, (hf y hs).prod (measurable_set_singleton y)) end /-- A piecewise function on countably many pieces is measurable if all the data is measurable. -/ @[measurability] lemma measurable.find {m : measurable_space α} {f : ℕ → α → β} {p : ℕ → α → Prop} [∀ n, decidable_pred (p n)] (hf : ∀ n, measurable (f n)) (hp : ∀ n, measurable_set {x | p n x}) (h : ∀ x, ∃ n, p n x) : measurable (λ x, f (nat.find (h x)) x) := begin have : measurable (λ (p : α × ℕ), f p.2 p.1) := measurable_from_prod_encodable (λ n, hf n), exact this.comp (measurable.prod_mk measurable_id (measurable_find h hp)), end /-- Given countably many disjoint measurable sets `t n` and countably many measurable functions `g n`, one can construct a measurable function that coincides with `g n` on `t n`. -/ lemma exists_measurable_piecewise_nat {m : measurable_space α} (t : ℕ → set β) (t_meas : ∀ n, measurable_set (t n)) (t_disj : pairwise (disjoint on t)) (g : ℕ → β → α) (hg : ∀ n, measurable (g n)) : ∃ f : β → α, measurable f ∧ (∀ n x, x ∈ t n → f x = g n x) := begin classical, let p : ℕ → β → Prop := λ n x, x ∈ t n ∪ (⋃ k, t k)ᶜ, have M : ∀ n, measurable_set {x | p n x} := λ n, (t_meas n).union (measurable_set.compl (measurable_set.Union t_meas)), have P : ∀ x, ∃ n, p n x, { assume x, by_cases H : ∀ (i : ℕ), x ∉ t i, { exact ⟨0, or.inr (by simpa only [mem_Inter, compl_Union] using H)⟩ }, { simp only [not_forall, not_not_mem] at H, rcases H with ⟨n, hn⟩, exact ⟨n, or.inl hn⟩ } }, refine ⟨λ x, g (nat.find (P x)) x, measurable.find hg M P, _⟩, assume n x hx, have : x ∈ t (nat.find (P x)), { have B : x ∈ t (nat.find (P x)) ∪ (⋃ k, t k)ᶜ := nat.find_spec (P x), have B' : (∀ (i : ℕ), x ∉ t i) ↔ false, { simp only [iff_false, not_forall, not_not_mem], exact ⟨n, hx⟩ }, simpa only [B', mem_union_eq, mem_Inter, or_false, compl_Union, mem_compl_eq] using B }, congr, by_contra h, exact t_disj n (nat.find (P x)) (ne.symm h) ⟨hx, this⟩ end end prod section pi variables {π : δ → Type*} [measurable_space α] instance measurable_space.pi [m : Π a, measurable_space (π a)] : measurable_space (Π a, π a) := ⨆ a, (m a).comap (λ b, b a) variables [Π a, measurable_space (π a)] [measurable_space γ] lemma measurable_pi_iff {g : α → Π a, π a} : measurable g ↔ ∀ a, measurable (λ x, g x a) := by simp_rw [measurable_iff_comap_le, measurable_space.pi, measurable_space.comap_supr, measurable_space.comap_comp, function.comp, supr_le_iff] @[measurability] lemma measurable_pi_apply (a : δ) : measurable (λ f : Π a, π a, f a) := measurable.of_comap_le $ le_supr _ a @[measurability] lemma measurable.eval {a : δ} {g : α → Π a, π a} (hg : measurable g) : measurable (λ x, g x a) := (measurable_pi_apply a).comp hg @[measurability] lemma measurable_pi_lambda (f : α → Π a, π a) (hf : ∀ a, measurable (λ c, f c a)) : measurable f := measurable_pi_iff.mpr hf /-- The function `update f a : π a → Π a, π a` is always measurable. This doesn't require `f` to be measurable. This should not be confused with the statement that `update f a x` is measurable. -/ @[measurability] lemma measurable_update (f : Π (a : δ), π a) {a : δ} [decidable_eq δ] : measurable (update f a) := begin apply measurable_pi_lambda, intro x, by_cases hx : x = a, { cases hx, convert measurable_id, ext, simp }, simp_rw [update_noteq hx], apply measurable_const, end /- Even though we cannot use projection notation, we still keep a dot to be consistent with similar lemmas, like `measurable_set.prod`. -/ @[measurability] lemma measurable_set.pi {s : set δ} {t : Π i : δ, set (π i)} (hs : countable s) (ht : ∀ i ∈ s, measurable_set (t i)) : measurable_set (s.pi t) := by { rw [pi_def], exact measurable_set.bInter hs (λ i hi, measurable_pi_apply _ (ht i hi)) } lemma measurable_set.univ_pi [encodable δ] {t : Π i : δ, set (π i)} (ht : ∀ i, measurable_set (t i)) : measurable_set (pi univ t) := measurable_set.pi (countable_encodable _) (λ i _, ht i) lemma measurable_set_pi_of_nonempty {s : set δ} {t : Π i, set (π i)} (hs : countable s) (h : (pi s t).nonempty) : measurable_set (pi s t) ↔ ∀ i ∈ s, measurable_set (t i) := begin classical, rcases h with ⟨f, hf⟩, refine ⟨λ hst i hi, _, measurable_set.pi hs⟩, convert measurable_update f hst, rw [update_preimage_pi hi], exact λ j hj _, hf j hj end lemma measurable_set_pi {s : set δ} {t : Π i, set (π i)} (hs : countable s) : measurable_set (pi s t) ↔ (∀ i ∈ s, measurable_set (t i)) ∨ pi s t = ∅ := begin cases (pi s t).eq_empty_or_nonempty with h h, { simp [h] }, { simp [measurable_set_pi_of_nonempty hs, h, ← not_nonempty_iff_eq_empty] } end section variable (π) @[measurability] lemma measurable_pi_equiv_pi_subtype_prod_symm (p : δ → Prop) [decidable_pred p] : measurable (equiv.pi_equiv_pi_subtype_prod p π).symm := begin apply measurable_pi_iff.2 (λ j, _), by_cases hj : p j, { simp only [hj, dif_pos, equiv.pi_equiv_pi_subtype_prod_symm_apply], have : measurable (λ (f : (Π (i : {x // p x}), π ↑i)), f ⟨j, hj⟩) := measurable_pi_apply ⟨j, hj⟩, exact measurable.comp this measurable_fst }, { simp only [hj, equiv.pi_equiv_pi_subtype_prod_symm_apply, dif_neg, not_false_iff], have : measurable (λ (f : (Π (i : {x // ¬ p x}), π ↑i)), f ⟨j, hj⟩) := measurable_pi_apply ⟨j, hj⟩, exact measurable.comp this measurable_snd } end @[measurability] lemma measurable_pi_equiv_pi_subtype_prod (p : δ → Prop) [decidable_pred p] : measurable (equiv.pi_equiv_pi_subtype_prod p π) := begin refine measurable_prod.2 _, split; { apply measurable_pi_iff.2 (λ j, _), simp only [pi_equiv_pi_subtype_prod_apply, measurable_pi_apply] } end end section fintype local attribute [instance] fintype.to_encodable lemma measurable_set.pi_fintype [fintype δ] {s : set δ} {t : Π i, set (π i)} (ht : ∀ i ∈ s, measurable_set (t i)) : measurable_set (pi s t) := measurable_set.pi (countable_encodable _) ht lemma measurable_set.univ_pi_fintype [fintype δ] {t : Π i, set (π i)} (ht : ∀ i, measurable_set (t i)) : measurable_set (pi univ t) := measurable_set.pi_fintype (λ i _, ht i) end fintype end pi instance tprod.measurable_space (π : δ → Type*) [∀ x, measurable_space (π x)] : ∀ (l : list δ), measurable_space (list.tprod π l) | [] := punit.measurable_space | (i :: is) := @prod.measurable_space _ _ _ (tprod.measurable_space is) section tprod open list variables {π : δ → Type*} [∀ x, measurable_space (π x)] lemma measurable_tprod_mk (l : list δ) : measurable (@tprod.mk δ π l) := begin induction l with i l ih, { exact measurable_const }, { exact (measurable_pi_apply i).prod_mk ih } end lemma measurable_tprod_elim [decidable_eq δ] : ∀ {l : list δ} {i : δ} (hi : i ∈ l), measurable (λ (v : tprod π l), v.elim hi) | (i :: is) j hj := begin by_cases hji : j = i, { subst hji, simp [measurable_fst] }, { rw [funext $ tprod.elim_of_ne _ hji], exact (measurable_tprod_elim (hj.resolve_left hji)).comp measurable_snd } end lemma measurable_tprod_elim' [decidable_eq δ] {l : list δ} (h : ∀ i, i ∈ l) : measurable (tprod.elim' h : tprod π l → Π i, π i) := measurable_pi_lambda _ (λ i, measurable_tprod_elim (h i)) lemma measurable_set.tprod (l : list δ) {s : ∀ i, set (π i)} (hs : ∀ i, measurable_set (s i)) : measurable_set (set.tprod l s) := by { induction l with i l ih, exact measurable_set.univ, exact (hs i).prod ih } end tprod instance {α β} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr section sum @[measurability] lemma measurable_inl [measurable_space α] [measurable_space β] : measurable (@sum.inl α β) := measurable.of_le_map inf_le_left @[measurability] lemma measurable_inr [measurable_space α] [measurable_space β] : measurable (@sum.inr α β) := measurable.of_le_map inf_le_right variables {m : measurable_space α} {mβ : measurable_space β} include m mβ lemma measurable_sum {mγ : measurable_space γ} {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable.of_comap_le $ le_inf (measurable_space.comap_le_iff_le_map.2 $ hl) (measurable_space.comap_le_iff_le_map.2 $ hr) @[measurability] lemma measurable.sum_elim {mγ : measurable_space γ} {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : measurable (sum.elim f g) := measurable_sum hf hg lemma measurable_set.inl_image {s : set α} (hs : measurable_set s) : measurable_set (sum.inl '' s : set (α ⊕ β)) := ⟨show measurable_set (sum.inl ⁻¹' _), by { rwa [preimage_image_eq], exact (λ a b, sum.inl.inj) }, have sum.inr ⁻¹' (sum.inl '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show measurable_set (sum.inr ⁻¹' _), by { rw [this], exact measurable_set.empty }⟩ lemma measurable_set_inr_image {s : set β} (hs : measurable_set s) : measurable_set (sum.inr '' s : set (α ⊕ β)) := ⟨ have sum.inl ⁻¹' (sum.inr '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show measurable_set (sum.inl ⁻¹' _), by { rw [this], exact measurable_set.empty }, show measurable_set (sum.inr ⁻¹' _), by { rwa [preimage_image_eq], exact λ a b, sum.inr.inj }⟩ omit m lemma measurable_set_range_inl [measurable_space α] : measurable_set (range sum.inl : set (α ⊕ β)) := by { rw [← image_univ], exact measurable_set.univ.inl_image } lemma measurable_set_range_inr [measurable_space α] : measurable_set (range sum.inr : set (α ⊕ β)) := by { rw [← image_univ], exact measurable_set_inr_image measurable_set.univ } end sum instance {α} {β : α → Type*} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions /-- A map `f : α → β` is called a *measurable embedding* if it is injective, measurable, and sends measurable sets to measurable sets. The latter assumption can be replaced with “`f` has measurable inverse `g : range f → α`”, see `measurable_embedding.measurable_range_splitting`, `measurable_embedding.of_measurable_inverse_range`, and `measurable_embedding.of_measurable_inverse`. One more interpretation: `f` is a measurable embedding if it defines a measurable equivalence to its range and the range is a measurable set. One implication is formalized as `measurable_embedding.equiv_range`; the other one follows from `measurable_equiv.measurable_embedding`, `measurable_embedding.subtype_coe`, and `measurable_embedding.comp`. -/ @[protect_proj] structure measurable_embedding {α β : Type*} [measurable_space α] [measurable_space β] (f : α → β) : Prop := (injective : injective f) (measurable : measurable f) (measurable_set_image' : ∀ ⦃s⦄, measurable_set s → measurable_set (f '' s)) namespace measurable_embedding variables {mα : measurable_space α} [measurable_space β] [measurable_space γ] {f : α → β} {g : β → γ} include mα lemma measurable_set_image (hf : measurable_embedding f) {s : set α} : measurable_set (f '' s) ↔ measurable_set s := ⟨λ h, by simpa only [hf.injective.preimage_image] using hf.measurable h, λ h, hf.measurable_set_image' h⟩ lemma id : measurable_embedding (id : α → α) := ⟨injective_id, measurable_id, λ s hs, by rwa image_id⟩ lemma comp (hg : measurable_embedding g) (hf : measurable_embedding f) : measurable_embedding (g ∘ f) := ⟨hg.injective.comp hf.injective, hg.measurable.comp hf.measurable, λ s hs, by rwa [← image_image, hg.measurable_set_image, hf.measurable_set_image]⟩ lemma subtype_coe {s : set α} (hs : measurable_set s) : measurable_embedding (coe : s → α) := { injective := subtype.coe_injective, measurable := measurable_subtype_coe, measurable_set_image' := λ _, measurable_set.subtype_image hs } lemma measurable_set_range (hf : measurable_embedding f) : measurable_set (range f) := by { rw ← image_univ, exact hf.measurable_set_image' measurable_set.univ } lemma measurable_set_preimage (hf : measurable_embedding f) {s : set β} : measurable_set (f ⁻¹' s) ↔ measurable_set (s ∩ range f) := by rw [← image_preimage_eq_inter_range, hf.measurable_set_image] lemma measurable_range_splitting (hf : measurable_embedding f) : measurable (range_splitting f) := λ s hs, by rwa [preimage_range_splitting hf.injective, ← (subtype_coe hf.measurable_set_range).measurable_set_image, ← image_comp, coe_comp_range_factorization, hf.measurable_set_image] lemma measurable_extend (hf : measurable_embedding f) {g : α → γ} {g' : β → γ} (hg : measurable g) (hg' : measurable g') : measurable (extend f g g') := begin refine measurable_of_restrict_of_restrict_compl hf.measurable_set_range _ _, { rw restrict_extend_range, simpa only [range_splitting] using hg.comp hf.measurable_range_splitting }, { rw restrict_extend_compl_range, exact hg'.comp measurable_subtype_coe } end lemma exists_measurable_extend (hf : measurable_embedding f) {g : α → γ} (hg : measurable g) (hne : β → nonempty γ) : ∃ g' : β → γ, measurable g' ∧ g' ∘ f = g := ⟨extend f g (λ x, classical.choice (hne x)), hf.measurable_extend hg (measurable_const' $ λ _ _, rfl), funext $ λ x, extend_apply hf.injective _ _ _⟩ lemma measurable_comp_iff (hg : measurable_embedding g) : measurable (g ∘ f) ↔ measurable f := begin refine ⟨λ H, _, hg.measurable.comp⟩, suffices : measurable ((range_splitting g ∘ range_factorization g) ∘ f), by rwa [(right_inverse_range_splitting hg.injective).comp_eq_id] at this, exact hg.measurable_range_splitting.comp H.subtype_mk end end measurable_embedding lemma measurable_set.exists_measurable_proj {m : measurable_space α} {s : set α} (hs : measurable_set s) (hne : s.nonempty) : ∃ f : α → s, measurable f ∧ ∀ x : s, f x = x := let ⟨f, hfm, hf⟩ := (measurable_embedding.subtype_coe hs).exists_measurable_extend measurable_id (λ _, hne.to_subtype) in ⟨f, hfm, congr_fun hf⟩ /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α β : Type*) [measurable_space α] [measurable_space β] extends α ≃ β := (measurable_to_fun : measurable to_equiv) (measurable_inv_fun : measurable to_equiv.symm) infix ` ≃ᵐ `:25 := measurable_equiv namespace measurable_equiv variables (α β) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] instance : has_coe_to_fun (α ≃ᵐ β) (λ _, α → β) := ⟨λ e, e.to_fun⟩ variables {α β} @[simp] lemma coe_to_equiv (e : α ≃ᵐ β) : (e.to_equiv : α → β) = e := rfl @[measurability] protected lemma measurable (e : α ≃ᵐ β) : measurable (e : α → β) := e.measurable_to_fun @[simp] lemma coe_mk (e : α ≃ β) (h1 : measurable e) (h2 : measurable e.symm) : ((⟨e, h1, h2⟩ : α ≃ᵐ β) : α → β) = e := rfl /-- Any measurable space is equivalent to itself. -/ def refl (α : Type*) [measurable_space α] : α ≃ᵐ α := { to_equiv := equiv.refl α, measurable_to_fun := measurable_id, measurable_inv_fun := measurable_id } instance : inhabited (α ≃ᵐ α) := ⟨refl α⟩ /-- The composition of equivalences between measurable spaces. -/ def trans (ab : α ≃ᵐ β) (bc : β ≃ᵐ γ) : α ≃ᵐ γ := { to_equiv := ab.to_equiv.trans bc.to_equiv, measurable_to_fun := bc.measurable_to_fun.comp ab.measurable_to_fun, measurable_inv_fun := ab.measurable_inv_fun.comp bc.measurable_inv_fun } /-- The inverse of an equivalence between measurable spaces. -/ def symm (ab : α ≃ᵐ β) : β ≃ᵐ α := { to_equiv := ab.to_equiv.symm, measurable_to_fun := ab.measurable_inv_fun, measurable_inv_fun := ab.measurable_to_fun } @[simp] lemma coe_to_equiv_symm (e : α ≃ᵐ β) : (e.to_equiv.symm : β → α) = e.symm := rfl /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (h : α ≃ᵐ β) : α → β := h /-- See Note [custom simps projection] -/ def simps.symm_apply (h : α ≃ᵐ β) : β → α := h.symm initialize_simps_projections measurable_equiv (to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply) lemma to_equiv_injective : injective (to_equiv : (α ≃ᵐ β) → (α ≃ β)) := by { rintro ⟨e₁, _, _⟩ ⟨e₂, _, _⟩ (rfl : e₁ = e₂), refl } @[ext] lemma ext {e₁ e₂ : α ≃ᵐ β} (h : (e₁ : α → β) = e₂) : e₁ = e₂ := to_equiv_injective $ equiv.coe_fn_injective h @[simp] lemma symm_mk (e : α ≃ β) (h1 : measurable e) (h2 : measurable e.symm) : (⟨e, h1, h2⟩ : α ≃ᵐ β).symm = ⟨e.symm, h2, h1⟩ := rfl attribute [simps apply to_equiv] trans refl @[simp] lemma symm_refl (α : Type*) [measurable_space α] : (refl α).symm = refl α := rfl @[simp] theorem symm_comp_self (e : α ≃ᵐ β) : e.symm ∘ e = id := funext e.left_inv @[simp] theorem self_comp_symm (e : α ≃ᵐ β) : e ∘ e.symm = id := funext e.right_inv @[simp] theorem apply_symm_apply (e : α ≃ᵐ β) (y : β) : e (e.symm y) = y := e.right_inv y @[simp] theorem symm_apply_apply (e : α ≃ᵐ β) (x : α) : e.symm (e x) = x := e.left_inv x @[simp] theorem symm_trans_self (e : α ≃ᵐ β) : e.symm.trans e = refl β := ext e.self_comp_symm @[simp] theorem self_trans_symm (e : α ≃ᵐ β) : e.trans e.symm = refl α := ext e.symm_comp_self protected theorem surjective (e : α ≃ᵐ β) : surjective e := e.to_equiv.surjective protected theorem bijective (e : α ≃ᵐ β) : bijective e := e.to_equiv.bijective protected theorem injective (e : α ≃ᵐ β) : injective e := e.to_equiv.injective @[simp] theorem symm_preimage_preimage (e : α ≃ᵐ β) (s : set β) : e.symm ⁻¹' (e ⁻¹' s) = s := e.to_equiv.symm_preimage_preimage s theorem image_eq_preimage (e : α ≃ᵐ β) (s : set α) : e '' s = e.symm ⁻¹' s := e.to_equiv.image_eq_preimage s @[simp] theorem measurable_set_preimage (e : α ≃ᵐ β) {s : set β} : measurable_set (e ⁻¹' s) ↔ measurable_set s := ⟨λ h, by simpa only [symm_preimage_preimage] using e.symm.measurable h, λ h, e.measurable h⟩ @[simp] theorem measurable_set_image (e : α ≃ᵐ β) {s : set α} : measurable_set (e '' s) ↔ measurable_set s := by rw [image_eq_preimage, measurable_set_preimage] /-- A measurable equivalence is a measurable embedding. -/ protected lemma measurable_embedding (e : α ≃ᵐ β) : measurable_embedding e := { injective := e.injective, measurable := e.measurable, measurable_set_image' := λ s, e.measurable_set_image.2 } /-- Equal measurable spaces are equivalent. -/ protected def cast {α β} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : α ≃ᵐ β := { to_equiv := equiv.cast h, measurable_to_fun := by { substI h, substI hi, exact measurable_id }, measurable_inv_fun := by { substI h, substI hi, exact measurable_id }} protected lemma measurable_comp_iff {f : β → γ} (e : α ≃ᵐ β) : measurable (f ∘ e) ↔ measurable f := iff.intro (assume hfe, have measurable (f ∘ (e.symm.trans e).to_equiv) := hfe.comp e.symm.measurable, by rwa [coe_to_equiv, symm_trans_self] at this) (λ h, h.comp e.measurable) /-- Any two types with unique elements are measurably equivalent. -/ def of_unique_of_unique (α β : Type*) [measurable_space α] [measurable_space β] [unique α] [unique β] : α ≃ᵐ β := { to_equiv := equiv_of_unique_of_unique, measurable_to_fun := subsingleton.measurable, measurable_inv_fun := subsingleton.measurable } /-- Products of equivalent measurable spaces are equivalent. -/ def prod_congr (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α × γ ≃ᵐ β × δ := { to_equiv := prod_congr ab.to_equiv cd.to_equiv, measurable_to_fun := (ab.measurable_to_fun.comp measurable_id.fst).prod_mk (cd.measurable_to_fun.comp measurable_id.snd), measurable_inv_fun := (ab.measurable_inv_fun.comp measurable_id.fst).prod_mk (cd.measurable_inv_fun.comp measurable_id.snd) } /-- Products of measurable spaces are symmetric. -/ def prod_comm : α × β ≃ᵐ β × α := { to_equiv := prod_comm α β, measurable_to_fun := measurable_id.snd.prod_mk measurable_id.fst, measurable_inv_fun := measurable_id.snd.prod_mk measurable_id.fst } /-- Products of measurable spaces are associative. -/ def prod_assoc : (α × β) × γ ≃ᵐ α × (β × γ) := { to_equiv := prod_assoc α β γ, measurable_to_fun := measurable_fst.fst.prod_mk $ measurable_fst.snd.prod_mk measurable_snd, measurable_inv_fun := (measurable_fst.prod_mk measurable_snd.fst).prod_mk measurable_snd.snd } /-- Sums of measurable spaces are symmetric. -/ def sum_congr (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α ⊕ γ ≃ᵐ β ⊕ δ := { to_equiv := sum_congr ab.to_equiv cd.to_equiv, measurable_to_fun := begin cases ab with ab' abm, cases ab', cases cd with cd' cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end, measurable_inv_fun := begin cases ab with ab' _ abm, cases ab', cases cd with cd' _ cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end } /-- `s ×ˢ t ≃ (s × t)` as measurable spaces. -/ def set.prod (s : set α) (t : set β) : ↥(s ×ˢ t) ≃ᵐ s × t := { to_equiv := equiv.set.prod s t, measurable_to_fun := measurable_id.subtype_coe.fst.subtype_mk.prod_mk measurable_id.subtype_coe.snd.subtype_mk, measurable_inv_fun := measurable.subtype_mk $ measurable_id.fst.subtype_coe.prod_mk measurable_id.snd.subtype_coe } /-- `univ α ≃ α` as measurable spaces. -/ def set.univ (α : Type*) [measurable_space α] : (univ : set α) ≃ᵐ α := { to_equiv := equiv.set.univ α, measurable_to_fun := measurable_id.subtype_coe, measurable_inv_fun := measurable_id.subtype_mk } /-- `{a} ≃ unit` as measurable spaces. -/ def set.singleton (a : α) : ({a} : set α) ≃ᵐ unit := { to_equiv := equiv.set.singleton a, measurable_to_fun := measurable_const, measurable_inv_fun := measurable_const } /-- A set is equivalent to its image under a function `f` as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.image (f : α → β) (s : set α) (hf : injective f) (hfm : measurable f) (hfi : ∀ s, measurable_set s → measurable_set (f '' s)) : s ≃ᵐ (f '' s) := { to_equiv := equiv.set.image f s hf, measurable_to_fun := (hfm.comp measurable_id.subtype_coe).subtype_mk, measurable_inv_fun := begin rintro t ⟨u, hu, rfl⟩, simp [preimage_preimage, set.image_symm_preimage hf], exact measurable_subtype_coe (hfi u hu) end } /-- The domain of `f` is equivalent to its range as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.range (f : α → β) (hf : injective f) (hfm : measurable f) (hfi : ∀ s, measurable_set s → measurable_set (f '' s)) : α ≃ᵐ (range f) := (measurable_equiv.set.univ _).symm.trans $ (measurable_equiv.set.image f univ hf hfm hfi).trans $ measurable_equiv.cast (by rw image_univ) (by rw image_univ) /-- `α` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inl : (range sum.inl : set (α ⊕ β)) ≃ᵐ α := { to_fun := λ ab, match ab with | ⟨sum.inl a, _⟩ := a | ⟨sum.inr b, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λ a, ⟨sum.inl a, a, rfl⟩, left_inv := by { rintro ⟨ab, a, rfl⟩, refl }, right_inv := assume a, rfl, measurable_to_fun := assume s (hs : measurable_set s), begin refine ⟨_, hs.inl_image, set.ext _⟩, rintros ⟨ab, a, rfl⟩, simp [set.range_inl._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inl } /-- `β` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inr : (range sum.inr : set (α ⊕ β)) ≃ᵐ β := { to_fun := λ ab, match ab with | ⟨sum.inr b, _⟩ := b | ⟨sum.inl a, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λ b, ⟨sum.inr b, b, rfl⟩, left_inv := by { rintro ⟨ab, b, rfl⟩, refl }, right_inv := assume b, rfl, measurable_to_fun := assume s (hs : measurable_set s), begin refine ⟨_, measurable_set_inr_image hs, set.ext _⟩, rintros ⟨ab, b, rfl⟩, simp [set.range_inr._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inr } /-- Products distribute over sums (on the right) as measurable spaces. -/ def sum_prod_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : (α ⊕ β) × γ ≃ᵐ (α × γ) ⊕ (β × γ) := { to_equiv := sum_prod_distrib α β γ, measurable_to_fun := begin refine measurable_of_measurable_union_cover (range sum.inl ×ˢ (univ : set γ)) (range sum.inr ×ˢ (univ : set γ)) (measurable_set_range_inl.prod measurable_set.univ) (measurable_set_range_inr.prod measurable_set.univ) (by { rintro ⟨a|b, c⟩; simp [set.prod_eq] }) _ _, { refine (set.prod (range sum.inl) univ).symm.measurable_comp_iff.1 _, refine (prod_congr set.range_inl (set.univ _)).symm.measurable_comp_iff.1 _, dsimp [(∘)], convert measurable_inl, ext ⟨a, c⟩, refl }, { refine (set.prod (range sum.inr) univ).symm.measurable_comp_iff.1 _, refine (prod_congr set.range_inr (set.univ _)).symm.measurable_comp_iff.1 _, dsimp [(∘)], convert measurable_inr, ext ⟨b, c⟩, refl } end, measurable_inv_fun := measurable_sum ((measurable_inl.comp measurable_fst).prod_mk measurable_snd) ((measurable_inr.comp measurable_fst).prod_mk measurable_snd) } /-- Products distribute over sums (on the left) as measurable spaces. -/ def prod_sum_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : α × (β ⊕ γ) ≃ᵐ (α × β) ⊕ (α × γ) := prod_comm.trans $ (sum_prod_distrib _ _ _).trans $ sum_congr prod_comm prod_comm /-- Products distribute over sums as measurable spaces. -/ def sum_prod_sum (α β γ δ) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : (α ⊕ β) × (γ ⊕ δ) ≃ᵐ ((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ)) := (sum_prod_distrib _ _ _).trans $ sum_congr (prod_sum_distrib _ _ _) (prod_sum_distrib _ _ _) variables {π π' : δ' → Type*} [∀ x, measurable_space (π x)] [∀ x, measurable_space (π' x)] /-- A family of measurable equivalences `Π a, β₁ a ≃ᵐ β₂ a` generates a measurable equivalence between `Π a, β₁ a` and `Π a, β₂ a`. -/ def Pi_congr_right (e : Π a, π a ≃ᵐ π' a) : (Π a, π a) ≃ᵐ (Π a, π' a) := { to_equiv := Pi_congr_right (λ a, (e a).to_equiv), measurable_to_fun := measurable_pi_lambda _ (λ i, (e i).measurable_to_fun.comp (measurable_pi_apply i)), measurable_inv_fun := measurable_pi_lambda _ (λ i, (e i).measurable_inv_fun.comp (measurable_pi_apply i)) } /-- Pi-types are measurably equivalent to iterated products. -/ @[simps {fully_applied := ff}] def pi_measurable_equiv_tprod [decidable_eq δ'] {l : list δ'} (hnd : l.nodup) (h : ∀ i, i ∈ l) : (Π i, π i) ≃ᵐ list.tprod π l := { to_equiv := list.tprod.pi_equiv_tprod hnd h, measurable_to_fun := measurable_tprod_mk l, measurable_inv_fun := measurable_tprod_elim' h } /-- If `α` has a unique term, then the type of function `α → β` is measurably equivalent to `β`. -/ @[simps {fully_applied := ff}] def fun_unique (α β : Type*) [unique α] [measurable_space β] : (α → β) ≃ᵐ β := { to_equiv := equiv.fun_unique α β, measurable_to_fun := measurable_pi_apply _, measurable_inv_fun := measurable_pi_iff.2 $ λ b, measurable_id } /-- The space `Π i : fin 2, α i` is measurably equivalent to `α 0 × α 1`. -/ @[simps {fully_applied := ff}] def pi_fin_two (α : fin 2 → Type*) [∀ i, measurable_space (α i)] : (Π i, α i) ≃ᵐ α 0 × α 1 := { to_equiv := pi_fin_two_equiv α, measurable_to_fun := measurable.prod (measurable_pi_apply _) (measurable_pi_apply _), measurable_inv_fun := measurable_pi_iff.2 $ fin.forall_fin_two.2 ⟨measurable_fst, measurable_snd⟩ } /-- The space `fin 2 → α` is measurably equivalent to `α × α`. -/ @[simps {fully_applied := ff}] def fin_two_arrow : (fin 2 → α) ≃ᵐ α × α := pi_fin_two (λ _, α) /-- Measurable equivalence between `Π j : fin (n + 1), α j` and `α i × Π j : fin n, α (fin.succ_above i j)`. -/ @[simps {fully_applied := ff}] def pi_fin_succ_above_equiv {n : ℕ} (α : fin (n + 1) → Type*) [Π i, measurable_space (α i)] (i : fin (n + 1)) : (Π j, α j) ≃ᵐ α i × (Π j, α (i.succ_above j)) := { to_equiv := pi_fin_succ_above_equiv α i, measurable_to_fun := (measurable_pi_apply i).prod_mk $ measurable_pi_iff.2 $ λ j, measurable_pi_apply _, measurable_inv_fun := by simp [measurable_pi_iff, i.forall_iff_succ_above, measurable_fst, (measurable_pi_apply _).comp measurable_snd] } variable (π) /-- Measurable equivalence between (dependent) functions on a type and pairs of functions on `{i // p i}` and `{i // ¬p i}`. See also `equiv.pi_equiv_pi_subtype_prod`. -/ @[simps {fully_applied := ff}] def pi_equiv_pi_subtype_prod (p : δ' → Prop) [decidable_pred p] : (Π i, π i) ≃ᵐ ((Π i : subtype p, π i) × (Π i : {i // ¬p i}, π i)) := { to_equiv := pi_equiv_pi_subtype_prod p π, measurable_to_fun := measurable_pi_equiv_pi_subtype_prod π p, measurable_inv_fun := measurable_pi_equiv_pi_subtype_prod_symm π p } end measurable_equiv namespace measurable_embedding variables [measurable_space α] [measurable_space β] [measurable_space γ] {f : α → β} /-- A measurable embedding defines a measurable equivalence between its domain and its range. -/ noncomputable def equiv_range (f : α → β) (hf : measurable_embedding f) : α ≃ᵐ range f := { to_equiv := equiv.of_injective f hf.injective, measurable_to_fun := hf.measurable.subtype_mk, measurable_inv_fun := by { rw coe_of_injective_symm, exact hf.measurable_range_splitting } } lemma of_measurable_inverse_on_range {g : range f → α} (hf₁ : measurable f) (hf₂ : measurable_set (range f)) (hg : measurable g) (H : left_inverse g (range_factorization f)) : measurable_embedding f := begin set e : α ≃ᵐ range f := ⟨⟨range_factorization f, g, H, H.right_inverse_of_surjective surjective_onto_range⟩, hf₁.subtype_mk, hg⟩, exact (measurable_embedding.subtype_coe hf₂).comp e.measurable_embedding end lemma of_measurable_inverse {g : β → α} (hf₁ : measurable f) (hf₂ : measurable_set (range f)) (hg : measurable g) (H : left_inverse g f) : measurable_embedding f := of_measurable_inverse_on_range hf₁ hf₂ (hg.comp measurable_subtype_coe) H end measurable_embedding namespace filter variables [measurable_space α] /-- A filter `f` is measurably generates if each `s ∈ f` includes a measurable `t ∈ f`. -/ class is_measurably_generated (f : filter α) : Prop := (exists_measurable_subset : ∀ ⦃s⦄, s ∈ f → ∃ t ∈ f, measurable_set t ∧ t ⊆ s) instance is_measurably_generated_bot : is_measurably_generated (⊥ : filter α) := ⟨λ _ _, ⟨∅, mem_bot, measurable_set.empty, empty_subset _⟩⟩ instance is_measurably_generated_top : is_measurably_generated (⊤ : filter α) := ⟨λ s hs, ⟨univ, univ_mem, measurable_set.univ, λ x _, hs x⟩⟩ lemma eventually.exists_measurable_mem {f : filter α} [is_measurably_generated f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ s ∈ f, measurable_set s ∧ ∀ x ∈ s, p x := is_measurably_generated.exists_measurable_subset h lemma eventually.exists_measurable_mem_of_small_sets {f : filter α} [is_measurably_generated f] {p : set α → Prop} (h : ∀ᶠ s in f.small_sets, p s) : ∃ s ∈ f, measurable_set s ∧ p s := let ⟨s, hsf, hs⟩ := eventually_small_sets.1 h, ⟨t, htf, htm, hts⟩ := is_measurably_generated.exists_measurable_subset hsf in ⟨t, htf, htm, hs t hts⟩ instance inf_is_measurably_generated (f g : filter α) [is_measurably_generated f] [is_measurably_generated g] : is_measurably_generated (f ⊓ g) := begin refine ⟨_⟩, rintros t ⟨sf, hsf, sg, hsg, rfl⟩, rcases is_measurably_generated.exists_measurable_subset hsf with ⟨s'f, hs'f, hmf, hs'sf⟩, rcases is_measurably_generated.exists_measurable_subset hsg with ⟨s'g, hs'g, hmg, hs'sg⟩, refine ⟨s'f ∩ s'g, inter_mem_inf hs'f hs'g, hmf.inter hmg, _⟩, exact inter_subset_inter hs'sf hs'sg end lemma principal_is_measurably_generated_iff {s : set α} : is_measurably_generated (𝓟 s) ↔ measurable_set s := begin refine ⟨_, λ hs, ⟨λ t ht, ⟨s, mem_principal_self s, hs, ht⟩⟩⟩, rintros ⟨hs⟩, rcases hs (mem_principal_self s) with ⟨t, ht, htm, hts⟩, have : t = s := subset.antisymm hts ht, rwa ← this end alias principal_is_measurably_generated_iff ↔ _ measurable_set.principal_is_measurably_generated instance infi_is_measurably_generated {f : ι → filter α} [∀ i, is_measurably_generated (f i)] : is_measurably_generated (⨅ i, f i) := begin refine ⟨λ s hs, _⟩, rw [← equiv.plift.surjective.infi_comp, mem_infi] at hs, rcases hs with ⟨t, ht, ⟨V, hVf, rfl⟩⟩, choose U hUf hU using λ i, is_measurably_generated.exists_measurable_subset (hVf i), refine ⟨⋂ i : t, U i, _, _, _⟩, { rw [← equiv.plift.surjective.infi_comp, mem_infi], refine ⟨t, ht, U, hUf, rfl⟩ }, { haveI := ht.countable.to_encodable, exact measurable_set.Inter (λ i, (hU i).1) }, { exact Inter_mono (λ i, (hU i).2) } end end filter /-- We say that a collection of sets is countably spanning if a countable subset spans the whole type. This is a useful condition in various parts of measure theory. For example, it is a needed condition to show that the product of two collections generate the product sigma algebra, see `generate_from_prod_eq`. -/ def is_countably_spanning (C : set (set α)) : Prop := ∃ (s : ℕ → set α), (∀ n, s n ∈ C) ∧ (⋃ n, s n) = univ lemma is_countably_spanning_measurable_set [measurable_space α] : is_countably_spanning {s : set α | measurable_set s} := ⟨λ _, univ, λ _, measurable_set.univ, Union_const _⟩ namespace measurable_set /-! ### Typeclasses on `subtype measurable_set` -/ variables [measurable_space α] instance : has_mem α (subtype (measurable_set : set α → Prop)) := ⟨λ a s, a ∈ (s : set α)⟩ @[simp] lemma mem_coe (a : α) (s : subtype (measurable_set : set α → Prop)) : a ∈ (s : set α) ↔ a ∈ s := iff.rfl instance : has_emptyc (subtype (measurable_set : set α → Prop)) := ⟨⟨∅, measurable_set.empty⟩⟩ @[simp] lemma coe_empty : ↑(∅ : subtype (measurable_set : set α → Prop)) = (∅ : set α) := rfl instance [measurable_singleton_class α] : has_insert α (subtype (measurable_set : set α → Prop)) := ⟨λ a s, ⟨has_insert.insert a s, s.prop.insert a⟩⟩ @[simp] lemma coe_insert [measurable_singleton_class α] (a : α) (s : subtype (measurable_set : set α → Prop)) : ↑(has_insert.insert a s) = (has_insert.insert a s : set α) := rfl instance : has_compl (subtype (measurable_set : set α → Prop)) := ⟨λ x, ⟨xᶜ, x.prop.compl⟩⟩ @[simp] lemma coe_compl (s : subtype (measurable_set : set α → Prop)) : ↑(sᶜ) = (sᶜ : set α) := rfl instance : has_union (subtype (measurable_set : set α → Prop)) := ⟨λ x y, ⟨x ∪ y, x.prop.union y.prop⟩⟩ @[simp] lemma coe_union (s t : subtype (measurable_set : set α → Prop)) : ↑(s ∪ t) = (s ∪ t : set α) := rfl instance : has_inter (subtype (measurable_set : set α → Prop)) := ⟨λ x y, ⟨x ∩ y, x.prop.inter y.prop⟩⟩ @[simp] lemma coe_inter (s t : subtype (measurable_set : set α → Prop)) : ↑(s ∩ t) = (s ∩ t : set α) := rfl instance : has_sdiff (subtype (measurable_set : set α → Prop)) := ⟨λ x y, ⟨x \ y, x.prop.diff y.prop⟩⟩ @[simp] lemma coe_sdiff (s t : subtype (measurable_set : set α → Prop)) : ↑(s \ t) = (s \ t : set α) := rfl instance : has_bot (subtype (measurable_set : set α → Prop)) := ⟨⟨⊥, measurable_set.empty⟩⟩ @[simp] lemma coe_bot : ↑(⊥ : subtype (measurable_set : set α → Prop)) = (⊥ : set α) := rfl instance : has_top (subtype (measurable_set : set α → Prop)) := ⟨⟨⊤, measurable_set.univ⟩⟩ @[simp] lemma coe_top : ↑(⊤ : subtype (measurable_set : set α → Prop)) = (⊤ : set α) := rfl instance : partial_order (subtype (measurable_set : set α → Prop)) := partial_order.lift _ subtype.coe_injective instance : distrib_lattice (subtype (measurable_set : set α → Prop)) := { sup := (∪), le_sup_left := λ a b, show (a : set α) ≤ a ⊔ b, from le_sup_left, le_sup_right := λ a b, show (b : set α) ≤ a ⊔ b, from le_sup_right, sup_le := λ a b c ha hb, show (a ⊔ b : set α) ≤ c, from sup_le ha hb, inf := (∩), inf_le_left := λ a b, show (a ⊓ b : set α) ≤ a, from inf_le_left, inf_le_right := λ a b, show (a ⊓ b : set α) ≤ b, from inf_le_right, le_inf := λ a b c ha hb, show (a : set α) ≤ b ⊓ c, from le_inf ha hb, le_sup_inf := λ x y z, show ((x ⊔ y) ⊓ (x ⊔ z) : set α) ≤ x ⊔ y ⊓ z, from le_sup_inf, .. measurable_set.subtype.partial_order } instance : bounded_order (subtype (measurable_set : set α → Prop)) := { top := ⊤, le_top := λ a, show (a : set α) ≤ ⊤, from le_top, bot := ⊥, bot_le := λ a, show (⊥ : set α) ≤ a, from bot_le } instance : boolean_algebra (subtype (measurable_set : set α → Prop)) := { sdiff := (\), sup_inf_sdiff := λ a b, subtype.eq $ sup_inf_sdiff a b, inf_inf_sdiff := λ a b, subtype.eq $ inf_inf_sdiff a b, compl := has_compl.compl, inf_compl_le_bot := λ a, boolean_algebra.inf_compl_le_bot (a : set α), top_le_sup_compl := λ a, boolean_algebra.top_le_sup_compl (a : set α), sdiff_eq := λ a b, subtype.eq $ sdiff_eq, .. measurable_set.subtype.bounded_order, .. measurable_set.subtype.distrib_lattice } end measurable_set
921391981a0c1ee76a96794ed8c1e1795fc1206f
ed27983dd289b3bcad416f0b1927105d6ef19db8
/src/exam1/lin2k_test.lean
28fde2181ddb4a7b60e4aa03f94ed1bbeae9a024
[]
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
12,163
lean
import data.real.basic import exam1.lin2k -- Let's work with rational number field abbreviation K := ℚ -- Here are nice abbreviations for types abbreviation scalr := K abbreviation vectr := K × K /- 1A. [10 points] Declare v1, v2, and v3 to be of type vectr with values (4,6), (-6,2), and (3, -7), respectively. -/ -- HERE def v1: vectr := ⟨4,6⟩ def v2: vectr := ⟨-6,2⟩ def v3: vectr := ⟨3, -7⟩ /- 1B. [10 points] Now define v4, *using the vector space operators, + and •, to be the following "linear combination" of vectors: twice v1 plus negative v2 plus v3. The negative of a vector is just -1 (in the field K) times the vector. Write -1 as (-1:K), as otherwise Lean will treat it as the integer -1. (Note that subtraction of vectors, v2 - v1 is defined as v2 + (-1:K) • v1.) -/ def v4: vectr := 2 • v1 + (-1:K) • v2 + v3 -- HERE /- Compute the correct answer by hand here, showing your work, and check that eval is producing the correct answer. -- HERE -/ --(17,3) #eval v4 /- 1C. [10 points] On a piece of paper, draw a picture of the preceding computation. Make a Cartesian plane with x and y axes. Draw each vector, v1, v2, v3, as an arrow from the origin to the point designated by the coordinates of the vector. Scalar multiplication stretches or shrinks a vector by a given factor. Show each of the scaled vectors in your picture: 2 • v1 and (-1:K) • v2. Finally vector addition in graphical terms works by putting the tail (non arrow) end of one vector at the head of the other then drawing the vector from the tail of the first to the head of the second. Draw the vectors that illustrate the sum, 2 • v1 + (-1:K) • v2, and then the sum of that with v3. You should come out with the same answer as before. Take a picture of your drawing and upload it with your test. -/ -- HERE /- 2. [15 points] Many sets can be viewed as fields. For example, the integers mod p, where p is any prime, has the structure of a field under the usual operations of addition and multiplication mod p. In case you forget about the integers mod n, it can be understood as the set of natural numbers from 0 to n-1, where addition and multiplication wrap around. For example, the integers mod 5 is the set {0, 1, 2, 3, 4}. Now 2 + 2 = 4 but 2 + 3 = 5 = 0. It's "clock arithmetic," as they say. Similarly 2 * 2 = 4 but 2 * 3 = 6 = 5 + 1 = 0 + 1 = 1. To show informally that the integers mod 5 is a field you have to show that every element of the set has an additive inverse and that every element of the set but 0 has a multiplicative inverse. Draw two tables below with the values of the integers mod 5 in each of the left column. In the second column of the first table, write in the additive inverses of each element. In the second table, write the multiplicative inverses. -/ --additive inverses | 0 | 0 | | 1 | 4 | | 2 | 3 | | 3 | 2 | | 4 | 1 | --multiplicative inverses | 0 | _ | | 1 | 1 | | 2 | 3 | | 3 | 2 | | 4 | 4 | -- HERE /- 4. [15 points] Is the integers mod 4 a field? If so, prove it informally by writing tables giving the inverses. If not, show that not every value in the integers mod 4 (except 0) has a multiplicative inverse, identify a value that doesn't have an inverse, and briefly explain why. -/ -- HERE Integers mod 4 is not a field, since 2 does not have a multiplicative inverse. --multiplicative inverses | 0 | _ | | 1 | 1 | | 2 | _ | | 3 | 3 | /- 5. [20 points] Write a function, sum_vectrs, that takes a list of our vectr objects as an argument and that reduces it to a single vector sum. To implement your function use a version of foldr as we developed it: one that takes an additive monoid implicit instance as an argument, ensuring consistency of the operator we are using to reduce the list (add) and the corresponding identity element. Copy and if needed modify the foldr definition here. It should use Lean's monoid class, as we've done throughout this exercise. You do not need to and should not try to use our algebra.lean file. Test your function by creating a list of vectrs, [v1, v2, v3, v4], from above, compute the expected sum, and show that your function returns the expected/correct result. -/ universe u def add_monoid_foldr {α : Type u} [add_monoid α] : list α → α | [] := has_zero.zero | (h::t) := has_add.add h (add_monoid_foldr t) -- HERE --(18,4) = (4,6) + (-6,2) + (3, -7) + (17,3) #eval add_monoid_foldr [v1,v2,v3,v4] /- 6. Required for graduate students, optional extra credit for undergrads. The set of integers mod p can be viewed as a field with the usual addition and multiplication operations mod p. These finite fields (with only a finite number of elements) play a crucial role in many areas of number theory (in mathematics), and in cryptography in computer science. A. [20 points] Instantiate the field typeclass for fs (a prime). You may and should stub out the proofs all along the way using "sorry", but before you do that, convince yourself that you are *justified* in doing so. Use a "fake" representation of the integers mod 5 for this exercise: as an enumerated type with five values. Call them zero, one, two, three, and four. Then define two functions, z5add and z5mul, to add and multiply values of this type. You can figure out the addition and multiplication tables and just write the functions by cases to return the right result in each case. Start with Lean's field typeclass, see what you need to instantiate it, and work backwards, recursively applying the same method until your reach clases that you can implement directly. Put your code for this problem below this comment. Replace the following "assumptions" with your actual definitions (commenting out the axioms as you replace them). You can right away right click on "field" and "go to definition" to see what you need to do. Solving this problem will require some digging through Lean library code. -/ inductive Z5 : Type | zero | one | two | three | four -- axioms -- (Z5 : Type) -- (zero one two three four: Z5) open Z5 -- HERE def z5add: Z5 → Z5 → Z5 | zero zero := zero | zero one := one | zero two := two | zero three := three | zero four := four | one zero := one | one one := two | one two := three | one three := four | one four := zero | two zero := two | two one := three | two two := four | two three := zero | two four := one | three zero := three | three one := four | three two := zero | three three := one | three four := two | four zero := four | four one := zero | four two := one | four three := two | four four := three def z5mul: Z5 → Z5 → Z5 | zero _ := zero | one zero := zero | one one := one | one two := two | one three := three | one four := four | two zero := zero | two one := two | two two := four | two three := one | two four := three | three zero := zero | three one := three | three two := one | three three := four | three four := two | four zero := zero | four one := four | four two := three | four three := two | four four := one --add_comm_group instance : has_zero Z5 := ⟨ zero ⟩ instance : has_add Z5 := ⟨ z5add ⟩ lemma add_assoc_Z5: ∀ (a b c : Z5), z5add a (z5add b c) = z5add (z5add a b) c := sorry instance : add_semigroup Z5 := ⟨ add_assoc_Z5 ⟩ lemma add_ident_left : ∀ (a : Z5), z5add zero a = a := sorry lemma add_ident_right: ∀ (a: Z5), z5add a zero = a := sorry instance : add_monoid Z5 := ⟨ add_ident_left , add_ident_right⟩ lemma add_left_ident : ∀ (a : Z5), ∃ (i : Z5), z5add i a = zero := sorry lemma add_right_ident : ∀ (a : Z5), ∃ (i : Z5), z5add a i = zero := sorry instance : add_group Z5 := ⟨add_left_ident, add_right_ident⟩ lemma add_comm_Z5 : ∀ (a b : Z5), z5add a b = z5add b a := sorry instance : add_comm_group Z5 := ⟨ add_comm_Z5 ⟩ --mul_comm_group instance : has_one Z5 := ⟨ one ⟩ instance : has_mul Z5 := ⟨ z5mul ⟩ lemma mul_assoc_Z5: ∀ (a b c : Z5), z5mul a (z5mul b c) = z5mul (z5mul a b) c := sorry instance : semigroup Z5 := ⟨ mul_assoc_Z5 ⟩ lemma mul_ident_left : ∀ (a : Z5), z5mul one a = a := sorry lemma mul_ident_right: ∀ (a: Z5), z5mul a one = a := sorry instance : monoid Z5 := ⟨ mul_ident_left , mul_ident_right⟩ lemma mul_left_ident : ∀ (a : Z5), ∃ (i : Z5), z5mul i a = one := sorry lemma mul_right_ident : ∀ (a : Z5), ∃ (i : Z5), z5mul a i = one := sorry instance : group Z5 := ⟨mul_left_ident, mul_right_ident⟩ lemma mul_comm_Z5 : ∀ (a b : Z5), z5mul a b =z5mul b a := sorry instance : comm_group Z5 := ⟨ mul_comm_Z5 ⟩ --distrib lemma left_distrib_Z5 : ∀ a b c : Z5, z5mul a (z5add b c) = z5add (z5mul a b) (z5mul a c) := sorry lemma right_distrib_Z5 : ∀ a b c : Z5, z5mul (z5add a b) c = z5add (z5mul a c) (z5mul b c) := sorry instance : distrib Z5 := ⟨left_distrib_Z5, right_distrib_Z5⟩ --ring instance : ring Z5 := ⟨ _ ⟩ --comm_semigroup lemma mul_comm_semi_Z5 : ∀ a b : Z5, z5mul a b = z5mul b a := sorry instance : comm_semigroup Z5 := ⟨ mul_comm_semi_Z5 ⟩ --comm_ring instance : comm_ring Z5:= ⟨ _ ⟩ --nontrivial lemma exists_pair_ne_Z5 : ∃ (x y :Z5), x ≠ y :=sorry instance : nontrivial Z5 :=⟨ exists_pair_ne_Z5 ⟩ --field lemma mul_inv_cancel_Z5 : ∀ {a : Z5}, a ≠ zero → a * a⁻¹ = one := sorry lemma inv_zero_Z5 : (zero : Z5)⁻¹ = zero := sorry instance field_Z5: field Z5 := ⟨ mul_inv_cancel_Z5, inv_zero_Z5 ⟩ /- class comm_ring (α : Type u) extends ring α, comm_semigroup α class field (K : Type u) extends comm_ring K, div_inv_monoid K, nontrivial K := (mul_inv_cancel : ∀ {a : K}, a ≠ 0 → a * a⁻¹ = 1) (inv_zero : (0 : K)⁻¹ = 0) -/ /- B. [15 points] Given that you've now presumably established that Z5 is a field, let z5scalr be an abbreviation for Z5, and z5vectr for Z5 ⨯ Z5. Then use #eval to evaluate an expression (that you make up) involving vector addition and scalar multiplication using our new z5vectr objects, i.e., vectors over Z5. These vectors will look like, e.g., (one, three). Work out the right answer by hand and test your code to gain confidence that it's working correctly. -/ inductive foo : Type | bar open foo def add_foo : foo → foo → foo | foo.bar foo.bar := foo.bar instance has_add_foo : has_add foo := ⟨ add_foo ⟩ #reduce (bar, bar) + (bar, bar) -- HERE abbreviation z5scalr [field Z5] := Z5 abbreviation z5vectr [field Z5] := (Z5, Z5) #check z5vectr def z1: z5vectr := (one, three) def z2: z5vectr := (two, three) def z3: z5vectr := two • z1 + z2 #reduce z3 /- Take away: Instantiating a typeclass for a given type can provide a whole set of operations and notations that you can use to "do algebra" with that type. The underlying types themselves can be very diverse. That is, we can impose the same abstract interface on sets of objects of different kinds, just as we previously imposed a group API on the elements of the symmetry group, D4, of a square. Here we've now seen that we can write vector space algebra computations involving 2-D vectors over both the rational and the integers mod 5. It's in this sense that instantiating a typeclass for a type provides a new "API" for manipulating values of that type. And while languages such as Haskell do provide typeclasses, they don't provide a language in which you can declaratively express and give proofs of the "rules" that structures have to follow to be valid instances. So, welcome to Lean, a language in which you can write mathematics and code, with strong automated type checking of both code and proofs. If it has to be right (which is the case for much crypto code), maybe write it like so! -/ inductive three : Type | O | I | II def mult : three → three → three := begin assume t1 t2, cases t1, cases t2, exact three.O, exact three.O, exact three.O, cases t2, exact three.O, exact three.I, exact three.II, cases t2, exact three.O, exact three.O, exact three.I, end open three #reduce mult II II lemma one_mult : ∀ (t : three), mult I t = t := λ (t : three), match t with | O := eq.refl O | I := rfl | II := rfl end
851cf9746f86b3176d414b29a3011ae4af3f71d9
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Parser/Tactic.lean
ac76e4b29790750bd63dca6c5edd9b0d96270540
[ "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
1,015
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.Parser.Term namespace Lean namespace Parser namespace Tactic builtin_initialize registerParserAlias! "tacticSeq" tacticSeq @[builtinTacticParser] def «unknown» := parser! withPosition (ident >> errorAtSavedPos "unknown tactic" true) @[builtinTacticParser] def nestedTactic := tacticSeqBracketed /- Auxiliary parser for expanding `match` tactic -/ @[builtinTacticParser] def eraseAuxDiscrs := parser!:maxPrec "eraseAuxDiscrs!" def matchRhs := Term.hole <|> Term.syntheticHole <|> tacticSeq def matchAlts := Term.matchAlts (rhsParser := matchRhs) @[builtinTacticParser] def «match» := parser!:leadPrec "match " >> sepBy1 Term.matchDiscr ", " >> Term.optType >> " with " >> matchAlts @[builtinTacticParser] def introMatch := parser! nonReservedSymbol "intro " >> matchAlts end Tactic end Parser end Lean
ae225b87be3bc1b8ee99739ce6416e55d94ee9db
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/hw4/hw4.lean
c7e610184e7f5fe90068b9c70685c17ea687bc1c
[]
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
7,257
lean
-- Justin Ngo -- jmn4fms -- 2/17/20 -- Sullivan 2102-001 /- Here we import the dm_option type defined in class from the instructor directory. This line shows how to include a file from the parent of the parent of the current directory (one dot = current, two dots = parent, three = parent of parent), descending into several subdirectories before finding the file that we want to import. Leave off the ".lean" extension. -/ import ...instructor.types.option.dm_option open hidden /- #1 Representing Partial Functions as Total Functions [20 points] Consider the strictly partial function, pid, from natural numbers to natural numbers, defined by cases as follows. If n is zero, the function is undefined, otherwise pid n = n. We can't represent this function directly in Lean, because Lean requires all functions to be total. The usual approach is to represent such a partial function as a total function that returns not a nat (for then it would have to return a nat, even when the argument is zero) but a value of type option nat. Use this approach to implement pid in Lean. Use "by cases" syntax. (Fill in the blanks.) -/ def pid : nat → dm_option nat | 0 := dm_option.none | n := dm_option.some n /- #2 Defining functions by cases (by pattern matching) [15 points] Given a value of type option ℕ, the value might be none or it might be some n, where n is a value of type ℕ. Write a funtion option_to_nat that takes any value of type option ℕ as an argument and that returns a natural number: namely 0 if the option value is none, and n if the option value is some n. Write your definition using C-style syntax, with an explicit return type specified. You will want to use a "match ... with ... end" expression to do the required pattern matching. (Note that it will be impossible to tell from the return value alone whether a given option was none or some 0.) -/ -- ANSWER HERE def option_to_nat (option :dm_option ℕ ):= match option with |(dm_option.none) := nat.zero |(dm_option.some n) := n end /- #3 Inductive definitions. [15 points] You have probably yelled into a canyon (or maybe between two buildings) and heard a reverberating echo. An echo is a sound followed by another echo, or, eventually an echo is no sound at all (at which point the reverberation ends). Define a data type, echo, values of which represent echoes. For our purposes, an echo comes in one of two forms: it is either "silence" (at which point there is no more reverberation) OR it is a "sound" followed another echo. You can think of "silence" as a "base case" and "sound" as an inductive case, in the sense that an echo of this form is a sound followed by a smaller echo. Give each of these cases its own constructor. Once you've defined your data type, define e0, e1, and e3 to be identifiers bound to three values of this type, where e0 is bound to "silence", e1 is bound to an echo with one sound followed by silence, and e3 is bound to an echo with three sounds followed by silence. -/ -- ANSWERS HERE inductive echo : Type | silence : echo | sound (n' : echo) : echo def e0 := echo.silence def e1 := echo.sound e0 def e3 := echo.sound (echo.sound e1) /- #4 Lists. A word list type. [10 points] Define a data type, list_words_ values of which represent lists of words, where words are represented as values of type string. For our purposes, such a list comes in one of two forms: it is either "nil" (the word we tend to use for empty lists), or it is *constructed* from a word followed by a smaller list of words. Give each form of list its own constructor. Call the constructors nil and cons. Once you've defined your data type, define l0, l1, and l3 to be identifiers bound to three values of this type, where l0 is bound to an empty list of words, l1 is bound to a list with one word (followed by the empty list), and l3 is bound to a list with three words. We don't care what words you put in your lists (but be nice :-). -/ -- ANSWERS HERE inductive list_words_ : Type | nil : list_words_ | cons (n : list_words_)(s : string) : list_words_ def l0 := list_words_.nil def l1 := list_words_.cons l0 "hi" def l3 := list_words_.cons (list_words_.cons l1 "hi") /- #5 Recursive definitions. Length of word list. [10 points] Define a function, num_words, that takes a word list (as just defined) as an argument and that returns the length of the list as a value of type ℕ. -/ def num_words: list_words_→ ℕ |(list_words_.nil) := 0 |(list_words_.cons l s):= 1 + (num_words l) /- #6 Recursion. Number of permutations of a set. [10 points] Suppose you have a set containing n objects, where n is a natural number. How many ways are there to make an ordered list of n objects from this (unordered) set? Such an ordered list is called a permutation. As an example, consider the set, { x, y, z}. Here are the lists: - x, y, z - x, z, y - y, x, z - y, z, x - z, x, y - z, y, x It's not too hard to see the answer to the question. First, if the set is empty, there is only *one* way to make a list: it is the empty list. If the list is not empty, there are n ways to pick the first element of the list (so in our example, there are three ways to pick the first element: it has to be x or y or z); and then what's left is to make the rest of each list from remaining n-1 (in our example, 2) elements. So the number of lists has to be n *times* the number of lists that can be produced from a set of size n-1. We can express this idea as a function. Let's call it the permutations function, or perms, for short. As we've seen, perms 0 must be one. This is the base case. Implement the function, perms: ℕ → ℕ, to compute the number of perms for a set of any given size, n. Note that in Lean you'll need to use "by cases" syntax to define a recursive function. -/ def perms: ℕ → ℕ | 0 := 1 | (nat.succ n) := (n+1)*(perms n) /- #7 Recursion. Number of subsets of a given set. [20 points] How many subsets are there of a set of size n? A subset of a set, s, is a set all of whose elements are in s. So every set is a subset of itself, and the empty set is a subset of every set, s (since all of its elements, of which there are none(!), are in s). So how many subsets are there of a set of size n? We can answer this question nicely using recursion. First, how many subsets are there of the empty set? It's one, right? If you don't see this immediately, reread the preceding explanation. Now, consider a set, s, of size n, where n is one more than some number, n'. How many subsets does s have? To see the answer, ask the question, how many subsets does a subset of s of size n' = (n-1) have? If you have the answer to that question, then you can easily compute the number of subsets of s. A set, s', of size n' must have left out one element of s, let's call it e. For each subset of s', you can form *two* subsets of s: one with, and one without e. Write a function, power_set_cardinality, that takes a natural number representing the size of a set, s, and that then returns a natural number expressing the number of subsets there are of a set of that size. -/ def power_set_cardinality: ℕ → ℕ |(nat.zero) := 1 |(nat.succ n'):= 2* (power_set_cardinality n')
36119b50a484d09062da7c1dacbdb3aee9f1575c
367134ba5a65885e863bdc4507601606690974c1
/src/computability/tm_computable.lean
4154e47fe9d9d02b816cf9fa9f9bd6cfb9a44d28
[ "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
11,344
lean
/- Copyright (c) 2020 Pim Spelier, Daan van Gent. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pim Spelier, Daan van Gent. -/ import computability.encoding import computability.turing_machine import data.polynomial.basic import data.polynomial.eval /-! # Computable functions This file contains the definition of a Turing machine with some finiteness conditions (bundling the definition of TM2 in turing_machine.lean), a definition of when a TM gives a certain output (in a certain time), and the definition of computability (in polytime or any time function) of a function between two types that have an encoding (as in encoding.lean). ## Main theorems - `id_computable_in_poly_time` : a TM + a proof it computes the identity on a type in polytime. - `id_computable` : a TM + a proof it computes the identity on a type. ## Implementation notes To count the execution time of a Turing machine, we have decided to count the number of times the `step` function is used. Each step executes a statement (of type stmt); this is a function, and generally contains multiple "fundamental" steps (pushing, popping, so on). However, as functions only contain a finite number of executions and each one is executed at most once, this execution time is up to multiplication by a constant the amount of fundamental steps. -/ open computability namespace turing /-- A bundled TM2 (an equivalent of the classical Turing machine, defined starting from the namespace `turing.TM2` in `turing_machine.lean`), with an input and output stack, a main function, an initial state and some finiteness guarantees. -/ structure fin_tm2 := {K : Type} [K_decidable_eq : decidable_eq K] [K_fin : fintype K] -- index type of stacks (k₀ k₁ : K) -- input and output stack (Γ : K → Type) -- type of stack elements (Λ : Type) (main : Λ) [Λ_fin : fintype Λ] -- type of function labels (σ : Type) (initial_state : σ) -- type of states of the machine [σ_fin : fintype σ] [Γk₀_fin : fintype (Γ k₀)] (M : Λ → turing.TM2.stmt Γ Λ σ) -- the program itself, i.e. one function for every function label namespace fin_tm2 section variable (tm : fin_tm2) instance : decidable_eq tm.K := tm.K_decidable_eq instance : inhabited tm.σ := ⟨tm.initial_state⟩ /-- The type of statements (functions) corresponding to this TM. -/ @[derive inhabited] def stmt : Type := turing.TM2.stmt tm.Γ tm.Λ tm.σ /-- The type of configurations (functions) corresponding to this TM. -/ def cfg : Type := turing.TM2.cfg tm.Γ tm.Λ tm.σ instance inhabited_cfg : inhabited (cfg tm) := turing.TM2.cfg.inhabited _ _ _ /-- The step function corresponding to this TM. -/ @[simp] def step : tm.cfg → option tm.cfg := turing.TM2.step tm.M end end fin_tm2 /-- The initial configuration corresponding to a list in the input alphabet. -/ def init_list (tm : fin_tm2) (s : list (tm.Γ tm.k₀)) : tm.cfg := { l := option.some tm.main, var := tm.initial_state, stk := λ k, @dite (list (tm.Γ k)) (k = tm.k₀) (tm.K_decidable_eq k tm.k₀) (λ h, begin rw h, exact s, end) (λ _,[]) } /-- The final configuration corresponding to a list in the output alphabet. -/ def halt_list (tm : fin_tm2) (s : list (tm.Γ tm.k₁)) : tm.cfg := { l := option.none, var := tm.initial_state, stk := λ k, @dite (list (tm.Γ k)) (k = tm.k₁) (tm.K_decidable_eq k tm.k₁) (λ h, begin rw h, exact s, end) (λ _,[]) } /-- A "proof" of the fact that f eventually reaches b when repeatedly evaluated on a, remembering the number of steps it takes. -/ structure evals_to {σ : Type*} (f : σ → option σ) (a : σ) (b : option σ) := (steps : ℕ) (evals_in_steps : ((flip bind f)^[steps] a) = b) /-- A "proof" of the fact that `f` eventually reaches `b` in at most `m` steps when repeatedly evaluated on `a`, remembering the number of steps it takes. -/ structure evals_to_in_time {σ : Type*} (f : σ → option σ) (a : σ) (b : option σ) (m : ℕ) extends evals_to f a b := (steps_le_m : steps ≤ m) /-- Reflexivity of `evals_to` in 0 steps. -/ @[refl] def evals_to.refl {σ : Type*} (f : σ → option σ) (a : σ) : evals_to f a a := ⟨0,rfl⟩ /-- Transitivity of `evals_to` in the sum of the numbers of steps. -/ @[trans] def evals_to.trans {σ : Type*} (f : σ → option σ) (a : σ) (b : σ) (c : option σ) (h₁ : evals_to f a b) (h₂ : evals_to f b c) : evals_to f a c := ⟨h₂.steps + h₁.steps, by rw [function.iterate_add_apply,h₁.evals_in_steps,h₂.evals_in_steps]⟩ /-- Reflexivity of `evals_to_in_time` in 0 steps. -/ @[refl] def evals_to_in_time.refl {σ : Type*} (f : σ → option σ) (a : σ) : evals_to_in_time f a a 0 := ⟨evals_to.refl f a, le_refl 0⟩ /-- Transitivity of `evals_to_in_time` in the sum of the numbers of steps. -/ @[trans] def evals_to_in_time.trans {σ : Type*} (f : σ → option σ) (a : σ) (b : σ) (c : option σ) (m₁ : ℕ) (m₂ : ℕ) (h₁ : evals_to_in_time f a b m₁) (h₂ : evals_to_in_time f b c m₂) : evals_to_in_time f a c (m₂ + m₁) := ⟨evals_to.trans f a b c h₁.to_evals_to h₂.to_evals_to, add_le_add h₂.steps_le_m h₁.steps_le_m⟩ /-- A proof of tm outputting l' when given l. -/ def tm2_outputs (tm : fin_tm2) (l : list (tm.Γ tm.k₀)) (l' : option (list (tm.Γ tm.k₁))) := evals_to tm.step (init_list tm l) ((option.map (halt_list tm)) l') /-- A proof of tm outputting l' when given l in at most m steps. -/ def tm2_outputs_in_time (tm : fin_tm2) (l : list (tm.Γ tm.k₀)) (l' : option (list (tm.Γ tm.k₁))) (m : ℕ) := evals_to_in_time tm.step (init_list tm l) ((option.map (halt_list tm)) l') m /-- The forgetful map, forgetting the upper bound on the number of steps. -/ def tm2_outputs_in_time.to_tm2_outputs {tm : fin_tm2} {l : list (tm.Γ tm.k₀)} {l' : option (list (tm.Γ tm.k₁))} {m : ℕ} (h : tm2_outputs_in_time tm l l' m) : tm2_outputs tm l l' := h.to_evals_to /-- A Turing machine with input alphabet equivalent to Γ₀ and output alphabet equivalent to Γ₁. -/ structure tm2_computable_aux (Γ₀ Γ₁ : Type) := ( tm : fin_tm2 ) ( input_alphabet : tm.Γ tm.k₀ ≃ Γ₀ ) ( output_alphabet : tm.Γ tm.k₁ ≃ Γ₁ ) /-- A Turing machine + a proof it outputs f. -/ structure tm2_computable {α β : Type} (ea : fin_encoding α) (eb : fin_encoding β) (f : α → β) extends tm2_computable_aux ea.Γ eb.Γ := (outputs_fun : ∀ a, tm2_outputs tm (list.map input_alphabet.inv_fun (ea.encode a)) (option.some ((list.map output_alphabet.inv_fun) (eb.encode (f a)))) ) /-- A Turing machine + a time function + a proof it outputs f in at most time(len(input)) steps. -/ structure tm2_computable_in_time {α β : Type} (ea : fin_encoding α) (eb : fin_encoding β) (f : α → β) extends tm2_computable_aux ea.Γ eb.Γ := ( time: ℕ → ℕ ) ( outputs_fun : ∀ a, tm2_outputs_in_time tm (list.map input_alphabet.inv_fun (ea.encode a)) (option.some ((list.map output_alphabet.inv_fun) (eb.encode (f a)))) (time (ea.encode a).length) ) /-- A Turing machine + a polynomial time function + a proof it outputs f in at most time(len(input)) steps. -/ structure tm2_computable_in_poly_time {α β : Type} (ea : fin_encoding α) (eb : fin_encoding β) (f : α → β) extends tm2_computable_aux ea.Γ eb.Γ := ( time: polynomial ℕ ) ( outputs_fun : ∀ a, tm2_outputs_in_time tm (list.map input_alphabet.inv_fun (ea.encode a)) (option.some ((list.map output_alphabet.inv_fun) (eb.encode (f a)))) (time.eval (ea.encode a).length) ) /-- A forgetful map, forgetting the time bound on the number of steps. -/ def tm2_computable_in_time.to_tm2_computable {α β : Type} {ea : fin_encoding α} {eb : fin_encoding β} {f : α → β} (h : tm2_computable_in_time ea eb f) : tm2_computable ea eb f := ⟨h.to_tm2_computable_aux, λ a, tm2_outputs_in_time.to_tm2_outputs (h.outputs_fun a)⟩ /-- A forgetful map, forgetting that the time function is polynomial. -/ def tm2_computable_in_poly_time.to_tm2_computable_in_time {α β : Type} {ea : fin_encoding α} {eb : fin_encoding β} {f : α → β} (h : tm2_computable_in_poly_time ea eb f) : tm2_computable_in_time ea eb f := ⟨h.to_tm2_computable_aux, λ n, h.time.eval n, h.outputs_fun⟩ open turing.TM2.stmt /-- A Turing machine computing the identity on α. -/ def id_computer {α : Type} (ea : fin_encoding α) : fin_tm2 := { K := unit, k₀ := ⟨⟩, k₁ := ⟨⟩, Γ := λ _, ea.Γ, Λ := unit, main := ⟨⟩, σ := unit, initial_state := ⟨⟩, Γk₀_fin := ea.Γ_fin, M := λ _, halt } instance inhabited_fin_tm2 : inhabited fin_tm2 := ⟨id_computer computability.inhabited_fin_encoding.default⟩ noncomputable theory /-- A proof that the identity map on α is computable in polytime. -/ def id_computable_in_poly_time {α : Type} (ea : fin_encoding α) : @tm2_computable_in_poly_time α α ea ea id := { tm := id_computer ea, input_alphabet := equiv.cast rfl, output_alphabet := equiv.cast rfl, time := 1, outputs_fun := λ _, { steps := 1, evals_in_steps := rfl, steps_le_m := by simp only [polynomial.eval_one] } } instance inhabited_tm2_computable_in_poly_time : inhabited (tm2_computable_in_poly_time (default (fin_encoding bool)) (default (fin_encoding bool)) id) := ⟨id_computable_in_poly_time computability.inhabited_fin_encoding.default⟩ instance inhabited_tm2_outputs_in_time : inhabited (tm2_outputs_in_time (id_computer fin_encoding_bool_bool) (list.map (equiv.cast rfl).inv_fun [ff]) (some (list.map (equiv.cast rfl).inv_fun [ff])) _) := ⟨(id_computable_in_poly_time fin_encoding_bool_bool).outputs_fun ff⟩ instance inhabited_tm2_outputs : inhabited (tm2_outputs (id_computer fin_encoding_bool_bool) (list.map (equiv.cast rfl).inv_fun [ff]) (some (list.map (equiv.cast rfl).inv_fun [ff]))) := ⟨tm2_outputs_in_time.to_tm2_outputs turing.inhabited_tm2_outputs_in_time.default⟩ instance inhabited_evals_to_in_time : inhabited (evals_to_in_time (λ _ : unit, some ⟨⟩) ⟨⟩ (some ⟨⟩) 0) := ⟨evals_to_in_time.refl _ _⟩ instance inhabited_tm2_evals_to : inhabited (evals_to (λ _ : unit, some ⟨⟩) ⟨⟩ (some ⟨⟩)) := ⟨evals_to.refl _ _⟩ /-- A proof that the identity map on α is computable in time. -/ def id_computable_in_time {α : Type} (ea : fin_encoding α) : @tm2_computable_in_time α α ea ea id := tm2_computable_in_poly_time.to_tm2_computable_in_time $ id_computable_in_poly_time ea instance inhabited_tm2_computable_in_time : inhabited (tm2_computable_in_time fin_encoding_bool_bool fin_encoding_bool_bool id) := ⟨id_computable_in_time computability.inhabited_fin_encoding.default⟩ /-- A proof that the identity map on α is computable. -/ def id_computable {α : Type} (ea : fin_encoding α) : @tm2_computable α α ea ea id := tm2_computable_in_time.to_tm2_computable $ id_computable_in_time ea instance inhabited_tm2_computable : inhabited (tm2_computable fin_encoding_bool_bool fin_encoding_bool_bool id) := ⟨id_computable computability.inhabited_fin_encoding.default⟩ instance inhabited_tm2_computable_aux : inhabited (tm2_computable_aux bool bool) := ⟨(default (tm2_computable fin_encoding_bool_bool fin_encoding_bool_bool id)).to_tm2_computable_aux⟩ end turing
fcdec36eb83d9bcdd1d417a8d04eafc511fdbc0b
b328e8ebb2ba923140e5137c83f09fa59516b793
/stage0/src/Lean/Elab/Quotation.lean
34713002a9bb1bf7c4fde7cf23732020277213ee
[ "Apache-2.0" ]
permissive
DrMaxis/lean4
a781bcc095511687c56ab060e816fd948553e162
5a02c4facc0658aad627cfdcc3db203eac0cb544
refs/heads/master
1,677,051,517,055
1,611,876,226,000
1,611,876,226,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
23,111
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich Elaboration of syntax quotations as terms and patterns (in `match_syntax`). See also `./Hygiene.lean` for the basic hygiene workings and data types. -/ import Lean.Syntax import Lean.ResolveName import Lean.Elab.Term import Lean.Elab.Quotation.Util import Lean.Parser.Term namespace Lean.Elab.Term.Quotation open Lean.Parser.Term open Lean.Syntax open Meta /-- `C[$(e)]` ~> `let a := e; C[$a]`. Used in the implementation of antiquot splices. -/ private partial def floatOutAntiquotTerms : Syntax → StateT (Syntax → TermElabM Syntax) TermElabM Syntax | stx@(Syntax.node k args) => do if isAntiquot stx && !isEscapedAntiquot stx then let e := getAntiquotTerm stx if !e.isIdent || !e.getId.isAtomic then return ← withFreshMacroScope do let a ← `(a) modify (fun cont stx => (`(let $a:ident := $e; $stx) : TermElabM _)) stx.setArg 2 a Syntax.node k (← args.mapM floatOutAntiquotTerms) | stx => pure stx private def getSepFromSplice (splice : Syntax) : Syntax := do let Syntax.atom _ sep ← getAntiquotSpliceSuffix splice | unreachable! Syntax.mkStrLit (sep.dropRight 1) partial def mkTuple : Array Syntax → TermElabM Syntax | #[] => `(Unit.unit) | #[e] => e | es => do let stx ← mkTuple (es.eraseIdx 0) `(Prod.mk $(es[0]) $stx) def resolveSectionVariable (sectionVars : NameMap Name) (id : Name) : List (Name × List String) := -- decode macro scopes from name before recursion let extractionResult := extractMacroScopes id let rec loop : Name → List String → List (Name × List String) | id@(Name.str p s _), projs => -- NOTE: we assume that macro scopes always belong to the projected constant, not the projections let id := { extractionResult with name := id }.review match sectionVars.find? id with | some newId => [(newId, projs)] | none => loop p (s::projs) | _, _ => [] loop extractionResult.name [] -- Elaborate the content of a syntax quotation term private partial def quoteSyntax : Syntax → TermElabM Syntax | Syntax.ident info rawVal val preresolved => do -- Add global scopes at compilation time (now), add macro scope at runtime (in the quotation). -- See the paper for details. let r ← resolveGlobalName val -- extension of the paper algorithm: also store unique section variable names as top-level scopes -- so they can be captured and used inside the section, but not outside let r' := resolveSectionVariable (← read).sectionVars val let preresolved := r ++ r' ++ preresolved let val := quote val -- `scp` is bound in stxQuot.expand `(Syntax.ident info $(quote rawVal) (addMacroScope mainModule $val scp) $(quote preresolved)) -- if antiquotation, insert contents as-is, else recurse | stx@(Syntax.node k _) => do if isAntiquot stx && !isEscapedAntiquot stx then getAntiquotTerm stx else if isTokenAntiquot stx && !isEscapedAntiquot stx then match stx[0] with | Syntax.atom _ val => `(Syntax.atom (Option.getD (getHeadInfo $(getAntiquotTerm stx)) info) $(quote val)) | _ => throwErrorAt stx "expected token" else if isAntiquotSuffixSplice stx && !isEscapedAntiquot stx then -- splices must occur in a `many` node throwErrorAt stx "unexpected antiquotation splice" else if isAntiquotSplice stx && !isEscapedAntiquot stx then throwErrorAt stx "unexpected antiquotation splice" else let empty ← `(Array.empty); -- if escaped antiquotation, decrement by one escape level let stx := unescapeAntiquot stx let args ← stx.getArgs.foldlM (fun args arg => do if k == nullKind && isAntiquotSuffixSplice arg then let antiquot := getAntiquotSuffixSpliceInner arg match antiquotSuffixSplice? arg with | `optional => `(Array.appendCore $args (match $(getAntiquotTerm antiquot):term with | some x => Array.empty.push x | none => Array.empty)) | `many => `(Array.appendCore $args $(getAntiquotTerm antiquot)) | `sepBy => `(Array.appendCore $args (@SepArray.elemsAndSeps $(getSepFromSplice arg) $(getAntiquotTerm antiquot))) | k => throwErrorAt! arg "invalid antiquotation suffix splice kind '{k}'" else if k == nullKind && isAntiquotSplice arg then let k := antiquotSpliceKind? arg let (arg, bindLets) ← floatOutAntiquotTerms arg |>.run pure let inner ← (getAntiquotSpliceContents arg).mapM quoteSyntax let ids ← getAntiquotationIds arg if ids.isEmpty then throwErrorAt stx "antiquotation splice must contain at least one antiquotation" let arr ← match k with | `optional => `(match $[$ids:ident],* with | $[some $ids:ident],* => $(quote inner) | none => Array.empty) | _ => let arr ← ids[:ids.size-1].foldrM (fun id arr => `(Array.zip $id $arr)) ids.back `(Array.map (fun $(← mkTuple ids) => $(inner[0])) $arr) let arr ← if k == `sepBy then `(mkSepArray $arr (mkAtom $(getSepFromSplice arg))) else arr let arr ← bindLets arr `(Array.appendCore $args $arr) else do let arg ← quoteSyntax arg; `(Array.push $args $arg)) empty `(Syntax.node $(quote k) $args) | Syntax.atom _ val => `(Syntax.atom info $(quote val)) | Syntax.missing => unreachable! def stxQuot.expand (stx : Syntax) : TermElabM Syntax := do /- Syntax quotations are monadic values depending on the current macro scope. For efficiency, we bind the macro scope once for each quotation, then build the syntax tree in a completely pure computation depending on this binding. Note that regular function calls do not introduce a new macro scope (i.e. we preserve referential transparency), so we can refer to this same `scp` inside `quoteSyntax` by including it literally in a syntax quotation. -/ -- TODO: simplify to `(do scp ← getCurrMacroScope; pure $(quoteSyntax quoted)) let stx ← quoteSyntax stx.getQuotContent; `(Bind.bind MonadRef.mkInfoFromRefPos (fun info => Bind.bind getCurrMacroScope (fun scp => Bind.bind getMainModule (fun mainModule => Pure.pure $stx)))) /- NOTE: It may seem like the newly introduced binding `scp` may accidentally capture identifiers in an antiquotation introduced by `quoteSyntax`. However, note that the syntax quotation above enjoys the same hygiene guarantees as anywhere else in Lean; that is, we implement hygienic quotations by making use of the hygienic quotation support of the bootstrapped Lean compiler! Aside: While this might sound "dangerous", it is in fact less reliant on a "chain of trust" than other bootstrapping parts of Lean: because this implementation itself never uses `scp` (or any other identifier) both inside and outside quotations, it can actually correctly be compiled by an unhygienic (but otherwise correct) implementation of syntax quotations. As long as it is then compiled again with the resulting executable (i.e. up to stage 2), the result is a correct hygienic implementation. In this sense the implementation is "self-stabilizing". It was in fact originally compiled by an unhygienic prototype implementation. -/ macro "elabStxQuot!" kind:ident : command => `(@[builtinTermElab $kind:ident] def elabQuot : TermElab := adaptExpander stxQuot.expand) -- elabStxQuot! Parser.Level.quot elabStxQuot! Parser.Term.quot elabStxQuot! Parser.Term.funBinder.quot elabStxQuot! Parser.Term.bracketedBinder.quot elabStxQuot! Parser.Term.matchDiscr.quot elabStxQuot! Parser.Tactic.quot elabStxQuot! Parser.Tactic.quotSeq elabStxQuot! Parser.Term.stx.quot elabStxQuot! Parser.Term.prec.quot elabStxQuot! Parser.Term.attr.quot elabStxQuot! Parser.Term.prio.quot elabStxQuot! Parser.Term.doElem.quot elabStxQuot! Parser.Term.dynamicQuot /- match -/ -- an "alternative" of patterns plus right-hand side private abbrev Alt := List Syntax × Syntax /-- In a single match step, we match the first discriminant against the "head" of the first pattern of the first alternative. This datatype describes what kind of check this involves, which helps other patterns decide if they are covered by the same check and don't have to be checked again (see also `MatchResult`). -/ inductive HeadCheck where -- match step that always succeeds: _, x, `($x), ... | unconditional -- match step based on kind and, optionally, arity of discriminant -- If `arity` is given, that number of new discriminants is introduced. `covered` patterns should then introduce the -- same number of new patterns. -- We actually check the arity at run time only in the case of `null` nodes since it should otherwise by implied by -- the node kind. -- without arity: `($x:k) -- with arity: any quotation without an antiquotation head pattern | shape (k : SyntaxNodeKind) (arity : Option Nat) -- Match step that succeeds on `null` nodes of arity at least `numPrefix + numSuffix`, introducing discriminants -- for the first `numPrefix` children, one `null` node for those in between, and for the `numSuffix` last children. -- example: `([$x, $xs,*, $y]) is `slice 2 2` | slice (numPrefix numSuffix : Nat) -- other, complicated match step that will probably only cover identical patterns -- example: antiquotation splices `($[...]*) | other (pat : Syntax) open HeadCheck /-- Describe whether a pattern is covered by a head check (induced by the pattern itself or a different pattern). -/ inductive MatchResult where -- Pattern agrees with head check, remove and transform remaining alternative. -- If `exhaustive` is `false`, *also* include unchanged alternative in the "no" branch. | covered (f : Alt → TermElabM Alt) (exhaustive : Bool) -- Pattern disagrees with head check, include in "no" branch only | uncovered -- Pattern is not quite sure yet; include unchanged in both branches | undecided open MatchResult /-- All necessary information on a pattern head. -/ structure HeadInfo where -- check induced by the pattern check : HeadCheck -- compute compatibility of pattern with given head check onMatch (taken : HeadCheck) : MatchResult -- actually run the specified head check, with the discriminant bound to `discr` doMatch (yes : (newDiscrs : List Syntax) → TermElabM Syntax) (no : TermElabM Syntax) : TermElabM Syntax /-- Adapt alternatives that do not introduce new discriminants in `doMatch`, but are covered by those that do so. -/ private def noOpMatchAdaptPats : HeadCheck → Alt → Alt | shape k (some sz), (pats, rhs) => (List.replicate sz (Unhygienic.run `(_)) ++ pats, rhs) | slice p s, (pats, rhs) => (List.replicate (p + 1 + s) (Unhygienic.run `(_)) ++ pats, rhs) | _, alt => alt private def adaptRhs (fn : Syntax → TermElabM Syntax) : Alt → TermElabM Alt | (pats, rhs) => do (pats, ← fn rhs) private partial def getHeadInfo (alt : Alt) : TermElabM HeadInfo := let pat := alt.fst.head! let unconditionally (rhsFn) := pure { check := unconditional, doMatch := fun yes no => yes [], onMatch := fun taken => covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (match taken with | unconditional => true | _ => false) } -- quotation pattern if isQuot pat then let quoted := getQuotContent pat if quoted.isAtom then -- We assume that atoms are uniquely determined by the node kind and never have to be checked unconditionally pure else if quoted.isTokenAntiquot then unconditionally (`(let $(quoted.getAntiquotTerm) := discr; $(·))) else if isAntiquot quoted && !isEscapedAntiquot quoted then -- quotation contains a single antiquotation let k := antiquotKind? quoted |>.get! -- Antiquotation kinds like `$id:ident` influence the parser, but also need to be considered by -- `match` (but not by quotation terms). For example, `($id:ident) and `($e) are not -- distinguishable without checking the kind of the node to be captured. Note that some -- antiquotations like the latter one for terms do not correspond to any actual node kind -- (signified by `k == Name.anonymous`), so we would only check for `ident` here. -- -- if stx.isOfKind `ident then -- let id := stx; let e := stx; ... -- else -- let e := stx; ... let anti := getAntiquotTerm quoted if anti.isIdent then let rhsFn := (`(let $anti := discr; $(·))) if k == Name.anonymous then unconditionally rhsFn else pure { check := shape k none, onMatch := fun | taken@(shape k' sz) => if k' == k then covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (exhaustive := sz.isNone) else uncovered | _ => uncovered, doMatch := fun yes no => do `(cond (Syntax.isOfKind discr $(quote k)) $(← yes []) $(← no)), } else throwErrorAt! anti "match_syntax: antiquotation must be variable {anti}" else if isAntiquotSuffixSplice quoted then throwErrorAt quoted "unexpected antiquotation splice" else if isAntiquotSplice quoted then throwErrorAt quoted "unexpected antiquotation splice" else if quoted.getArgs.size == 1 && isAntiquotSuffixSplice quoted[0] then let anti := getAntiquotTerm (getAntiquotSuffixSpliceInner quoted[0]) unconditionally fun rhs => match antiquotSuffixSplice? quoted[0] with | `optional => `(let $anti := Syntax.getOptional? discr; $rhs) | `many => `(let $anti := Syntax.getArgs discr; $rhs) | `sepBy => `(let $anti := @SepArray.mk $(getSepFromSplice quoted[0]) (Syntax.getArgs discr); $rhs) | k => throwErrorAt! quoted "invalid antiquotation suffix splice kind '{k}'" else if quoted.getArgs.size == 1 && isAntiquotSplice quoted[0] then pure { check := other pat, onMatch := fun | other pat' => if pat' == pat then covered pure (exhaustive := true) else undecided | _ => undecided, doMatch := fun yes no => do let splice := quoted[0] let k := antiquotSpliceKind? splice let contents := getAntiquotSpliceContents splice let ids ← getAntiquotationIds splice let yes ← yes [] let no ← no match k with | `optional => let nones := mkArray ids.size (← `(none)) `(let* yes _ $ids* := $yes; if discr.isNone then yes () $[ $nones]* else match discr with | `($(mkNullNode contents)) => yes () $[ (some $ids)]* | _ => $no) | _ => let mut discrs ← `(Syntax.getArgs discr) if k == `sepBy then discrs ← `(Array.getSepElems $discrs) let tuple ← mkTuple ids let mut yes := yes let resId ← match ids with | #[id] => id | _ => for id in ids do yes ← `(let $id := tuples.map (fun $tuple => $id); $yes) `(tuples) `(match ($(discrs).sequenceMap fun | `($(contents[0])) => some $tuple | _ => none) with | some $resId => $yes | none => $no) } else if let some idx := quoted.getArgs.findIdx? (fun arg => isAntiquotSuffixSplice arg || isAntiquotSplice arg) then do /- pattern of the form `match discr, ... with | `(pat_0 ... pat_(idx-1) $[...]* pat_(idx+1) ...), ...` transform to ``` if discr.getNumArgs >= $quoted.getNumArgs - 1 then match discr[0], ..., discr[idx-1], mkNullNode (discr.getArgs.extract idx (discr.getNumArgs - $numSuffix))), ..., discr[quoted.getNumArgs - 1] with | `(pat_0), ... `(pat_(idx-1)), `($[...])*, `(pat_(idx+1)), ... ``` -/ let numSuffix := quoted.getNumArgs - 1 - idx pure { check := slice idx numSuffix onMatch := fun | slice p s => if p == idx && s == numSuffix then let argPats := quoted.getArgs.mapIdx fun i arg => let arg := if (i : Nat) == idx then mkNullNode #[arg] else arg Unhygienic.run `(`($(arg))) covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true) else uncovered | _ => uncovered doMatch := fun yes no => do let prefixDiscrs ← (List.range idx).mapM (`(Syntax.getArg discr $(quote ·))) let sliceDiscr ← `(mkNullNode (discr.getArgs.extract $(quote idx) (discr.getNumArgs - $(quote numSuffix)))) let suffixDiscrs ← (List.range numSuffix).mapM fun i => `(Syntax.getArg discr (discr.getNumArgs - $(quote (numSuffix - i)))) `(ite (GreaterEq discr.getNumArgs $(quote (quoted.getNumArgs - 1))) $(← yes (prefixDiscrs ++ sliceDiscr :: suffixDiscrs)) $(← no)) } else -- not an antiquotation, or an escaped antiquotation: match head shape let quoted := unescapeAntiquot quoted let kind := quoted.getKind let argPats := quoted.getArgs.map fun arg => Unhygienic.run `(`($(arg))) pure { check := shape kind argPats.size, onMatch := fun taken => if (match taken with | shape k' sz => k' == kind && sz == argPats.size | _ => false : Bool) then covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true) else uncovered, doMatch := fun yes no => do let cond ← match kind with | `null => `(and (Syntax.isOfKind discr $(quote kind)) (BEq.beq (Array.size (Syntax.getArgs discr)) $(quote argPats.size))) | _ => `(Syntax.isOfKind discr $(quote kind)) let newDiscrs ← (List.range argPats.size).mapM fun i => `(Syntax.getArg discr $(quote i)) `(ite (Eq $cond true) $(← yes newDiscrs) $(← no)) } else match pat with | `(_) => unconditionally pure | `($id:ident) => unconditionally (`(let $id := discr; $(·))) | `($id:ident@$pat) => do let info ← getHeadInfo (pat::alt.1.tail!, alt.2) { info with onMatch := fun taken => match info.onMatch taken with | covered f exh => covered (fun alt => f alt >>= adaptRhs (`(let $id := discr; $(·)))) exh | r => r } | _ => throwErrorAt! pat "match_syntax: unexpected pattern kind {pat}" -- Bind right-hand side to new `let*` decl in order to prevent code duplication private def deduplicate (floatedLetDecls : Array Syntax) : Alt → TermElabM (Array Syntax × Alt) -- NOTE: new macro scope so that introduced bindings do not collide | (pats, rhs) => do if let `($f:ident $[ $args:ident]*) := rhs then -- looks simple enough/created by this function, skip return (floatedLetDecls, (pats, rhs)) withFreshMacroScope do match ← getPatternsVars pats.toArray with | #[] => -- no antiquotations => introduce Unit parameter to preserve evaluation order let rhs' ← `(rhs Unit.unit) (floatedLetDecls.push (← `(letDecl|rhs _ := $rhs)), (pats, rhs')) | vars => let rhs' ← `(rhs $vars*) (floatedLetDecls.push (← `(letDecl|rhs $vars:ident* := $rhs)), (pats, rhs')) private partial def compileStxMatch (discrs : List Syntax) (alts : List Alt) : TermElabM Syntax := do trace[Elab.match_syntax]! "match {discrs} with {alts}" match discrs, alts with | [], ([], rhs)::_ => pure rhs -- nothing left to match | _, [] => throwError "non-exhaustive 'match_syntax'" | discr::discrs, alt::alts => do let info ← getHeadInfo alt let pat := alt.1.head! let alts ← (alt::alts).mapM fun alt => do ((← getHeadInfo alt).onMatch info.check, alt) let mut yesAlts := #[] let mut undecidedAlts := #[] let mut nonExhaustiveAlts := #[] let mut floatedLetDecls := #[] for alt in alts do let mut alt := alt match alt with | (covered f exh, alt) => -- we can only factor out a common check if there are no undecided patterns in between; -- otherwise we would change the order of alternatives if undecidedAlts.isEmpty then yesAlts ← yesAlts.push <$> f (alt.1.tail!, alt.2) if !exh then nonExhaustiveAlts := nonExhaustiveAlts.push alt else (floatedLetDecls, alt) ← deduplicate floatedLetDecls alt undecidedAlts := undecidedAlts.push alt nonExhaustiveAlts := nonExhaustiveAlts.push alt | (undecided, alt) => (floatedLetDecls, alt) ← deduplicate floatedLetDecls alt undecidedAlts := undecidedAlts.push alt nonExhaustiveAlts := nonExhaustiveAlts.push alt | (uncovered, alt) => nonExhaustiveAlts := nonExhaustiveAlts.push alt let mut stx ← info.doMatch (yes := fun newDiscrs => do let mut yesAlts := yesAlts if !undecidedAlts.isEmpty then -- group undecided alternatives in a new default case `| discr2, ... => match discr, discr2, ... with ...` let vars ← discrs.mapM fun _ => withFreshMacroScope `(discr) let pats := List.replicate newDiscrs.length (Unhygienic.run `(_)) ++ vars let alts ← undecidedAlts.mapM fun alt => `(matchAltExpr| | $(alt.1.toArray),* => $(alt.2)) let rhs ← `(match discr, $[$(vars.toArray):term],* with $alts:matchAlt*) yesAlts := yesAlts.push (pats, rhs) withFreshMacroScope $ compileStxMatch (newDiscrs ++ discrs) yesAlts.toList) (no := withFreshMacroScope $ compileStxMatch (discr::discrs) nonExhaustiveAlts.toList) for d in floatedLetDecls do stx ← `(let* $d:letDecl; $stx) `(let discr := $discr; $stx) | _, _ => unreachable! def match_syntax.expand (stx : Syntax) : TermElabM Syntax := do match stx with | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do if !patss.any (·.any (fun | `($id@$pat) => pat.isQuot | pat => pat.isQuot)) then -- no quotations => fall back to regular `match` throwUnsupportedSyntax let stx ← compileStxMatch discrs.toList (patss.map (·.toList) |>.zip rhss).toList trace[Elab.match_syntax.result]! "{stx}" stx | _ => throwUnsupportedSyntax @[builtinTermElab «match»] def elabMatchSyntax : TermElab := adaptExpander match_syntax.expand builtin_initialize registerTraceClass `Elab.match_syntax registerTraceClass `Elab.match_syntax.result end Lean.Elab.Term.Quotation
feeb3c8239caf45704179f0a535de0c5abd22c8c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/multiset/functor.lean
b545105906f951c03ae8c0fda068e2b7305302ac
[ "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
4,266
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Simon Hudon, Kenny Lau -/ import data.multiset.basic import control.traversable.lemmas import control.traversable.instances /-! # Functoriality of `multiset`. -/ universes u namespace multiset open list instance : functor multiset := { map := @map } @[simp] lemma fmap_def {α' β'} {s : multiset α'} (f : α' → β') : f <$> s = s.map f := rfl instance : is_lawful_functor multiset := by refine { .. }; intros; simp open is_lawful_traversable is_comm_applicative variables {F : Type u → Type u} [applicative F] [is_comm_applicative F] variables {α' β' : Type u} (f : α' → F β') def traverse : multiset α' → F (multiset β') := quotient.lift (functor.map coe ∘ traversable.traverse f) begin introv p, unfold function.comp, induction p, case perm.nil { refl }, case perm.cons { have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) = multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂), { rw [p_ih] }, simpa with functor_norm }, case perm.swap { have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x = (λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y, { rw [is_comm_applicative.commutative_map], congr, funext a b l, simpa [flip] using perm.swap b a l }, simp [(∘), this] with functor_norm }, case perm.trans { simp [*] } end instance : monad multiset := { pure := λ α x, x ::ₘ 0, bind := @bind, .. multiset.functor } @[simp] lemma pure_def {α} : (pure : α → multiset α) = (λ x, x ::ₘ 0) := rfl @[simp] lemma bind_def {α β} : (>>=) = @bind α β := rfl instance : is_lawful_monad multiset := { bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih, by simp, pure_bind := λ α β x f, by simp, bind_assoc := @bind_assoc } open functor open traversable is_lawful_traversable @[simp] lemma lift_coe {α β : Type*} (x : list α) (f : list α → β) (h : ∀ a b : list α, a ≈ b → f a = f b) : quotient.lift f h (x : multiset α) = f x := quotient.lift_mk _ _ _ @[simp] lemma map_comp_coe {α β} (h : α → β) : functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) := by funext; simp [functor.map] lemma id_traverse {α : Type*} (x : multiset α) : traverse id.mk x = x := quotient.induction_on x begin intro, simp [traverse], refl end lemma comp_traverse {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] {α β γ : Type*} (g : α → G β) (h : β → H γ) (x : multiset α) : traverse (comp.mk ∘ functor.map h ∘ g) x = comp.mk (functor.map (traverse h) (traverse g x)) := quotient.induction_on x (by intro; simp [traverse,comp_traverse] with functor_norm; simp [(<$>),(∘)] with functor_norm) lemma map_traverse {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → G β) (h : β → γ) (x : multiset α) : functor.map (functor.map h) (traverse g x) = traverse (functor.map h ∘ g) x := quotient.induction_on x (by intro; simp [traverse] with functor_norm; rw [is_lawful_functor.comp_map, map_traverse]) lemma traverse_map {G : Type* → Type*} [applicative G] [is_comm_applicative G] {α β γ : Type*} (g : α → β) (h : β → G γ) (x : multiset α) : traverse h (map g x) = traverse (h ∘ g) x := quotient.induction_on x (by intro; simp [traverse]; rw [← traversable.traverse_map h g]; [ refl, apply_instance ]) lemma naturality {G H : Type* → Type*} [applicative G] [applicative H] [is_comm_applicative G] [is_comm_applicative H] (eta : applicative_transformation G H) {α β : Type*} (f : α → G β) (x : multiset α) : eta (traverse f x) = traverse (@eta _ ∘ f) x := quotient.induction_on x (by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm) end multiset
41f09459f0dde018f53ec179dbc1955c32287b65
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/structInst2.lean
2de347a0836d941e17dd61ef7f43cb192e5dc9df
[ "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
1,516
lean
import Init.Control.Option universe u v def OptionT2 (m : Type u → Type v) (α : Type u) : Type v := m (Option α) namespace OptionT2 variable {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def bind (ma : OptionT2 m α) (f : α → OptionT2 m β) : OptionT2 m β := (do { let a? ← ma; (match a? with | some a => f a | none => pure none) } : m (Option β)) @[inline] protected def pure (a : α) : OptionT2 m α := (Pure.pure (some a) : m (Option α)) @[inline] protected def orelse (ma : OptionT2 m α) (mb : OptionT2 m α) : OptionT2 m α := (do { let a? ← ma; (match a? with | some a => pure (some a) | _ => mb) } : m (Option α)) @[inline] protected def fail : OptionT2 m α := (pure none : m (Option α)) end OptionT2 instance optMonad1 {m} [Monad m] : Monad (OptionT2 m) := { pure := OptionT2.pure, bind := OptionT2.bind } def optMonad2 {m} [Monad m] : Monad (OptionT m) := { pure := OptionT.pure, bind := OptionT.bind } def optAlt1 {m} [Monad m] : Alternative (OptionT m) := { failure := OptionT.fail, orElse := OptionT.orElse, toApplicative := Monad.toApplicative } def optAlt2 {m} [Monad m] : Alternative (OptionT m) := ⟨OptionT.fail, OptionT.orElse⟩ -- it works because it treats `toApplicative` as an instance implicit argument def optAlt3 {m} [Monad m] : Alternative (OptionT2 m) := { failure := OptionT2.fail, orElse := OptionT2.orelse, toApplicative := Monad.toApplicative }
b2356d9f891287a59f0497a8b3673b9b0ac9aac4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/lie/centralizer.lean
eb28c3e542be6801ad12246261e7d5febe15a4d1
[ "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
6,648
lean
/- Copyright (c) 2022 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.abelian import algebra.lie.ideal_operations import algebra.lie.quotient /-! # The centralizer of a Lie submodule and the normalizer of a Lie subalgebra. Given a Lie module `M` over a Lie subalgebra `L`, the centralizer of a Lie submodule `N ⊆ M` is the Lie submodule with underlying set `{ m | ∀ (x : L), ⁅x, m⁆ ∈ N }`. The lattice of Lie submodules thus has two natural operations, the centralizer: `N ↦ N.centralizer` and the ideal operation: `N ↦ ⁅⊤, N⁆`; these are adjoint, i.e., they form a Galois connection. This adjointness is the reason that we may define nilpotency in terms of either the upper or lower central series. Given a Lie subalgebra `H ⊆ L`, we may regard `H` as a Lie submodule of `L` over `H`, and thus consider the centralizer. This turns out to be a Lie subalgebra and is known as the normalizer. ## Main definitions * `lie_submodule.centralizer` * `lie_subalgebra.normalizer` * `lie_submodule.gc_top_lie_centralizer` ## Tags lie algebra, centralizer, normalizer -/ variables {R L M M' : Type*} variables [comm_ring R] [lie_ring L] [lie_algebra R L] variables [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] variables [add_comm_group M'] [module R M'] [lie_ring_module L M'] [lie_module R L M'] namespace lie_submodule variables (N : lie_submodule R L M) {N₁ N₂ : lie_submodule R L M} /-- The centralizer of a Lie submodule. -/ def centralizer : lie_submodule R L M := { carrier := { m | ∀ (x : L), ⁅x, m⁆ ∈ N }, add_mem' := λ m₁ m₂ hm₁ hm₂ x, by { rw lie_add, exact N.add_mem' (hm₁ x) (hm₂ x), }, zero_mem' := λ x, by simp, smul_mem' := λ t m hm x, by { rw lie_smul, exact N.smul_mem' t (hm x), }, lie_mem := λ x m hm y, by { rw leibniz_lie, exact N.add_mem' (hm ⁅y, x⁆) (N.lie_mem (hm y)), } } @[simp] lemma mem_centralizer (m : M) : m ∈ N.centralizer ↔ ∀ (x : L), ⁅x, m⁆ ∈ N := iff.rfl lemma le_centralizer : N ≤ N.centralizer := begin intros m hm, rw mem_centralizer, exact λ x, N.lie_mem hm, end lemma centralizer_inf : (N₁ ⊓ N₂).centralizer = N₁.centralizer ⊓ N₂.centralizer := by { ext, simp [← forall_and_distrib], } @[mono] lemma monotone_centalizer : monotone (centralizer : lie_submodule R L M → lie_submodule R L M) := begin intros N₁ N₂ h m hm, rw mem_centralizer at hm ⊢, exact λ x, h (hm x), end @[simp] lemma comap_centralizer (f : M' →ₗ⁅R,L⁆ M) : N.centralizer.comap f = (N.comap f).centralizer := by { ext, simp, } lemma top_lie_le_iff_le_centralizer (N' : lie_submodule R L M) : ⁅(⊤ : lie_ideal R L), N⁆ ≤ N' ↔ N ≤ N'.centralizer := by { rw lie_le_iff, tauto, } lemma gc_top_lie_centralizer : galois_connection (λ N : lie_submodule R L M, ⁅(⊤ : lie_ideal R L), N⁆) centralizer := top_lie_le_iff_le_centralizer variables (R L M) lemma centralizer_bot_eq_max_triv_submodule : (⊥ : lie_submodule R L M).centralizer = lie_module.max_triv_submodule R L M := rfl end lie_submodule namespace lie_subalgebra variables (H : lie_subalgebra R L) /-- Regarding a Lie subalgebra `H ⊆ L` as a module over itself, its centralizer is in fact a Lie subalgebra. This is called the normalizer of the Lie subalgebra. -/ def normalizer : lie_subalgebra R L := { lie_mem' := λ y z hy hz x, begin rw [coe_bracket_of_module, mem_to_lie_submodule, leibniz_lie, ← lie_skew y, ← sub_eq_add_neg], exact H.sub_mem (hz ⟨_, hy x⟩) (hy ⟨_, hz x⟩), end, .. H.to_lie_submodule.centralizer } lemma mem_normalizer_iff' (x : L) : x ∈ H.normalizer ↔ ∀ (y : L), (y ∈ H) → ⁅y, x⁆ ∈ H := by { rw subtype.forall', refl, } lemma mem_normalizer_iff (x : L) : x ∈ H.normalizer ↔ ∀ (y : L), (y ∈ H) → ⁅x, y⁆ ∈ H := begin rw mem_normalizer_iff', refine forall₂_congr (λ y hy, _), rw [← lie_skew, neg_mem_iff], end lemma le_normalizer : H ≤ H.normalizer := H.to_lie_submodule.le_centralizer lemma coe_centralizer_eq_normalizer : (H.to_lie_submodule.centralizer : submodule R L) = H.normalizer := rfl variables {H} lemma lie_mem_sup_of_mem_normalizer {x y z : L} (hx : x ∈ H.normalizer) (hy : y ∈ (R ∙ x) ⊔ ↑H) (hz : z ∈ (R ∙ x) ⊔ ↑H) : ⁅y, z⁆ ∈ (R ∙ x) ⊔ ↑H := begin rw submodule.mem_sup at hy hz, obtain ⟨u₁, hu₁, v, hv : v ∈ H, rfl⟩ := hy, obtain ⟨u₂, hu₂, w, hw : w ∈ H, rfl⟩ := hz, obtain ⟨t, rfl⟩ := submodule.mem_span_singleton.mp hu₁, obtain ⟨s, rfl⟩ := submodule.mem_span_singleton.mp hu₂, apply submodule.mem_sup_right, simp only [lie_subalgebra.mem_coe_submodule, smul_lie, add_lie, zero_add, lie_add, smul_zero, lie_smul, lie_self], refine H.add_mem (H.smul_mem s _) (H.add_mem (H.smul_mem t _) (H.lie_mem hv hw)), exacts [(H.mem_normalizer_iff' x).mp hx v hv, (H.mem_normalizer_iff x).mp hx w hw], end /-- A Lie subalgebra is an ideal of its normalizer. -/ lemma ideal_in_normalizer {x y : L} (hx : x ∈ H.normalizer) (hy : y ∈ H) : ⁅x,y⁆ ∈ H := begin rw [← lie_skew, neg_mem_iff], exact hx ⟨y, hy⟩, end /-- A Lie subalgebra `H` is an ideal of any Lie subalgebra `K` containing `H` and contained in the normalizer of `H`. -/ lemma exists_nested_lie_ideal_of_le_normalizer {K : lie_subalgebra R L} (h₁ : H ≤ K) (h₂ : K ≤ H.normalizer) : ∃ (I : lie_ideal R K), (I : lie_subalgebra R K) = of_le h₁ := begin rw exists_nested_lie_ideal_coe_eq_iff, exact λ x y hx hy, ideal_in_normalizer (h₂ hx) hy, end variables (H) lemma normalizer_eq_self_iff : H.normalizer = H ↔ (lie_module.max_triv_submodule R H $ L ⧸ H.to_lie_submodule) = ⊥ := begin rw lie_submodule.eq_bot_iff, refine ⟨λ h, _, λ h, le_antisymm (λ x hx, _) H.le_normalizer⟩, { rintros ⟨x⟩ hx, suffices : x ∈ H, by simpa, rw [← h, H.mem_normalizer_iff'], intros y hy, replace hx : ⁅_, lie_submodule.quotient.mk' _ x⁆ = 0 := hx ⟨y, hy⟩, rwa [← lie_module_hom.map_lie, lie_submodule.quotient.mk_eq_zero] at hx, }, { let y := lie_submodule.quotient.mk' H.to_lie_submodule x, have hy : y ∈ lie_module.max_triv_submodule R H (L ⧸ H.to_lie_submodule), { rintros ⟨z, hz⟩, rw [← lie_module_hom.map_lie, lie_submodule.quotient.mk_eq_zero, coe_bracket_of_module, submodule.coe_mk, mem_to_lie_submodule], exact (H.mem_normalizer_iff' x).mp hx z hz, }, simpa using h y hy, }, end end lie_subalgebra
c38d4b330ba7d71fff7a3d707c21e54d40990730
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/list_local_vars.lean
0e5dbb907bb8be66a6233af49a2183ec5e36c286
[ "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
1,996
lean
-- #exit open interactive tactic.interactive namespace tactic.interactive open lean.parser meta def tac (ls : parse lean.parser.list_include_var_names) : tactic unit := trace ls open interactive.types @[user_command] meta def tac_cmd (_ : parse $ tk "stuff") : lean.parser unit := with_local_scope $ do ls ← lean.parser.list_available_include_vars, trace ls, ls ← lean.parser.list_include_var_names, (n,t) ← brackets "(" ")" (prod.mk <$> (ident <* tk ":") <*> texpr), t ← tactic.to_expr t, v ← tactic.mk_local_def n t, lean.parser.add_local v, (n',t') ← brackets "(" ")" (prod.mk <$> (ident <* tk ":") <*> texpr), t' ← tactic.to_expr t', v ← tactic.mk_local_def n' t', lean.parser.add_local v, include_var v.local_pp_name, trace ls, ls ← tactic.local_context, trace ls, brackets "(" ")" texpr, ↑(ls.mmap' $ trace ∘ to_string) @[user_command] meta def add_var_cmd (_ : parse $ tk "add_var") : lean.parser unit := do (n,t) ← brackets "(" ")" (prod.mk <$> (ident <* tk ":") <*> texpr), t ← tactic.to_expr t, v ← tactic.mk_local_def n t, add_local_level `u, lean.parser.add_local v, include_var v.local_pp_name, (n',t') ← brackets "(" ")" (prod.mk <$> (ident <* tk ":") <*> texpr), t' ← tactic.to_expr t', v ← tactic.mk_local_def n' t', lean.parser.add_local v, include_var v.local_pp_name, omit_var v.local_pp_name, ls ← lean.parser.list_include_var_names, -- trace ls, trace_state end tactic.interactive variables (a b c : ℕ) include a b variables {α : Type} section stuff (β : Type) (γ : Type) (α × β × γ) def x := β def y := γ #check x section add_var (β : Type) (γ : Type u) def x' : β → β := id def y' : γ → γ := id end def x'' := β def y'' := γ #check x' #check y' section parameter δ : Type #print δ #print β end #print γ end example : c ≤ 3 := begin (do v ← tactic.get_local `a, trace $ v.local_pp_name ), tac end
551280518cedee43fd6d77873712d136a3d2cd75
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/calculus/cont_diff.lean
1cd0fd7da5153a0d787a33fb33af669b336ee300
[ "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
143,605
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.calculus.mean_value import analysis.normed_space.multilinear import analysis.calculus.formal_multilinear_series /-! # Higher differentiability A function is `C^1` on a domain if it is differentiable there, and its derivative is continuous. By induction, it is `C^n` if it is `C^{n-1}` and its (n-1)-th derivative is `C^1` there or, equivalently, if it is `C^1` and its derivative is `C^{n-1}`. Finally, it is `C^∞` if it is `C^n` for all n. We formalize these notions by defining iteratively the `n+1`-th derivative of a function as the derivative of the `n`-th derivative. It is called `iterated_fderiv 𝕜 n f x` where `𝕜` is the field, `n` is the number of iterations, `f` is the function and `x` is the point, and it is given as an `n`-multilinear map. We also define a version `iterated_fderiv_within` relative to a domain, as well as predicates `cont_diff_within_at`, `cont_diff_at`, `cont_diff_on` and `cont_diff` saying that the function is `C^n` within a set at a point, at a point, on a set and on the whole space respectively. To avoid the issue of choice when choosing a derivative in sets where the derivative is not necessarily unique, `cont_diff_on` is not defined directly in terms of the regularity of the specific choice `iterated_fderiv_within 𝕜 n f s` inside `s`, but in terms of the existence of a nice sequence of derivatives, expressed with a predicate `has_ftaylor_series_up_to_on`. We prove basic properties of these notions. ## Main definitions and results Let `f : E → F` be a map between normed vector spaces over a nondiscrete normed field `𝕜`. * `has_ftaylor_series_up_to n f p`: expresses that the formal multilinear series `p` is a sequence of iterated derivatives of `f`, up to the `n`-th term (where `n` is a natural number or `∞`). * `has_ftaylor_series_up_to_on n f p s`: same thing, but inside a set `s`. The notion of derivative is now taken inside `s`. In particular, derivatives don't have to be unique. * `cont_diff 𝕜 n f`: expresses that `f` is `C^n`, i.e., it admits a Taylor series up to rank `n`. * `cont_diff_on 𝕜 n f s`: expresses that `f` is `C^n` in `s`. * `cont_diff_at 𝕜 n f x`: expresses that `f` is `C^n` around `x`. * `cont_diff_within_at 𝕜 n f s x`: expresses that `f` is `C^n` around `x` within the set `s`. * `iterated_fderiv_within 𝕜 n f s x` is an `n`-th derivative of `f` over the field `𝕜` on the set `s` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative within `s` of `iterated_fderiv_within 𝕜 (n-1) f s` if one exists, and `0` otherwise. * `iterated_fderiv 𝕜 n f x` is the `n`-th derivative of `f` over the field `𝕜` at the point `x`. It is a continuous multilinear map from `E^n` to `F`, defined as a derivative of `iterated_fderiv 𝕜 (n-1) f` if one exists, and `0` otherwise. In sets of unique differentiability, `cont_diff_on 𝕜 n f s` can be expressed in terms of the properties of `iterated_fderiv_within 𝕜 m f s` for `m ≤ n`. In the whole space, `cont_diff 𝕜 n f` can be expressed in terms of the properties of `iterated_fderiv 𝕜 m f` for `m ≤ n`. We also prove that the usual operations (addition, multiplication, difference, composition, and so on) preserve `C^n` functions. ## Implementation notes The definitions in this file are designed to work on any field `𝕜`. They are sometimes slightly more complicated than the naive definitions one would guess from the intuition over the real or complex numbers, but they are designed to circumvent the lack of gluing properties and partitions of unity in general. In the usual situations, they coincide with the usual definitions. ### Definition of `C^n` functions in domains One could define `C^n` functions in a domain `s` by fixing an arbitrary choice of derivatives (this is what we do with `iterated_fderiv_within`) and requiring that all these derivatives up to `n` are continuous. If the derivative is not unique, this could lead to strange behavior like two `C^n` functions `f` and `g` on `s` whose sum is not `C^n`. A better definition is thus to say that a function is `C^n` inside `s` if it admits a sequence of derivatives up to `n` inside `s`. This definition still has the problem that a function which is locally `C^n` would not need to be `C^n`, as different choices of sequences of derivatives around different points might possibly not be glued together to give a globally defined sequence of derivatives. (Note that this issue can not happen over reals, thanks to partition of unity, but the behavior over a general field is not so clear, and we want a definition for general fields). Also, there are locality problems for the order parameter: one could image a function which, for each `n`, has a nice sequence of derivatives up to order `n`, but they do not coincide for varying `n` and can therefore not be glued to give rise to an infinite sequence of derivatives. This would give a function which is `C^n` for all `n`, but not `C^∞`. We solve this issue by putting locality conditions in space and order in our definition of `cont_diff_within_at` and `cont_diff_on`. The resulting definition is slightly more complicated to work with (in fact not so much), but it gives rise to completely satisfactory theorems. For instance, with this definition, a real function which is `C^m` (but not better) on `(-1/m, 1/m)` for each natural `m` is by definition `C^∞` at `0`. There is another issue with the definition of `cont_diff_within_at 𝕜 n f s x`. We can require the existence and good behavior of derivatives up to order `n` on a neighborhood of `x` within `s`. However, this does not imply continuity or differentiability within `s` of the function at `x` when `x` does not belong to `s`. Therefore, we require such existence and good behavior on a neighborhood of `x` within `s ∪ {x}` (which appears as `insert x s` in this file). ### Side of the composition, and universe issues With a naïve direct definition, the `n`-th derivative of a function belongs to the space `E →L[𝕜] (E →L[𝕜] (E ... F)...)))` where there are n iterations of `E →L[𝕜]`. This space may also be seen as the space of continuous multilinear functions on `n` copies of `E` with values in `F`, by uncurrying. This is the point of view that is usually adopted in textbooks, and that we also use. This means that the definition and the first proofs are slightly involved, as one has to keep track of the uncurrying operation. The uncurrying can be done from the left or from the right, amounting to defining the `n+1`-th derivative either as the derivative of the `n`-th derivative, or as the `n`-th derivative of the derivative. For proofs, it would be more convenient to use the latter approach (from the right), as it means to prove things at the `n+1`-th step we only need to understand well enough the derivative in `E →L[𝕜] F` (contrary to the approach from the left, where one would need to know enough on the `n`-th derivative to deduce things on the `n+1`-th derivative). However, the definition from the right leads to a universe polymorphism problem: if we define `iterated_fderiv 𝕜 (n + 1) f x = iterated_fderiv 𝕜 n (fderiv 𝕜 f) x` by induction, we need to generalize over all spaces (as `f` and `fderiv 𝕜 f` don't take values in the same space). It is only possible to generalize over all spaces in some fixed universe in an inductive definition. For `f : E → F`, then `fderiv 𝕜 f` is a map `E → (E →L[𝕜] F)`. Therefore, the definition will only work if `F` and `E →L[𝕜] F` are in the same universe. This issue does not appear with the definition from the left, where one does not need to generalize over all spaces. Therefore, we use the definition from the left. This means some proofs later on become a little bit more complicated: to prove that a function is `C^n`, the most efficient approach is to exhibit a formula for its `n`-th derivative and prove it is continuous (contrary to the inductive approach where one would prove smoothness statements without giving a formula for the derivative). In the end, this approach is still satisfactory as it is good to have formulas for the iterated derivatives in various constructions. One point where we depart from this explicit approach is in the proof of smoothness of a composition: there is a formula for the `n`-th derivative of a composition (Faà di Bruno's formula), but it is very complicated and barely usable, while the inductive proof is very simple. Thus, we give the inductive proof. As explained above, it works by generalizing over the target space, hence it only works well if all spaces belong to the same universe. To get the general version, we lift things to a common universe using a trick. ### Variables management The textbook definitions and proofs use various identifications and abuse of notations, for instance when saying that the natural space in which the derivative lives, i.e., `E →L[𝕜] (E →L[𝕜] ( ... →L[𝕜] F))`, is the same as a space of multilinear maps. When doing things formally, we need to provide explicit maps for these identifications, and chase some diagrams to see everything is compatible with the identifications. In particular, one needs to check that taking the derivative and then doing the identification, or first doing the identification and then taking the derivative, gives the same result. The key point for this is that taking the derivative commutes with continuous linear equivalences. Therefore, we need to implement all our identifications with continuous linear equivs. ## Notations We use the notation `E [×n]→L[𝕜] F` for the space of continuous multilinear maps on `E^n` with values in `F`. This is the space in which the `n`-th derivative of a function from `E` to `F` lives. In this file, we denote `⊤ : with_top ℕ` with `∞`. ## Tags derivative, differentiability, higher derivative, `C^n`, multilinear, Taylor series, formal series -/ noncomputable theory open_locale classical big_operators nnreal local notation `∞` := (⊤ : with_top ℕ) universes u v w local attribute [instance, priority 1001] normed_group.to_add_comm_group normed_space.to_module' add_comm_group.to_add_comm_monoid open set fin filter open_locale topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] {s s₁ t u : set E} {f f₁ : E → F} {g : F → G} {x : E} {c : F} {b : E × F → G} {m n : with_top ℕ} /-! ### Functions with a Taylor series on a domain -/ variable {p : E → formal_multilinear_series 𝕜 E F} /-- `has_ftaylor_series_up_to_on n f p s` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_within_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to_on (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) (s : set E) : Prop := (zero_eq : ∀ x ∈ s, (p x 0).uncurry0 = f x) (fderiv_within : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x ∈ s, has_fderiv_within_at (λ y, p y m) (p x m.succ).curry_left s x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous_on (λ x, p x m) s) lemma has_ftaylor_series_up_to_on.zero_eq' (h : has_ftaylor_series_up_to_on n f p s) {x : E} (hx : x ∈ s) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } /-- If two functions coincide on a set `s`, then a Taylor series for the first one is as well a Taylor series for the second one. -/ lemma has_ftaylor_series_up_to_on.congr (h : has_ftaylor_series_up_to_on n f p s) (h₁ : ∀ x ∈ s, f₁ x = f x) : has_ftaylor_series_up_to_on n f₁ p s := begin refine ⟨λ x hx, _, h.fderiv_within, h.cont⟩, rw h₁ x hx, exact h.zero_eq x hx end lemma has_ftaylor_series_up_to_on.mono (h : has_ftaylor_series_up_to_on n f p s) {t : set E} (hst : t ⊆ s) : has_ftaylor_series_up_to_on n f p t := ⟨λ x hx, h.zero_eq x (hst hx), λ m hm x hx, (h.fderiv_within m hm x (hst hx)).mono hst, λ m hm, (h.cont m hm).mono hst⟩ lemma has_ftaylor_series_up_to_on.of_le (h : has_ftaylor_series_up_to_on n f p s) (hmn : m ≤ n) : has_ftaylor_series_up_to_on m f p s := ⟨h.zero_eq, λ k hk x hx, h.fderiv_within k (lt_of_lt_of_le hk hmn) x hx, λ k hk, h.cont k (le_trans hk hmn)⟩ lemma has_ftaylor_series_up_to_on.continuous_on (h : has_ftaylor_series_up_to_on n f p s) : continuous_on f s := begin have := (h.cont 0 bot_le).congr (λ x hx, (h.zero_eq' hx).symm), rwa linear_isometry_equiv.comp_continuous_on_iff at this end lemma has_ftaylor_series_up_to_on_zero_iff : has_ftaylor_series_up_to_on 0 f p s ↔ continuous_on f s ∧ (∀ x ∈ s, (p x 0).uncurry0 = f x) := begin refine ⟨λ H, ⟨H.continuous_on, H.zero_eq⟩, λ H, ⟨H.2, λ m hm, false.elim (not_le.2 hm bot_le), _⟩⟩, assume m hm, obtain rfl : m = 0, by exact_mod_cast (hm.antisymm (zero_le _)), have : ∀ x ∈ s, p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x), by { assume x hx, rw ← H.2 x hx, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ }, rw [continuous_on_congr this, linear_isometry_equiv.comp_continuous_on_iff], exact H.1 end lemma has_ftaylor_series_up_to_on_top_iff : (has_ftaylor_series_up_to_on ∞ f p s) ↔ (∀ (n : ℕ), has_ftaylor_series_up_to_on n f p s) := begin split, { assume H n, exact H.of_le le_top }, { assume H, split, { exact (H 0).zero_eq }, { assume m hm, apply (H m.succ).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) }, { assume m hm, apply (H m).cont m le_rfl } } end /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_within_at (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : x ∈ s) : has_fderiv_within_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x := begin have A : ∀ y ∈ s, f y = (continuous_multilinear_curry_fin0 𝕜 E F) (p y 0), { assume y hy, rw ← h.zero_eq y hy, refl }, suffices H : has_fderiv_within_at (λ y, continuous_multilinear_curry_fin0 𝕜 E F (p y 0)) (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) s x, by exact H.congr A (A x hx), rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', have : ((0 : ℕ) : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 nat.zero_lt_one) hn, convert h.fderiv_within _ this x hx, ext y v, change (p x 1) (snoc 0 y) = (p x 1) (cons y v), unfold_coes, congr' with i, rw unique.eq_default i, refl end lemma has_ftaylor_series_up_to_on.differentiable_on (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h.has_fderiv_within_at hn hx).differentiable_within_at /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then the term of order `1` of this series is a derivative of `f` at `x`. -/ lemma has_ftaylor_series_up_to_on.has_fderiv_at (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := (h.has_fderiv_within_at hn (mem_of_mem_nhds hx)).has_fderiv_at hx /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then in a neighborhood of `x`, the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.eventually_has_fderiv_at (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : ∀ᶠ y in 𝓝 x, has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p y 1)) y := (eventually_eventually_nhds.2 hx).mono $ λ y hy, h.has_fderiv_at hn hy /-- If a function has a Taylor series at order at least `1` on a neighborhood of `x`, then it is differentiable at `x`. -/ lemma has_ftaylor_series_up_to_on.differentiable_at (h : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hx : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := (h.has_fderiv_at hn hx).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p` is a Taylor series up to `n`, and `p (n + 1)` is a derivative of `p n`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_left {n : ℕ} : has_ftaylor_series_up_to_on (n + 1) f p s ↔ has_ftaylor_series_up_to_on n f p s ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y n) (p x n.succ).curry_left s x) ∧ continuous_on (λ x, p x (n + 1)) s := begin split, { assume h, exact ⟨h.of_le (with_top.coe_le_coe.2 (nat.le_succ n)), h.fderiv_within _ (with_top.coe_lt_coe.2 (lt_add_one n)), h.cont (n + 1) le_rfl⟩ }, { assume h, split, { exact h.1.zero_eq }, { assume m hm, by_cases h' : m < n, { exact h.1.fderiv_within m (with_top.coe_lt_coe.2 h') }, { have : m = n := nat.eq_of_lt_succ_of_not_lt (with_top.coe_lt_coe.1 hm) h', rw this, exact h.2.1 } }, { assume m hm, by_cases h' : m ≤ n, { apply h.1.cont m (with_top.coe_le_coe.2 h') }, { have : m = (n + 1) := le_antisymm (with_top.coe_le_coe.1 hm) (not_le.1 h'), rw this, exact h.2.2 } } } end /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_on_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to_on ((n + 1) : ℕ) f p s ↔ (∀ x ∈ s, (p x 0).uncurry0 = f x) ∧ (∀ x ∈ s, has_fderiv_within_at (λ y, p y 0) (p x 1).curry_left s x) ∧ has_ftaylor_series_up_to_on n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) s := begin split, { assume H, refine ⟨H.zero_eq, H.fderiv_within 0 (with_top.coe_lt_coe.2 (nat.succ_pos n)), _⟩, split, { assume x hx, refl }, { assume m (hm : (m : with_top ℕ) < n) x (hx : x ∈ s), have A : (m.succ : with_top ℕ) < n.succ, by { rw with_top.coe_lt_coe at ⊢ hm, exact nat.lt_succ_iff.mpr hm }, change has_fderiv_within_at ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) (p x m.succ.succ).curry_right.curry_left s x, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', convert H.fderiv_within _ A x hx, ext y v, change (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))) = (p x (nat.succ (nat.succ m))) (cons y v), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] }, { assume m (hm : (m : with_top ℕ) ≤ n), have A : (m.succ : with_top ℕ) ≤ n.succ, by { rw with_top.coe_le_coe at ⊢ hm, exact nat.pred_le_iff.mp hm }, change continuous_on ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) s, rw linear_isometry_equiv.comp_continuous_on_iff, exact H.cont _ A } }, { rintros ⟨Hzero_eq, Hfderiv_zero, Htaylor⟩, split, { exact Hzero_eq }, { assume m (hm : (m : with_top ℕ) < n.succ) x (hx : x ∈ s), cases m, { exact Hfderiv_zero x hx }, { have A : (m : with_top ℕ) < n, by { rw with_top.coe_lt_coe at hm ⊢, exact nat.lt_of_succ_lt_succ hm }, have : has_fderiv_within_at ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) ((p x).shift m.succ).curry_left s x := Htaylor.fderiv_within _ A x hx, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff' at this, convert this, ext y v, change (p x (nat.succ (nat.succ m))) (cons y v) = (p x m.succ.succ) (snoc (cons y (init v)) (v (last _))), rw [← cons_snoc_eq_snoc_cons, snoc_init_self] } }, { assume m (hm : (m : with_top ℕ) ≤ n.succ), cases m, { have : differentiable_on 𝕜 (λ x, p x 0) s := λ x hx, (Hfderiv_zero x hx).differentiable_within_at, exact this.continuous_on }, { have A : (m : with_top ℕ) ≤ n, by { rw with_top.coe_le_coe at hm ⊢, exact nat.lt_succ_iff.mp hm }, have : continuous_on ((continuous_multilinear_curry_right_equiv' 𝕜 m E F).symm ∘ (λ (y : E), p y m.succ)) s := Htaylor.cont _ A, rwa linear_isometry_equiv.comp_continuous_on_iff at this } } } end /-! ### Smooth functions within a set around a point -/ variable (𝕜) /-- A function is continuously differentiable up to order `n` within a set `s` at a point `x` if it admits continuous derivatives up to order `n` in a neighborhood of `x` in `s ∪ {x}`. For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may depend on the finite order we consider). For instance, a real function which is `C^m` on `(-1/m, 1/m)` for each natural `m`, but not better, is `C^∞` at `0` within `univ`. -/ def cont_diff_within_at (n : with_top ℕ) (f : E → F) (s : set E) (x : E) := ∀ (m : ℕ), (m : with_top ℕ) ≤ n → ∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on m f p u variable {𝕜} lemma cont_diff_within_at_nat {n : ℕ} : cont_diff_within_at 𝕜 n f s x ↔ ∃ u ∈ 𝓝[insert x s] x, ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to_on n f p u := ⟨λ H, H n le_rfl, λ ⟨u, hu, p, hp⟩ m hm, ⟨u, hu, p, hp.of_le hm⟩⟩ lemma cont_diff_within_at.of_le (h : cont_diff_within_at 𝕜 n f s x) (hmn : m ≤ n) : cont_diff_within_at 𝕜 m f s x := λ k hk, h k (le_trans hk hmn) lemma cont_diff_within_at_iff_forall_nat_le : cont_diff_within_at 𝕜 n f s x ↔ ∀ m : ℕ, ↑m ≤ n → cont_diff_within_at 𝕜 m f s x := ⟨λ H m hm, H.of_le hm, λ H m hm, H m hm _ le_rfl⟩ lemma cont_diff_within_at_top : cont_diff_within_at 𝕜 ∞ f s x ↔ ∀ (n : ℕ), cont_diff_within_at 𝕜 n f s x := cont_diff_within_at_iff_forall_nat_le.trans $ by simp only [forall_prop_of_true, le_top] lemma cont_diff_within_at.continuous_within_at (h : cont_diff_within_at 𝕜 n f s x) : continuous_within_at f s x := begin rcases h 0 bot_le with ⟨u, hu, p, H⟩, rw [mem_nhds_within_insert] at hu, exact (H.continuous_on.continuous_within_at hu.1).mono_of_mem hu.2 end lemma cont_diff_within_at.congr_of_eventually_eq (h : cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : cont_diff_within_at 𝕜 n f₁ s x := λ m hm, let ⟨u, hu, p, H⟩ := h m hm in ⟨{x ∈ u | f₁ x = f x}, filter.inter_mem hu (mem_nhds_within_insert.2 ⟨hx, h₁⟩), p, (H.mono (sep_subset _ _)).congr (λ _, and.right)⟩ lemma cont_diff_within_at.congr_of_eventually_eq' (h : cont_diff_within_at 𝕜 n f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : cont_diff_within_at 𝕜 n f₁ s x := h.congr_of_eventually_eq h₁ $ h₁.self_of_nhds_within hx lemma filter.eventually_eq.cont_diff_within_at_iff (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : cont_diff_within_at 𝕜 n f₁ s x ↔ cont_diff_within_at 𝕜 n f s x := ⟨λ H, cont_diff_within_at.congr_of_eventually_eq H h₁.symm hx.symm, λ H, H.congr_of_eventually_eq h₁ hx⟩ lemma cont_diff_within_at.congr (h : cont_diff_within_at 𝕜 n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : f₁ x = f x) : cont_diff_within_at 𝕜 n f₁ s x := h.congr_of_eventually_eq (filter.eventually_eq_of_mem self_mem_nhds_within h₁) hx lemma cont_diff_within_at.congr' (h : cont_diff_within_at 𝕜 n f s x) (h₁ : ∀ y ∈ s, f₁ y = f y) (hx : x ∈ s) : cont_diff_within_at 𝕜 n f₁ s x := h.congr h₁ (h₁ _ hx) lemma cont_diff_within_at.mono_of_mem (h : cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : s ∈ 𝓝[t] x) : cont_diff_within_at 𝕜 n f t x := begin assume m hm, rcases h m hm with ⟨u, hu, p, H⟩, exact ⟨u, nhds_within_le_of_mem (insert_mem_nhds_within_insert hst) hu, p, H⟩ end lemma cont_diff_within_at.mono (h : cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : t ⊆ s) : cont_diff_within_at 𝕜 n f t x := h.mono_of_mem $ filter.mem_of_superset self_mem_nhds_within hst lemma cont_diff_within_at.congr_nhds (h : cont_diff_within_at 𝕜 n f s x) {t : set E} (hst : 𝓝[s] x = 𝓝[t] x) : cont_diff_within_at 𝕜 n f t x := h.mono_of_mem $ hst ▸ self_mem_nhds_within lemma cont_diff_within_at_congr_nhds {t : set E} (hst : 𝓝[s] x = 𝓝[t] x) : cont_diff_within_at 𝕜 n f s x ↔ cont_diff_within_at 𝕜 n f t x := ⟨λ h, h.congr_nhds hst, λ h, h.congr_nhds hst.symm⟩ lemma cont_diff_within_at_inter' (h : t ∈ 𝓝[s] x) : cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ cont_diff_within_at 𝕜 n f s x := cont_diff_within_at_congr_nhds $ eq.symm $ nhds_within_restrict'' _ h lemma cont_diff_within_at_inter (h : t ∈ 𝓝 x) : cont_diff_within_at 𝕜 n f (s ∩ t) x ↔ cont_diff_within_at 𝕜 n f s x := cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds h) /-- If a function is `C^n` within a set at a point, with `n ≥ 1`, then it is differentiable within this set at this point. -/ lemma cont_diff_within_at.differentiable_within_at' (h : cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) : differentiable_within_at 𝕜 f (insert x s) x := begin rcases h 1 hn with ⟨u, hu, p, H⟩, rcases mem_nhds_within.1 hu with ⟨t, t_open, xt, tu⟩, rw inter_comm at tu, have := ((H.mono tu).differentiable_on le_rfl) x ⟨mem_insert x s, xt⟩, exact (differentiable_within_at_inter (is_open.mem_nhds t_open xt)).1 this, end lemma cont_diff_within_at.differentiable_within_at (h : cont_diff_within_at 𝕜 n f s x) (hn : 1 ≤ n) : differentiable_within_at 𝕜 f s x := (h.differentiable_within_at' hn).mono (subset_insert x s) /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem cont_diff_within_at_succ_iff_has_fderiv_within_at {n : ℕ} : cont_diff_within_at 𝕜 ((n + 1) : ℕ) f s x ↔ ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (cont_diff_within_at 𝕜 n f' u x) := begin split, { assume h, rcases h n.succ le_rfl with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, assume m hm, refine ⟨u, _, λ (y : E), (p y).shift, _⟩, { convert self_mem_nhds_within, have : x ∈ insert x s, by simp, exact (insert_eq_of_mem (mem_of_mem_nhds_within this hu)) }, { rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, exact Hp.2.2.of_le hm } }, { rintros ⟨u, hu, f', f'_eq_deriv, Hf'⟩, rw cont_diff_within_at_nat, rcases Hf' n le_rfl with ⟨v, hv, p', Hp'⟩, refine ⟨v ∩ u, _, λ x, (p' x).unshift (f x), _⟩, { apply filter.inter_mem _ hu, apply nhds_within_le_of_mem hu, exact nhds_within_mono _ (subset_insert x u) hv }, { rw has_ftaylor_series_up_to_on_succ_iff_right, refine ⟨λ y hy, rfl, λ y hy, _, _⟩, { change has_fderiv_within_at (λ z, (continuous_multilinear_curry_fin0 𝕜 E F).symm (f z)) ((formal_multilinear_series.unshift (p' y) (f y) 1).curry_left) (v ∩ u) y, rw linear_isometry_equiv.comp_has_fderiv_within_at_iff', convert (f'_eq_deriv y hy.2).mono (inter_subset_right v u), rw ← Hp'.zero_eq y hy.1, ext z, change ((p' y 0) (init (@cons 0 (λ i, E) z 0))) (@cons 0 (λ i, E) z 0 (last 0)) = ((p' y 0) 0) z, unfold_coes, congr }, { convert (Hp'.mono (inter_subset_left v u)).congr (λ x hx, Hp'.zero_eq x hx.1), { ext x y, change p' x 0 (init (@snoc 0 (λ i : fin 1, E) 0 y)) y = p' x 0 0 y, rw init_snoc }, { ext x k v y, change p' x k (init (@snoc k (λ i : fin k.succ, E) v y)) (@snoc k (λ i : fin k.succ, E) v y (last k)) = p' x k v y, rw [snoc_last, init_snoc] } } } } end /-! ### Smooth functions within a set -/ variable (𝕜) /-- A function is continuously differentiable up to `n` on `s` if, for any point `x` in `s`, it admits continuous derivatives up to order `n` on a neighborhood of `x` in `s`. For `n = ∞`, we only require that this holds up to any finite order (where the neighborhood may depend on the finite order we consider). -/ definition cont_diff_on (n : with_top ℕ) (f : E → F) (s : set E) := ∀ x ∈ s, cont_diff_within_at 𝕜 n f s x variable {𝕜} lemma cont_diff_on.cont_diff_within_at (h : cont_diff_on 𝕜 n f s) (hx : x ∈ s) : cont_diff_within_at 𝕜 n f s x := h x hx lemma cont_diff_within_at.cont_diff_on {m : ℕ} (hm : (m : with_top ℕ) ≤ n) (h : cont_diff_within_at 𝕜 n f s x) : ∃ u ∈ 𝓝[insert x s] x, u ⊆ insert x s ∧ cont_diff_on 𝕜 m f u := begin rcases h m hm with ⟨u, u_nhd, p, hp⟩, refine ⟨u ∩ insert x s, filter.inter_mem u_nhd self_mem_nhds_within, inter_subset_right _ _, _⟩, assume y hy m' hm', refine ⟨u ∩ insert x s, _, p, (hp.mono (inter_subset_left _ _)).of_le hm'⟩, convert self_mem_nhds_within, exact insert_eq_of_mem hy end protected lemma cont_diff_within_at.eventually {n : ℕ} (h : cont_diff_within_at 𝕜 n f s x) : ∀ᶠ y in 𝓝[insert x s] x, cont_diff_within_at 𝕜 n f s y := begin rcases h.cont_diff_on le_rfl with ⟨u, hu, hu_sub, hd⟩, have : ∀ᶠ (y : E) in 𝓝[insert x s] x, u ∈ 𝓝[insert x s] y ∧ y ∈ u, from (eventually_nhds_within_nhds_within.2 hu).and hu, refine this.mono (λ y hy, (hd y hy.2).mono_of_mem _), exact nhds_within_mono y (subset_insert _ _) hy.1 end lemma cont_diff_on.of_le (h : cont_diff_on 𝕜 n f s) (hmn : m ≤ n) : cont_diff_on 𝕜 m f s := λ x hx, (h x hx).of_le hmn lemma cont_diff_on_iff_forall_nat_le : cont_diff_on 𝕜 n f s ↔ ∀ m : ℕ, ↑m ≤ n → cont_diff_on 𝕜 m f s := ⟨λ H m hm, H.of_le hm, λ H x hx m hm, H m hm x hx m le_rfl⟩ lemma cont_diff_on_top : cont_diff_on 𝕜 ∞ f s ↔ ∀ (n : ℕ), cont_diff_on 𝕜 n f s := cont_diff_on_iff_forall_nat_le.trans $ by simp only [le_top, forall_prop_of_true] lemma cont_diff_on_all_iff_nat : (∀ n, cont_diff_on 𝕜 n f s) ↔ (∀ n : ℕ, cont_diff_on 𝕜 n f s) := begin refine ⟨λ H n, H n, _⟩, rintro H (_|n), exacts [cont_diff_on_top.2 H, H n] end lemma cont_diff_on.continuous_on (h : cont_diff_on 𝕜 n f s) : continuous_on f s := λ x hx, (h x hx).continuous_within_at lemma cont_diff_on.congr (h : cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s, f₁ x = f x) : cont_diff_on 𝕜 n f₁ s := λ x hx, (h x hx).congr h₁ (h₁ x hx) lemma cont_diff_on_congr (h₁ : ∀ x ∈ s, f₁ x = f x) : cont_diff_on 𝕜 n f₁ s ↔ cont_diff_on 𝕜 n f s := ⟨λ H, H.congr (λ x hx, (h₁ x hx).symm), λ H, H.congr h₁⟩ lemma cont_diff_on.mono (h : cont_diff_on 𝕜 n f s) {t : set E} (hst : t ⊆ s) : cont_diff_on 𝕜 n f t := λ x hx, (h x (hst hx)).mono hst lemma cont_diff_on.congr_mono (hf : cont_diff_on 𝕜 n f s) (h₁ : ∀ x ∈ s₁, f₁ x = f x) (hs : s₁ ⊆ s) : cont_diff_on 𝕜 n f₁ s₁ := (hf.mono hs).congr h₁ /-- If a function is `C^n` on a set with `n ≥ 1`, then it is differentiable there. -/ lemma cont_diff_on.differentiable_on (h : cont_diff_on 𝕜 n f s) (hn : 1 ≤ n) : differentiable_on 𝕜 f s := λ x hx, (h x hx).differentiable_within_at hn /-- If a function is `C^n` around each point in a set, then it is `C^n` on the set. -/ lemma cont_diff_on_of_locally_cont_diff_on (h : ∀ x ∈ s, ∃u, is_open u ∧ x ∈ u ∧ cont_diff_on 𝕜 n f (s ∩ u)) : cont_diff_on 𝕜 n f s := begin assume x xs, rcases h x xs with ⟨u, u_open, xu, hu⟩, apply (cont_diff_within_at_inter _).1 (hu x ⟨xs, xu⟩), exact is_open.mem_nhds u_open xu end /-- A function is `C^(n + 1)` on a domain iff locally, it has a derivative which is `C^n`. -/ theorem cont_diff_on_succ_iff_has_fderiv_within_at {n : ℕ} : cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ ∀ x ∈ s, ∃ u ∈ 𝓝[insert x s] x, ∃ f' : E → (E →L[𝕜] F), (∀ x ∈ u, has_fderiv_within_at f (f' x) u x) ∧ (cont_diff_on 𝕜 n f' u) := begin split, { assume h x hx, rcases (h x hx) n.succ le_rfl with ⟨u, hu, p, Hp⟩, refine ⟨u, hu, λ y, (continuous_multilinear_curry_fin1 𝕜 E F) (p y 1), λ y hy, Hp.has_fderiv_within_at (with_top.coe_le_coe.2 (nat.le_add_left 1 n)) hy, _⟩, rw has_ftaylor_series_up_to_on_succ_iff_right at Hp, assume z hz m hm, refine ⟨u, _, λ (x : E), (p x).shift, Hp.2.2.of_le hm⟩, convert self_mem_nhds_within, exact insert_eq_of_mem hz, }, { assume h x hx, rw cont_diff_within_at_succ_iff_has_fderiv_within_at, rcases h x hx with ⟨u, u_nhbd, f', hu, hf'⟩, have : x ∈ u := mem_of_mem_nhds_within (mem_insert _ _) u_nhbd, exact ⟨u, u_nhbd, f', hu, hf' x this⟩ } end /-! ### Iterated derivative within a set -/ variable (𝕜) /-- The `n`-th derivative of a function along a set, defined inductively by saying that the `n+1`-th derivative of `f` is the derivative of the `n`-th derivative of `f` along this set, together with an uncurrying step to see it as a multilinear map in `n+1` variables.. -/ noncomputable def iterated_fderiv_within (n : ℕ) (f : E → F) (s : set E) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv_within 𝕜 rec s x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series_within (f : E → F) (s : set E) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv_within 𝕜 n f s x variable {𝕜} @[simp] lemma iterated_fderiv_within_zero_apply (m : (fin 0) → E) : (iterated_fderiv_within 𝕜 0 f s x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_within_zero_eq_comp : iterated_fderiv_within 𝕜 0 f s = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_within_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_left {n : ℕ} : iterated_fderiv_within 𝕜 (n + 1) f s = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n f s) s) := rfl theorem iterated_fderiv_within_succ_apply_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : fin (n + 1) → E) : (iterated_fderiv_within 𝕜 (n + 1) f s x : (fin (n + 1) → E) → F) m = iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s x (init m) (m (last n)) := begin induction n with n IH generalizing x, { rw [iterated_fderiv_within_succ_eq_comp_left, iterated_fderiv_within_zero_eq_comp, iterated_fderiv_within_zero_apply, function.comp_apply, linear_isometry_equiv.comp_fderiv_within _ (hs x hx)], refl }, { let I := continuous_multilinear_curry_right_equiv' 𝕜 n E F, have A : ∀ y ∈ s, iterated_fderiv_within 𝕜 n.succ f s y = (I ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) y, by { assume y hy, ext m, rw @IH m y hy, refl }, calc (iterated_fderiv_within 𝕜 (n+2) f s x : (fin (n+2) → E) → F) m = (fderiv_within 𝕜 (iterated_fderiv_within 𝕜 n.succ f s) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : rfl ... = (fderiv_within 𝕜 (I ∘ (iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by rw fderiv_within_congr (hs x hx) A (A x hx) ... = (I ∘ fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (fderiv_within 𝕜 f s) s)) s x : E → (E [×(n + 1)]→L[𝕜] F)) (m 0) (tail m) : by { rw linear_isometry_equiv.comp_fderiv_within _ (hs x hx), refl } ... = (fderiv_within 𝕜 ((iterated_fderiv_within 𝕜 n (λ y, fderiv_within 𝕜 f s y) s)) s x : E → (E [×n]→L[𝕜] (E →L[𝕜] F))) (m 0) (init (tail m)) ((tail m) (last n)) : rfl ... = iterated_fderiv_within 𝕜 (nat.succ n) (λ y, fderiv_within 𝕜 f s y) s x (init m) (m (last (n + 1))) : by { rw [iterated_fderiv_within_succ_apply_left, tail_init_eq_init_tail], refl } } end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_within_succ_eq_comp_right {n : ℕ} (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : iterated_fderiv_within 𝕜 (n + 1) f s x = ((continuous_multilinear_curry_right_equiv' 𝕜 n E F) ∘ (iterated_fderiv_within 𝕜 n (λy, fderiv_within 𝕜 f s y) s)) x := by { ext m, rw iterated_fderiv_within_succ_apply_right hs hx, refl } @[simp] lemma iterated_fderiv_within_one_apply (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) (m : (fin 1) → E) : (iterated_fderiv_within 𝕜 1 f s x : ((fin 1) → E) → F) m = (fderiv_within 𝕜 f s x : E → F) (m 0) := by { rw [iterated_fderiv_within_succ_apply_right hs hx, iterated_fderiv_within_zero_apply], refl } /-- If two functions coincide on a set `s` of unique differentiability, then their iterated differentials within this set coincide. -/ lemma iterated_fderiv_within_congr {n : ℕ} (hs : unique_diff_on 𝕜 s) (hL : ∀y∈s, f₁ y = f y) (hx : x ∈ s) : iterated_fderiv_within 𝕜 n f₁ s x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp [hL x hx] }, { have : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f₁ s y) s x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, this] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with an open set containing `x`. -/ lemma iterated_fderiv_within_inter_open {n : ℕ} (hu : is_open u) (hs : unique_diff_on 𝕜 (s ∩ u)) (hx : x ∈ s ∩ u) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin induction n with n IH generalizing x, { ext m, simp }, { have A : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f (s ∩ u) y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x := fderiv_within_congr (hs x hx) (λ y hy, IH hy) (IH hx), have B : fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) (s ∩ u) x = fderiv_within 𝕜 (λ y, iterated_fderiv_within 𝕜 n f s y) s x := fderiv_within_inter (is_open.mem_nhds hu hx.2) ((unique_diff_within_at_inter (is_open.mem_nhds hu hx.2)).1 (hs x hx)), ext m, rw [iterated_fderiv_within_succ_apply_left, iterated_fderiv_within_succ_apply_left, A, B] } end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x` within `s`. -/ lemma iterated_fderiv_within_inter' {n : ℕ} (hu : u ∈ 𝓝[s] x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := begin obtain ⟨v, v_open, xv, vu⟩ : ∃ v, is_open v ∧ x ∈ v ∧ v ∩ s ⊆ u := mem_nhds_within.1 hu, have A : (s ∩ u) ∩ v = s ∩ v, { apply subset.antisymm (inter_subset_inter (inter_subset_left _ _) (subset.refl _)), exact λ y ⟨ys, yv⟩, ⟨⟨ys, vu ⟨yv, ys⟩⟩, yv⟩ }, have : iterated_fderiv_within 𝕜 n f (s ∩ v) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter_open v_open (hs.inter v_open) ⟨xs, xv⟩, rw ← this, have : iterated_fderiv_within 𝕜 n f ((s ∩ u) ∩ v) x = iterated_fderiv_within 𝕜 n f (s ∩ u) x, { refine iterated_fderiv_within_inter_open v_open _ ⟨⟨xs, vu ⟨xv, xs⟩⟩, xv⟩, rw A, exact hs.inter v_open }, rw A at this, rw ← this end /-- The iterated differential within a set `s` at a point `x` is not modified if one intersects `s` with a neighborhood of `x`. -/ lemma iterated_fderiv_within_inter {n : ℕ} (hu : u ∈ 𝓝 x) (hs : unique_diff_on 𝕜 s) (xs : x ∈ s) : iterated_fderiv_within 𝕜 n f (s ∩ u) x = iterated_fderiv_within 𝕜 n f s x := iterated_fderiv_within_inter' (mem_nhds_within_of_mem_nhds hu) hs xs @[simp] lemma cont_diff_on_zero : cont_diff_on 𝕜 0 f s ↔ continuous_on f s := begin refine ⟨λ H, H.continuous_on, λ H, _⟩, assume x hx m hm, have : (m : with_top ℕ) = 0 := le_antisymm hm bot_le, rw this, refine ⟨insert x s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, rw has_ftaylor_series_up_to_on_zero_iff, exact ⟨by rwa insert_eq_of_mem hx, λ x hx, by simp [ftaylor_series_within]⟩ end lemma cont_diff_within_at_zero (hx : x ∈ s) : cont_diff_within_at 𝕜 0 f s x ↔ ∃ u ∈ 𝓝[s] x, continuous_on f (s ∩ u) := begin split, { intros h, obtain ⟨u, H, p, hp⟩ := h 0 (by norm_num), refine ⟨u, _, _⟩, { simpa [hx] using H }, { simp only [with_top.coe_zero, has_ftaylor_series_up_to_on_zero_iff] at hp, exact hp.1.mono (inter_subset_right s u) } }, { rintros ⟨u, H, hu⟩, rw ← cont_diff_within_at_inter' H, have h' : x ∈ s ∩ u := ⟨hx, mem_of_mem_nhds_within hx H⟩, exact (cont_diff_on_zero.mpr hu).cont_diff_within_at h' } end /-- On a set with unique differentiability, any choice of iterated differential has to coincide with the one we have chosen in `iterated_fderiv_within 𝕜 m f s`. -/ theorem has_ftaylor_series_up_to_on.eq_ftaylor_series_of_unique_diff_on (h : has_ftaylor_series_up_to_on n f p s) {m : ℕ} (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) (hx : x ∈ s) : p x m = iterated_fderiv_within 𝕜 m f s x := begin induction m with m IH generalizing x, { rw [h.zero_eq' hx, iterated_fderiv_within_zero_eq_comp] }, { have A : (m : with_top ℕ) < n := lt_of_lt_of_le (with_top.coe_lt_coe.2 (lt_add_one m)) hmn, have : has_fderiv_within_at (λ (y : E), iterated_fderiv_within 𝕜 m f s y) (continuous_multilinear_map.curry_left (p x (nat.succ m))) s x := (h.fderiv_within m A x hx).congr (λ y hy, (IH (le_of_lt A) hy).symm) (IH (le_of_lt A) hx).symm, rw [iterated_fderiv_within_succ_eq_comp_left, function.comp_apply, this.fderiv_within (hs x hx)], exact (continuous_multilinear_map.uncurry_curry_left _).symm } end /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem cont_diff_on.ftaylor_series_within (h : cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) : has_ftaylor_series_up_to_on n f (ftaylor_series_within 𝕜 f s) s := begin split, { assume x hx, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume m hm x hx, rcases (h x hx) m.succ (with_top.add_one_le_of_lt hm) with ⟨u, hu, p, Hp⟩, rw insert_eq_of_mem hx at hu, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw inter_comm at ho, have : p x m.succ = ftaylor_series_within 𝕜 f s x m.succ, { change p x m.succ = iterated_fderiv_within 𝕜 m.succ f s x, rw ← iterated_fderiv_within_inter (is_open.mem_nhds o_open xo) hs hx, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on le_rfl (hs.inter o_open) ⟨hx, xo⟩ }, rw [← this, ← has_fderiv_within_at_inter (is_open.mem_nhds o_open xo)], have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (is_open.mem_nhds o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on (with_top.coe_le_coe.2 (nat.le_succ m)) (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).fderiv_within m (with_top.coe_lt_coe.2 (lt_add_one m)) x ⟨hx, xo⟩).congr (λ y hy, (A y hy).symm) (A x ⟨hx, xo⟩).symm }, { assume m hm, apply continuous_on_of_locally_continuous_on, assume x hx, rcases h x hx m hm with ⟨u, hu, p, Hp⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw insert_eq_of_mem hx at ho, rw inter_comm at ho, refine ⟨o, o_open, xo, _⟩, have A : ∀ y ∈ s ∩ o, p y m = ftaylor_series_within 𝕜 f s y m, { rintros y ⟨hy, yo⟩, change p y m = iterated_fderiv_within 𝕜 m f s y, rw ← iterated_fderiv_within_inter (is_open.mem_nhds o_open yo) hs hy, exact (Hp.mono ho).eq_ftaylor_series_of_unique_diff_on le_rfl (hs.inter o_open) ⟨hy, yo⟩ }, exact ((Hp.mono ho).cont m le_rfl).congr (λ y hy, (A y hy).symm) } end lemma cont_diff_on_of_continuous_on_differentiable_on (Hcont : ∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) (Hdiff : ∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) : cont_diff_on 𝕜 n f s := begin assume x hx m hm, rw insert_eq_of_mem hx, refine ⟨s, self_mem_nhds_within, ftaylor_series_within 𝕜 f s, _⟩, split, { assume y hy, simp only [ftaylor_series_within, continuous_multilinear_map.uncurry0_apply, iterated_fderiv_within_zero_apply] }, { assume k hk y hy, convert (Hdiff k (lt_of_lt_of_le hk hm) y hy).has_fderiv_within_at, simp only [ftaylor_series_within, iterated_fderiv_within_succ_eq_comp_left, continuous_linear_equiv.coe_apply, function.comp_app, coe_fn_coe_base], exact continuous_linear_map.curry_uncurry_left _ }, { assume k hk, exact Hcont k (le_trans hk hm) } end lemma cont_diff_on_of_differentiable_on (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s) : cont_diff_on 𝕜 n f s := cont_diff_on_of_continuous_on_differentiable_on (λ m hm, (h m hm).continuous_on) (λ m hm, (h m (le_of_lt hm))) lemma cont_diff_on.continuous_on_iterated_fderiv_within {m : ℕ} (h : cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) ≤ n) (hs : unique_diff_on 𝕜 s) : continuous_on (iterated_fderiv_within 𝕜 m f s) s := (h.ftaylor_series_within hs).cont m hmn lemma cont_diff_on.differentiable_on_iterated_fderiv_within {m : ℕ} (h : cont_diff_on 𝕜 n f s) (hmn : (m : with_top ℕ) < n) (hs : unique_diff_on 𝕜 s) : differentiable_on 𝕜 (iterated_fderiv_within 𝕜 m f s) s := λ x hx, ((h.ftaylor_series_within hs).fderiv_within m hmn x hx).differentiable_within_at lemma cont_diff_on_iff_continuous_on_differentiable_on (hs : unique_diff_on 𝕜 s) : cont_diff_on 𝕜 n f s ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous_on (λ x, iterated_fderiv_within 𝕜 m f s x) s) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable_on 𝕜 (λ x, iterated_fderiv_within 𝕜 m f s x) s) := begin split, { assume h, split, { assume m hm, exact h.continuous_on_iterated_fderiv_within hm hs }, { assume m hm, exact h.differentiable_on_iterated_fderiv_within hm hs } }, { assume h, exact cont_diff_on_of_continuous_on_differentiable_on h.1 h.2 } end lemma cont_diff_on_succ_of_fderiv_within {n : ℕ} (hf : differentiable_on 𝕜 f s) (h : cont_diff_on 𝕜 n (λ y, fderiv_within 𝕜 f s y) s) : cont_diff_on 𝕜 ((n + 1) : ℕ) f s := begin intros x hx, rw [cont_diff_within_at_succ_iff_has_fderiv_within_at, insert_eq_of_mem hx], exact ⟨s, self_mem_nhds_within, fderiv_within 𝕜 f s, λ y hy, (hf y hy).has_fderiv_within_at, h x hx⟩ end /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv_within`) is `C^n`. -/ theorem cont_diff_on_succ_iff_fderiv_within {n : ℕ} (hs : unique_diff_on 𝕜 s) : cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ cont_diff_on 𝕜 n (λ y, fderiv_within 𝕜 f s y) s := begin refine ⟨λ H, _, λ h, cont_diff_on_succ_of_fderiv_within h.1 h.2⟩, refine ⟨H.differentiable_on (with_top.coe_le_coe.2 (nat.le_add_left 1 n)), λ x hx, _⟩, rcases cont_diff_within_at_succ_iff_has_fderiv_within_at.1 (H x hx) with ⟨u, hu, f', hff', hf'⟩, rcases mem_nhds_within.1 hu with ⟨o, o_open, xo, ho⟩, rw [inter_comm, insert_eq_of_mem hx] at ho, have := hf'.mono ho, rw cont_diff_within_at_inter' (mem_nhds_within_of_mem_nhds (is_open.mem_nhds o_open xo)) at this, apply this.congr_of_eventually_eq' _ hx, have : o ∩ s ∈ 𝓝[s] x := mem_nhds_within.2 ⟨o, o_open, xo, subset.refl _⟩, rw inter_comm at this, apply filter.eventually_eq_of_mem this (λ y hy, _), have A : fderiv_within 𝕜 f (s ∩ o) y = f' y := ((hff' y (ho hy)).mono ho).fderiv_within (hs.inter o_open y hy), rwa fderiv_within_inter (is_open.mem_nhds o_open hy.2) (hs y hy.1) at A end /-- A function is `C^(n + 1)` on an open domain if and only if it is differentiable there, and its derivative (expressed with `fderiv`) is `C^n`. -/ theorem cont_diff_on_succ_iff_fderiv_of_open {n : ℕ} (hs : is_open s) : cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ cont_diff_on 𝕜 n (λ y, fderiv 𝕜 f y) s := begin rw cont_diff_on_succ_iff_fderiv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply cont_diff_on_congr, assume x hx, exact fderiv_within_of_open hs hx end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (expressed with `fderiv_within`) is `C^∞`. -/ theorem cont_diff_on_top_iff_fderiv_within (hs : unique_diff_on 𝕜 s) : cont_diff_on 𝕜 ∞ f s ↔ differentiable_on 𝕜 f s ∧ cont_diff_on 𝕜 ∞ (λ y, fderiv_within 𝕜 f s y) s := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply cont_diff_on_top.2 (λ n, ((cont_diff_on_succ_iff_fderiv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ∞ := le_top, apply ((cont_diff_on_succ_iff_fderiv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end /-- A function is `C^∞` on an open domain if and only if it is differentiable there, and its derivative (expressed with `fderiv`) is `C^∞`. -/ theorem cont_diff_on_top_iff_fderiv_of_open (hs : is_open s) : cont_diff_on 𝕜 ∞ f s ↔ differentiable_on 𝕜 f s ∧ cont_diff_on 𝕜 ∞ (λ y, fderiv 𝕜 f y) s := begin rw cont_diff_on_top_iff_fderiv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply cont_diff_on_congr, assume x hx, exact fderiv_within_of_open hs hx end lemma cont_diff_on.fderiv_within (hf : cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : cont_diff_on 𝕜 m (λ y, fderiv_within 𝕜 f s y) s := begin cases m, { change ∞ + 1 ≤ n at hmn, have : n = ∞, by simpa using hmn, rw this at hf, exact ((cont_diff_on_top_iff_fderiv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((cont_diff_on_succ_iff_fderiv_within hs).1 (hf.of_le hmn)).2 } end lemma cont_diff_on.fderiv_of_open (hf : cont_diff_on 𝕜 n f s) (hs : is_open s) (hmn : m + 1 ≤ n) : cont_diff_on 𝕜 m (λ y, fderiv 𝕜 f y) s := (hf.fderiv_within hs.unique_diff_on hmn).congr (λ x hx, (fderiv_within_of_open hs hx).symm) lemma cont_diff_on.continuous_on_fderiv_within (h : cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv_within 𝕜 f s x) s := ((cont_diff_on_succ_iff_fderiv_within hs).1 (h.of_le hn)).2.continuous_on lemma cont_diff_on.continuous_on_fderiv_of_open (h : cont_diff_on 𝕜 n f s) (hs : is_open s) (hn : 1 ≤ n) : continuous_on (λ x, fderiv 𝕜 f x) s := ((cont_diff_on_succ_iff_fderiv_of_open hs).1 (h.of_le hn)).2.continuous_on /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma cont_diff_on.continuous_on_fderiv_within_apply (h : cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hn : 1 ≤ n) : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1 : E → F) p.2) (s ×ˢ (univ : set E)) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous_on (λp : E × E, (fderiv_within 𝕜 f s p.1, p.2)) (s ×ˢ (univ : set E)), { apply continuous_on.prod _ continuous_snd.continuous_on, exact continuous_on.comp (h.continuous_on_fderiv_within hs hn) continuous_fst.continuous_on (prod_subset_preimage_fst _ _) }, exact A.comp_continuous_on B end /-! ### Functions with a Taylor series on the whole space -/ /-- `has_ftaylor_series_up_to n f p` registers the fact that `p 0 = f` and `p (m+1)` is a derivative of `p m` for `m < n`, and is continuous for `m ≤ n`. This is a predicate analogous to `has_fderiv_at` but for higher order derivatives. -/ structure has_ftaylor_series_up_to (n : with_top ℕ) (f : E → F) (p : E → formal_multilinear_series 𝕜 E F) : Prop := (zero_eq : ∀ x, (p x 0).uncurry0 = f x) (fderiv : ∀ (m : ℕ) (hm : (m : with_top ℕ) < n), ∀ x, has_fderiv_at (λ y, p y m) (p x m.succ).curry_left x) (cont : ∀ (m : ℕ) (hm : (m : with_top ℕ) ≤ n), continuous (λ x, p x m)) lemma has_ftaylor_series_up_to.zero_eq' (h : has_ftaylor_series_up_to n f p) (x : E) : p x 0 = (continuous_multilinear_curry_fin0 𝕜 E F).symm (f x) := by { rw ← h.zero_eq x, symmetry, exact continuous_multilinear_map.uncurry0_curry0 _ } lemma has_ftaylor_series_up_to_on_univ_iff : has_ftaylor_series_up_to_on n f p univ ↔ has_ftaylor_series_up_to n f p := begin split, { assume H, split, { exact λ x, H.zero_eq x (mem_univ x) }, { assume m hm x, rw ← has_fderiv_within_at_univ, exact H.fderiv_within m hm x (mem_univ x) }, { assume m hm, rw continuous_iff_continuous_on_univ, exact H.cont m hm } }, { assume H, split, { exact λ x hx, H.zero_eq x }, { assume m hm x hx, rw has_fderiv_within_at_univ, exact H.fderiv m hm x }, { assume m hm, rw ← continuous_iff_continuous_on_univ, exact H.cont m hm } } end lemma has_ftaylor_series_up_to.has_ftaylor_series_up_to_on (h : has_ftaylor_series_up_to n f p) (s : set E) : has_ftaylor_series_up_to_on n f p s := (has_ftaylor_series_up_to_on_univ_iff.2 h).mono (subset_univ _) lemma has_ftaylor_series_up_to.of_le (h : has_ftaylor_series_up_to n f p) (hmn : m ≤ n) : has_ftaylor_series_up_to m f p := by { rw ← has_ftaylor_series_up_to_on_univ_iff at h ⊢, exact h.of_le hmn } lemma has_ftaylor_series_up_to.continuous (h : has_ftaylor_series_up_to n f p) : continuous f := begin rw ← has_ftaylor_series_up_to_on_univ_iff at h, rw continuous_iff_continuous_on_univ, exact h.continuous_on end lemma has_ftaylor_series_up_to_zero_iff : has_ftaylor_series_up_to 0 f p ↔ continuous f ∧ (∀ x, (p x 0).uncurry0 = f x) := by simp [has_ftaylor_series_up_to_on_univ_iff.symm, continuous_iff_continuous_on_univ, has_ftaylor_series_up_to_on_zero_iff] /-- If a function has a Taylor series at order at least `1`, then the term of order `1` of this series is a derivative of `f`. -/ lemma has_ftaylor_series_up_to.has_fderiv_at (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) (x : E) : has_fderiv_at f (continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) x := begin rw [← has_fderiv_within_at_univ], exact (has_ftaylor_series_up_to_on_univ_iff.2 h).has_fderiv_within_at hn (mem_univ _) end lemma has_ftaylor_series_up_to.differentiable (h : has_ftaylor_series_up_to n f p) (hn : 1 ≤ n) : differentiable 𝕜 f := λ x, (h.has_fderiv_at hn x).differentiable_at /-- `p` is a Taylor series of `f` up to `n+1` if and only if `p.shift` is a Taylor series up to `n` for `p 1`, which is a derivative of `f`. -/ theorem has_ftaylor_series_up_to_succ_iff_right {n : ℕ} : has_ftaylor_series_up_to ((n + 1) : ℕ) f p ↔ (∀ x, (p x 0).uncurry0 = f x) ∧ (∀ x, has_fderiv_at (λ y, p y 0) (p x 1).curry_left x) ∧ has_ftaylor_series_up_to n (λ x, continuous_multilinear_curry_fin1 𝕜 E F (p x 1)) (λ x, (p x).shift) := by simp [has_ftaylor_series_up_to_on_succ_iff_right, has_ftaylor_series_up_to_on_univ_iff.symm, -add_comm, -with_zero.coe_add] /-! ### Smooth functions at a point -/ variable (𝕜) /-- A function is continuously differentiable up to `n` at a point `x` if, for any integer `k ≤ n`, there is a neighborhood of `x` where `f` admits derivatives up to order `n`, which are continuous. -/ def cont_diff_at (n : with_top ℕ) (f : E → F) (x : E) := cont_diff_within_at 𝕜 n f univ x variable {𝕜} theorem cont_diff_within_at_univ : cont_diff_within_at 𝕜 n f univ x ↔ cont_diff_at 𝕜 n f x := iff.rfl lemma cont_diff_at_top : cont_diff_at 𝕜 ∞ f x ↔ ∀ (n : ℕ), cont_diff_at 𝕜 n f x := by simp [← cont_diff_within_at_univ, cont_diff_within_at_top] lemma cont_diff_at.cont_diff_within_at (h : cont_diff_at 𝕜 n f x) : cont_diff_within_at 𝕜 n f s x := h.mono (subset_univ _) lemma cont_diff_within_at.cont_diff_at (h : cont_diff_within_at 𝕜 n f s x) (hx : s ∈ 𝓝 x) : cont_diff_at 𝕜 n f x := by rwa [cont_diff_at, ← cont_diff_within_at_inter hx, univ_inter] lemma cont_diff_at.congr_of_eventually_eq (h : cont_diff_at 𝕜 n f x) (hg : f₁ =ᶠ[𝓝 x] f) : cont_diff_at 𝕜 n f₁ x := h.congr_of_eventually_eq' (by rwa nhds_within_univ) (mem_univ x) lemma cont_diff_at.of_le (h : cont_diff_at 𝕜 n f x) (hmn : m ≤ n) : cont_diff_at 𝕜 m f x := h.of_le hmn lemma cont_diff_at.continuous_at (h : cont_diff_at 𝕜 n f x) : continuous_at f x := by simpa [continuous_within_at_univ] using h.continuous_within_at /-- If a function is `C^n` with `n ≥ 1` at a point, then it is differentiable there. -/ lemma cont_diff_at.differentiable_at (h : cont_diff_at 𝕜 n f x) (hn : 1 ≤ n) : differentiable_at 𝕜 f x := by simpa [hn, differentiable_within_at_univ] using h.differentiable_within_at /-- A function is `C^(n + 1)` at a point iff locally, it has a derivative which is `C^n`. -/ theorem cont_diff_at_succ_iff_has_fderiv_at {n : ℕ} : cont_diff_at 𝕜 ((n + 1) : ℕ) f x ↔ (∃ f' : E → E →L[𝕜] F, (∃ u ∈ 𝓝 x, ∀ x ∈ u, has_fderiv_at f (f' x) x) ∧ cont_diff_at 𝕜 n f' x) := begin rw [← cont_diff_within_at_univ, cont_diff_within_at_succ_iff_has_fderiv_within_at], simp only [nhds_within_univ, exists_prop, mem_univ, insert_eq_of_mem], split, { rintros ⟨u, H, f', h_fderiv, h_cont_diff⟩, rcases mem_nhds_iff.mp H with ⟨t, htu, ht, hxt⟩, refine ⟨f', ⟨t, _⟩, h_cont_diff.cont_diff_at H⟩, refine ⟨mem_nhds_iff.mpr ⟨t, subset.rfl, ht, hxt⟩, _⟩, intros y hyt, refine (h_fderiv y (htu hyt)).has_fderiv_at _, exact mem_nhds_iff.mpr ⟨t, htu, ht, hyt⟩ }, { rintros ⟨f', ⟨u, H, h_fderiv⟩, h_cont_diff⟩, refine ⟨u, H, f', _, h_cont_diff.cont_diff_within_at⟩, intros x hxu, exact (h_fderiv x hxu).has_fderiv_within_at } end protected theorem cont_diff_at.eventually {n : ℕ} (h : cont_diff_at 𝕜 n f x) : ∀ᶠ y in 𝓝 x, cont_diff_at 𝕜 n f y := by simpa [nhds_within_univ] using h.eventually /-! ### Smooth functions -/ variable (𝕜) /-- A function is continuously differentiable up to `n` if it admits derivatives up to order `n`, which are continuous. Contrary to the case of definitions in domains (where derivatives might not be unique) we do not need to localize the definition in space or time. -/ definition cont_diff (n : with_top ℕ) (f : E → F) := ∃ p : E → formal_multilinear_series 𝕜 E F, has_ftaylor_series_up_to n f p variable {𝕜} theorem cont_diff_on_univ : cont_diff_on 𝕜 n f univ ↔ cont_diff 𝕜 n f := begin split, { assume H, use ftaylor_series_within 𝕜 f univ, rw ← has_ftaylor_series_up_to_on_univ_iff, exact H.ftaylor_series_within unique_diff_on_univ }, { rintros ⟨p, hp⟩ x hx m hm, exact ⟨univ, filter.univ_sets _, p, (hp.has_ftaylor_series_up_to_on univ).of_le hm⟩ } end lemma cont_diff_iff_cont_diff_at : cont_diff 𝕜 n f ↔ ∀ x, cont_diff_at 𝕜 n f x := by simp [← cont_diff_on_univ, cont_diff_on, cont_diff_at] lemma cont_diff.cont_diff_at (h : cont_diff 𝕜 n f) : cont_diff_at 𝕜 n f x := cont_diff_iff_cont_diff_at.1 h x lemma cont_diff.cont_diff_within_at (h : cont_diff 𝕜 n f) : cont_diff_within_at 𝕜 n f s x := h.cont_diff_at.cont_diff_within_at lemma cont_diff_top : cont_diff 𝕜 ∞ f ↔ ∀ (n : ℕ), cont_diff 𝕜 n f := by simp [cont_diff_on_univ.symm, cont_diff_on_top] lemma cont_diff_all_iff_nat : (∀ n, cont_diff 𝕜 n f) ↔ (∀ n : ℕ, cont_diff 𝕜 n f) := by simp only [← cont_diff_on_univ, cont_diff_on_all_iff_nat] lemma cont_diff.cont_diff_on (h : cont_diff 𝕜 n f) : cont_diff_on 𝕜 n f s := (cont_diff_on_univ.2 h).mono (subset_univ _) @[simp] lemma cont_diff_zero : cont_diff 𝕜 0 f ↔ continuous f := begin rw [← cont_diff_on_univ, continuous_iff_continuous_on_univ], exact cont_diff_on_zero end lemma cont_diff_at_zero : cont_diff_at 𝕜 0 f x ↔ ∃ u ∈ 𝓝 x, continuous_on f u := by { rw ← cont_diff_within_at_univ, simp [cont_diff_within_at_zero, nhds_within_univ] } theorem cont_diff_at_one_iff : cont_diff_at 𝕜 1 f x ↔ ∃ f' : E → (E →L[𝕜] F), ∃ u ∈ 𝓝 x, continuous_on f' u ∧ ∀ x ∈ u, has_fderiv_at f (f' x) x := by simp_rw [show (1 : with_top ℕ) = (0 + 1 : ℕ), from (zero_add 1).symm, cont_diff_at_succ_iff_has_fderiv_at, show ((0 : ℕ) : with_top ℕ) = 0, from rfl, cont_diff_at_zero, exists_mem_and_iff antitone_bforall antitone_continuous_on, and_comm] lemma cont_diff.of_le (h : cont_diff 𝕜 n f) (hmn : m ≤ n) : cont_diff 𝕜 m f := cont_diff_on_univ.1 $ (cont_diff_on_univ.2 h).of_le hmn lemma cont_diff.of_succ {n : ℕ} (h : cont_diff 𝕜 (n + 1) f) : cont_diff 𝕜 n f := h.of_le $ with_top.coe_le_coe.mpr le_self_add lemma cont_diff.one_of_succ {n : ℕ} (h : cont_diff 𝕜 (n + 1) f) : cont_diff 𝕜 1 f := h.of_le $ with_top.coe_le_coe.mpr le_add_self lemma cont_diff.continuous (h : cont_diff 𝕜 n f) : continuous f := cont_diff_zero.1 (h.of_le bot_le) /-- If a function is `C^n` with `n ≥ 1`, then it is differentiable. -/ lemma cont_diff.differentiable (h : cont_diff 𝕜 n f) (hn : 1 ≤ n) : differentiable 𝕜 f := differentiable_on_univ.1 $ (cont_diff_on_univ.2 h).differentiable_on hn /-! ### Iterated derivative -/ variable (𝕜) /-- The `n`-th derivative of a function, as a multilinear map, defined inductively. -/ noncomputable def iterated_fderiv (n : ℕ) (f : E → F) : E → (E [×n]→L[𝕜] F) := nat.rec_on n (λ x, continuous_multilinear_map.curry0 𝕜 E (f x)) (λ n rec x, continuous_linear_map.uncurry_left (fderiv 𝕜 rec x)) /-- Formal Taylor series associated to a function within a set. -/ def ftaylor_series (f : E → F) (x : E) : formal_multilinear_series 𝕜 E F := λ n, iterated_fderiv 𝕜 n f x variable {𝕜} @[simp] lemma iterated_fderiv_zero_apply (m : (fin 0) → E) : (iterated_fderiv 𝕜 0 f x : ((fin 0) → E) → F) m = f x := rfl lemma iterated_fderiv_zero_eq_comp : iterated_fderiv 𝕜 0 f = (continuous_multilinear_curry_fin0 𝕜 E F).symm ∘ f := rfl lemma iterated_fderiv_succ_apply_left {n : ℕ} (m : fin (n + 1) → E): (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = (fderiv 𝕜 (iterated_fderiv 𝕜 n f) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) := rfl /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the derivative of the `n`-th derivative. -/ lemma iterated_fderiv_succ_eq_comp_left {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f = (continuous_multilinear_curry_left_equiv 𝕜 (λ(i : fin (n + 1)), E) F) ∘ (fderiv 𝕜 (iterated_fderiv 𝕜 n f)) := rfl lemma iterated_fderiv_within_univ {n : ℕ} : iterated_fderiv_within 𝕜 n f univ = iterated_fderiv 𝕜 n f := begin induction n with n IH, { ext x, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, iterated_fderiv_within_succ_apply_left, IH, fderiv_within_univ] } end /-- In an open set, the iterated derivative within this set coincides with the global iterated derivative. -/ lemma iterated_fderiv_within_of_is_open (n : ℕ) (hs : is_open s) : eq_on (iterated_fderiv_within 𝕜 n f s) (iterated_fderiv 𝕜 n f) s := begin induction n with n IH, { assume x hx, ext1 m, simp only [iterated_fderiv_within_zero_apply, iterated_fderiv_zero_apply] }, { assume x hx, rw [iterated_fderiv_succ_eq_comp_left, iterated_fderiv_within_succ_eq_comp_left], dsimp, congr' 1, rw fderiv_within_of_open hs hx, apply filter.eventually_eq.fderiv_eq, filter_upwards [hs.mem_nhds hx], exact IH } end lemma ftaylor_series_within_univ : ftaylor_series_within 𝕜 f univ = ftaylor_series 𝕜 f := begin ext1 x, ext1 n, change iterated_fderiv_within 𝕜 n f univ x = iterated_fderiv 𝕜 n f x, rw iterated_fderiv_within_univ end theorem iterated_fderiv_succ_apply_right {n : ℕ} (m : fin (n + 1) → E) : (iterated_fderiv 𝕜 (n + 1) f x : (fin (n + 1) → E) → F) m = iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y) x (init m) (m (last n)) := begin rw [← iterated_fderiv_within_univ, ← iterated_fderiv_within_univ, ← fderiv_within_univ], exact iterated_fderiv_within_succ_apply_right unique_diff_on_univ (mem_univ _) _ end /-- Writing explicitly the `n+1`-th derivative as the composition of a currying linear equiv, and the `n`-th derivative of the derivative. -/ lemma iterated_fderiv_succ_eq_comp_right {n : ℕ} : iterated_fderiv 𝕜 (n + 1) f x = ((continuous_multilinear_curry_right_equiv' 𝕜 n E F) ∘ (iterated_fderiv 𝕜 n (λy, fderiv 𝕜 f y))) x := by { ext m, rw iterated_fderiv_succ_apply_right, refl } @[simp] lemma iterated_fderiv_one_apply (m : (fin 1) → E) : (iterated_fderiv 𝕜 1 f x : ((fin 1) → E) → F) m = (fderiv 𝕜 f x : E → F) (m 0) := by { rw [iterated_fderiv_succ_apply_right, iterated_fderiv_zero_apply], refl } /-- When a function is `C^n` in a set `s` of unique differentiability, it admits `ftaylor_series_within 𝕜 f s` as a Taylor series up to order `n` in `s`. -/ theorem cont_diff_on_iff_ftaylor_series : cont_diff 𝕜 n f ↔ has_ftaylor_series_up_to n f (ftaylor_series 𝕜 f) := begin split, { rw [← cont_diff_on_univ, ← has_ftaylor_series_up_to_on_univ_iff, ← ftaylor_series_within_univ], exact λ h, cont_diff_on.ftaylor_series_within h unique_diff_on_univ }, { assume h, exact ⟨ftaylor_series 𝕜 f, h⟩ } end lemma cont_diff_iff_continuous_differentiable : cont_diff 𝕜 n f ↔ (∀ (m : ℕ), (m : with_top ℕ) ≤ n → continuous (λ x, iterated_fderiv 𝕜 m f x)) ∧ (∀ (m : ℕ), (m : with_top ℕ) < n → differentiable 𝕜 (λ x, iterated_fderiv 𝕜 m f x)) := by simp [cont_diff_on_univ.symm, continuous_iff_continuous_on_univ, differentiable_on_univ.symm, iterated_fderiv_within_univ, cont_diff_on_iff_continuous_on_differentiable_on unique_diff_on_univ] lemma cont_diff_of_differentiable_iterated_fderiv (h : ∀(m : ℕ), (m : with_top ℕ) ≤ n → differentiable 𝕜 (iterated_fderiv 𝕜 m f)) : cont_diff 𝕜 n f := cont_diff_iff_continuous_differentiable.2 ⟨λ m hm, (h m hm).continuous, λ m hm, (h m (le_of_lt hm))⟩ /-- A function is `C^(n + 1)` if and only if it is differentiable, and its derivative (formulated in terms of `fderiv`) is `C^n`. -/ theorem cont_diff_succ_iff_fderiv {n : ℕ} : cont_diff 𝕜 ((n + 1) : ℕ) f ↔ differentiable 𝕜 f ∧ cont_diff 𝕜 n (λ y, fderiv 𝕜 f y) := by simp [cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ, cont_diff_on_succ_iff_fderiv_within unique_diff_on_univ, -with_zero.coe_add, -add_comm] theorem cont_diff_one_iff_fderiv : cont_diff 𝕜 1 f ↔ differentiable 𝕜 f ∧ continuous (fderiv 𝕜 f) := cont_diff_succ_iff_fderiv.trans $ iff.rfl.and cont_diff_zero /-- A function is `C^∞` if and only if it is differentiable, and its derivative (formulated in terms of `fderiv`) is `C^∞`. -/ theorem cont_diff_top_iff_fderiv : cont_diff 𝕜 ∞ f ↔ differentiable 𝕜 f ∧ cont_diff 𝕜 ∞ (λ y, fderiv 𝕜 f y) := begin simp [cont_diff_on_univ.symm, differentiable_on_univ.symm, fderiv_within_univ.symm, - fderiv_within_univ], rw cont_diff_on_top_iff_fderiv_within unique_diff_on_univ, end lemma cont_diff.continuous_fderiv (h : cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λ x, fderiv 𝕜 f x) := ((cont_diff_succ_iff_fderiv).1 (h.of_le hn)).2.continuous /-- If a function is at least `C^1`, its bundled derivative (mapping `(x, v)` to `Df(x) v`) is continuous. -/ lemma cont_diff.continuous_fderiv_apply (h : cont_diff 𝕜 n f) (hn : 1 ≤ n) : continuous (λp : E × E, (fderiv 𝕜 f p.1 : E → F) p.2) := begin have A : continuous (λq : (E →L[𝕜] F) × E, q.1 q.2) := is_bounded_bilinear_map_apply.continuous, have B : continuous (λp : E × E, (fderiv 𝕜 f p.1, p.2)), { apply continuous.prod_mk _ continuous_snd, exact continuous.comp (h.continuous_fderiv hn) continuous_fst }, exact A.comp B end /-! ### Constants -/ lemma iterated_fderiv_within_zero_fun {n : ℕ} : iterated_fderiv 𝕜 n (λ x : E, (0 : F)) = 0 := begin induction n with n IH, { ext m, simp }, { ext x m, rw [iterated_fderiv_succ_apply_left, IH], change (fderiv 𝕜 (λ (x : E), (0 : (E [×n]→L[𝕜] F))) x : E → (E [×n]→L[𝕜] F)) (m 0) (tail m) = _, rw fderiv_const, refl } end lemma cont_diff_zero_fun : cont_diff 𝕜 n (λ x : E, (0 : F)) := begin apply cont_diff_of_differentiable_iterated_fderiv (λm hm, _), rw iterated_fderiv_within_zero_fun, apply differentiable_const (0 : (E [×m]→L[𝕜] F)) end /-- Constants are `C^∞`. -/ lemma cont_diff_const {c : F} : cont_diff 𝕜 n (λx : E, c) := begin suffices h : cont_diff 𝕜 ∞ (λx : E, c), by exact h.of_le le_top, rw cont_diff_top_iff_fderiv, refine ⟨differentiable_const c, _⟩, rw fderiv_const, exact cont_diff_zero_fun end lemma cont_diff_on_const {c : F} {s : set E} : cont_diff_on 𝕜 n (λx : E, c) s := cont_diff_const.cont_diff_on lemma cont_diff_at_const {c : F} : cont_diff_at 𝕜 n (λx : E, c) x := cont_diff_const.cont_diff_at lemma cont_diff_within_at_const {c : F} : cont_diff_within_at 𝕜 n (λx : E, c) s x := cont_diff_at_const.cont_diff_within_at @[nontriviality] lemma cont_diff_of_subsingleton [subsingleton F] : cont_diff 𝕜 n f := by { rw [subsingleton.elim f (λ _, 0)], exact cont_diff_const } @[nontriviality] lemma cont_diff_at_of_subsingleton [subsingleton F] : cont_diff_at 𝕜 n f x := by { rw [subsingleton.elim f (λ _, 0)], exact cont_diff_at_const } @[nontriviality] lemma cont_diff_within_at_of_subsingleton [subsingleton F] : cont_diff_within_at 𝕜 n f s x := by { rw [subsingleton.elim f (λ _, 0)], exact cont_diff_within_at_const } @[nontriviality] lemma cont_diff_on_of_subsingleton [subsingleton F] : cont_diff_on 𝕜 n f s := by { rw [subsingleton.elim f (λ _, 0)], exact cont_diff_on_const } /-! ### Smoothness of linear functions -/ /-- Unbundled bounded linear functions are `C^∞`. -/ lemma is_bounded_linear_map.cont_diff (hf : is_bounded_linear_map 𝕜 f) : cont_diff 𝕜 n f := begin suffices h : cont_diff 𝕜 ∞ f, by exact h.of_le le_top, rw cont_diff_top_iff_fderiv, refine ⟨hf.differentiable, _⟩, simp_rw [hf.fderiv], exact cont_diff_const end lemma continuous_linear_map.cont_diff (f : E →L[𝕜] F) : cont_diff 𝕜 n f := f.is_bounded_linear_map.cont_diff lemma continuous_linear_equiv.cont_diff (f : E ≃L[𝕜] F) : cont_diff 𝕜 n f := (f : E →L[𝕜] F).cont_diff lemma linear_isometry.cont_diff (f : E →ₗᵢ[𝕜] F) : cont_diff 𝕜 n f := f.to_continuous_linear_map.cont_diff lemma linear_isometry_equiv.cont_diff (f : E ≃ₗᵢ[𝕜] F) : cont_diff 𝕜 n f := (f : E →L[𝕜] F).cont_diff /-- The identity is `C^∞`. -/ lemma cont_diff_id : cont_diff 𝕜 n (id : E → E) := is_bounded_linear_map.id.cont_diff lemma cont_diff_within_at_id {s x} : cont_diff_within_at 𝕜 n (id : E → E) s x := cont_diff_id.cont_diff_within_at lemma cont_diff_at_id {x} : cont_diff_at 𝕜 n (id : E → E) x := cont_diff_id.cont_diff_at lemma cont_diff_on_id {s} : cont_diff_on 𝕜 n (id : E → E) s := cont_diff_id.cont_diff_on /-- Bilinear functions are `C^∞`. -/ lemma is_bounded_bilinear_map.cont_diff (hb : is_bounded_bilinear_map 𝕜 b) : cont_diff 𝕜 n b := begin suffices h : cont_diff 𝕜 ∞ b, by exact h.of_le le_top, rw cont_diff_top_iff_fderiv, refine ⟨hb.differentiable, _⟩, simp [hb.fderiv], exact hb.is_bounded_linear_map_deriv.cont_diff end /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `g ∘ f` admits a Taylor series whose `k`-th term is given by `g ∘ (p k)`. -/ lemma has_ftaylor_series_up_to_on.continuous_linear_map_comp (g : F →L[𝕜] G) (hf : has_ftaylor_series_up_to_on n f p s) : has_ftaylor_series_up_to_on n (g ∘ f) (λ x k, g.comp_continuous_multilinear_map (p x k)) s := begin set L : Π m : ℕ, (E [×m]→L[𝕜] F) →L[𝕜] (E [×m]→L[𝕜] G) := λ m, continuous_linear_map.comp_continuous_multilinear_mapL g, split, { exact λ x hx, congr_arg g (hf.zero_eq x hx) }, { intros m hm x hx, convert (L m).has_fderiv_at.comp_has_fderiv_within_at x (hf.fderiv_within m hm x hx) }, { intros m hm, convert (L m).continuous.comp_continuous_on (hf.cont m hm) } end /-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain at a point. -/ lemma cont_diff_within_at.continuous_linear_map_comp (g : F →L[𝕜] G) (hf : cont_diff_within_at 𝕜 n f s x) : cont_diff_within_at 𝕜 n (g ∘ f) s x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, exact ⟨u, hu, _, hp.continuous_linear_map_comp g⟩, end /-- Composition by continuous linear maps on the left preserves `C^n` functions in a domain at a point. -/ lemma cont_diff_at.continuous_linear_map_comp (g : F →L[𝕜] G) (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (g ∘ f) x := cont_diff_within_at.continuous_linear_map_comp g hf /-- Composition by continuous linear maps on the left preserves `C^n` functions on domains. -/ lemma cont_diff_on.continuous_linear_map_comp (g : F →L[𝕜] G) (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (g ∘ f) s := λ x hx, (hf x hx).continuous_linear_map_comp g /-- Composition by continuous linear maps on the left preserves `C^n` functions. -/ lemma cont_diff.continuous_linear_map_comp {f : E → F} (g : F →L[𝕜] G) (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λx, g (f x)) := cont_diff_on_univ.1 $ cont_diff_on.continuous_linear_map_comp _ (cont_diff_on_univ.2 hf) /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_cont_diff_within_at_iff (e : F ≃L[𝕜] G) : cont_diff_within_at 𝕜 n (e ∘ f) s x ↔ cont_diff_within_at 𝕜 n f s x := ⟨λ H, by simpa only [(∘), e.symm.coe_coe, e.symm_apply_apply] using H.continuous_linear_map_comp (e.symm : G →L[𝕜] F), λ H, H.continuous_linear_map_comp (e : F →L[𝕜] G)⟩ /-- Composition by continuous linear equivs on the left respects higher differentiability on domains. -/ lemma continuous_linear_equiv.comp_cont_diff_on_iff (e : F ≃L[𝕜] G) : cont_diff_on 𝕜 n (e ∘ f) s ↔ cont_diff_on 𝕜 n f s := by simp [cont_diff_on, e.comp_cont_diff_within_at_iff] /-- If `f` admits a Taylor series `p` in a set `s`, and `g` is linear, then `f ∘ g` admits a Taylor series in `g ⁻¹' s`, whose `k`-th term is given by `p k (g v₁, ..., g vₖ)` . -/ lemma has_ftaylor_series_up_to_on.comp_continuous_linear_map (hf : has_ftaylor_series_up_to_on n f p s) (g : G →L[𝕜] E) : has_ftaylor_series_up_to_on n (f ∘ g) (λ x k, (p (g x) k).comp_continuous_linear_map (λ _, g)) (g ⁻¹' s) := begin let A : Π m : ℕ, (E [×m]→L[𝕜] F) → (G [×m]→L[𝕜] F) := λ m h, h.comp_continuous_linear_map (λ _, g), have hA : ∀ m, is_bounded_linear_map 𝕜 (A m) := λ m, is_bounded_linear_map_continuous_multilinear_map_comp_linear g, split, { assume x hx, simp only [(hf.zero_eq (g x) hx).symm, function.comp_app], change p (g x) 0 (λ (i : fin 0), g 0) = p (g x) 0 0, rw continuous_linear_map.map_zero, refl }, { assume m hm x hx, convert ((hA m).has_fderiv_at).comp_has_fderiv_within_at x ((hf.fderiv_within m hm (g x) hx).comp x (g.has_fderiv_within_at) (subset.refl _)), ext y v, change p (g x) (nat.succ m) (g ∘ (cons y v)) = p (g x) m.succ (cons (g y) (g ∘ v)), rw comp_cons }, { assume m hm, exact (hA m).continuous.comp_continuous_on ((hf.cont m hm).comp g.continuous.continuous_on (subset.refl _)) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions at a point on a domain. -/ lemma cont_diff_within_at.comp_continuous_linear_map {x : G} (g : G →L[𝕜] E) (hf : cont_diff_within_at 𝕜 n f s (g x)) : cont_diff_within_at 𝕜 n (f ∘ g) (g ⁻¹' s) x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, refine ⟨g ⁻¹' u, _, _, hp.comp_continuous_linear_map g⟩, apply continuous_within_at.preimage_mem_nhds_within', { exact g.continuous.continuous_within_at }, { apply nhds_within_mono (g x) _ hu, rw image_insert_eq, exact insert_subset_insert (image_preimage_subset g s) } end /-- Composition by continuous linear maps on the right preserves `C^n` functions on domains. -/ lemma cont_diff_on.comp_continuous_linear_map (hf : cont_diff_on 𝕜 n f s) (g : G →L[𝕜] E) : cont_diff_on 𝕜 n (f ∘ g) (g ⁻¹' s) := λ x hx, (hf (g x) hx).comp_continuous_linear_map g /-- Composition by continuous linear maps on the right preserves `C^n` functions. -/ lemma cont_diff.comp_continuous_linear_map {f : E → F} {g : G →L[𝕜] E} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (f ∘ g) := cont_diff_on_univ.1 $ cont_diff_on.comp_continuous_linear_map (cont_diff_on_univ.2 hf) _ /-- Composition by continuous linear equivs on the right respects higher differentiability at a point in a domain. -/ lemma continuous_linear_equiv.cont_diff_within_at_comp_iff (e : G ≃L[𝕜] E) : cont_diff_within_at 𝕜 n (f ∘ e) (e ⁻¹' s) (e.symm x) ↔ cont_diff_within_at 𝕜 n f s x := begin split, { assume H, simpa [← preimage_comp, (∘)] using H.comp_continuous_linear_map (e.symm : E →L[𝕜] G) }, { assume H, rw [← e.apply_symm_apply x, ← e.coe_coe] at H, exact H.comp_continuous_linear_map _ }, end /-- Composition by continuous linear equivs on the right respects higher differentiability on domains. -/ lemma continuous_linear_equiv.cont_diff_on_comp_iff (e : G ≃L[𝕜] E) : cont_diff_on 𝕜 n (f ∘ e) (e ⁻¹' s) ↔ cont_diff_on 𝕜 n f s := begin refine ⟨λ H, _, λ H, H.comp_continuous_linear_map (e : G →L[𝕜] E)⟩, have A : f = (f ∘ e) ∘ e.symm, by { ext y, simp only [function.comp_app], rw e.apply_symm_apply y }, have B : e.symm ⁻¹' (e ⁻¹' s) = s, by { rw [← preimage_comp, e.self_comp_symm], refl }, rw [A, ← B], exact H.comp_continuous_linear_map (e.symm : E →L[𝕜] G) end /-- If two functions `f` and `g` admit Taylor series `p` and `q` in a set `s`, then the cartesian product of `f` and `g` admits the cartesian product of `p` and `q` as a Taylor series. -/ lemma has_ftaylor_series_up_to_on.prod (hf : has_ftaylor_series_up_to_on n f p s) {g : E → G} {q : E → formal_multilinear_series 𝕜 E G} (hg : has_ftaylor_series_up_to_on n g q s) : has_ftaylor_series_up_to_on n (λ y, (f y, g y)) (λ y k, (p y k).prod (q y k)) s := begin set L := λ m, continuous_multilinear_map.prodL 𝕜 (λ i : fin m, E) F G, split, { assume x hx, rw [← hf.zero_eq x hx, ← hg.zero_eq x hx], refl }, { assume m hm x hx, convert (L m).has_fderiv_at.comp_has_fderiv_within_at x ((hf.fderiv_within m hm x hx).prod (hg.fderiv_within m hm x hx)) }, { assume m hm, exact (L m).continuous.comp_continuous_on ((hf.cont m hm).prod (hg.cont m hm)) } end /-- The cartesian product of `C^n` functions at a point in a domain is `C^n`. -/ lemma cont_diff_within_at.prod {s : set E} {f : E → F} {g : E → G} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) : cont_diff_within_at 𝕜 n (λx:E, (f x, g x)) s x := begin assume m hm, rcases hf m hm with ⟨u, hu, p, hp⟩, rcases hg m hm with ⟨v, hv, q, hq⟩, exact ⟨u ∩ v, filter.inter_mem hu hv, _, (hp.mono (inter_subset_left u v)).prod (hq.mono (inter_subset_right u v))⟩ end /-- The cartesian product of `C^n` functions on domains is `C^n`. -/ lemma cont_diff_on.prod {s : set E} {f : E → F} {g : E → G} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) : cont_diff_on 𝕜 n (λ x : E, (f x, g x)) s := λ x hx, (hf x hx).prod (hg x hx) /-- The cartesian product of `C^n` functions at a point is `C^n`. -/ lemma cont_diff_at.prod {f : E → F} {g : E → G} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) : cont_diff_at 𝕜 n (λ x : E, (f x, g x)) x := cont_diff_within_at_univ.1 $ cont_diff_within_at.prod (cont_diff_within_at_univ.2 hf) (cont_diff_within_at_univ.2 hg) /-- The cartesian product of `C^n` functions is `C^n`.-/ lemma cont_diff.prod {f : E → F} {g : E → G} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (λ x : E, (f x, g x)) := cont_diff_on_univ.1 $ cont_diff_on.prod (cont_diff_on_univ.2 hf) (cont_diff_on_univ.2 hg) /-! ### Composition of `C^n` functions We show that the composition of `C^n` functions is `C^n`. One way to prove it would be to write the `n`-th derivative of the composition (this is Faà di Bruno's formula) and check its continuity, but this is very painful. Instead, we go for a simple inductive proof. Assume it is done for `n`. Then, to check it for `n+1`, one needs to check that the derivative of `g ∘ f` is `C^n`, i.e., that `Dg(f x) ⬝ Df(x)` is `C^n`. The term `Dg (f x)` is the composition of two `C^n` functions, so it is `C^n` by the inductive assumption. The term `Df(x)` is also `C^n`. Then, the matrix multiplication is the application of a bilinear map (which is `C^∞`, and therefore `C^n`) to `x ↦ (Dg(f x), Df x)`. As the composition of two `C^n` maps, it is again `C^n`, and we are done. There is a subtlety in this argument: we apply the inductive assumption to functions on other Banach spaces. In maths, one would say: prove by induction over `n` that, for all `C^n` maps between all pairs of Banach spaces, their composition is `C^n`. In Lean, this is fine as long as the spaces stay in the same universe. This is not the case in the above argument: if `E` lives in universe `u` and `F` lives in universe `v`, then linear maps from `E` to `F` (to which the derivative of `f` belongs) is in universe `max u v`. If one could quantify over finitely many universes, the above proof would work fine, but this is not the case. One could still write the proof considering spaces in any universe in `u, v, w, max u v, max v w, max u v w`, but it would be extremely tedious and lead to a lot of duplication. Instead, we formulate the above proof when all spaces live in the same universe (where everything is fine), and then we deduce the general result by lifting all our spaces to a common universe. We use the trick that any space `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map (λ (i : fin 0), E × F × G) H` to change the universe level, and then argue that composing with such a linear equiv does not change the fact of being `C^n`, which we have already proved previously. -/ /-- Auxiliary lemma proving that the composition of `C^n` functions on domains is `C^n` when all spaces live in the same universe. Use instead `cont_diff_on.comp` which removes the universe assumption (but is deduced from this one). -/ private lemma cont_diff_on.comp_same_univ {Eu : Type u} [normed_group Eu] [normed_space 𝕜 Eu] {Fu : Type u} [normed_group Fu] [normed_space 𝕜 Fu] {Gu : Type u} [normed_group Gu] [normed_space 𝕜 Gu] {s : set Eu} {t : set Fu} {g : Fu → Gu} {f : Eu → Fu} (hg : cont_diff_on 𝕜 n g t) (hf : cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : cont_diff_on 𝕜 n (g ∘ f) s := begin unfreezingI { induction n using with_top.nat_induction with n IH Itop generalizing Eu Fu Gu }, { rw cont_diff_on_zero at hf hg ⊢, exact continuous_on.comp hg hf st }, { rw cont_diff_on_succ_iff_has_fderiv_within_at at hg ⊢, assume x hx, rcases (cont_diff_on_succ_iff_has_fderiv_within_at.1 hf) x hx with ⟨u, hu, f', hf', f'_diff⟩, rcases hg (f x) (st hx) with ⟨v, hv, g', hg', g'_diff⟩, rw insert_eq_of_mem hx at hu ⊢, have xu : x ∈ u := mem_of_mem_nhds_within hx hu, let w := s ∩ (u ∩ f⁻¹' v), have wv : w ⊆ f ⁻¹' v := λ y hy, hy.2.2, have wu : w ⊆ u := λ y hy, hy.2.1, have ws : w ⊆ s := λ y hy, hy.1, refine ⟨w, _, λ y, (g' (f y)).comp (f' y), _, _⟩, show w ∈ 𝓝[s] x, { apply filter.inter_mem self_mem_nhds_within, apply filter.inter_mem hu, apply continuous_within_at.preimage_mem_nhds_within', { rw ← continuous_within_at_inter' hu, exact (hf' x xu).differentiable_within_at.continuous_within_at.mono (inter_subset_right _ _) }, { apply nhds_within_mono _ _ hv, exact subset.trans (image_subset_iff.mpr st) (subset_insert (f x) t) } }, show ∀ y ∈ w, has_fderiv_within_at (g ∘ f) ((g' (f y)).comp (f' y)) w y, { rintros y ⟨ys, yu, yv⟩, exact (hg' (f y) yv).comp y ((hf' y yu).mono wu) wv }, show cont_diff_on 𝕜 n (λ y, (g' (f y)).comp (f' y)) w, { have A : cont_diff_on 𝕜 n (λ y, g' (f y)) w := IH g'_diff ((hf.of_le (with_top.coe_le_coe.2 (nat.le_succ n))).mono ws) wv, have B : cont_diff_on 𝕜 n f' w := f'_diff.mono wu, have C : cont_diff_on 𝕜 n (λ y, (f' y, g' (f y))) w := cont_diff_on.prod B A, have D : cont_diff_on 𝕜 n (λ(p : (Eu →L[𝕜] Fu) × (Fu →L[𝕜] Gu)), p.2.comp p.1) univ := is_bounded_bilinear_map_comp.cont_diff.cont_diff_on, exact IH D C (subset_univ _) } }, { rw cont_diff_on_top at hf hg ⊢, assume n, apply Itop n (hg n) (hf n) st } end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma cont_diff_on.comp {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : cont_diff_on 𝕜 n g t) (hf : cont_diff_on 𝕜 n f s) (st : s ⊆ f ⁻¹' t) : cont_diff_on 𝕜 n (g ∘ f) s := begin /- we lift all the spaces to a common universe, as we have already proved the result in this situation. For the lift, we use the trick that `H` is isomorphic through a continuous linear equiv to `continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) H`, and continuous linear equivs respect smoothness classes. -/ let Eu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) E, letI : normed_group Eu := by apply_instance, letI : normed_space 𝕜 Eu := by apply_instance, let Fu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) F, letI : normed_group Fu := by apply_instance, letI : normed_space 𝕜 Fu := by apply_instance, let Gu := continuous_multilinear_map 𝕜 (λ (i : fin 0), (E × F × G)) G, letI : normed_group Gu := by apply_instance, letI : normed_space 𝕜 Gu := by apply_instance, -- declare the isomorphisms let isoE : Eu ≃L[𝕜] E := continuous_multilinear_curry_fin0 𝕜 (E × F × G) E, let isoF : Fu ≃L[𝕜] F := continuous_multilinear_curry_fin0 𝕜 (E × F × G) F, let isoG : Gu ≃L[𝕜] G := continuous_multilinear_curry_fin0 𝕜 (E × F × G) G, -- lift the functions to the new spaces, check smoothness there, and then go back. let fu : Eu → Fu := (isoF.symm ∘ f) ∘ isoE, have fu_diff : cont_diff_on 𝕜 n fu (isoE ⁻¹' s), by rwa [isoE.cont_diff_on_comp_iff, isoF.symm.comp_cont_diff_on_iff], let gu : Fu → Gu := (isoG.symm ∘ g) ∘ isoF, have gu_diff : cont_diff_on 𝕜 n gu (isoF ⁻¹' t), by rwa [isoF.cont_diff_on_comp_iff, isoG.symm.comp_cont_diff_on_iff], have main : cont_diff_on 𝕜 n (gu ∘ fu) (isoE ⁻¹' s), { apply cont_diff_on.comp_same_univ gu_diff fu_diff, assume y hy, simp only [fu, continuous_linear_equiv.coe_apply, function.comp_app, mem_preimage], rw isoF.apply_symm_apply (f (isoE y)), exact st hy }, have : gu ∘ fu = (isoG.symm ∘ (g ∘ f)) ∘ isoE, { ext y, simp only [function.comp_apply, gu, fu], rw isoF.apply_symm_apply (f (isoE y)) }, rwa [this, isoE.cont_diff_on_comp_iff, isoG.symm.comp_cont_diff_on_iff] at main end /-- The composition of `C^n` functions on domains is `C^n`. -/ lemma cont_diff_on.comp' {s : set E} {t : set F} {g : F → G} {f : E → F} (hg : cont_diff_on 𝕜 n g t) (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) /-- The composition of a `C^n` function on a domain with a `C^n` function is `C^n`. -/ lemma cont_diff.comp_cont_diff_on {s : set E} {g : F → G} {f : E → F} (hg : cont_diff 𝕜 n g) (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (g ∘ f) s := (cont_diff_on_univ.2 hg).comp hf subset_preimage_univ /-- The composition of `C^n` functions is `C^n`. -/ lemma cont_diff.comp {g : F → G} {f : E → F} (hg : cont_diff 𝕜 n g) (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (g ∘ f) := cont_diff_on_univ.1 $ cont_diff_on.comp (cont_diff_on_univ.2 hg) (cont_diff_on_univ.2 hf) (subset_univ _) /-- The composition of `C^n` functions at points in domains is `C^n`. -/ lemma cont_diff_within_at.comp {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E) (hg : cont_diff_within_at 𝕜 n g t (f x)) (hf : cont_diff_within_at 𝕜 n f s x) (st : s ⊆ f ⁻¹' t) : cont_diff_within_at 𝕜 n (g ∘ f) s x := begin assume m hm, rcases hg.cont_diff_on hm with ⟨u, u_nhd, ut, hu⟩, rcases hf.cont_diff_on hm with ⟨v, v_nhd, vs, hv⟩, have xmem : x ∈ f ⁻¹' u ∩ v := ⟨(mem_of_mem_nhds_within (mem_insert (f x) _) u_nhd : _), mem_of_mem_nhds_within (mem_insert x s) v_nhd⟩, have : f ⁻¹' u ∈ 𝓝[insert x s] x, { apply hf.continuous_within_at.insert_self.preimage_mem_nhds_within', apply nhds_within_mono _ _ u_nhd, rw image_insert_eq, exact insert_subset_insert (image_subset_iff.mpr st) }, have Z := ((hu.comp (hv.mono (inter_subset_right (f ⁻¹' u) v)) (inter_subset_left _ _)) .cont_diff_within_at) xmem m le_rfl, have : 𝓝[f ⁻¹' u ∩ v] x = 𝓝[insert x s] x, { have A : f ⁻¹' u ∩ v = (insert x s) ∩ (f ⁻¹' u ∩ v), { apply subset.antisymm _ (inter_subset_right _ _), rintros y ⟨hy1, hy2⟩, simp [hy1, hy2, vs hy2] }, rw [A, ← nhds_within_restrict''], exact filter.inter_mem this v_nhd }, rwa [insert_eq_of_mem xmem, this] at Z, end /-- The composition of `C^n` functions at points in domains is `C^n`. -/ lemma cont_diff_within_at.comp' {s : set E} {t : set F} {g : F → G} {f : E → F} (x : E) (hg : cont_diff_within_at 𝕜 n g t (f x)) (hf : cont_diff_within_at 𝕜 n f s x) : cont_diff_within_at 𝕜 n (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp x (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma cont_diff_at.comp_cont_diff_within_at {n} (x : E) (hg : cont_diff_at 𝕜 n g (f x)) (hf : cont_diff_within_at 𝕜 n f s x) : cont_diff_within_at 𝕜 n (g ∘ f) s x := hg.comp x hf (maps_to_univ _ _) /-- The composition of `C^n` functions at points is `C^n`. -/ lemma cont_diff_at.comp (x : E) (hg : cont_diff_at 𝕜 n g (f x)) (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (g ∘ f) x := hg.comp x hf subset_preimage_univ lemma cont_diff.comp_cont_diff_within_at {g : F → G} {f : E → F} (h : cont_diff 𝕜 n g) (hf : cont_diff_within_at 𝕜 n f t x) : cont_diff_within_at 𝕜 n (g ∘ f) t x := begin have : cont_diff_within_at 𝕜 n g univ (f x) := h.cont_diff_at.cont_diff_within_at, exact this.comp x hf (subset_univ _), end lemma cont_diff.comp_cont_diff_at {g : F → G} {f : E → F} (x : E) (hg : cont_diff 𝕜 n g) (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (g ∘ f) x := hg.comp_cont_diff_within_at hf /-! ### Smoothness of projections -/ /-- The first projection in a product is `C^∞`. -/ lemma cont_diff_fst : cont_diff 𝕜 n (prod.fst : E × F → E) := is_bounded_linear_map.cont_diff is_bounded_linear_map.fst /-- Postcomposing `f` with `prod.fst` is `C^n` -/ lemma cont_diff.fst {f : E → F × G} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x, (f x).1) := cont_diff_fst.comp hf /-- Precomposing `f` with `prod.fst` is `C^n` -/ lemma cont_diff.fst' {f : E → G} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x : E × F, f x.1) := hf.comp cont_diff_fst /-- The first projection on a domain in a product is `C^∞`. -/ lemma cont_diff_on_fst {s : set (E × F)} : cont_diff_on 𝕜 n (prod.fst : E × F → E) s := cont_diff.cont_diff_on cont_diff_fst lemma cont_diff_on.fst {f : E → F × G} {s : set E} (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (λ x, (f x).1) s := cont_diff_fst.comp_cont_diff_on hf /-- The first projection at a point in a product is `C^∞`. -/ lemma cont_diff_at_fst {p : E × F} : cont_diff_at 𝕜 n (prod.fst : E × F → E) p := cont_diff_fst.cont_diff_at /-- Postcomposing `f` with `prod.fst` is `C^n` at `(x, y)` -/ lemma cont_diff_at.fst {f : E → F × G} {x : E} (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (λ x, (f x).1) x := cont_diff_at_fst.comp x hf /-- Precomposing `f` with `prod.fst` is `C^n` at `(x, y)` -/ lemma cont_diff_at.fst' {f : E → G} {x : E} {y : F} (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (λ x : E × F, f x.1) (x, y) := cont_diff_at.comp (x, y) hf cont_diff_at_fst /-- Precomposing `f` with `prod.fst` is `C^n` at `x : E × F` -/ lemma cont_diff_at.fst'' {f : E → G} {x : E × F} (hf : cont_diff_at 𝕜 n f x.1) : cont_diff_at 𝕜 n (λ x : E × F, f x.1) x := hf.comp x cont_diff_at_fst /-- The first projection within a domain at a point in a product is `C^∞`. -/ lemma cont_diff_within_at_fst {s : set (E × F)} {p : E × F} : cont_diff_within_at 𝕜 n (prod.fst : E × F → E) s p := cont_diff_fst.cont_diff_within_at /-- The second projection in a product is `C^∞`. -/ lemma cont_diff_snd : cont_diff 𝕜 n (prod.snd : E × F → F) := is_bounded_linear_map.cont_diff is_bounded_linear_map.snd /-- Postcomposing `f` with `prod.snd` is `C^n` -/ lemma cont_diff.snd {f : E → F × G} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x, (f x).2) := cont_diff_snd.comp hf /-- Precomposing `f` with `prod.snd` is `C^n` -/ lemma cont_diff.snd' {f : F → G} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x : E × F, f x.2) := hf.comp cont_diff_snd /-- The second projection on a domain in a product is `C^∞`. -/ lemma cont_diff_on_snd {s : set (E × F)} : cont_diff_on 𝕜 n (prod.snd : E × F → F) s := cont_diff.cont_diff_on cont_diff_snd lemma cont_diff_on.snd {f : E → F × G} {s : set E} (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (λ x, (f x).2) s := cont_diff_snd.comp_cont_diff_on hf /-- The second projection at a point in a product is `C^∞`. -/ lemma cont_diff_at_snd {p : E × F} : cont_diff_at 𝕜 n (prod.snd : E × F → F) p := cont_diff_snd.cont_diff_at /-- Postcomposing `f` with `prod.snd` is `C^n` at `x` -/ lemma cont_diff_at.snd {f : E → F × G} {x : E} (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (λ x, (f x).2) x := cont_diff_at_snd.comp x hf /-- Precomposing `f` with `prod.snd` is `C^n` at `(x, y)` -/ lemma cont_diff_at.snd' {f : F → G} {x : E} {y : F} (hf : cont_diff_at 𝕜 n f y) : cont_diff_at 𝕜 n (λ x : E × F, f x.2) (x, y) := cont_diff_at.comp (x, y) hf cont_diff_at_snd /-- Precomposing `f` with `prod.snd` is `C^n` at `x : E × F` -/ lemma cont_diff_at.snd'' {f : F → G} {x : E × F} (hf : cont_diff_at 𝕜 n f x.2) : cont_diff_at 𝕜 n (λ x : E × F, f x.2) x := hf.comp x cont_diff_at_snd /-- The second projection within a domain at a point in a product is `C^∞`. -/ lemma cont_diff_within_at_snd {s : set (E × F)} {p : E × F} : cont_diff_within_at 𝕜 n (prod.snd : E × F → F) s p := cont_diff_snd.cont_diff_within_at section n_ary variables {E₁ E₂ E₃ E₄ : Type*} variables [normed_group E₁] [normed_group E₂] [normed_group E₃] [normed_group E₄] variables [normed_space 𝕜 E₁] [normed_space 𝕜 E₂] [normed_space 𝕜 E₃] [normed_space 𝕜 E₄] lemma cont_diff.comp₂ {g : E₁ × E₂ → G} {f₁ : F → E₁} {f₂ : F → E₂} (hg : cont_diff 𝕜 n g) (hf₁ : cont_diff 𝕜 n f₁) (hf₂ : cont_diff 𝕜 n f₂) : cont_diff 𝕜 n (λ x, g (f₁ x, f₂ x)) := hg.comp $ hf₁.prod hf₂ lemma cont_diff.comp₃ {g : E₁ × E₂ × E₃ → G} {f₁ : F → E₁} {f₂ : F → E₂} {f₃ : F → E₃} (hg : cont_diff 𝕜 n g) (hf₁ : cont_diff 𝕜 n f₁) (hf₂ : cont_diff 𝕜 n f₂) (hf₃ : cont_diff 𝕜 n f₃) : cont_diff 𝕜 n (λ x, g (f₁ x, f₂ x, f₃ x)) := hg.comp₂ hf₁ $ hf₂.prod hf₃ end n_ary /-- The natural equivalence `(E × F) × G ≃ E × (F × G)` is smooth. Warning: if you think you need this lemma, it is likely that you can simplify your proof by reformulating the lemma that you're applying next using the tips in Note [continuity lemma statement] -/ lemma cont_diff_prod_assoc : cont_diff 𝕜 ⊤ $ equiv.prod_assoc E F G := (linear_isometry_equiv.prod_assoc 𝕜 E F G).cont_diff /-- The natural equivalence `E × (F × G) ≃ (E × F) × G` is smooth. Warning: see remarks attached to `cont_diff_prod_assoc` -/ lemma cont_diff_prod_assoc_symm : cont_diff 𝕜 ⊤ $ (equiv.prod_assoc E F G).symm := (linear_isometry_equiv.prod_assoc 𝕜 E F G).symm.cont_diff /-! ### Bundled derivatives -/ /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma cont_diff_on_fderiv_within_apply {m n : with_top ℕ} {s : set E} {f : E → F} (hf : cont_diff_on 𝕜 n f s) (hs : unique_diff_on 𝕜 s) (hmn : m + 1 ≤ n) : cont_diff_on 𝕜 m (λp : E × E, (fderiv_within 𝕜 f s p.1 : E →L[𝕜] F) p.2) (s ×ˢ (univ : set E)) := begin have A : cont_diff 𝕜 m (λp : (E →L[𝕜] F) × E, p.1 p.2), { apply is_bounded_bilinear_map.cont_diff, exact is_bounded_bilinear_map_apply }, have B : cont_diff_on 𝕜 m (λ (p : E × E), ((fderiv_within 𝕜 f s p.fst), p.snd)) (s ×ˢ univ), { apply cont_diff_on.prod _ _, { have I : cont_diff_on 𝕜 m (λ (x : E), fderiv_within 𝕜 f s x) s := hf.fderiv_within hs hmn, have J : cont_diff_on 𝕜 m (λ (x : E × E), x.1) (s ×ˢ univ) := cont_diff_fst.cont_diff_on, exact cont_diff_on.comp I J (prod_subset_preimage_fst _ _) }, { apply cont_diff.cont_diff_on _ , apply is_bounded_linear_map.snd.cont_diff } }, exact A.comp_cont_diff_on B end /-- The bundled derivative of a `C^{n+1}` function is `C^n`. -/ lemma cont_diff.cont_diff_fderiv_apply {f : E → F} (hf : cont_diff 𝕜 n f) (hmn : m + 1 ≤ n) : cont_diff 𝕜 m (λp : E × E, (fderiv 𝕜 f p.1 : E →L[𝕜] F) p.2) := begin rw ← cont_diff_on_univ at ⊢ hf, rw [← fderiv_within_univ, ← univ_prod_univ], exact cont_diff_on_fderiv_within_apply hf unique_diff_on_univ hmn end /-! ### Smoothness of functions `f : E → Π i, F' i` -/ section pi variables {ι ι' : Type*} [fintype ι] [fintype ι'] {F' : ι → Type*} [Π i, normed_group (F' i)] [Π i, normed_space 𝕜 (F' i)] {φ : Π i, E → F' i} {p' : Π i, E → formal_multilinear_series 𝕜 E (F' i)} {Φ : E → Π i, F' i} {P' : E → formal_multilinear_series 𝕜 E (Π i, F' i)} lemma has_ftaylor_series_up_to_on_pi : has_ftaylor_series_up_to_on n (λ x i, φ i x) (λ x m, continuous_multilinear_map.pi (λ i, p' i x m)) s ↔ ∀ i, has_ftaylor_series_up_to_on n (φ i) (p' i) s := begin set pr := @continuous_linear_map.proj 𝕜 _ ι F' _ _ _, letI : Π (m : ℕ) (i : ι), normed_space 𝕜 (E [×m]→L[𝕜] (F' i)) := λ m i, infer_instance, set L : Π m : ℕ, (Π i, E [×m]→L[𝕜] (F' i)) ≃ₗᵢ[𝕜] (E [×m]→L[𝕜] (Π i, F' i)) := λ m, continuous_multilinear_map.piₗᵢ _ _, refine ⟨λ h i, _, λ h, ⟨λ x hx, _, _, _⟩⟩, { convert h.continuous_linear_map_comp (pr i), ext, refl }, { ext1 i, exact (h i).zero_eq x hx }, { intros m hm x hx, have := has_fderiv_within_at_pi.2 (λ i, (h i).fderiv_within m hm x hx), convert (L m).has_fderiv_at.comp_has_fderiv_within_at x this }, { intros m hm, have := continuous_on_pi.2 (λ i, (h i).cont m hm), convert (L m).continuous.comp_continuous_on this } end @[simp] lemma has_ftaylor_series_up_to_on_pi' : has_ftaylor_series_up_to_on n Φ P' s ↔ ∀ i, has_ftaylor_series_up_to_on n (λ x, Φ x i) (λ x m, (@continuous_linear_map.proj 𝕜 _ ι F' _ _ _ i).comp_continuous_multilinear_map (P' x m)) s := by { convert has_ftaylor_series_up_to_on_pi, ext, refl } lemma cont_diff_within_at_pi : cont_diff_within_at 𝕜 n Φ s x ↔ ∀ i, cont_diff_within_at 𝕜 n (λ x, Φ x i) s x := begin set pr := @continuous_linear_map.proj 𝕜 _ ι F' _ _ _, refine ⟨λ h i, h.continuous_linear_map_comp (pr i), λ h m hm, _⟩, choose u hux p hp using λ i, h i m hm, exact ⟨⋂ i, u i, filter.Inter_mem.2 hux, _, has_ftaylor_series_up_to_on_pi.2 (λ i, (hp i).mono $ Inter_subset _ _)⟩, end lemma cont_diff_on_pi : cont_diff_on 𝕜 n Φ s ↔ ∀ i, cont_diff_on 𝕜 n (λ x, Φ x i) s := ⟨λ h i x hx, cont_diff_within_at_pi.1 (h x hx) _, λ h x hx, cont_diff_within_at_pi.2 (λ i, h i x hx)⟩ lemma cont_diff_at_pi : cont_diff_at 𝕜 n Φ x ↔ ∀ i, cont_diff_at 𝕜 n (λ x, Φ x i) x := cont_diff_within_at_pi lemma cont_diff_pi : cont_diff 𝕜 n Φ ↔ ∀ i, cont_diff 𝕜 n (λ x, Φ x i) := by simp only [← cont_diff_on_univ, cont_diff_on_pi] variables (𝕜 E) lemma cont_diff_apply (i : ι) : cont_diff 𝕜 n (λ (f : ι → E), f i) := cont_diff_pi.mp cont_diff_id i lemma cont_diff_apply_apply (i : ι) (j : ι') : cont_diff 𝕜 n (λ (f : ι → ι' → E), f i j) := cont_diff_pi.mp (cont_diff_apply 𝕜 (ι' → E) i) j variables {𝕜 E} end pi /-! ### Sum of two functions -/ /- The sum is smooth. -/ lemma cont_diff_add : cont_diff 𝕜 n (λp : F × F, p.1 + p.2) := (is_bounded_linear_map.fst.add is_bounded_linear_map.snd).cont_diff /-- The sum of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma cont_diff_within_at.add {s : set E} {f g : E → F} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) : cont_diff_within_at 𝕜 n (λx, f x + g x) s x := cont_diff_add.cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The sum of two `C^n` functions at a point is `C^n` at this point. -/ lemma cont_diff_at.add {f g : E → F} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) : cont_diff_at 𝕜 n (λx, f x + g x) x := by rw [← cont_diff_within_at_univ] at *; exact hf.add hg /-- The sum of two `C^n`functions is `C^n`. -/ lemma cont_diff.add {f g : E → F} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (λx, f x + g x) := cont_diff_add.comp (hf.prod hg) /-- The sum of two `C^n` functions on a domain is `C^n`. -/ lemma cont_diff_on.add {s : set E} {f g : E → F} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) : cont_diff_on 𝕜 n (λx, f x + g x) s := λ x hx, (hf x hx).add (hg x hx) /-! ### Negative -/ /- The negative is smooth. -/ lemma cont_diff_neg : cont_diff 𝕜 n (λp : F, -p) := is_bounded_linear_map.id.neg.cont_diff /-- The negative of a `C^n` function within a domain at a point is `C^n` within this domain at this point. -/ lemma cont_diff_within_at.neg {s : set E} {f : E → F} (hf : cont_diff_within_at 𝕜 n f s x) : cont_diff_within_at 𝕜 n (λx, -f x) s x := cont_diff_neg.cont_diff_within_at.comp x hf subset_preimage_univ /-- The negative of a `C^n` function at a point is `C^n` at this point. -/ lemma cont_diff_at.neg {f : E → F} (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (λx, -f x) x := by rw ← cont_diff_within_at_univ at *; exact hf.neg /-- The negative of a `C^n`function is `C^n`. -/ lemma cont_diff.neg {f : E → F} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λx, -f x) := cont_diff_neg.comp hf /-- The negative of a `C^n` function on a domain is `C^n`. -/ lemma cont_diff_on.neg {s : set E} {f : E → F} (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (λx, -f x) s := λ x hx, (hf x hx).neg /-! ### Subtraction -/ /-- The difference of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma cont_diff_within_at.sub {s : set E} {f g : E → F} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) : cont_diff_within_at 𝕜 n (λx, f x - g x) s x := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions at a point is `C^n` at this point. -/ lemma cont_diff_at.sub {f g : E → F} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) : cont_diff_at 𝕜 n (λx, f x - g x) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions on a domain is `C^n`. -/ lemma cont_diff_on.sub {s : set E} {f g : E → F} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) : cont_diff_on 𝕜 n (λx, f x - g x) s := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-- The difference of two `C^n` functions is `C^n`. -/ lemma cont_diff.sub {f g : E → F} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (λx, f x - g x) := by simpa only [sub_eq_add_neg] using hf.add hg.neg /-! ### Sum of finitely many functions -/ lemma cont_diff_within_at.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {t : set E} {x : E} (h : ∀ i ∈ s, cont_diff_within_at 𝕜 n (λ x, f i x) t x) : cont_diff_within_at 𝕜 n (λ x, (∑ i in s, f i x)) t x := begin classical, induction s using finset.induction_on with i s is IH, { simp [cont_diff_within_at_const] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end lemma cont_diff_at.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {x : E} (h : ∀ i ∈ s, cont_diff_at 𝕜 n (λ x, f i x) x) : cont_diff_at 𝕜 n (λ x, (∑ i in s, f i x)) x := by rw [← cont_diff_within_at_univ] at *; exact cont_diff_within_at.sum h lemma cont_diff_on.sum {ι : Type*} {f : ι → E → F} {s : finset ι} {t : set E} (h : ∀ i ∈ s, cont_diff_on 𝕜 n (λ x, f i x) t) : cont_diff_on 𝕜 n (λ x, (∑ i in s, f i x)) t := λ x hx, cont_diff_within_at.sum (λ i hi, h i hi x hx) lemma cont_diff.sum {ι : Type*} {f : ι → E → F} {s : finset ι} (h : ∀ i ∈ s, cont_diff 𝕜 n (λ x, f i x)) : cont_diff 𝕜 n (λ x, (∑ i in s, f i x)) := by simp [← cont_diff_on_univ] at *; exact cont_diff_on.sum h /-! ### Product of two functions -/ /- The product is smooth. -/ lemma cont_diff_mul : cont_diff 𝕜 n (λ p : 𝕜 × 𝕜, p.1 * p.2) := is_bounded_bilinear_map_mul.cont_diff /-- The product of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma cont_diff_within_at.mul {s : set E} {f g : E → 𝕜} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) : cont_diff_within_at 𝕜 n (λ x, f x * g x) s x := cont_diff_mul.cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The product of two `C^n` functions at a point is `C^n` at this point. -/ lemma cont_diff_at.mul {f g : E → 𝕜} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) : cont_diff_at 𝕜 n (λ x, f x * g x) x := by rw [← cont_diff_within_at_univ] at *; exact hf.mul hg /-- The product of two `C^n` functions on a domain is `C^n`. -/ lemma cont_diff_on.mul {s : set E} {f g : E → 𝕜} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) : cont_diff_on 𝕜 n (λ x, f x * g x) s := λ x hx, (hf x hx).mul (hg x hx) /-- The product of two `C^n`functions is `C^n`. -/ lemma cont_diff.mul {f g : E → 𝕜} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (λ x, f x * g x) := cont_diff_mul.comp (hf.prod hg) lemma cont_diff_within_at.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : cont_diff_within_at 𝕜 n f s x) : cont_diff_within_at 𝕜 n (λ x, f x / c) s x := by simpa only [div_eq_mul_inv] using hf.mul cont_diff_within_at_const lemma cont_diff_at.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : cont_diff_at 𝕜 n f x) : cont_diff_at 𝕜 n (λ x, f x / c) x := by simpa only [div_eq_mul_inv] using hf.mul cont_diff_at_const lemma cont_diff_on.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : cont_diff_on 𝕜 n f s) : cont_diff_on 𝕜 n (λ x, f x / c) s := by simpa only [div_eq_mul_inv] using hf.mul cont_diff_on_const lemma cont_diff.div_const {f : E → 𝕜} {n} {c : 𝕜} (hf : cont_diff 𝕜 n f) : cont_diff 𝕜 n (λ x, f x / c) := by simpa only [div_eq_mul_inv] using hf.mul cont_diff_const lemma cont_diff.pow {f : E → 𝕜} (hf : cont_diff 𝕜 n f) : ∀ m : ℕ, cont_diff 𝕜 n (λ x, (f x) ^ m) | 0 := by simpa using cont_diff_const | (m + 1) := by simpa [pow_succ] using hf.mul (cont_diff.pow m) lemma cont_diff_at.pow {f : E → 𝕜} (hf : cont_diff_at 𝕜 n f x) (m : ℕ) : cont_diff_at 𝕜 n (λ y, f y ^ m) x := (cont_diff_id.pow m).cont_diff_at.comp x hf lemma cont_diff_within_at.pow {f : E → 𝕜} (hf : cont_diff_within_at 𝕜 n f s x) (m : ℕ) : cont_diff_within_at 𝕜 n (λ y, f y ^ m) s x := (cont_diff_id.pow m).cont_diff_at.comp_cont_diff_within_at x hf lemma cont_diff_on.pow {f : E → 𝕜} (hf : cont_diff_on 𝕜 n f s) (m : ℕ) : cont_diff_on 𝕜 n (λ y, f y ^ m) s := λ y hy, (hf y hy).pow m /-! ### Scalar multiplication -/ /- The scalar multiplication is smooth. -/ lemma cont_diff_smul : cont_diff 𝕜 n (λ p : 𝕜 × F, p.1 • p.2) := is_bounded_bilinear_map_smul.cont_diff /-- The scalar multiplication of two `C^n` functions within a set at a point is `C^n` within this set at this point. -/ lemma cont_diff_within_at.smul {s : set E} {f : E → 𝕜} {g : E → F} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) : cont_diff_within_at 𝕜 n (λ x, f x • g x) s x := cont_diff_smul.cont_diff_within_at.comp x (hf.prod hg) subset_preimage_univ /-- The scalar multiplication of two `C^n` functions at a point is `C^n` at this point. -/ lemma cont_diff_at.smul {f : E → 𝕜} {g : E → F} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) : cont_diff_at 𝕜 n (λ x, f x • g x) x := by rw [← cont_diff_within_at_univ] at *; exact hf.smul hg /-- The scalar multiplication of two `C^n` functions is `C^n`. -/ lemma cont_diff.smul {f : E → 𝕜} {g : E → F} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (λ x, f x • g x) := cont_diff_smul.comp (hf.prod hg) /-- The scalar multiplication of two `C^n` functions on a domain is `C^n`. -/ lemma cont_diff_on.smul {s : set E} {f : E → 𝕜} {g : E → F} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) : cont_diff_on 𝕜 n (λ x, f x • g x) s := λ x hx, (hf x hx).smul (hg x hx) /-! ### Cartesian product of two functions -/ section prod_map variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] variables {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma cont_diff_within_at.prod_map' {s : set E} {t : set E'} {f : E → F} {g : E' → F'} {p : E × E'} (hf : cont_diff_within_at 𝕜 n f s p.1) (hg : cont_diff_within_at 𝕜 n g t p.2) : cont_diff_within_at 𝕜 n (prod.map f g) (s ×ˢ t) p := (hf.comp p cont_diff_within_at_fst (prod_subset_preimage_fst _ _)).prod (hg.comp p cont_diff_within_at_snd (prod_subset_preimage_snd _ _)) lemma cont_diff_within_at.prod_map {s : set E} {t : set E'} {f : E → F} {g : E' → F'} {x : E} {y : E'} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g t y) : cont_diff_within_at 𝕜 n (prod.map f g) (s ×ˢ t) (x, y) := cont_diff_within_at.prod_map' hf hg /-- The product map of two `C^n` functions on a set is `C^n` on the product set. -/ lemma cont_diff_on.prod_map {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] {s : set E} {t : set E'} {f : E → F} {g : E' → F'} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g t) : cont_diff_on 𝕜 n (prod.map f g) (s ×ˢ t) := (hf.comp cont_diff_on_fst (prod_subset_preimage_fst _ _)).prod (hg.comp (cont_diff_on_snd) (prod_subset_preimage_snd _ _)) /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma cont_diff_at.prod_map {f : E → F} {g : E' → F'} {x : E} {y : E'} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g y) : cont_diff_at 𝕜 n (prod.map f g) (x, y) := begin rw cont_diff_at at *, convert hf.prod_map hg, simp only [univ_prod_univ] end /-- The product map of two `C^n` functions within a set at a point is `C^n` within the product set at the product point. -/ lemma cont_diff_at.prod_map' {f : E → F} {g : E' → F'} {p : E × E'} (hf : cont_diff_at 𝕜 n f p.1) (hg : cont_diff_at 𝕜 n g p.2) : cont_diff_at 𝕜 n (prod.map f g) p := begin rcases p, exact cont_diff_at.prod_map hf hg end /-- The product map of two `C^n` functions is `C^n`. -/ lemma cont_diff.prod_map {f : E → F} {g : E' → F'} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) : cont_diff 𝕜 n (prod.map f g) := begin rw cont_diff_iff_cont_diff_at at *, exact λ ⟨x, y⟩, (hf x).prod_map (hg y) end lemma cont_diff_prod_mk_left (f₀ : F) : cont_diff 𝕜 n (λ e : E, (e, f₀)) := cont_diff_id.prod cont_diff_const lemma cont_diff_prod_mk_right (e₀ : E) : cont_diff 𝕜 n (λ f : F, (e₀, f)) := cont_diff_const.prod cont_diff_id end prod_map /-! ### Inversion in a complete normed algebra -/ section algebra_inverse variables (𝕜) {R : Type*} [normed_ring R] [normed_algebra 𝕜 R] open normed_ring continuous_linear_map ring /-- In a complete normed algebra, the operation of inversion is `C^n`, for all `n`, at each invertible element. The proof is by induction, bootstrapping using an identity expressing the derivative of inversion as a bilinear map of inversion itself. -/ lemma cont_diff_at_ring_inverse [complete_space R] (x : Rˣ) : cont_diff_at 𝕜 n ring.inverse (x : R) := begin induction n using with_top.nat_induction with n IH Itop, { intros m hm, refine ⟨{y : R | is_unit y}, _, _⟩, { simp [nhds_within_univ], exact x.nhds }, { use (ftaylor_series_within 𝕜 inverse univ), rw [le_antisymm hm bot_le, has_ftaylor_series_up_to_on_zero_iff], split, { rintros _ ⟨x', rfl⟩, exact (inverse_continuous_at x').continuous_within_at }, { simp [ftaylor_series_within] } } }, { apply cont_diff_at_succ_iff_has_fderiv_at.mpr, refine ⟨λ (x : R), - lmul_left_right 𝕜 R (inverse x) (inverse x), _, _⟩, { refine ⟨{y : R | is_unit y}, x.nhds, _⟩, rintros _ ⟨y, rfl⟩, rw [inverse_unit], exact has_fderiv_at_ring_inverse y }, { convert (lmul_left_right_is_bounded_bilinear 𝕜 R).cont_diff.neg.comp_cont_diff_at (x : R) (IH.prod IH) } }, { exact cont_diff_at_top.mpr Itop } end variables (𝕜) {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [complete_space 𝕜'] lemma cont_diff_at_inv {x : 𝕜'} (hx : x ≠ 0) {n} : cont_diff_at 𝕜 n has_inv.inv x := by simpa only [ring.inverse_eq_inv'] using cont_diff_at_ring_inverse 𝕜 (units.mk0 x hx) lemma cont_diff_on_inv {n} : cont_diff_on 𝕜 n (has_inv.inv : 𝕜' → 𝕜') {0}ᶜ := λ x hx, (cont_diff_at_inv 𝕜 hx).cont_diff_within_at variable {𝕜} -- TODO: the next few lemmas don't need `𝕜` or `𝕜'` to be complete -- A good way to show this is to generalize `cont_diff_at_ring_inverse` to the setting -- of a function `f` such that `∀ᶠ x in 𝓝 a, x * f x = 1`. lemma cont_diff_within_at.inv {f : E → 𝕜'} {n} (hf : cont_diff_within_at 𝕜 n f s x) (hx : f x ≠ 0) : cont_diff_within_at 𝕜 n (λ x, (f x)⁻¹) s x := (cont_diff_at_inv 𝕜 hx).comp_cont_diff_within_at x hf lemma cont_diff_on.inv {f : E → 𝕜'} {n} (hf : cont_diff_on 𝕜 n f s) (h : ∀ x ∈ s, f x ≠ 0) : cont_diff_on 𝕜 n (λ x, (f x)⁻¹) s := λ x hx, (hf.cont_diff_within_at hx).inv (h x hx) lemma cont_diff_at.inv {f : E → 𝕜'} {n} (hf : cont_diff_at 𝕜 n f x) (hx : f x ≠ 0) : cont_diff_at 𝕜 n (λ x, (f x)⁻¹) x := hf.inv hx lemma cont_diff.inv {f : E → 𝕜'} {n} (hf : cont_diff 𝕜 n f) (h : ∀ x, f x ≠ 0) : cont_diff 𝕜 n (λ x, (f x)⁻¹) := by { rw cont_diff_iff_cont_diff_at, exact λ x, hf.cont_diff_at.inv (h x) } -- TODO: generalize to `f g : E → 𝕜'` lemma cont_diff_within_at.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : cont_diff_within_at 𝕜 n f s x) (hg : cont_diff_within_at 𝕜 n g s x) (hx : g x ≠ 0) : cont_diff_within_at 𝕜 n (λ x, f x / g x) s x := by simpa only [div_eq_mul_inv] using hf.mul (hg.inv hx) lemma cont_diff_on.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : cont_diff_on 𝕜 n f s) (hg : cont_diff_on 𝕜 n g s) (h₀ : ∀ x ∈ s, g x ≠ 0) : cont_diff_on 𝕜 n (f / g) s := λ x hx, (hf x hx).div (hg x hx) (h₀ x hx) lemma cont_diff_at.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : cont_diff_at 𝕜 n f x) (hg : cont_diff_at 𝕜 n g x) (hx : g x ≠ 0) : cont_diff_at 𝕜 n (λ x, f x / g x) x := hf.div hg hx lemma cont_diff.div [complete_space 𝕜] {f g : E → 𝕜} {n} (hf : cont_diff 𝕜 n f) (hg : cont_diff 𝕜 n g) (h0 : ∀ x, g x ≠ 0) : cont_diff 𝕜 n (λ x, f x / g x) := begin simp only [cont_diff_iff_cont_diff_at] at *, exact λ x, (hf x).div (hg x) (h0 x) end end algebra_inverse /-! ### Inversion of continuous linear maps between Banach spaces -/ section map_inverse open continuous_linear_map /-- At a continuous linear equivalence `e : E ≃L[𝕜] F` between Banach spaces, the operation of inversion is `C^n`, for all `n`. -/ lemma cont_diff_at_map_inverse [complete_space E] (e : E ≃L[𝕜] F) : cont_diff_at 𝕜 n inverse (e : E →L[𝕜] F) := begin nontriviality E, -- first, we use the lemma `to_ring_inverse` to rewrite in terms of `ring.inverse` in the ring -- `E →L[𝕜] E` let O₁ : (E →L[𝕜] E) → (F →L[𝕜] E) := λ f, f.comp (e.symm : (F →L[𝕜] E)), let O₂ : (E →L[𝕜] F) → (E →L[𝕜] E) := λ f, (e.symm : (F →L[𝕜] E)).comp f, have : continuous_linear_map.inverse = O₁ ∘ ring.inverse ∘ O₂ := funext (to_ring_inverse e), rw this, -- `O₁` and `O₂` are `cont_diff`, -- so we reduce to proving that `ring.inverse` is `cont_diff` have h₁ : cont_diff 𝕜 n O₁, from is_bounded_bilinear_map_comp.cont_diff.comp (cont_diff_const.prod cont_diff_id), have h₂ : cont_diff 𝕜 n O₂, from is_bounded_bilinear_map_comp.cont_diff.comp (cont_diff_id.prod cont_diff_const), refine h₁.cont_diff_at.comp _ (cont_diff_at.comp _ _ h₂.cont_diff_at), convert cont_diff_at_ring_inverse 𝕜 (1 : (E →L[𝕜] E)ˣ), simp [O₂, one_def] end end map_inverse section function_inverse open continuous_linear_map /-- If `f` is a local homeomorphism and the point `a` is in its target, and if `f` is `n` times continuously differentiable at `f.symm a`, and if the derivative at `f.symm a` is a continuous linear equivalence, then `f.symm` is `n` times continuously differentiable at the point `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem local_homeomorph.cont_diff_at_symm [complete_space E] (f : local_homeomorph E F) {f₀' : E ≃L[𝕜] F} {a : F} (ha : a ∈ f.target) (hf₀' : has_fderiv_at f (f₀' : E →L[𝕜] F) (f.symm a)) (hf : cont_diff_at 𝕜 n f (f.symm a)) : cont_diff_at 𝕜 n f.symm a := begin -- We prove this by induction on `n` induction n using with_top.nat_induction with n IH Itop, { rw cont_diff_at_zero, exact ⟨f.target, is_open.mem_nhds f.open_target ha, f.continuous_inv_fun⟩ }, { obtain ⟨f', ⟨u, hu, hff'⟩, hf'⟩ := cont_diff_at_succ_iff_has_fderiv_at.mp hf, apply cont_diff_at_succ_iff_has_fderiv_at.mpr, -- For showing `n.succ` times continuous differentiability (the main inductive step), it -- suffices to produce the derivative and show that it is `n` times continuously differentiable have eq_f₀' : f' (f.symm a) = f₀', { exact (hff' (f.symm a) (mem_of_mem_nhds hu)).unique hf₀' }, -- This follows by a bootstrapping formula expressing the derivative as a function of `f` itself refine ⟨inverse ∘ f' ∘ f.symm, _, _⟩, { -- We first check that the derivative of `f` is that formula have h_nhds : {y : E | ∃ (e : E ≃L[𝕜] F), ↑e = f' y} ∈ 𝓝 ((f.symm) a), { have hf₀' := f₀'.nhds, rw ← eq_f₀' at hf₀', exact hf'.continuous_at.preimage_mem_nhds hf₀' }, obtain ⟨t, htu, ht, htf⟩ := mem_nhds_iff.mp (filter.inter_mem hu h_nhds), use f.target ∩ (f.symm) ⁻¹' t, refine ⟨is_open.mem_nhds _ _, _⟩, { exact f.preimage_open_of_open_symm ht }, { exact mem_inter ha (mem_preimage.mpr htf) }, intros x hx, obtain ⟨hxu, e, he⟩ := htu hx.2, have h_deriv : has_fderiv_at f ↑e ((f.symm) x), { rw he, exact hff' (f.symm x) hxu }, convert f.has_fderiv_at_symm hx.1 h_deriv, simp [← he] }, { -- Then we check that the formula, being a composition of `cont_diff` pieces, is -- itself `cont_diff` have h_deriv₁ : cont_diff_at 𝕜 n inverse (f' (f.symm a)), { rw eq_f₀', exact cont_diff_at_map_inverse _ }, have h_deriv₂ : cont_diff_at 𝕜 n f.symm a, { refine IH (hf.of_le _), norm_cast, exact nat.le_succ n }, exact (h_deriv₁.comp _ hf').comp _ h_deriv₂ } }, { refine cont_diff_at_top.mpr _, intros n, exact Itop n (cont_diff_at_top.mp hf n) } end /-- Let `f` be a local homeomorphism of a nondiscrete normed field, let `a` be a point in its target. if `f` is `n` times continuously differentiable at `f.symm a`, and if the derivative at `f.symm a` is nonzero, then `f.symm` is `n` times continuously differentiable at the point `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem local_homeomorph.cont_diff_at_symm_deriv [complete_space 𝕜] (f : local_homeomorph 𝕜 𝕜) {f₀' a : 𝕜} (h₀ : f₀' ≠ 0) (ha : a ∈ f.target) (hf₀' : has_deriv_at f f₀' (f.symm a)) (hf : cont_diff_at 𝕜 n f (f.symm a)) : cont_diff_at 𝕜 n f.symm a := f.cont_diff_at_symm ha (hf₀'.has_fderiv_at_equiv h₀) hf end function_inverse /-! ### Finite dimensional results -/ section finite_dimensional open function finite_dimensional variables [complete_space 𝕜] /-- A family of continuous linear maps is `C^n` on `s` if all its applications are. -/ lemma cont_diff_on_clm_apply {n : with_top ℕ} {f : E → F →L[𝕜] G} {s : set E} [finite_dimensional 𝕜 F] : cont_diff_on 𝕜 n f s ↔ ∀ y, cont_diff_on 𝕜 n (λ x, f x y) s := begin refine ⟨λ h y, (continuous_linear_map.apply 𝕜 G y).cont_diff.comp_cont_diff_on h, λ h, _⟩, let d := finrank 𝕜 F, have hd : d = finrank 𝕜 (fin d → 𝕜) := (finrank_fin_fun 𝕜).symm, let e₁ := continuous_linear_equiv.of_finrank_eq hd, let e₂ := (e₁.arrow_congr (1 : G ≃L[𝕜] G)).trans (continuous_linear_equiv.pi_ring (fin d)), rw [← comp.left_id f, ← e₂.symm_comp_self], exact e₂.symm.cont_diff.comp_cont_diff_on (cont_diff_on_pi.mpr (λ i, h _)) end lemma cont_diff_clm_apply {n : with_top ℕ} {f : E → F →L[𝕜] G} [finite_dimensional 𝕜 F] : cont_diff 𝕜 n f ↔ ∀ y, cont_diff 𝕜 n (λ x, f x y) := by simp_rw [← cont_diff_on_univ, cont_diff_on_clm_apply] /-- This is a useful lemma to prove that a certain operation preserves functions being `C^n`. When you do induction on `n`, this gives a useful characterization of a function being `C^(n+1)`, assuming you have already computed the derivative. The advantage of this version over `cont_diff_succ_iff_fderiv` is that both occurences of `cont_diff` are for functions with the same domain and codomain (`E` and `F`). This is not the case for `cont_diff_succ_iff_fderiv`, which often requires an inconvenient need to generalize `F`, which results in universe issues (see the discussion in the section of `cont_diff.comp`). This lemma avoids these universe issues, but only applies for finite dimensional `E`. -/ lemma cont_diff_succ_iff_fderiv_apply [finite_dimensional 𝕜 E] {n : ℕ} {f : E → F} : cont_diff 𝕜 ((n + 1) : ℕ) f ↔ differentiable 𝕜 f ∧ ∀ y, cont_diff 𝕜 n (λ x, fderiv 𝕜 f x y) := by rw [cont_diff_succ_iff_fderiv, cont_diff_clm_apply] lemma cont_diff_on_succ_of_fderiv_apply [finite_dimensional 𝕜 E] {n : ℕ} {f : E → F} {s : set E} (hf : differentiable_on 𝕜 f s) (h : ∀ y, cont_diff_on 𝕜 n (λ x, fderiv_within 𝕜 f s x y) s) : cont_diff_on 𝕜 ((n + 1) : ℕ) f s := cont_diff_on_succ_of_fderiv_within hf $ cont_diff_on_clm_apply.mpr h lemma cont_diff_on_succ_iff_fderiv_apply [finite_dimensional 𝕜 E] {n : ℕ} {f : E → F} {s : set E} (hs : unique_diff_on 𝕜 s) : cont_diff_on 𝕜 ((n + 1) : ℕ) f s ↔ differentiable_on 𝕜 f s ∧ ∀ y, cont_diff_on 𝕜 n (λ x, fderiv_within 𝕜 f s x y) s := by rw [cont_diff_on_succ_iff_fderiv_within hs, cont_diff_on_clm_apply] end finite_dimensional section real /-! ### Results over `ℝ` or `ℂ` The results in this section rely on the Mean Value Theorem, and therefore hold only over `ℝ` (and its extension fields such as `ℂ`). -/ variables {𝕂 : Type*} [is_R_or_C 𝕂] {E' : Type*} [normed_group E'] [normed_space 𝕂 E'] {F' : Type*} [normed_group F'] [normed_space 𝕂 F'] /-- If a function has a Taylor series at order at least 1, then at points in the interior of the domain of definition, the term of order 1 of this series is a strict derivative of `f`. -/ lemma has_ftaylor_series_up_to_on.has_strict_fderiv_at {s : set E'} {f : E' → F'} {x : E'} {p : E' → formal_multilinear_series 𝕂 E' F'} (hf : has_ftaylor_series_up_to_on n f p s) (hn : 1 ≤ n) (hs : s ∈ 𝓝 x) : has_strict_fderiv_at f ((continuous_multilinear_curry_fin1 𝕂 E' F') (p x 1)) x := has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hf.eventually_has_fderiv_at hn hs) $ (continuous_multilinear_curry_fin1 𝕂 E' F').continuous_at.comp $ (hf.cont 1 hn).continuous_at hs /-- If a function is `C^n` with `1 ≤ n` around a point, and its derivative at that point is given to us as `f'`, then `f'` is also a strict derivative. -/ lemma cont_diff_at.has_strict_fderiv_at' {f : E' → F'} {f' : E' →L[𝕂] F'} {x : E'} (hf : cont_diff_at 𝕂 n f x) (hf' : has_fderiv_at f f' x) (hn : 1 ≤ n) : has_strict_fderiv_at f f' x := begin rcases hf 1 hn with ⟨u, H, p, hp⟩, simp only [nhds_within_univ, mem_univ, insert_eq_of_mem] at H, have := hp.has_strict_fderiv_at le_rfl H, rwa hf'.unique this.has_fderiv_at end /-- If a function is `C^n` with `1 ≤ n` around a point, and its derivative at that point is given to us as `f'`, then `f'` is also a strict derivative. -/ lemma cont_diff_at.has_strict_deriv_at' {f : 𝕂 → F'} {f' : F'} {x : 𝕂} (hf : cont_diff_at 𝕂 n f x) (hf' : has_deriv_at f f' x) (hn : 1 ≤ n) : has_strict_deriv_at f f' x := hf.has_strict_fderiv_at' hf' hn /-- If a function is `C^n` with `1 ≤ n` around a point, then the derivative of `f` at this point is also a strict derivative. -/ lemma cont_diff_at.has_strict_fderiv_at {f : E' → F'} {x : E'} (hf : cont_diff_at 𝕂 n f x) (hn : 1 ≤ n) : has_strict_fderiv_at f (fderiv 𝕂 f x) x := hf.has_strict_fderiv_at' (hf.differentiable_at hn).has_fderiv_at hn /-- If a function is `C^n` with `1 ≤ n` around a point, then the derivative of `f` at this point is also a strict derivative. -/ lemma cont_diff_at.has_strict_deriv_at {f : 𝕂 → F'} {x : 𝕂} (hf : cont_diff_at 𝕂 n f x) (hn : 1 ≤ n) : has_strict_deriv_at f (deriv f x) x := (hf.has_strict_fderiv_at hn).has_strict_deriv_at /-- If a function is `C^n` with `1 ≤ n`, then the derivative of `f` is also a strict derivative. -/ lemma cont_diff.has_strict_fderiv_at {f : E' → F'} {x : E'} (hf : cont_diff 𝕂 n f) (hn : 1 ≤ n) : has_strict_fderiv_at f (fderiv 𝕂 f x) x := hf.cont_diff_at.has_strict_fderiv_at hn /-- If a function is `C^n` with `1 ≤ n`, then the derivative of `f` is also a strict derivative. -/ lemma cont_diff.has_strict_deriv_at {f : 𝕂 → F'} {x : 𝕂} (hf : cont_diff 𝕂 n f) (hn : 1 ≤ n) : has_strict_deriv_at f (deriv f x) x := hf.cont_diff_at.has_strict_deriv_at hn /-- If `f` has a formal Taylor series `p` up to order `1` on `{x} ∪ s`, where `s` is a convex set, and `∥p x 1∥₊ < K`, then `f` is `K`-Lipschitz in a neighborhood of `x` within `s`. -/ lemma has_ftaylor_series_up_to_on.exists_lipschitz_on_with_of_nnnorm_lt {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {f : E → F} {p : E → formal_multilinear_series ℝ E F} {s : set E} {x : E} (hf : has_ftaylor_series_up_to_on 1 f p (insert x s)) (hs : convex ℝ s) (K : ℝ≥0) (hK : ∥p x 1∥₊ < K) : ∃ t ∈ 𝓝[s] x, lipschitz_on_with K f t := begin set f' := λ y, continuous_multilinear_curry_fin1 ℝ E F (p y 1), have hder : ∀ y ∈ s, has_fderiv_within_at f (f' y) s y, from λ y hy, (hf.has_fderiv_within_at le_rfl (subset_insert x s hy)).mono (subset_insert x s), have hcont : continuous_within_at f' s x, from (continuous_multilinear_curry_fin1 ℝ E F).continuous_at.comp_continuous_within_at ((hf.cont _ le_rfl _ (mem_insert _ _)).mono (subset_insert x s)), replace hK : ∥f' x∥₊ < K, by simpa only [linear_isometry_equiv.nnnorm_map], exact hs.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt (eventually_nhds_within_iff.2 $ eventually_of_forall hder) hcont K hK end /-- If `f` has a formal Taylor series `p` up to order `1` on `{x} ∪ s`, where `s` is a convex set, then `f` is Lipschitz in a neighborhood of `x` within `s`. -/ lemma has_ftaylor_series_up_to_on.exists_lipschitz_on_with {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {f : E → F} {p : E → formal_multilinear_series ℝ E F} {s : set E} {x : E} (hf : has_ftaylor_series_up_to_on 1 f p (insert x s)) (hs : convex ℝ s) : ∃ K (t ∈ 𝓝[s] x), lipschitz_on_with K f t := (exists_gt _).imp $ hf.exists_lipschitz_on_with_of_nnnorm_lt hs /-- If `f` is `C^1` within a conves set `s` at `x`, then it is Lipschitz on a neighborhood of `x` within `s`. -/ lemma cont_diff_within_at.exists_lipschitz_on_with {E F : Type*} [normed_group E] [normed_space ℝ E] [normed_group F] [normed_space ℝ F] {f : E → F} {s : set E} {x : E} (hf : cont_diff_within_at ℝ 1 f s x) (hs : convex ℝ s) : ∃ (K : ℝ≥0) (t ∈ 𝓝[s] x), lipschitz_on_with K f t := begin rcases hf 1 le_rfl with ⟨t, hst, p, hp⟩, rcases metric.mem_nhds_within_iff.mp hst with ⟨ε, ε0, hε⟩, replace hp : has_ftaylor_series_up_to_on 1 f p (metric.ball x ε ∩ insert x s) := hp.mono hε, clear hst hε t, rw [← insert_eq_of_mem (metric.mem_ball_self ε0), ← insert_inter_distrib] at hp, rcases hp.exists_lipschitz_on_with ((convex_ball _ _).inter hs) with ⟨K, t, hst, hft⟩, rw [inter_comm, ← nhds_within_restrict' _ (metric.ball_mem_nhds _ ε0)] at hst, exact ⟨K, t, hst, hft⟩ end /-- If `f` is `C^1` at `x` and `K > ∥fderiv 𝕂 f x∥`, then `f` is `K`-Lipschitz in a neighborhood of `x`. -/ lemma cont_diff_at.exists_lipschitz_on_with_of_nnnorm_lt {f : E' → F'} {x : E'} (hf : cont_diff_at 𝕂 1 f x) (K : ℝ≥0) (hK : ∥fderiv 𝕂 f x∥₊ < K) : ∃ t ∈ 𝓝 x, lipschitz_on_with K f t := (hf.has_strict_fderiv_at le_rfl).exists_lipschitz_on_with_of_nnnorm_lt K hK /-- If `f` is `C^1` at `x`, then `f` is Lipschitz in a neighborhood of `x`. -/ lemma cont_diff_at.exists_lipschitz_on_with {f : E' → F'} {x : E'} (hf : cont_diff_at 𝕂 1 f x) : ∃ K (t ∈ 𝓝 x), lipschitz_on_with K f t := (hf.has_strict_fderiv_at le_rfl).exists_lipschitz_on_with end real section deriv /-! ### One dimension All results up to now have been expressed in terms of the general Fréchet derivative `fderiv`. For maps defined on the field, the one-dimensional derivative `deriv` is often easier to use. In this paragraph, we reformulate some higher smoothness results in terms of `deriv`. -/ variables {f₂ : 𝕜 → F} {s₂ : set 𝕜} open continuous_linear_map (smul_right) /-- A function is `C^(n + 1)` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (formulated with `deriv_within`) is `C^n`. -/ theorem cont_diff_on_succ_iff_deriv_within {n : ℕ} (hs : unique_diff_on 𝕜 s₂) : cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ cont_diff_on 𝕜 n (deriv_within f₂ s₂) s₂ := begin rw cont_diff_on_succ_iff_fderiv_within hs, congr' 2, apply le_antisymm, { assume h, have : deriv_within f₂ s₂ = (λ u : 𝕜 →L[𝕜] F, u 1) ∘ (fderiv_within 𝕜 f₂ s₂), by { ext x, refl }, simp only [this], apply cont_diff.comp_cont_diff_on _ h, exact (is_bounded_bilinear_map_apply.is_bounded_linear_map_left _).cont_diff }, { assume h, have : fderiv_within 𝕜 f₂ s₂ = smul_right (1 : 𝕜 →L[𝕜] 𝕜) ∘ deriv_within f₂ s₂, by { ext x, simp [deriv_within] }, simp only [this], apply cont_diff.comp_cont_diff_on _ h, have : is_bounded_bilinear_map 𝕜 (λ _ : (𝕜 →L[𝕜] 𝕜) × F, _) := is_bounded_bilinear_map_smul_right, exact (this.is_bounded_linear_map_right _).cont_diff } end /-- A function is `C^(n + 1)` on an open domain if and only if it is differentiable there, and its derivative (formulated with `deriv`) is `C^n`. -/ theorem cont_diff_on_succ_iff_deriv_of_open {n : ℕ} (hs : is_open s₂) : cont_diff_on 𝕜 ((n + 1) : ℕ) f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ cont_diff_on 𝕜 n (deriv f₂) s₂ := begin rw cont_diff_on_succ_iff_deriv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply cont_diff_on_congr, assume x hx, exact deriv_within_of_open hs hx end /-- A function is `C^∞` on a domain with unique derivatives if and only if it is differentiable there, and its derivative (formulated with `deriv_within`) is `C^∞`. -/ theorem cont_diff_on_top_iff_deriv_within (hs : unique_diff_on 𝕜 s₂) : cont_diff_on 𝕜 ∞ f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ cont_diff_on 𝕜 ∞ (deriv_within f₂ s₂) s₂ := begin split, { assume h, refine ⟨h.differentiable_on le_top, _⟩, apply cont_diff_on_top.2 (λ n, ((cont_diff_on_succ_iff_deriv_within hs).1 _).2), exact h.of_le le_top }, { assume h, refine cont_diff_on_top.2 (λ n, _), have A : (n : with_top ℕ) ≤ ∞ := le_top, apply ((cont_diff_on_succ_iff_deriv_within hs).2 ⟨h.1, h.2.of_le A⟩).of_le, exact with_top.coe_le_coe.2 (nat.le_succ n) } end /-- A function is `C^∞` on an open domain if and only if it is differentiable there, and its derivative (formulated with `deriv`) is `C^∞`. -/ theorem cont_diff_on_top_iff_deriv_of_open (hs : is_open s₂) : cont_diff_on 𝕜 ∞ f₂ s₂ ↔ differentiable_on 𝕜 f₂ s₂ ∧ cont_diff_on 𝕜 ∞ (deriv f₂) s₂ := begin rw cont_diff_on_top_iff_deriv_within hs.unique_diff_on, congr' 2, rw ← iff_iff_eq, apply cont_diff_on_congr, assume x hx, exact deriv_within_of_open hs hx end lemma cont_diff_on.deriv_within (hf : cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hmn : m + 1 ≤ n) : cont_diff_on 𝕜 m (deriv_within f₂ s₂) s₂ := begin cases m, { change ∞ + 1 ≤ n at hmn, have : n = ∞, by simpa using hmn, rw this at hf, exact ((cont_diff_on_top_iff_deriv_within hs).1 hf).2 }, { change (m.succ : with_top ℕ) ≤ n at hmn, exact ((cont_diff_on_succ_iff_deriv_within hs).1 (hf.of_le hmn)).2 } end lemma cont_diff_on.deriv_of_open (hf : cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hmn : m + 1 ≤ n) : cont_diff_on 𝕜 m (deriv f₂) s₂ := (hf.deriv_within hs.unique_diff_on hmn).congr (λ x hx, (deriv_within_of_open hs hx).symm) lemma cont_diff_on.continuous_on_deriv_within (h : cont_diff_on 𝕜 n f₂ s₂) (hs : unique_diff_on 𝕜 s₂) (hn : 1 ≤ n) : continuous_on (deriv_within f₂ s₂) s₂ := ((cont_diff_on_succ_iff_deriv_within hs).1 (h.of_le hn)).2.continuous_on lemma cont_diff_on.continuous_on_deriv_of_open (h : cont_diff_on 𝕜 n f₂ s₂) (hs : is_open s₂) (hn : 1 ≤ n) : continuous_on (deriv f₂) s₂ := ((cont_diff_on_succ_iff_deriv_of_open hs).1 (h.of_le hn)).2.continuous_on /-- A function is `C^(n + 1)` if and only if it is differentiable, and its derivative (formulated in terms of `deriv`) is `C^n`. -/ theorem cont_diff_succ_iff_deriv {n : ℕ} : cont_diff 𝕜 ((n + 1) : ℕ) f₂ ↔ differentiable 𝕜 f₂ ∧ cont_diff 𝕜 n (deriv f₂) := by simp only [← cont_diff_on_univ, cont_diff_on_succ_iff_deriv_of_open, is_open_univ, differentiable_on_univ] theorem cont_diff_one_iff_deriv : cont_diff 𝕜 1 f₂ ↔ differentiable 𝕜 f₂ ∧ continuous (deriv f₂) := cont_diff_succ_iff_deriv.trans $ iff.rfl.and cont_diff_zero /-- A function is `C^∞` if and only if it is differentiable, and its derivative (formulated in terms of `deriv`) is `C^∞`. -/ theorem cont_diff_top_iff_deriv : cont_diff 𝕜 ∞ f₂ ↔ differentiable 𝕜 f₂ ∧ cont_diff 𝕜 ∞ (deriv f₂) := begin simp [cont_diff_on_univ.symm, differentiable_on_univ.symm, deriv_within_univ.symm, - deriv_within_univ], rw cont_diff_on_top_iff_deriv_within unique_diff_on_univ, end lemma cont_diff.continuous_deriv (h : cont_diff 𝕜 n f₂) (hn : 1 ≤ n) : continuous (deriv f₂) := (cont_diff_succ_iff_deriv.mp (h.of_le hn)).2.continuous end deriv section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is `n` times continuously differentiable over `ℂ`, then it is `n` times continuously 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 𝕜'] [normed_algebra 𝕜 𝕜'] variables [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] variables [normed_space 𝕜' F] [is_scalar_tower 𝕜 𝕜' F] variables {p' : E → formal_multilinear_series 𝕜' E F} lemma has_ftaylor_series_up_to_on.restrict_scalars (h : has_ftaylor_series_up_to_on n f p' s) : has_ftaylor_series_up_to_on n f (λ x, (p' x).restrict_scalars 𝕜) s := { zero_eq := λ x hx, h.zero_eq x hx, fderiv_within := begin intros m hm x hx, convert ((continuous_multilinear_map.restrict_scalars_linear 𝕜).has_fderiv_at) .comp_has_fderiv_within_at _ ((h.fderiv_within m hm x hx).restrict_scalars 𝕜), end, cont := λ m hm, continuous_multilinear_map.continuous_restrict_scalars.comp_continuous_on (h.cont m hm) } lemma cont_diff_within_at.restrict_scalars (h : cont_diff_within_at 𝕜' n f s x) : cont_diff_within_at 𝕜 n f s x := begin intros m hm, rcases h m hm with ⟨u, u_mem, p', hp'⟩, exact ⟨u, u_mem, _, hp'.restrict_scalars _⟩ end lemma cont_diff_on.restrict_scalars (h : cont_diff_on 𝕜' n f s) : cont_diff_on 𝕜 n f s := λ x hx, (h x hx).restrict_scalars _ lemma cont_diff_at.restrict_scalars (h : cont_diff_at 𝕜' n f x) : cont_diff_at 𝕜 n f x := cont_diff_within_at_univ.1 $ h.cont_diff_within_at.restrict_scalars _ lemma cont_diff.restrict_scalars (h : cont_diff 𝕜' n f) : cont_diff 𝕜 n f := cont_diff_iff_cont_diff_at.2 $ λ x, h.cont_diff_at.restrict_scalars _ end restrict_scalars
c47ce3c3f28e2ac755e7fd65c6cb89a7e5c1e7ba
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/library/logic/axioms/prop_complete.lean
cce9392c9ba43b78f36601fb688e55fd5d419df9
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,246
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: logic.axioms.classical Author: Leonardo de Moura -/ import logic.connectives logic.quantifiers logic.cast algebra.relation open eq.ops axiom prop_complete (a : Prop) : a = true ∨ a = false definition eq_true_or_eq_false := prop_complete theorem cases_true_false (P : Prop → Prop) (H1 : P true) (H2 : P false) (a : Prop) : P a := or.elim (prop_complete a) (assume Ht : a = true, Ht⁻¹ ▸ H1) (assume Hf : a = false, Hf⁻¹ ▸ H2) theorem cases_on (a : Prop) {P : Prop → Prop} (H1 : P true) (H2 : P false) : P a := cases_true_false P H1 H2 a -- this supercedes the em in decidable theorem em (a : Prop) : a ∨ ¬a := or.elim (prop_complete a) (assume Ht : a = true, or.inl (of_eq_true Ht)) (assume Hf : a = false, or.inr (not_of_eq_false Hf)) -- this supercedes by_cases in decidable definition by_cases {p q : Prop} (Hpq : p → q) (Hnpq : ¬p → q) : q := or.elim (em p) (assume Hp, Hpq Hp) (assume Hnp, Hnpq Hnp) -- this supercedes by_contradiction in decidable theorem by_contradiction {p : Prop} (H : ¬p → false) : p := by_cases (assume H1 : p, H1) (assume H1 : ¬p, false.rec _ (H H1)) theorem eq_false_or_eq_true (a : Prop) : a = false ∨ a = true := cases_true_false (λ x, x = false ∨ x = true) (or.inr rfl) (or.inl rfl) a theorem propext {a b : Prop} (Hab : a → b) (Hba : b → a) : a = b := or.elim (prop_complete a) (assume Hat, or.elim (prop_complete b) (assume Hbt, Hat ⬝ Hbt⁻¹) (assume Hbf, false.elim (Hbf ▸ (Hab (of_eq_true Hat))))) (assume Haf, or.elim (prop_complete b) (assume Hbt, false.elim (Haf ▸ (Hba (of_eq_true Hbt)))) (assume Hbf, Haf ⬝ Hbf⁻¹)) theorem eq.of_iff {a b : Prop} (H : a ↔ b) : a = b := iff.elim (assume H1 H2, propext H1 H2) H theorem iff_eq_eq {a b : Prop} : (a ↔ b) = (a = b) := propext (assume H, eq.of_iff H) (assume H, iff.of_eq H) open relation theorem iff_congruence [instance] (P : Prop → Prop) : is_congruence iff iff P := is_congruence.mk (take (a b : Prop), assume H : a ↔ b, show P a ↔ P b, from iff.of_eq (eq.of_iff H ▸ eq.refl (P a)))
a6a452dd080240d69cfb04d680433cb300b24688
e8d53a7b78545d183a23dd7bd921bc7ff312989f
/imp_prop_trunc.hlean
e242e43ce1261f9ab5b28a731bfe6828af51c141
[]
no_license
Sumit0730/Impredicative
857007626592440a27cf4440aa9a226d0ede7f3e
a75cb9989a684133d31d4889a746ee4fa7b66cea
refs/heads/master
1,631,994,804,745
1,531,980,761,000
1,531,980,761,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,951
hlean
/- Copyright (c) 2015 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Floris van Doorn Proof of the theorem that (is_trunc n A) is a mere proposition We prove this here to avoid circular dependency of files We want to use this in .equiv; .equiv is imported by .function and .function is imported by .trunc -/ import types.pi open equiv sigma sigma.ops eq function pi namespace is_trunc definition is_contr.sigma_char (A : Type) : (Σ (center : A), Π (a : A), center = a) ≃ (is_contr A) := begin fapply equiv.MK, { intro S, exact (is_contr.mk S.1 S.2)}, { intro H, cases H with H', cases H' with ce co, exact ⟨ce, co⟩}, { intro H, cases H with H', cases H' with ce co, exact idp}, { intro S, cases S, apply idp} end definition is_trunc.pi_char (n : trunc_index) (A : Type) : (Π (x y : A), is_trunc n (x = y)) ≃ (is_trunc (n .+1) A) := begin fapply equiv.MK, { intro H, apply is_trunc_succ_intro}, { intro H x y, apply is_trunc_eq}, { intro H, cases H, apply idp}, { intro P, apply eq_of_homotopy, intro a, apply eq_of_homotopy, intro b, change is_trunc.mk (to_internal n (a = b)) = P a b, induction (P a b), apply idp}, end definition is_prop_is_trunc (n : trunc_index) : Π (A : Type), is_prop (is_trunc n A) := begin induction n, { intro A, apply is_trunc_is_equiv_closed, { apply equiv.to_is_equiv, apply is_contr.sigma_char}, apply is_prop.mk, intros, fapply sigma_eq, apply x.2, apply is_prop.elimo}, { intro A, apply is_trunc_is_equiv_closed, apply equiv.to_is_equiv, apply is_trunc.pi_char}, end local attribute is_prop_is_trunc [instance] definition is_trunc_succ_is_trunc [instance] (n m : ℕ₋₂) (A : Type) : is_trunc (n.+1) (is_trunc m A) := !is_trunc_succ_of_is_prop end is_trunc
7f363cbc0ef537d34e246f160a730e0884592f57
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/run/tactic3.lean
6ecc69c0354bf42b16c837fb101d6cf429c5c1c8
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
193
lean
import logic open tactic theorem tst {A B : Prop} (H1 : A) (H2 : B) : A := by [trace "first"; state; now | trace "second"; state; fail | trace "third"; assumption] check tst
3ad4d9f807f38d32fc84ab79e9bb9e1844c9ea2f
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/tests/lean/run/cc1.lean
2df4edfd8718cbdfd84bd974ce5e23a859817cf3
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
2,142
lean
open tactic set_option pp.implicit true example (a b c d : nat) (f : nat → nat → nat) : a = b → b = c → d + (if b > 0 then a else b) = 0 → f (b + b) b ≠ f (a + c) c → false := by do intros, s ← cc_state.mk_using_hs, trace s, t₁ ← to_expr `(f (b + b) b), t₂ ← to_expr `(f (a + c) c), b ← to_expr `(b), d ← to_expr `(d), guard (s^.inconsistent), guard (s^.eqc_size b = 4), guard (not (s^.in_singlenton_eqc b)), guard (s^.in_singlenton_eqc d), trace ">>> Equivalence roots", trace s^.roots, trace ">>> b's equivalence class", trace (s^.eqc_of b), pr ← s^.eqv_proof t₁ t₂, note `h pr, contradiction example (a b : nat) (f : nat → nat) : a = b → f a = f b := by cc example (a b : nat) (f : nat → nat) : a = b → f a ≠ f b → false := by cc example (a b : nat) (f : nat → nat) : a = b → f (f a) ≠ f (f b) → false := by cc example (a b c : nat) (f : nat → nat) : a = b → c = b → f (f a) ≠ f (f c) → false := by cc example (a b c : nat) (f : nat → nat → nat) : a = b → c = b → f (f a b) a ≠ f (f c c) c → false := by cc example (a b c : nat) (f : nat → nat → nat) : a = b → c = b → f (f a b) a = f (f c c) c := by cc example (a b c d : nat) : a == b → b = c → c == d → a == d := by cc example (a b c d : nat) : a = b → b = c → c == d → a == d := by cc example (a b c d : nat) : a = b → b == c → c == d → a == d := by cc example (a b c d : nat) : a == b → b == c → c = d → a == d := by cc example (a b c d : nat) : a == b → b = c → c = d → a == d := by cc example (a b c d : nat) : a = b → b = c → c = d → a == d := by cc example (a b c d : nat) : a = b → b == c → c = d → a == d := by cc constant f {α : Type} : α → α → α constant g : nat → nat example (a b c : nat) : a = b → g a == g b := by cc example (a b c : nat) : a = b → c = b → f (f a b) (g c) = f (f c a) (g b) := by cc example (a b c d e x y : nat) : a = b → a = x → b = y → c = d → c = e → c = b → a = e := by cc
f34de66a00409887a46395119e41cf40dfbc45ed
4727251e0cd73359b15b664c3170e5d754078599
/src/order/bounded.lean
4c29d5138dae00fe6d15e9649eb3688aa3e01edd
[ "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
14,070
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import order.min_max import order.rel_classes import data.set.intervals.basic /-! # Bounded and unbounded sets We prove miscellaneous lemmas about bounded and unbounded sets. Many of these are just variations on the same ideas, or similar results with a few minor differences. The file is divided into these different general ideas. -/ namespace set variables {α : Type*} {r : α → α → Prop} {s t : set α} /-! ### Subsets of bounded and unbounded sets -/ theorem bounded.mono (hst : s ⊆ t) (hs : bounded r t) : bounded r s := hs.imp $ λ a ha b hb, ha b (hst hb) theorem unbounded.mono (hst : s ⊆ t) (hs : unbounded r s) : unbounded r t := λ a, let ⟨b, hb, hb'⟩ := hs a in ⟨b, hst hb, hb'⟩ /-! ### Alternate characterizations of unboundedness on orders -/ lemma unbounded_le_of_forall_exists_lt [preorder α] (h : ∀ a, ∃ b ∈ s, a < b) : unbounded (≤) s := λ a, let ⟨b, hb, hb'⟩ := h a in ⟨b, hb, λ hba, hba.not_lt hb'⟩ lemma unbounded_le_iff [linear_order α] : unbounded (≤) s ↔ ∀ a, ∃ b ∈ s, a < b := by simp only [unbounded, not_le] lemma unbounded_lt_of_forall_exists_le [preorder α] (h : ∀ a, ∃ b ∈ s, a ≤ b) : unbounded (<) s := λ a, let ⟨b, hb, hb'⟩ := h a in ⟨b, hb, λ hba, hba.not_le hb'⟩ lemma unbounded_lt_iff [linear_order α] : unbounded (<) s ↔ ∀ a, ∃ b ∈ s, a ≤ b := by simp only [unbounded, not_lt] lemma unbounded_ge_of_forall_exists_gt [preorder α] (h : ∀ a, ∃ b ∈ s, b < a) : unbounded (≥) s := @unbounded_le_of_forall_exists_lt αᵒᵈ _ _ h lemma unbounded_ge_iff [linear_order α] : unbounded (≥) s ↔ ∀ a, ∃ b ∈ s, b < a := ⟨λ h a, let ⟨b, hb, hba⟩ := h a in ⟨b, hb, lt_of_not_ge hba⟩, unbounded_ge_of_forall_exists_gt⟩ lemma unbounded_gt_of_forall_exists_ge [preorder α] (h : ∀ a, ∃ b ∈ s, b ≤ a) : unbounded (>) s := λ a, let ⟨b, hb, hb'⟩ := h a in ⟨b, hb, λ hba, not_le_of_gt hba hb'⟩ lemma unbounded_gt_iff [linear_order α] : unbounded (>) s ↔ ∀ a, ∃ b ∈ s, b ≤ a := ⟨λ h a, let ⟨b, hb, hba⟩ := h a in ⟨b, hb, le_of_not_gt hba⟩, unbounded_gt_of_forall_exists_ge⟩ /-! ### Relation between boundedness by strict and nonstrict orders. -/ /-! #### Less and less or equal -/ lemma bounded.rel_mono {r' : α → α → Prop} (h : bounded r s) (hrr' : r ≤ r') : bounded r' s := let ⟨a, ha⟩ := h in ⟨a, λ b hb, hrr' b a (ha b hb)⟩ lemma bounded_le_of_bounded_lt [preorder α] (h : bounded (<) s) : bounded (≤) s := h.rel_mono $ λ _ _, le_of_lt lemma unbounded.rel_mono {r' : α → α → Prop} (hr : r' ≤ r) (h : unbounded r s) : unbounded r' s := λ a, let ⟨b, hb, hba⟩ := h a in ⟨b, hb, λ hba', hba (hr b a hba')⟩ lemma unbounded_lt_of_unbounded_le [preorder α] (h : unbounded (≤) s) : unbounded (<) s := h.rel_mono $ λ _ _, le_of_lt lemma bounded_le_iff_bounded_lt [preorder α] [no_max_order α] : bounded (≤) s ↔ bounded (<) s := begin refine ⟨λ h, _, bounded_le_of_bounded_lt⟩, cases h with a ha, cases exists_gt a with b hb, exact ⟨b, λ c hc, lt_of_le_of_lt (ha c hc) hb⟩ end lemma unbounded_lt_iff_unbounded_le [preorder α] [no_max_order α] : unbounded (<) s ↔ unbounded (≤) s := by simp_rw [← not_bounded_iff, bounded_le_iff_bounded_lt] /-! #### Greater and greater or equal -/ lemma bounded_ge_of_bounded_gt [preorder α] (h : bounded (>) s) : bounded (≥) s := let ⟨a, ha⟩ := h in ⟨a, λ b hb, le_of_lt (ha b hb)⟩ lemma unbounded_gt_of_unbounded_ge [preorder α] (h : unbounded (≥) s) : unbounded (>) s := λ a, let ⟨b, hb, hba⟩ := h a in ⟨b, hb, λ hba', hba (le_of_lt hba')⟩ lemma bounded_ge_iff_bounded_gt [preorder α] [no_min_order α] : bounded (≥) s ↔ bounded (>) s := @bounded_le_iff_bounded_lt αᵒᵈ _ _ _ lemma unbounded_gt_iff_unbounded_ge [preorder α] [no_min_order α] : unbounded (>) s ↔ unbounded (≥) s := @unbounded_lt_iff_unbounded_le αᵒᵈ _ _ _ /-! ### The universal set -/ theorem unbounded_le_univ [has_le α] [no_top_order α] : unbounded (≤) (@set.univ α) := λ a, let ⟨b, hb⟩ := exists_not_le a in ⟨b, ⟨⟩, hb⟩ theorem unbounded_lt_univ [preorder α] [no_top_order α] : unbounded (<) (@set.univ α) := unbounded_lt_of_unbounded_le unbounded_le_univ theorem unbounded_ge_univ [has_le α] [no_bot_order α] : unbounded (≥) (@set.univ α) := λ a, let ⟨b, hb⟩ := exists_not_ge a in ⟨b, ⟨⟩, hb⟩ theorem unbounded_gt_univ [preorder α] [no_bot_order α] : unbounded (>) (@set.univ α) := unbounded_gt_of_unbounded_ge unbounded_ge_univ /-! ### Bounded and unbounded intervals -/ theorem bounded_self (a : α) : bounded r {b | r b a} := ⟨a, λ x, id⟩ /-! #### Half-open bounded intervals -/ theorem bounded_lt_Iio [preorder α] (a : α) : bounded (<) (set.Iio a) := bounded_self a theorem bounded_le_Iio [preorder α] (a : α) : bounded (≤) (set.Iio a) := bounded_le_of_bounded_lt (bounded_lt_Iio a) theorem bounded_le_Iic [preorder α] (a : α) : bounded (≤) (set.Iic a) := bounded_self a theorem bounded_lt_Iic [preorder α] [no_max_order α] (a : α) : bounded (<) (set.Iic a) := by simp only [← bounded_le_iff_bounded_lt, bounded_le_Iic] theorem bounded_gt_Ioi [preorder α] (a : α) : bounded (>) (set.Ioi a) := bounded_self a theorem bounded_ge_Ioi [preorder α] (a : α) : bounded (≥) (set.Ioi a) := bounded_ge_of_bounded_gt (bounded_gt_Ioi a) theorem bounded_ge_Ici [preorder α] (a : α) : bounded (≥) (set.Ici a) := bounded_self a theorem bounded_gt_Ici [preorder α] [no_min_order α] (a : α) : bounded (>) (set.Ici a) := by simp only [← bounded_ge_iff_bounded_gt, bounded_ge_Ici] /-! #### Other bounded intervals -/ theorem bounded_lt_Ioo [preorder α] (a b : α) : bounded (<) (set.Ioo a b) := (bounded_lt_Iio b).mono set.Ioo_subset_Iio_self theorem bounded_lt_Ico [preorder α] (a b : α) : bounded (<) (set.Ico a b) := (bounded_lt_Iio b).mono set.Ico_subset_Iio_self theorem bounded_lt_Ioc [preorder α] [no_max_order α] (a b : α) : bounded (<) (set.Ioc a b) := (bounded_lt_Iic b).mono set.Ioc_subset_Iic_self theorem bounded_lt_Icc [preorder α] [no_max_order α] (a b : α) : bounded (<) (set.Icc a b) := (bounded_lt_Iic b).mono set.Icc_subset_Iic_self theorem bounded_le_Ioo [preorder α] (a b : α) : bounded (≤) (set.Ioo a b) := (bounded_le_Iio b).mono set.Ioo_subset_Iio_self theorem bounded_le_Ico [preorder α] (a b : α) : bounded (≤) (set.Ico a b) := (bounded_le_Iio b).mono set.Ico_subset_Iio_self theorem bounded_le_Ioc [preorder α] (a b : α) : bounded (≤) (set.Ioc a b) := (bounded_le_Iic b).mono set.Ioc_subset_Iic_self theorem bounded_le_Icc [preorder α] (a b : α) : bounded (≤) (set.Icc a b) := (bounded_le_Iic b).mono set.Icc_subset_Iic_self theorem bounded_gt_Ioo [preorder α] (a b : α) : bounded (>) (set.Ioo a b) := (bounded_gt_Ioi a).mono set.Ioo_subset_Ioi_self theorem bounded_gt_Ioc [preorder α] (a b : α) : bounded (>) (set.Ioc a b) := (bounded_gt_Ioi a).mono set.Ioc_subset_Ioi_self theorem bounded_gt_Ico [preorder α] [no_min_order α] (a b : α) : bounded (>) (set.Ico a b) := (bounded_gt_Ici a).mono set.Ico_subset_Ici_self theorem bounded_gt_Icc [preorder α] [no_min_order α] (a b : α) : bounded (>) (set.Icc a b) := (bounded_gt_Ici a).mono set.Icc_subset_Ici_self theorem bounded_ge_Ioo [preorder α] (a b : α) : bounded (≥) (set.Ioo a b) := (bounded_ge_Ioi a).mono set.Ioo_subset_Ioi_self theorem bounded_ge_Ioc [preorder α] (a b : α) : bounded (≥) (set.Ioc a b) := (bounded_ge_Ioi a).mono set.Ioc_subset_Ioi_self theorem bounded_ge_Ico [preorder α] (a b : α) : bounded (≥) (set.Ico a b) := (bounded_ge_Ici a).mono set.Ico_subset_Ici_self theorem bounded_ge_Icc [preorder α] (a b : α) : bounded (≥) (set.Icc a b) := (bounded_ge_Ici a).mono set.Icc_subset_Ici_self /-! #### Unbounded intervals -/ theorem unbounded_le_Ioi [semilattice_sup α] [no_max_order α] (a : α) : unbounded (≤) (set.Ioi a) := λ b, let ⟨c, hc⟩ := exists_gt (a ⊔ b) in ⟨c, le_sup_left.trans_lt hc, (le_sup_right.trans_lt hc).not_le⟩ theorem unbounded_le_Ici [semilattice_sup α] [no_max_order α] (a : α) : unbounded (≤) (set.Ici a) := (unbounded_le_Ioi a).mono set.Ioi_subset_Ici_self theorem unbounded_lt_Ioi [semilattice_sup α] [no_max_order α] (a : α) : unbounded (<) (set.Ioi a) := unbounded_lt_of_unbounded_le (unbounded_le_Ioi a) theorem unbounded_lt_Ici [semilattice_sup α] (a : α) : unbounded (<) (set.Ici a) := λ b, ⟨a ⊔ b, le_sup_left, le_sup_right.not_lt⟩ /-! ### Bounded initial segments -/ theorem bounded_inter_not (H : ∀ a b, ∃ m, ∀ c, r c a ∨ r c b → r c m) (a : α) : bounded r (s ∩ {b | ¬ r b a}) ↔ bounded r s := begin refine ⟨_, bounded.mono (set.inter_subset_left s _)⟩, rintro ⟨b, hb⟩, cases H a b with m hm, exact ⟨m, λ c hc, hm c (or_iff_not_imp_left.2 (λ hca, (hb c ⟨hc, hca⟩)))⟩ end theorem unbounded_inter_not (H : ∀ a b, ∃ m, ∀ c, r c a ∨ r c b → r c m) (a : α) : unbounded r (s ∩ {b | ¬ r b a}) ↔ unbounded r s := by simp_rw [← not_bounded_iff, bounded_inter_not H] /-! #### Less or equal -/ theorem bounded_le_inter_not_le [semilattice_sup α] (a : α) : bounded (≤) (s ∩ {b | ¬ b ≤ a}) ↔ bounded (≤) s := bounded_inter_not (λ x y, ⟨x ⊔ y, λ z h, h.elim le_sup_of_le_left le_sup_of_le_right⟩) a theorem unbounded_le_inter_not_le [semilattice_sup α] (a : α) : unbounded (≤) (s ∩ {b | ¬ b ≤ a}) ↔ unbounded (≤) s := begin rw [←not_bounded_iff, ←not_bounded_iff, not_iff_not], exact bounded_le_inter_not_le a end theorem bounded_le_inter_lt [linear_order α] (a : α) : bounded (≤) (s ∩ {b | a < b}) ↔ bounded (≤) s := by simp_rw [← not_le, bounded_le_inter_not_le] theorem unbounded_le_inter_lt [linear_order α] (a : α) : unbounded (≤) (s ∩ {b | a < b}) ↔ unbounded (≤) s := by { convert unbounded_le_inter_not_le a, ext, exact lt_iff_not_le } theorem bounded_le_inter_le [linear_order α] (a : α) : bounded (≤) (s ∩ {b | a ≤ b}) ↔ bounded (≤) s := begin refine ⟨_, bounded.mono (set.inter_subset_left s _)⟩, rw ←@bounded_le_inter_lt _ s _ a, exact bounded.mono (λ x ⟨hx, hx'⟩, ⟨hx, le_of_lt hx'⟩) end theorem unbounded_le_inter_le [linear_order α] (a : α) : unbounded (≤) (s ∩ {b | a ≤ b}) ↔ unbounded (≤) s := begin rw [←not_bounded_iff, ←not_bounded_iff, not_iff_not], exact bounded_le_inter_le a end /-! #### Less than -/ theorem bounded_lt_inter_not_lt [semilattice_sup α] (a : α) : bounded (<) (s ∩ {b | ¬ b < a}) ↔ bounded (<) s := bounded_inter_not (λ x y, ⟨x ⊔ y, λ z h, h.elim lt_sup_of_lt_left lt_sup_of_lt_right⟩) a theorem unbounded_lt_inter_not_lt [semilattice_sup α] (a : α) : unbounded (<) (s ∩ {b | ¬ b < a}) ↔ unbounded (<) s := begin rw [←not_bounded_iff, ←not_bounded_iff, not_iff_not], exact bounded_lt_inter_not_lt a end theorem bounded_lt_inter_le [linear_order α] (a : α) : bounded (<) (s ∩ {b | a ≤ b}) ↔ bounded (<) s := by { convert bounded_lt_inter_not_lt a, ext, exact not_lt.symm } theorem unbounded_lt_inter_le [linear_order α] (a : α) : unbounded (<) (s ∩ {b | a ≤ b}) ↔ unbounded (<) s := by { convert unbounded_lt_inter_not_lt a, ext, exact not_lt.symm } theorem bounded_lt_inter_lt [linear_order α] [no_max_order α] (a : α) : bounded (<) (s ∩ {b | a < b}) ↔ bounded (<) s := begin rw [←bounded_le_iff_bounded_lt, ←bounded_le_iff_bounded_lt], exact bounded_le_inter_lt a end theorem unbounded_lt_inter_lt [linear_order α] [no_max_order α] (a : α) : unbounded (<) (s ∩ {b | a < b}) ↔ unbounded (<) s := begin rw [←not_bounded_iff, ←not_bounded_iff, not_iff_not], exact bounded_lt_inter_lt a end /-! #### Greater or equal -/ theorem bounded_ge_inter_not_ge [semilattice_inf α] (a : α) : bounded (≥) (s ∩ {b | ¬ a ≤ b}) ↔ bounded (≥) s := @bounded_le_inter_not_le αᵒᵈ s _ a theorem unbounded_ge_inter_not_ge [semilattice_inf α] (a : α) : unbounded (≥) (s ∩ {b | ¬ a ≤ b}) ↔ unbounded (≥) s := @unbounded_le_inter_not_le αᵒᵈ s _ a theorem bounded_ge_inter_gt [linear_order α] (a : α) : bounded (≥) (s ∩ {b | b < a}) ↔ bounded (≥) s := @bounded_le_inter_lt αᵒᵈ s _ a theorem unbounded_ge_inter_gt [linear_order α] (a : α) : unbounded (≥) (s ∩ {b | b < a}) ↔ unbounded (≥) s := @unbounded_le_inter_lt αᵒᵈ s _ a theorem bounded_ge_inter_ge [linear_order α] (a : α) : bounded (≥) (s ∩ {b | b ≤ a}) ↔ bounded (≥) s := @bounded_le_inter_le αᵒᵈ s _ a theorem unbounded_ge_iff_unbounded_inter_ge [linear_order α] (a : α) : unbounded (≥) (s ∩ {b | b ≤ a}) ↔ unbounded (≥) s := @unbounded_le_inter_le αᵒᵈ s _ a /-! #### Greater than -/ theorem bounded_gt_inter_not_gt [semilattice_inf α] (a : α) : bounded (>) (s ∩ {b | ¬ a < b}) ↔ bounded (>) s := @bounded_lt_inter_not_lt αᵒᵈ s _ a theorem unbounded_gt_inter_not_gt [semilattice_inf α] (a : α) : unbounded (>) (s ∩ {b | ¬ a < b}) ↔ unbounded (>) s := @unbounded_lt_inter_not_lt αᵒᵈ s _ a theorem bounded_gt_inter_ge [linear_order α] (a : α) : bounded (>) (s ∩ {b | b ≤ a}) ↔ bounded (>) s := @bounded_lt_inter_le αᵒᵈ s _ a theorem unbounded_inter_ge [linear_order α] (a : α) : unbounded (>) (s ∩ {b | b ≤ a}) ↔ unbounded (>) s := @unbounded_lt_inter_le αᵒᵈ s _ a theorem bounded_gt_inter_gt [linear_order α] [no_min_order α] (a : α) : bounded (>) (s ∩ {b | b < a}) ↔ bounded (>) s := @bounded_lt_inter_lt αᵒᵈ s _ _ a theorem unbounded_gt_inter_gt [linear_order α] [no_min_order α] (a : α) : unbounded (>) (s ∩ {b | b < a}) ↔ unbounded (>) s := @unbounded_lt_inter_lt αᵒᵈ s _ _ a end set
b5181cdc2d0a99fcd9b8cd93ee317e0ddac1f1be
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/monoid/with_zero/basic.lean
35dc4316881639cdd7c87bffd4b4010d70be7907
[ "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
1,079
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.order.monoid.with_zero.defs import algebra.group_with_zero.basic /-! # An instance orphaned from `algebra.order.monoid.with_zero.defs` We put this here to minimise imports: if you can move it back into `algebra.order.monoid.with_zero.defs` without increasing imports, please do. -/ open function universe u variables {α : Type u} namespace with_zero instance contravariant_class_mul_lt {α : Type u} [has_mul α] [partial_order α] [contravariant_class α α (*) (<)] : contravariant_class (with_zero α) (with_zero α) (*) (<) := begin refine ⟨λ a b c h, _⟩, have := ((zero_le _).trans_lt h).ne', lift a to α using left_ne_zero_of_mul this, lift c to α using right_ne_zero_of_mul this, induction b using with_zero.rec_zero_coe, exacts [zero_lt_coe _, coe_lt_coe.mpr (lt_of_mul_lt_mul_left' $ coe_lt_coe.mp h)] end end with_zero
bab80e35f2756a2752aa4f6ab1146376b99938d2
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/padics/padic_numbers.lean
ce2f68965732e147a369f8d21a4ac109f53b0a7d
[ "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
32,536
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.real.cau_seq_completion import data.padics.padic_norm algebra.archimedean analysis.normed_space.basic import tactic.norm_cast /-! # 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] @[move_cast] lemma coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y := by simp [cast_eq_of_rat] @[move_cast] lemma coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x := by simp [cast_eq_of_rat] @[move_cast] lemma coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y := by simp [cast_eq_of_rat] @[move_cast] lemma coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y := by simp [cast_eq_of_rat] @[move_cast] lemma coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y := by simp [cast_eq_of_rat] @[squash_cast] lemma coe_one : (↑1 : ℚ_[p]) = 1 := rfl @[squash_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⟩ @[elim_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], 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
4f64b4a14ba5c27d2c9106ddf2ac7a4c065c11ee
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/shapes/finite_limits.lean
c3664f088370a29d969859d01e075fce4385ca69
[ "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
8,685
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.fin_category import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.equalizers import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.pullbacks import data.fintype.option /-! # Categories with finite limits. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A typeclass for categories with all finite (co)limits. -/ universes w' w v' u' v u noncomputable theory open category_theory namespace category_theory.limits variables (C : Type u) [category.{v} C] /-- A category has all finite limits if every functor `J ⥤ C` with a `fin_category J` instance and `J : Type` has a limit. This is often called 'finitely complete'. -/ -- We can't just made this an `abbreviation` -- because of https://github.com/leanprover-community/lean/issues/429 class has_finite_limits : Prop := (out (J : Type) [𝒥 : small_category J] [@fin_category J 𝒥] : @has_limits_of_shape J 𝒥 C _) @[priority 100] instance has_limits_of_shape_of_has_finite_limits (J : Type w) [small_category J] [fin_category J] [has_finite_limits C] : has_limits_of_shape J C := begin apply has_limits_of_shape_of_equivalence (fin_category.equiv_as_type J), apply has_finite_limits.out end @[priority 100] instance has_finite_limits_of_has_limits_of_size [has_limits_of_size.{v' u'} C] : has_finite_limits C := ⟨λ J hJ hJ', by { haveI := has_limits_of_size_shrink.{0 0} C, exact has_limits_of_shape_of_equivalence (fin_category.equiv_as_type J) }⟩ /-- If `C` has all limits, it has finite limits. -/ @[priority 100] instance has_finite_limits_of_has_limits [has_limits C] : has_finite_limits C := infer_instance /-- We can always derive `has_finite_limits C` by providing limits at an arbitrary universe. -/ lemma has_finite_limits_of_has_finite_limits_of_size (h : ∀ (J : Type w) {𝒥 : small_category J} (hJ : @fin_category J 𝒥), by { resetI, exact has_limits_of_shape J C }) : has_finite_limits C := ⟨λ J hJ hhJ, begin resetI, letI : category.{w w} (ulift_hom.{w} (ulift.{w 0} J)), { apply ulift_hom.category.{0}, exact category_theory.ulift_category J }, haveI := h (ulift_hom.{w} (ulift.{w} J)) category_theory.fin_category_ulift, exact has_limits_of_shape_of_equivalence (ulift_hom_ulift_category.equiv.{w w} J).symm end ⟩ /-- A category has all finite colimits if every functor `J ⥤ C` with a `fin_category J` instance and `J : Type` has a colimit. This is often called 'finitely cocomplete'. -/ class has_finite_colimits : Prop := (out (J : Type) [𝒥 : small_category J] [@fin_category J 𝒥] : @has_colimits_of_shape J 𝒥 C _) @[priority 100] instance has_colimits_of_shape_of_has_finite_colimits (J : Type w) [small_category J] [fin_category J] [has_finite_colimits C] : has_colimits_of_shape J C := begin apply has_colimits_of_shape_of_equivalence (fin_category.equiv_as_type J), apply has_finite_colimits.out end @[priority 100] instance has_finite_colimits_of_has_colimits_of_size [has_colimits_of_size.{v' u'} C] : has_finite_colimits C := ⟨λ J hJ hJ', by { haveI := has_colimits_of_size_shrink.{0 0} C, exact has_colimits_of_shape_of_equivalence (fin_category.equiv_as_type J) }⟩ /-- We can always derive `has_finite_colimits C` by providing colimits at an arbitrary universe. -/ lemma has_finite_colimits_of_has_finite_colimits_of_size (h : ∀ (J : Type w) {𝒥 : small_category J} (hJ : @fin_category J 𝒥), by { resetI, exact has_colimits_of_shape J C }) : has_finite_colimits C := ⟨λ J hJ hhJ, begin resetI, letI : category.{w w} (ulift_hom.{w} (ulift.{w 0} J)), { apply ulift_hom.category.{0}, exact category_theory.ulift_category J }, haveI := h (ulift_hom.{w} (ulift.{w} J)) category_theory.fin_category_ulift, exact has_colimits_of_shape_of_equivalence (ulift_hom_ulift_category.equiv.{w w} J).symm end ⟩ section open walking_parallel_pair walking_parallel_pair_hom instance fintype_walking_parallel_pair : fintype walking_parallel_pair := { elems := [walking_parallel_pair.zero, walking_parallel_pair.one].to_finset, complete := λ x, by { cases x; simp } } local attribute [tidy] tactic.case_bash instance (j j' : walking_parallel_pair) : fintype (walking_parallel_pair_hom j j') := { elems := walking_parallel_pair.rec_on j (walking_parallel_pair.rec_on j' [walking_parallel_pair_hom.id zero].to_finset [left, right].to_finset) (walking_parallel_pair.rec_on j' ∅ [walking_parallel_pair_hom.id one].to_finset), complete := by tidy } end instance : fin_category walking_parallel_pair := { } /-- Equalizers are finite limits, so if `C` has all finite limits, it also has all equalizers -/ example [has_finite_limits C] : has_equalizers C := by apply_instance /-- Coequalizers are finite colimits, of if `C` has all finite colimits, it also has all coequalizers -/ example [has_finite_colimits C] : has_coequalizers C := by apply_instance variables {J : Type v} local attribute [tidy] tactic.case_bash namespace wide_pullback_shape instance fintype_obj [fintype J] : fintype (wide_pullback_shape J) := by { rw wide_pullback_shape, apply_instance } instance fintype_hom (j j' : wide_pullback_shape J) : fintype (j ⟶ j') := { elems := begin cases j', { cases j, { exact {hom.id none} }, { exact {hom.term j} } }, { by_cases some j' = j, { rw h, exact {hom.id j} }, { exact ∅ } } end, complete := by tidy } end wide_pullback_shape namespace wide_pushout_shape instance fintype_obj [fintype J] : fintype (wide_pushout_shape J) := by { rw wide_pushout_shape, apply_instance } instance fintype_hom (j j' : wide_pushout_shape J) : fintype (j ⟶ j') := { elems := begin cases j, { cases j', { exact {hom.id none} }, { exact {hom.init j'} } }, { by_cases some j = j', { rw h, exact {hom.id j'} }, { exact ∅ } } end, complete := by tidy } end wide_pushout_shape instance fin_category_wide_pullback [fintype J] : fin_category (wide_pullback_shape J) := { fintype_hom := wide_pullback_shape.fintype_hom } instance fin_category_wide_pushout [fintype J] : fin_category (wide_pushout_shape J) := { fintype_hom := wide_pushout_shape.fintype_hom } /-- `has_finite_wide_pullbacks` represents a choice of wide pullback for every finite collection of morphisms -/ -- We can't just made this an `abbreviation` -- because of https://github.com/leanprover-community/lean/issues/429 class has_finite_wide_pullbacks : Prop := (out (J : Type) [fintype J] : has_limits_of_shape (wide_pullback_shape J) C) instance has_limits_of_shape_wide_pullback_shape (J : Type) [finite J] [has_finite_wide_pullbacks C] : has_limits_of_shape (wide_pullback_shape J) C := by { casesI nonempty_fintype J, haveI := @has_finite_wide_pullbacks.out C _ _ J, apply_instance } /-- `has_finite_wide_pushouts` represents a choice of wide pushout for every finite collection of morphisms -/ class has_finite_wide_pushouts : Prop := (out (J : Type) [fintype J] : has_colimits_of_shape (wide_pushout_shape J) C) instance has_colimits_of_shape_wide_pushout_shape (J : Type) [finite J] [has_finite_wide_pushouts C] : has_colimits_of_shape (wide_pushout_shape J) C := by { casesI nonempty_fintype J, haveI := @has_finite_wide_pushouts.out C _ _ J, apply_instance } /-- Finite wide pullbacks are finite limits, so if `C` has all finite limits, it also has finite wide pullbacks -/ lemma has_finite_wide_pullbacks_of_has_finite_limits [has_finite_limits C] : has_finite_wide_pullbacks C := ⟨λ J _, by exactI has_finite_limits.out _⟩ /-- Finite wide pushouts are finite colimits, so if `C` has all finite colimits, it also has finite wide pushouts -/ lemma has_finite_wide_pushouts_of_has_finite_limits [has_finite_colimits C] : has_finite_wide_pushouts C := ⟨λ J _, by exactI has_finite_colimits.out _⟩ instance fintype_walking_pair : fintype walking_pair := { elems := {walking_pair.left, walking_pair.right}, complete := λ x, by { cases x; simp } } /-- Pullbacks are finite limits, so if `C` has all finite limits, it also has all pullbacks -/ example [has_finite_wide_pullbacks C] : has_pullbacks C := by apply_instance /-- Pushouts are finite colimits, so if `C` has all finite colimits, it also has all pushouts -/ example [has_finite_wide_pushouts C] : has_pushouts C := by apply_instance end category_theory.limits
31369b8401d52f9d8667a18986516085bca902b0
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/balg.lean
d91cd224167f98e4a86036fd5b4447a5b3938e58
[ "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,471
lean
import Lean universe u structure Magma where α : Type u mul : α → α → α instance : CoeSort Magma (Type u) where coe s := s.α abbrev mul {M : Magma} (a b : M) : M := M.mul a b set_option pp.all true infixl:70 (priority := high) "*" => mul structure Semigroup extends Magma where mul_assoc (a b c : α) : a * b * c = a * (b * c) instance : CoeSort Semigroup (Type u) where coe s := s.α structure CommSemigroup extends Semigroup where mul_comm (a b : α) : a * b = b * a structure Monoid extends Semigroup where one : α one_mul (a : α) : one * a = a mul_one (a : α) : a * one = a instance : CoeSort Monoid (Type u) where coe s := s.α structure CommMonoid extends Monoid where mul_comm (a b : α) : a * b = b * a instance : Coe CommMonoid CommSemigroup where coe s := { α := s.α mul := s.mul mul_assoc := s.mul_assoc mul_comm := s.mul_comm } structure Group extends Monoid where inv : α → α mul_left_inv (a : α) : (inv a) * a = one instance : CoeSort Group (Type u) where coe s := s.α abbrev inv {G : Group} (a : G) : G := G.inv a postfix:max "⁻¹" => inv instance (G : Group) : OfNat (CoeSort.coe G.toMagma) (nat_lit 1) where ofNat := G.one instance (G : Group) : OfNat (G.toMagma.α) (nat_lit 1) where ofNat := G.one structure CommGroup extends Group where mul_comm (a b : α) : a * b = b * a instance : CoeSort CommGroup (Type u) where coe s := s.α theorem inv_mul_cancel_left {G : Group} (a b : G) : a⁻¹ * (a * b) = b := by rw [← G.mul_assoc, G.mul_left_inv, G.one_mul] theorem toMonoidOneEq {G : Group} : G.toMonoid.one = 1 := rfl theorem inv_eq_of_mul_eq_one {G : Group} {a b : G} (h : a * b = 1) : a⁻¹ = b := by rw [← G.mul_one a⁻¹, toMonoidOneEq, ←h, ← G.mul_assoc, G.mul_left_inv, G.one_mul] theorem inv_inv {G : Group} (a : G) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (G.mul_left_inv a) theorem mul_right_inv {G : Group} (a : G) : a * a⁻¹ = 1 := by have : a⁻¹⁻¹ * a⁻¹ = 1 := by rw [G.mul_left_inv]; rfl rw [inv_inv] at this assumption unif_hint (G : Group) where |- G.toMonoid.one =?= 1 theorem mul_inv_rev {G : Group} (a b : G) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := by apply inv_eq_of_mul_eq_one rw [G.mul_assoc, ← G.mul_assoc b, mul_right_inv, G.one_mul, mul_right_inv] theorem mul_inv {G : CommGroup} (a b : G) : (a * b)⁻¹ = a⁻¹ * b⁻¹ := by rw [mul_inv_rev, G.mul_comm]
187b3a14acd6320250e7fcbcf786aa791a7bb364
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/library/init/category/alternative.lean
c34d46d9b4b888691468356732fbbf8eb07436ee
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,095
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.logic init.category.applicative universes u v class alternative (f : Type u → Type v) extends applicative f : Type (max u+1 v) := (failure : Π {α : Type u}, f α) (orelse : Π {α : Type u}, f α → f α → f α) section variables {f : Type u → Type v} [alternative f] {α : Type u} @[inline] def failure : f α := alternative.failure f @[inline] def orelse : f α → f α → f α := alternative.orelse infixr ` <|> `:2 := orelse @[inline] def guard {f : Type → Type v} [alternative f] (p : Prop) [decidable p] : f unit := if p then pure () else failure /- Later we define a coercion from bool to Prop, but this version will still be useful. Given (t : tactic bool), we can write t >>= guardb -/ @[inline] def guardb {f : Type → Type v} [alternative f] : bool → f unit | tt := pure () | ff := failure @[inline] def optional (x : f α) : f (option α) := some <$> x <|> pure none end
58b20fd82ca164ec1a890825674e86bacd987951
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/data/nat/div.lean
0730f629c50961b179967c3a0e6df859fc1d2ccd
[ "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
27,204
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 Definitions and properties of div and mod. Much of the development follows Isabelle's library. -/ import .sub open well_founded decidable prod namespace nat /- div -/ -- auxiliary lemma used to justify div private definition div_rec_lemma {x y : nat} : 0 < y ∧ y ≤ x → x - y < x := and.rec (λ ypos ylex, sub_lt (lt_of_lt_of_le ypos ylex) ypos) private definition div.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat := if H : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma H) y + 1 else zero protected definition div := fix lt_wf div.F definition nat_has_divide : has_div nat := has_div.mk nat.div local attribute [instance] nat_has_divide theorem div_def (x y : nat) : div x y = if 0 < y ∧ y ≤ x then div (x - y) y + 1 else 0 := congr_fun (fix_eq lt_wf div.F x) y attribute [simp] protected theorem div_zero (a : ℕ) : a / 0 = 0 := eq.trans (div_def a 0) $ if_neg (not_and_of_not_left (0 ≤ a) (lt.irrefl 0)) theorem div_eq_zero_of_lt {a b : ℕ} (h : a < b) : a / b = 0 := eq.trans (div_def a b) $ if_neg (not_and_of_not_right (0 < b) (not_le_of_gt h)) attribute [simp] protected theorem zero_div (b : ℕ) : 0 / b = 0 := eq.trans (div_def 0 b) $ if_neg (and.rec not_le_of_gt) theorem div_eq_succ_sub_div {a b : ℕ} (h₁ : b > 0) (h₂ : a ≥ b) : a / b = succ ((a - b) / b) := eq.trans (div_def a b) $ if_pos (and.intro h₁ h₂) theorem add_div_self (x : ℕ) {z : ℕ} (H : z > 0) : (x + z) / z = succ (x / z) := sorry /- calc (x + z) / z = if 0 < z ∧ z ≤ x + z then (x + z - z) / z + 1 else 0 : !div_def ... = (x + z - z) / z + 1 : if_pos (and.intro H (le_add_left z x)) ... = succ (x / z) : by rewrite nat.add_sub_cancel -/ theorem add_div_self_left {x : ℕ} (z : ℕ) (H : x > 0) : (x + z) / x = succ (z / x) := add.comm z x ▸ add_div_self z H local attribute succ_mul [simp] theorem add_mul_div_self {x y z : ℕ} (H : z > 0) : (x + y * z) / z = x / z + y := sorry /- nat.induction_on y (by simp) (take y, assume IH : (x + y * z) / z = x / z + y, calc (x + succ y * z) / z = (x + y * z + z) / z : by inst_simp ... = succ ((x + y * z) / z) : !add_div_self H ... = succ (x / z + y) : by rewrite IH) -/ theorem add_mul_div_self_left (x z : ℕ) {y : ℕ} (H : y > 0) : (x + y * z) / y = x / y + z := mul.comm z y ▸ add_mul_div_self H protected theorem mul_div_cancel (m : ℕ) {n : ℕ} (H : n > 0) : m * n / n = m := sorry /- calc m * n / n = (0 + m * n) / n : by simp ... = 0 / n + m : add_mul_div_self H ... = m : by simp -/ protected theorem mul_div_cancel_left {m : ℕ} (n : ℕ) (H : m > 0) : m * n / m = n := mul.comm n m ▸ nat.mul_div_cancel n H /- mod -/ private definition mod.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat := if H : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma H) y else x protected definition mod := fix lt_wf mod.F definition nat_has_mod : has_mod nat := has_mod.mk nat.mod local attribute [instance] nat_has_mod notation [priority nat.prio] a ≡ b `[mod `:0 c:0 `]` := a % c = b % c theorem mod_def (x y : nat) : mod x y = if 0 < y ∧ y ≤ x then mod (x - y) y else x := congr_fun (fix_eq lt_wf mod.F x) y attribute [simp] theorem mod_zero (a : ℕ) : a % 0 = a := eq.trans (mod_def a 0) $ if_neg (not_and_of_not_left (0 ≤ a) (lt.irrefl 0)) theorem mod_eq_of_lt {a b : ℕ} (h : a < b) : a % b = a := eq.trans (mod_def a b) $ if_neg (not_and_of_not_right (0 < b) (not_le_of_gt h)) attribute [simp] theorem zero_mod (b : ℕ) : 0 % b = 0 := eq.trans (mod_def 0 b) $ if_neg (λ h, and.rec_on h (λ l r, absurd (lt_of_lt_of_le l r) (lt.irrefl 0))) theorem mod_eq_sub_mod {a b : ℕ} (h₁ : b > 0) (h₂ : a ≥ b) : a % b = (a - b) % b := eq.trans (mod_def a b) $ if_pos (and.intro h₁ h₂) attribute [simp] theorem add_mod_self (x z : ℕ) : (x + z) % z = x % z := sorry /- by_cases_zero_pos z (by rewrite add_zero) (take z, assume H : z > 0, calc (x + z) % z = if 0 < z ∧ z ≤ x + z then (x + z - z) % z else _ : !mod_def ... = (x + z - z) % z : if_pos (and.intro H (le_add_left z x)) ... = x % z : by rewrite nat.add_sub_cancel) -/ attribute [simp] theorem add_mod_self_left (x z : ℕ) : (x + z) % x = z % x := add.comm z x ▸ add_mod_self z x local attribute succ_mul [simp] attribute [simp] theorem add_mul_mod_self (x y z : ℕ) : (x + y * z) % z = x % z := sorry -- nat.induction_on y (by simp) (by inst_simp) attribute [simp] theorem add_mul_mod_self_left (x y z : ℕ) : (x + y * z) % y = x % y := sorry -- by inst_simp attribute [simp] theorem mul_mod_left (m n : ℕ) : (m * n) % n = 0 := sorry /- calc (m * n) % n = (0 + m * n) % n : by simp ... = 0 : by inst_simp -/ attribute [simp] theorem mul_mod_right (m n : ℕ) : (m * n) % m = 0 := sorry -- by inst_simp theorem mod_lt (x : ℕ) {y : ℕ} (H : y > 0) : x % y < y := nat.case_strong_induction_on x (show 0 % y < y, from eq.symm (zero_mod y) ▸ H) (take x, assume IH : ∀x', x' ≤ x → x' % y < y, show succ x % y < y, from by_cases -- (succ x < y) (assume H1 : succ x < y, have succ x % y = succ x, from mod_eq_of_lt H1, show succ x % y < y, from eq.symm this ▸ H1) (assume H1 : ¬ succ x < y, have y ≤ succ x, from le_of_not_gt H1, have h : succ x % y = (succ x - y) % y, from mod_eq_sub_mod H this, have succ x - y < succ x, from sub_lt (succ_pos x) H, have succ x - y ≤ x, from le_of_lt_succ this, show succ x % y < y, from eq.symm h ▸ IH _ this)) theorem mod_one (n : ℕ) : n % 1 = 0 := have H1 : n % 1 < 1, from (mod_lt n) (succ_pos 0), eq_zero_of_le_zero (le_of_lt_succ H1) /- properties of div and mod -/ -- the quotient - remainder theorem theorem eq_div_mul_add_mod (x y : ℕ) : x = x / y * y + x % y := sorry /- begin eapply by_cases_zero_pos y, show x = x / 0 * 0 + x % 0, from (calc x / 0 * 0 + x % 0 = 0 + x % 0 : by rewrite mul_zero ... = x % 0 : by rewrite zero_add ... = x : by rewrite mod_zero)⁻¹, intro y H, show x = x / y * y + x % y, begin eapply nat.case_strong_induction_on x, show 0 = (0 / y) * y + 0 % y, by rewrite [zero_mod, add_zero, nat.zero_div, zero_mul], intro x IH, show succ x = succ x / y * y + succ x % y, from if H1 : succ x < y then have H2 : succ x / y = 0, from div_eq_zero_of_lt H1, have H3 : succ x % y = succ x, from mod_eq_of_lt H1, begin rewrite [H2, H3, zero_mul, zero_add] end else have H2 : y ≤ succ x, from le_of_not_gt H1, have H3 : succ x / y = succ ((succ x - y) / y), from div_eq_succ_sub_div H H2, have H4 : succ x % y = (succ x - y) % y, from mod_eq_sub_mod H H2, have H5 : succ x - y < succ x, from sub_lt !succ_pos H, have H6 : succ x - y ≤ x, from le_of_lt_succ H5, (calc succ x / y * y + succ x % y = succ ((succ x - y) / y) * y + succ x % y : by rewrite H3 ... = ((succ x - y) / y) * y + y + succ x % y : by rewrite succ_mul ... = ((succ x - y) / y) * y + y + (succ x - y) % y : by rewrite H4 ... = ((succ x - y) / y) * y + (succ x - y) % y + y : by rewrite add.right_comm ... = succ x - y + y : by rewrite -(IH _ H6) ... = succ x : nat.sub_add_cancel H2)⁻¹ end end -/ theorem mod_eq_sub_div_mul (x y : ℕ) : x % y = x - x / y * y := nat.eq_sub_of_add_eq (eq.symm (add.comm (x / y * y) (x % y) ▸ eq_div_mul_add_mod x y)) theorem mod_add_mod (m n k : ℕ) : (m % n + k) % n = (m + k) % n := sorry -- by rewrite [eq_div_mul_add_mod m n at {2}, add.assoc, add.comm (m / n * n), add_mul_mod_self] theorem add_mod_mod (m n k : ℕ) : (m + n % k) % k = (m + n) % k := sorry -- by rewrite [add.comm, mod_add_mod, add.comm] theorem add_mod_eq_add_mod_right {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (m + i) % n = (k + i) % n := sorry -- by rewrite [-mod_add_mod, -mod_add_mod k, H] theorem add_mod_eq_add_mod_left {m n k : ℕ} (i : ℕ) (H : m % n = k % n) : (i + m) % n = (i + k) % n := sorry -- by rewrite [add.comm, add_mod_eq_add_mod_right _ H, add.comm] theorem mod_eq_mod_of_add_mod_eq_add_mod_right {m n k i : ℕ} : (m + i) % n = (k + i) % n → m % n = k % n := sorry /- by_cases_zero_pos n (by rewrite [*mod_zero]; apply eq_of_add_eq_add_right) (take n, assume npos : n > 0, assume H1 : (m + i) % n = (k + i) % n, have H2 : (m + i % n) % n = (k + i % n) % n, by rewrite [*add_mod_mod, H1], have H3 : (m + i % n + (n - i % n)) % n = (k + i % n + (n - i % n)) % n, from add_mod_eq_add_mod_right _ H2, begin revert H3, rewrite [*add.assoc, add_sub_of_le (le_of_lt (!mod_lt npos)), *add_mod_self], intros, assumption end) -/ theorem mod_eq_mod_of_add_mod_eq_add_mod_left {m n k i : ℕ} : (i + m) % n = (i + k) % n → m % n = k % n := sorry -- by rewrite [add.comm i m, add.comm i k]; apply mod_eq_mod_of_add_mod_eq_add_mod_right theorem mod_le {x y : ℕ} : x % y ≤ x := eq.symm (eq_div_mul_add_mod x y) ▸ le_add_left (x % y) (x / y * y) theorem eq_remainder {q1 r1 q2 r2 y : ℕ} (H1 : r1 < y) (H2 : r2 < y) (H3 : q1 * y + r1 = q2 * y + r2) : r1 = r2 := sorry /- calc r1 = r1 % y : eq.symm (mod_eq_of_lt H1) ... = (r1 + q1 * y) % y : !add_mul_mod_self⁻¹ ... = (q1 * y + r1) % y : by rewrite add.comm ... = (r2 + q2 * y) % y : by rewrite [H3, add.comm] ... = r2 % y : !add_mul_mod_self ... = r2 : mod_eq_of_lt H2 -/ theorem eq_quotient {q1 r1 q2 r2 y : ℕ} (H1 : r1 < y) (H2 : r2 < y) (H3 : q1 * y + r1 = q2 * y + r2) : q1 = q2 := have H4 : q1 * y + r2 = q2 * y + r2, from (eq_remainder H1 H2 H3) ▸ H3, have H5 : q1 * y = q2 * y, from add.right_cancel H4, have H6 : y > 0, from lt_of_le_of_lt (zero_le r1) H1, show q1 = q2, from eq_of_mul_eq_mul_right H6 H5 protected theorem mul_div_mul_left {z : ℕ} (x y : ℕ) (zpos : z > 0) : (z * x) / (z * y) = x / y := sorry /- if H : y = 0 then by rewrite [H, mul_zero, *nat.div_zero] else have ypos : y > 0, from pos_of_ne_zero H, have zypos : z * y > 0, from mul_pos zpos ypos, have H1 : (z * x) % (z * y) < z * y, from !mod_lt zypos, have H2 : z * (x % y) < z * y, from mul_lt_mul_of_pos_left (!mod_lt ypos) zpos, eq_quotient H1 H2 (calc ((z * x) / (z * y)) * (z * y) + (z * x) % (z * y) = z * x : by rewrite -eq_div_mul_add_mod ... = z * (x / y * y + x % y) : by rewrite -eq_div_mul_add_mod ... = z * (x / y * y) + z * (x % y) : !left_distrib ... = (x / y) * (z * y) + z * (x % y) : by rewrite mul.left_comm) -/ protected theorem mul_div_mul_right {x z y : ℕ} (zpos : z > 0) : (x * z) / (y * z) = x / y := mul.comm z y ▸ mul.comm z x ▸ nat.mul_div_mul_left x y zpos theorem mul_mod_mul_left (z x y : ℕ) : (z * x) % (z * y) = z * (x % y) := sorry /- or.elim (eq_zero_or_pos z) (assume H : z = 0, H⁻¹ ▸ calc (0 * x) % (z * y) = 0 % (z * y) : by rewrite zero_mul ... = 0 : by rewrite zero_mod ... = 0 * (x % y) : by rewrite zero_mul) (assume zpos : z > 0, or.elim (eq_zero_or_pos y) (assume H : y = 0, by rewrite [H, mul_zero, *mod_zero]) (assume ypos : y > 0, have zypos : z * y > 0, from mul_pos zpos ypos, have H1 : (z * x) % (z * y) < z * y, from !mod_lt zypos, have H2 : z * (x % y) < z * y, from mul_lt_mul_of_pos_left (!mod_lt ypos) zpos, eq_remainder H1 H2 (calc ((z * x) / (z * y)) * (z * y) + (z * x) % (z * y) = z * x : by rewrite -eq_div_mul_add_mod ... = z * (x / y * y + x % y) : by rewrite -eq_div_mul_add_mod ... = z * (x / y * y) + z * (x % y) : by rewrite left_distrib ... = (x / y) * (z * y) + z * (x % y) : by rewrite mul.left_comm))) -/ theorem mul_mod_mul_right (x z y : ℕ) : (x * z) % (y * z) = (x % y) * z := mul.comm z x ▸ mul.comm z y ▸ mul.comm z (x % y) ▸ mul_mod_mul_left z x y theorem mod_self (n : ℕ) : n % n = 0 := sorry /- nat.cases_on n (by rewrite zero_mod) (take n, by rewrite [-zero_add (succ n) at {1}, add_mod_self]) -/ theorem mul_mod_eq_mod_mul_mod (m n k : nat) : (m * n) % k = ((m % k) * n) % k := sorry /- calc (m * n) % k = (((m / k) * k + m % k) * n) % k : by rewrite -eq_div_mul_add_mod ... = ((m % k) * n) % k : by rewrite [right_distrib, mul.right_comm, add.comm, add_mul_mod_self] -/ theorem mul_mod_eq_mul_mod_mod (m n k : nat) : (m * n) % k = (m * (n % k)) % k := mul.comm (n % k) m ▸ mul.comm n m ▸ mul_mod_eq_mod_mul_mod n m k protected theorem div_one (n : ℕ) : n / 1 = n := sorry /- have n / 1 * 1 + n % 1 = n, from !eq_div_mul_add_mod⁻¹, begin rewrite [-this at {2}, mul_one, mod_one] end -/ protected theorem div_self {n : ℕ} (H : n > 0) : n / n = 1 := sorry /- have (n * 1) / (n * 1) = 1 / 1, from !nat.mul_div_mul_left H, by rewrite [nat.div_one at this, -this, *mul_one] -/ theorem div_mul_cancel_of_mod_eq_zero {m n : ℕ} (H : m % n = 0) : m / n * n = m := sorry -- by rewrite [eq_div_mul_add_mod m n at {2}, H, add_zero] theorem mul_div_cancel_of_mod_eq_zero {m n : ℕ} (H : m % n = 0) : n * (m / n) = m := mul.comm (m / n) n ▸ div_mul_cancel_of_mod_eq_zero H /- dvd -/ theorem dvd_of_mod_eq_zero {m n : ℕ} (H : n % m = 0) : m ∣ n := dvd.intro (mul.comm (n / m) m ▸ div_mul_cancel_of_mod_eq_zero H) theorem mod_eq_zero_of_dvd {m n : ℕ} (H : m ∣ n) : n % m = 0 := dvd.elim H (take z, assume H1 : n = m * z, eq.symm H1 ▸ mul_mod_right m z) theorem dvd_iff_mod_eq_zero (m n : ℕ) : m ∣ n ↔ n % m = 0 := iff.intro mod_eq_zero_of_dvd dvd_of_mod_eq_zero definition dvd.decidable_rel : decidable_rel dvd := take m n, decidable_of_decidable_of_iff _ (iff.symm $ dvd_iff_mod_eq_zero m n) protected theorem div_mul_cancel {m n : ℕ} (H : n ∣ m) : m / n * n = m := div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H) protected theorem mul_div_cancel' {m n : ℕ} (H : n ∣ m) : n * (m / n) = m := mul.comm (m / n) n ▸ nat.div_mul_cancel H theorem dvd_of_dvd_add_left {m n₁ n₂ : ℕ} (H₁ : m ∣ n₁ + n₂) (H₂ : m ∣ n₁) : m ∣ n₂ := sorry /- obtain (c₁ : nat) (Hc₁ : n₁ + n₂ = m * c₁), from H₁, obtain (c₂ : nat) (Hc₂ : n₁ = m * c₂), from H₂, have aux : m * (c₁ - c₂) = n₂, from calc m * (c₁ - c₂) = m * c₁ - m * c₂ : !nat.mul_sub_left_distrib ... = n₁ + n₂ - m * c₂ : by rewrite Hc₁ ... = n₁ + n₂ - n₁ : by rewrite Hc₂ ... = n₂ : !nat.add_sub_cancel_left, dvd.intro aux -/ theorem dvd_of_dvd_add_right {m n₁ n₂ : ℕ} (H : m ∣ n₁ + n₂) : m ∣ n₂ → m ∣ n₁ := nat.dvd_of_dvd_add_left (add.comm n₁ n₂ ▸ H) theorem dvd_sub {m n₁ n₂ : ℕ} (H1 : m ∣ n₁) (H2 : m ∣ n₂) : m ∣ n₁ - n₂ := by_cases (assume H3 : n₁ ≥ n₂, have H4 : n₁ = n₁ - n₂ + n₂, from eq.symm (nat.sub_add_cancel H3), show m ∣ n₁ - n₂, from nat.dvd_of_dvd_add_right (H4 ▸ H1) H2) (assume H3 : ¬ (n₁ ≥ n₂), have H4 : n₁ - n₂ = 0, from sub_eq_zero_of_le (le_of_lt (lt_of_not_ge H3)), show m ∣ n₁ - n₂, from eq.symm H4 ▸ dvd_zero _) theorem dvd.antisymm {m n : ℕ} : m ∣ n → n ∣ m → m = n := sorry /- by_cases_zero_pos n (assume H1, assume H2 : 0 ∣ m, eq_zero_of_zero_dvd H2) (take n, assume Hpos : n > 0, assume H1 : m ∣ n, assume H2 : n ∣ m, obtain k (Hk : n = m * k), from exists_eq_mul_right_of_dvd H1, obtain l (Hl : m = n * l), from exists_eq_mul_right_of_dvd H2, have n * (l * k) = n, from !mul.assoc ▸ Hl ▸ Hk⁻¹, have l * k = 1, from eq_one_of_mul_eq_self_right Hpos this, have k = 1, from eq_one_of_mul_eq_one_left this, show m = n, from (mul_one m)⁻¹ ⬝ (this ▸ Hk⁻¹)) -/ protected theorem mul_div_assoc (m : ℕ) {n k : ℕ} (H : k ∣ n) : m * n / k = m * (n / k) := sorry /- or.elim (eq_zero_or_pos k) (assume H1 : k = 0, calc m * n / k = m * n / 0 : by rewrite H1 ... = 0 : by rewrite nat.div_zero ... = m * 0 : mul_zero m ... = m * (n / 0) : by rewrite nat.div_zero ... = m * (n / k) : by rewrite H1) (assume H1 : k > 0, have H2 : n = n / k * k, from (nat.div_mul_cancel H)⁻¹, calc m * n / k = m * (n / k * k) / k : by rewrite -H2 ... = m * (n / k) * k / k : by rewrite mul.assoc ... = m * (n / k) : nat.mul_div_cancel _ H1) -/ theorem dvd_of_mul_dvd_mul_left {m n k : ℕ} (kpos : k > 0) (H : k * m ∣ k * n) : m ∣ n := dvd.elim H (take l, assume H1 : k * n = k * m * l, have H2 : n = m * l, from eq_of_mul_eq_mul_left kpos (eq.trans H1 $ mul.assoc k m l), dvd.intro (eq.symm H2)) theorem dvd_of_mul_dvd_mul_right {m n k : ℕ} (kpos : k > 0) (H : m * k ∣ n * k) : m ∣ n := nat.dvd_of_mul_dvd_mul_left kpos (mul.comm n k ▸ mul.comm m k ▸ H) lemma dvd_of_eq_mul (i j n : nat) : n = j*i → j ∣ n := sorry -- begin intros, subst n, apply dvd_mul_right end theorem div_dvd_div {k m n : ℕ} (H1 : k ∣ m) (H2 : m ∣ n) : m / k ∣ n / k := have H3 : m = m / k * k, from eq.symm (nat.div_mul_cancel H1), have H4 : n = n / k * k, from eq.symm (nat.div_mul_cancel (dvd.trans H1 H2)), or.elim (eq_zero_or_pos k) (assume H5 : k = 0, have H6: n / k = 0, from (eq.trans (congr_arg _ H5) $ nat.div_zero n), eq.symm H6 ▸ dvd_zero (m / k)) (assume H5 : k > 0, nat.dvd_of_mul_dvd_mul_right H5 (H3 ▸ H4 ▸ H2)) protected theorem div_eq_iff_eq_mul_right {m n : ℕ} (k : ℕ) (H : n > 0) (H' : n ∣ m) : m / n = k ↔ m = n * k := sorry /- iff.intro (assume H1, by rewrite [-H1, nat.mul_div_cancel' H']) (assume H1, by rewrite [H1, !nat.mul_div_cancel_left H]) -/ protected theorem div_eq_iff_eq_mul_left {m n : ℕ} (k : ℕ) (H : n > 0) (H' : n ∣ m) : m / n = k ↔ m = k * n := mul.comm n k ▸ nat.div_eq_iff_eq_mul_right k H H' protected theorem eq_mul_of_div_eq_right {m n k : ℕ} (H1 : n ∣ m) (H2 : m / n = k) : m = n * k := sorry /- calc m = n * (m / n) : by rewrite (nat.mul_div_cancel' H1) ... = n * k : by rewrite H2 -/ protected theorem div_eq_of_eq_mul_right {m n k : ℕ} (H1 : n > 0) (H2 : m = n * k) : m / n = k := sorry /- calc m / n = n * k / n : by rewrite -H2 ... = k : by rewrite (!nat.mul_div_cancel_left H1) -/ protected theorem eq_mul_of_div_eq_left {m n k : ℕ} (H1 : n ∣ m) (H2 : m / n = k) : m = k * n := mul.comm n k ▸ nat.eq_mul_of_div_eq_right H1 H2 protected theorem div_eq_of_eq_mul_left {m n k : ℕ} (H1 : n > 0) (H2 : m = k * n) : m / n = k := nat.div_eq_of_eq_mul_right H1 (mul.comm k n ▸ H2) lemma add_mod_eq_of_dvd (i j n : nat) : n ∣ j → (i + j) % n = i % n := sorry /- assume h, obtain k (hk : j = n * k), from exists_eq_mul_right_of_dvd h, begin subst j, rewrite mul.comm, apply add_mul_mod_self end -/ /- / and ordering -/ lemma le_of_dvd {m n : nat} : n > 0 → m ∣ n → m ≤ n := sorry /- assume (h₁ : n > 0) (h₂ : m ∣ n), have h₃ : n % m = 0, from mod_eq_zero_of_dvd h₂, by_contradiction (λ nle : ¬ m ≤ n, have h₄ : m > n, from lt_of_not_ge nle, have h₅ : n % m = n, from mod_eq_of_lt h₄, begin rewrite h₃ at h₅, subst n, exact absurd h₁ (lt.irrefl 0) end) -/ theorem div_mul_le (m n : ℕ) : m / n * n ≤ m := sorry /- calc m = m / n * n + m % n : by rewrite -eq_div_mul_add_mod ... ≥ m / n * n : !le_add_right -/ protected theorem div_le_of_le_mul {m n k : ℕ} (H : m ≤ n * k) : m / k ≤ n := sorry /- or.elim (eq_zero_or_pos k) (assume H1 : k = 0, calc m / k = m / 0 : by rewrite H1 ... = 0 : by rewrite nat.div_zero ... ≤ n : !zero_le) (assume H1 : k > 0, le_of_mul_le_mul_right (calc m / k * k ≤ m / k * k + m % k : !le_add_right ... = m : by rewrite -eq_div_mul_add_mod ... ≤ n * k : H) H1) -/ protected theorem div_le_self (m n : ℕ) : m / n ≤ m := sorry /- nat.cases_on n (!nat.div_zero⁻¹ ▸ !zero_le) take n, have H : m ≤ m * succ n, from calc m = m * 1 : by rewrite mul_one ... ≤ m * succ n : !mul_le_mul_left (succ_le_succ !zero_le), nat.div_le_of_le_mul H -/ protected theorem mul_le_of_le_div {m n k : ℕ} (H : m ≤ n / k) : m * k ≤ n := calc m * k ≤ n / k * k : mul_le_mul_right k H ... ≤ n : div_mul_le n k protected theorem le_div_of_mul_le {m n k : ℕ} (H1 : k > 0) (H2 : m * k ≤ n) : m ≤ n / k := sorry /- have H3 : m * k < (succ (n / k)) * k, from calc m * k ≤ n : H2 ... = n / k * k + n % k : by rewrite -eq_div_mul_add_mod ... < n / k * k + k : add_lt_add_left (!mod_lt H1) _ ... = (succ (n / k)) * k : by rewrite succ_mul, le_of_lt_succ (lt_of_mul_lt_mul_right H3) -/ protected theorem le_div_iff_mul_le {m n k : ℕ} (H : k > 0) : m ≤ n / k ↔ m * k ≤ n := iff.intro nat.mul_le_of_le_div (nat.le_div_of_mul_le H) protected theorem div_le_div {m n : ℕ} (k : ℕ) (H : m ≤ n) : m / k ≤ n / k := sorry /- by_cases_zero_pos k (by rewrite [*nat.div_zero]) (take k, assume H1 : k > 0, nat.le_div_of_mul_le H1 (le.trans !div_mul_le H)) -/ protected theorem div_lt_of_lt_mul {m n k : ℕ} (H : m < n * k) : m / k < n := sorry /- lt_of_mul_lt_mul_right (calc m / k * k ≤ m / k * k + m % k : !le_add_right ... = m : by rewrite -eq_div_mul_add_mod ... < n * k : H) -/ protected theorem lt_mul_of_div_lt {m n k : ℕ} (H1 : k > 0) (H2 : m / k < n) : m < n * k := sorry /- have H3 : succ (m / k) * k ≤ n * k, from !mul_le_mul_right (succ_le_of_lt H2), have H4 : m / k * k + k ≤ n * k, by rewrite [succ_mul at H3]; apply H3, calc m = m / k * k + m % k : by rewrite -eq_div_mul_add_mod ... < m / k * k + k : add_lt_add_left (!mod_lt H1) _ ... ≤ n * k : H4 -/ protected theorem div_lt_iff_lt_mul {m n k : ℕ} (H : k > 0) : m / k < n ↔ m < n * k := iff.intro (nat.lt_mul_of_div_lt H) nat.div_lt_of_lt_mul protected theorem div_le_iff_le_mul_of_div {m n : ℕ} (k : ℕ) (H : n > 0) (H' : n ∣ m) : m / n ≤ k ↔ m ≤ k * n := sorry -- by refine iff.trans (!le_iff_mul_le_mul_right H) _; rewrite [!nat.div_mul_cancel H'] protected theorem le_mul_of_div_le_of_div {m n k : ℕ} (H1 : n > 0) (H2 : n ∣ m) (H3 : m / n ≤ k) : m ≤ k * n := iff.mp (nat.div_le_iff_le_mul_of_div k H1 H2) H3 -- needed for integer division theorem mul_sub_div_of_lt {m n k : ℕ} (H : k < m * n) : (m * n - (k + 1)) / m = n - k / m - 1 := sorry /- begin have H1 : k / m < n, from nat.div_lt_of_lt_mul (!mul.comm ▸ H), have H2 : n - k / m ≥ 1, from nat.le_sub_of_add_le (calc 1 + k / m = succ (k / m) : by rewrite add.comm ... ≤ n : succ_le_of_lt H1), have H3 : n - k / m = n - k / m - 1 + 1, from (nat.sub_add_cancel H2)⁻¹, have H4 : m > 0, from pos_of_ne_zero (assume H': m = 0, not_lt_zero k (begin rewrite [H' at H, zero_mul at H], exact H end)), have H5 : k % m + 1 ≤ m, from succ_le_of_lt (!mod_lt H4), have H6 : m - (k % m + 1) < m, from nat.sub_lt_self H4 !succ_pos, calc (m * n - (k + 1)) / m = (m * n - (k / m * m + k % m + 1)) / m : by rewrite -eq_div_mul_add_mod ... = (m * n - k / m * m - (k % m + 1)) / m : by rewrite [*nat.sub_sub] ... = ((n - k / m) * m - (k % m + 1)) / m : by rewrite [mul.comm m, nat.mul_sub_right_distrib] ... = ((n - k / m - 1) * m + m - (k % m + 1)) / m : by rewrite [H3 at {1}, right_distrib, nat.one_mul] ... = ((n - k / m - 1) * m + (m - (k % m + 1))) / m : by rewrite (nat.add_sub_assoc H5 _) ... = (m - (k % m + 1)) / m + (n - k / m - 1) : by rewrite [add.comm, (add_mul_div_self H4)] ... = n - k / m - 1 : by rewrite [div_eq_zero_of_lt H6, zero_add] end -/ private lemma div_div_aux (a b c : nat) : b > 0 → c > 0 → (a / b) / c = a / (b * c) := sorry /- suppose b > 0, suppose c > 0, nat.strong_induction_on a (λ a ih, let k₁ := a / (b*c) in let k₂ := a %(b*c) in have bc_pos : b*c > 0, from mul_pos `b > 0` `c > 0`, have k₂ < b * c, from mod_lt _ bc_pos, have k₂ ≤ a, from !mod_le, or.elim (eq_or_lt_of_le this) (suppose k₂ = a, have i₁ : a < b * c, by rewrite -this; assumption, have k₁ = 0, from div_eq_zero_of_lt i₁, have a / b < c, by rewrite [mul.comm at i₁]; exact nat.div_lt_of_lt_mul i₁, begin rewrite [`k₁ = 0`], show (a / b) / c = 0, from div_eq_zero_of_lt `a / b < c` end) (suppose k₂ < a, have a = k₁*(b*c) + k₂, from eq_div_mul_add_mod a (b*c), have a / b = k₁*c + k₂ / b, by rewrite [this at {1}, mul.comm b c at {2}, -mul.assoc, add.comm, add_mul_div_self `b > 0`, add.comm], have e₁ : (a / b) / c = k₁ + (k₂ / b) / c, by rewrite [this, add.comm, add_mul_div_self `c > 0`, add.comm], have e₂ : (k₂ / b) / c = k₂ / (b * c), from ih k₂ `k₂ < a`, have e₃ : k₂ / (b * c) = 0, from div_eq_zero_of_lt `k₂ < b * c`, have (k₂ / b) / c = 0, by rewrite [e₂, e₃], show (a / b) / c = k₁, by rewrite [e₁, this])) -/ protected lemma div_div_eq_div_mul (a b c : nat) : (a / b) / c = a / (b * c) := sorry /- begin cases b with b, rewrite [zero_mul, *nat.div_zero, nat.zero_div], cases c with c, rewrite [mul_zero, *nat.div_zero], apply div_div_aux a (succ b) (succ c) dec_trivial dec_trivial end -/ lemma div_lt_of_ne_zero : ∀ {n : nat}, n ≠ 0 → n / 2 < n := sorry /- | 0 h := absurd rfl h | (succ n) h := begin apply nat.div_lt_of_lt_mul, rewrite [-add_one, right_distrib], change n + 1 < (n * 1 + n) + (1 + 1), rewrite [mul_one, -add.assoc], apply add_lt_add_right, show n < n + n + 1, begin rewrite [add.assoc, -add_zero n at {1}], apply add_lt_add_left, apply zero_lt_succ end end -/ end nat attribute [instance, priority nat.prio] nat.nat_has_divide nat.nat_has_mod nat.dvd.decidable_rel
6fe0c3eabc20fc24bbcf094943498d18ecc7b4b0
28be2ab6091504b6ba250b367205fb94d50ab284
/src/game/world10/level6.lean
f36b40ccbf99f53240d90c7d05bbea1dd637dbbe
[ "Apache-2.0" ]
permissive
postmasters/natural_number_game
87304ac22e5e1c5ac2382d6e523d6914dd67a92d
38a7adcdfdb18c49c87b37831736c8f15300d821
refs/heads/master
1,649,856,819,031
1,586,444,676,000
1,586,444,676,000
255,006,061
0
0
Apache-2.0
1,586,664,599,000
1,586,664,598,000
null
UTF-8
Lean
false
false
846
lean
import game.world10.level5 -- hide namespace mynat -- hide /- # Inequality world. ## Level 6: `le_antisymm` In Advanced Addition World you proved `eq_zero_of_add_right_eq_self (a b : mynat) : a + b = a → b = 0`. This might be useful in this level. -/ /- Lemma $\le$ is antisymmetric. In other words, if $a\le b$ and $b\le a$ then $a = b$. -/ theorem le_antisymm (a b : mynat) (hab : a ≤ b) (hba : b ≤ a) : a = b := begin [nat_num_game] cases hab with c hc, cases hba with d hd, rw hc at hd, rw add_assoc at hd, symmetry at hd, have h := eq_zero_of_add_right_eq_self _ _ hd, have h2 := add_right_eq_zero h, rw h2 at hc, rw hc, exact add_zero a, end /- Congratulations -- you just proved that the natural numbers are a partial order! -/ instance : partial_order mynat := by structure_helper end mynat -- hide
2c7e1f1925a058879d3787b0191b9be0d9678f7c
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/topology/metric_space/basic.lean
02ed06bd2c0d469d8d914fcba805c0a6d05f16c4
[ "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
68,117
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity -/ import data.real.nnreal topology.metric_space.emetric_space topology.algebra.ordered open lattice set filter classical topological_space noncomputable theory open_locale uniformity open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Construct a uniform structure from a distance function and metric space axioms -/ def uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) section prio set_option default_priority 100 -- see Note [default priority] /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. In the same way, each metric space induces an emetric space structure. It is included in the structure, but filled in by default. When one instantiates a metric space structure, for instance a product structure, this makes it possible to use a uniform structure and an edistance that are exactly the ones for the uniform spaces product and the emetric spaces products, thereby ensuring that everything in defeq in diamonds.-/ class metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (edist : α → α → ennreal := λx y, ennreal.of_real (dist x y)) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac) (to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : 𝓤 α = ⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) end prio variables [metric_space α] @[priority 100] -- see Note [lower instance priority] instance metric_space.to_uniform_space' : uniform_space α := metric_space.to_uniform_space α @[priority 200] -- see Note [lower instance priority] instance metric_space.to_has_edist : has_edist α := ⟨metric_space.edist⟩ @[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) := metric_space.edist_dist _ x y @[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle lemma dist_triangle4 (x y z w : α) : dist x w ≤ dist x y + dist y z + dist z w := calc dist x w ≤ dist x z + dist z w : dist_triangle x z w ... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (metric_space.dist_triangle x y z) _ lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) : dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) := by rw [add_left_comm, dist_comm x₁, ← add_assoc]; apply dist_triangle4 lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) : dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ := by rw [add_right_comm, dist_comm y₁]; apply dist_triangle4 /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) : dist (f m) (f n) ≤ (finset.Ico m n).sum (λ i, dist (f i) (f (i + 1))) := begin revert n, apply nat.le_induction, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, dist_self] }, { assume n hn hrec, calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _ ... ≤ (finset.Ico m n).sum _ + _ : add_le_add hrec (le_refl _) ... = (finset.Ico m (n+1)).sum _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) : dist (f 0) (f n) ≤ (finset.range n).sum (λ i, dist (f i) (f (i + 1))) := finset.Ico.zero_bot n ▸ dist_le_Ico_sum_dist f (nat.zero_le n) /-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f m) (f n) ≤ (finset.Ico m n).sum d := le_trans (dist_le_Ico_sum_dist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f 0) (f n) ≤ (finset.range n).sum d := finset.Ico.zero_bot n ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd) theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this two_pos @[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y := by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y) @[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b := abs_of_nonneg dist_nonneg theorem eq_of_forall_dist_le {x y : α} (h : ∀ε, ε > 0 → dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) /-- Distance as a nonnegative real number. -/ def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩ /--Express `nndist` in terms of `edist`-/ lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal := by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real] /--Express `edist` in terms of `nndist`-/ lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) := by { rw [edist_dist, nndist, ennreal.of_real_eq_coe_nnreal] } /--In a metric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := by rw [edist_dist x y]; apply ennreal.coe_ne_top /--`nndist x x` vanishes-/ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) /--Express `dist` in terms of `nndist`-/ lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl /--Express `nndist` in terms of `dist`-/ lemma nndist_dist (x y : α) : nndist x y = nnreal.of_real (dist x y) := by rw [dist_nndist, nnreal.of_real_coe] /--Deduce the equality of points with the vanishing of the nonnegative distance-/ theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa [nnreal.eq_iff.symm] using dist_comm x y /--Characterize the equality of points with the vanishing of the nonnegative distance-/ @[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y := by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, zero_eq_dist] /--Triangle inequality for the nonnegative distance-/ theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := by simpa [nnreal.coe_le] using dist_triangle x y z theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := by simpa [nnreal.coe_le] using dist_triangle_left x y z theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := by simpa [nnreal.coe_le] using dist_triangle_right x y z /--Express `dist` in terms of `edist`-/ lemma dist_edist (x y : α) : dist x y = (edist x y).to_real := by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)] namespace metric /- instantiate metric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y, by simp; intros h; apply le_of_lt h theorem pos_of_mem_ball (hy : y ∈ ball x ε) : ε > 0 := lt_of_le_of_lt dist_nonneg hy theorem mem_ball_self (h : ε > 0) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption theorem mem_closed_ball_self (h : ε ≥ 0) : x ∈ closed_ball x ε := show dist x x ≤ ε, by rw dist_self; assumption theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball {α : Type u} [metric_space α] {ε₁ ε₂ : ℝ} {x : α} (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' two_pos] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ theorem ball_eq_empty_iff_nonpos : ε ≤ 0 ↔ ball x ε = ∅ := (eq_empty_iff_forall_not_mem.trans ⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0, λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩).symm theorem uniformity_dist : 𝓤 α = (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}) := metric_space.uniformity_dist _ theorem uniformity_dist' : 𝓤 α = (⨅ε:{ε:ℝ // ε>0}, principal {p:α×α | dist p.1 p.2 < ε.val}) := by simp [infi_subtype]; exact uniformity_dist theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := begin rw [uniformity_dist', mem_infi], simp [subset_def], exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (≥)] {contextual := tt}⟩, exact ⟨⟨1, zero_lt_one⟩⟩ end theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_iff [metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniform_continuous_def.trans ⟨λ H ε ε0, mem_uniformity_dist.1 $ H _ $ dist_mem_uniformity ε0, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_uniformity_dist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩ theorem uniform_embedding_iff [metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between metric spaces is a uniform embedding if and only if the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [metric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : dist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : dist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ /-- A metric space space is totally bounded if one can reconstruct up to any ε>0 any element of the space from finitely many data. -/ lemma totally_bounded_of_finite_discretization {α : Type u} [metric_space α] {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin classical, by_cases hs : s = ∅, { rw hs, exact totally_bounded_empty }, rcases exists_mem_of_ne_empty hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, let Finv := function.inv_fun F, refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩, let x' := Finv (F ⟨x, xs⟩), have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩, simp only [set.mem_Union, set.mem_range], exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩ end protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := cauchy_iff.trans $ and_congr iff.rfl ⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (dist_mem_uniformity ε0) in ⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, tf, h⟩ := H ε ε0 in ⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩ theorem nhds_eq : 𝓝 x = (⨅ε:{ε:ℝ // ε>0}, principal (ball x ε.val)) := begin rw [nhds_eq_uniformity, uniformity_dist', lift'_infi], { apply congr_arg, funext ε, rw [lift'_principal], { simp [ball, dist_comm] }, { exact monotone_preimage } }, { exact ⟨⟨1, zero_lt_one⟩⟩ }, { intros, refl } end theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := begin rw [nhds_eq, mem_infi], { simp }, { intros y z, cases y with y hy, cases z with z hz, refine ⟨⟨min y z, lt_min hy hz⟩, _⟩, simp [ball_subset_ball, min_le_left, min_le_right, (≥)] }, { exact ⟨⟨1, zero_lt_one⟩⟩ } end theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp [is_open_iff_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) @[nolint] theorem mem_nhds_within_iff {t : set α} : s ∈ nhds_within x t ↔ ∃ε>0, ball x ε ∩ t ⊆ s := begin rw [mem_nhds_within_iff_exists_mem_nhds_inter], split, { rintros ⟨u, hu, H⟩, rcases mem_nhds_iff.1 hu with ⟨ε, ε_pos, hε⟩, exact ⟨ε, ε_pos, subset.trans (inter_subset_inter_left _ hε) H⟩ }, { rintros ⟨ε, ε_pos, H⟩, exact ⟨ball x ε, ball_mem_nhds x ε_pos, H⟩ } end @[nolint] theorem tendsto_nhds_within_nhds_within [metric_space β] {t : set β} {f : α → β} {a b} : tendsto f (nhds_within a s) (nhds_within b t) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε := begin split, { assume H ε ε_pos, have : ball b ε ∩ t ∈ nhds_within b t, by { rw mem_nhds_within_iff, exact ⟨ε, ε_pos, subset.refl _⟩ }, rcases mem_nhds_within_iff.1 (H this) with ⟨δ, δ_pos, hδ⟩, exact ⟨δ, δ_pos, λx xs dx, ⟨(hδ ⟨dx, xs⟩).2, (hδ ⟨dx, xs⟩).1⟩⟩ }, { assume H u hu, rcases mem_nhds_within_iff.1 hu with ⟨ε, ε_pos, hε⟩, rcases H ε ε_pos with ⟨δ, δ_pos, hδ⟩, rw [mem_map, mem_nhds_within_iff], exact ⟨δ, δ_pos, λx hx, hε ⟨(hδ hx.2 hx.1).2, (hδ hx.2 hx.1).1⟩⟩ } end @[nolint] theorem tendsto_nhds_within_nhds [metric_space β] {f : α → β} {a b} : tendsto f (nhds_within a s) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ, tendsto_nhds_within_nhds_within], simp } @[nolint] theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ, ← nhds_within_univ, tendsto_nhds_within_nhds_within], simp } theorem continuous_iff [metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds theorem exists_delta_of_continuous [metric_space β] {f : α → β} {ε : ℝ} (hf : continuous f) (hε : ε > 0) (b : α) : ∃ δ > 0, ∀a, dist a b ≤ δ → dist (f a) (f b) < ε := let ⟨δ, δ_pos, hδ⟩ := continuous_iff.1 hf b ε hε in ⟨δ / 2, half_pos δ_pos, assume a ha, hδ a $ lt_of_le_of_lt ha $ div_two_lt_of_pos δ_pos⟩ theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∃ n ∈ f, ∀x ∈ n, dist (u x) a < ε := by simp only [metric.nhds_eq, tendsto_infi, subtype.forall, tendsto_principal, mem_ball]; exact forall_congr (assume ε, forall_congr (assume hε, exists_sets_subset_iff.symm)) theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∃ n ∈ 𝓝 a, ∀b ∈ n, dist (f b) (f a) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε := by simp only [metric.nhds_eq, tendsto_infi, subtype.forall, tendsto_at_top_principal]; refl end metric open metric @[priority 100] -- see Note [lower instance priority] instance metric_space.to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-Instantiate a metric space as an emetric space. Before we can state the instance, we need to show that the uniform structure coming from the edistance and the distance coincide. -/ /-- Expressing the uniformity in terms of `edist` -/ protected lemma metric.mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := begin refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { refine ⟨ennreal.of_real ε, _, λ a b, _⟩, { rwa [gt, ennreal.of_real_pos] }, { rw [edist_dist, ennreal.of_real_lt_of_real_iff ε0], exact Hε } }, { rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩, rw [ennreal.of_real_pos] at ε0', refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩, rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] } end protected theorem metric.uniformity_edist' : 𝓤 α = (⨅ε:{ε:ennreal // ε>0}, principal {p:α×α | edist p.1 p.2 < ε.val}) := begin ext s, rw mem_infi, { simp [metric.mem_uniformity_edist, subset_def] }, { rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩, simp [lt_min_iff, (≥)] {contextual := tt} }, { exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ } end theorem uniformity_edist : 𝓤 α = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) := by simpa [infi_subtype] using @metric.uniformity_edist' α _ /-- A metric space induces an emetric space -/ @[priority 100] -- see Note [lower instance priority] instance metric_space.to_emetric_space : emetric_space α := { edist := edist, edist_self := by simp [edist_dist], eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h, edist_comm := by simp only [edist_dist, dist_comm]; simp, edist_triangle := assume x y z, begin simp only [edist_dist, (ennreal.of_real_add _ _).symm, dist_nonneg], rw ennreal.of_real_le_of_real_iff _, { exact dist_triangle _ _ _ }, { simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg } end, uniformity_edist := uniformity_edist, ..‹metric_space α› } /-- Balls defined using the distance or the edistance coincide -/ lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε := begin classical, by_cases h : 0 < ε, { ext y, by simp [edist_dist, ennreal.of_real_lt_of_real_iff h] }, { have h' : ε ≤ 0, by simpa using h, have A : ball x ε = ∅, by simpa [ball_eq_empty_iff_nonpos.symm], have B : emetric.ball x (ennreal.of_real ε) = ∅, by simp [ennreal.of_real_eq_zero.2 h', emetric.ball_eq_empty_iff], rwa [A, B] } end /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) : emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε := by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α) (H : @uniformity _ U = @uniformity _ (metric_space.to_uniform_space α)) : metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, dist_comm := dist_comm, dist_triangle := dist_triangle, edist := edist, edist_dist := edist_dist, to_uniform_space := U, uniformity_dist := H.trans (metric_space.uniformity_dist α) } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : metric_space α := let m : metric_space α := { dist := dist, eq_of_dist_eq_zero := λx y hxy, by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy, dist_self := λx, by simp [h], dist_comm := λx y, by simp [h, emetric_space.edist_comm], dist_triangle := λx y z, begin simp only [h], rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _), ennreal.to_real_le_to_real (edist_ne_top _ _)], { exact edist_triangle _ _ _ }, { simp [ennreal.add_eq_top, edist_ne_top] } end, edist := λx y, edist x y, edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in metric_space.replace_uniformity m (by rw [uniformity_edist, uniformity_edist']; refl) /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. -/ def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : metric_space α := emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := begin -- this follows from the same criterion in emetric spaces. We just need to translate -- the convergence assumption from `dist` to `edist` apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)), { simp [hB] }, { assume u Hu, apply H, assume N n m hn hm, rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist], exact Hu N n m hn hm } end theorem metric.complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := emetric.complete_of_cauchy_seq_tendsto section real /-- Instantiate the reals as a metric space. -/ instance real.metric_space : metric_space ℝ := { dist := λx y, abs (x - y), dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [add_neg_eq_zero], dist_comm := assume x y, abs_sub _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x := by simp [real.dist_eq] instance : order_topology ℝ := order_topology_of_nhds_abs $ λ x, begin simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r, by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]], apply le_antisymm, { simp [le_infi_iff], exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) }, { intros s h, rcases mem_nhds_iff.1 h with ⟨ε, ε0, ss⟩, exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) }, end lemma closed_ball_Icc {x r : ℝ} : closed_ball x r = Icc (x-r) (x+r) := by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq, abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le] lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := begin apply tendsto_of_tendsto_of_tendsto_of_le_of_le (tendsto_const_nhds) g0; simp [*]; exact filter.univ_mem_sets end theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) := begin simp only [uniformity_dist', nhds_eq, comap_infi, comap_principal], congr, funext ε, rw [principal_eq_iff_eq], ext ⟨a, b⟩, simp [real.dist_0_eq_abs] end lemma cauchy_seq_iff_tendsto_dist_at_top_0 [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) := by rw [cauchy_seq_iff_prod_map, metric.uniformity_eq_comap_nhds_zero, ← map_le_iff_le_comap, filter.map_map, tendsto, prod.map_def] end real section cauchy_seq variables [inhabited β] [semilattice_sup β] /-- In a metric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := begin unfold cauchy_seq, rw metric.cauchy_iff, simp only [true_and, exists_prop, filter.mem_at_top_sets, filter.at_top_ne_bot, filter.mem_map, ne.def, filter.map_eq_bot_iff, not_false_iff, set.mem_set_of_eq], split, { intros H ε εpos, rcases H ε εpos with ⟨t, ⟨N, hN⟩, ht⟩, exact ⟨N, λm n hm hn, ht _ _ (hN _ hm) (hN _ hn)⟩ }, { intros H ε εpos, rcases H (ε/2) (half_pos εpos) with ⟨N, hN⟩, existsi ball (u N) (ε/2), split, { exact ⟨N, λx hx, hN _ _ hx (le_refl N)⟩ }, { exact λx y hx hy, calc dist x y ≤ dist x (u N) + dist y (u N) : dist_triangle_right _ _ _ ... < ε/2 + ε/2 : add_lt_add hx hy ... = ε : add_halves _ } } end /-- A variation around the metric characterization of Cauchy sequences -/ theorem metric.cauchy_seq_iff' {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε := begin rw metric.cauchy_seq_iff, split, { intros H ε εpos, rcases H ε εpos with ⟨N, hN⟩, exact ⟨N, λn hn, hN _ _ hn (le_refl N)⟩ }, { intros H ε εpos, rcases H (ε/2) (half_pos εpos) with ⟨N, hN⟩, exact ⟨N, λ m n hm hn, calc dist (u m) (u n) ≤ dist (u m) (u N) + dist (u n) (u N) : dist_triangle_right _ _ _ ... < ε/2 + ε/2 : add_lt_add (hN _ hm) (hN _ hn) ... = ε : add_halves _⟩ } end /-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ) (h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) : cauchy_seq s := metric.cauchy_seq_iff.2 $ λ ε ε0, (metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn, calc dist (s m) (s n) ≤ b N : h m n N hm hn ... ≤ abs (b N) : le_abs_self _ ... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl ... < ε : (hN _ (le_refl N)) /-- A Cauchy sequence on the natural numbers is bounded. -/ theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) : ∃ R > 0, ∀ m n, dist (u m) (u n) < R := begin rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩, suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R, { rcases this with ⟨R, R0, H⟩, exact ⟨_, add_pos R0 R0, λ m n, lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ }, let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)), refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩, cases le_or_lt N n, { exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) }, { have : _ ≤ R := finset.le_sup (finset.mem_range.2 h), exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) } end /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ, (∀ n, 0 ≤ b n) ∧ (∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧ tendsto b at_top (𝓝 0) := ⟨λ hs, begin /- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`. First, we prove that all these distances are bounded, as otherwise the Sup would not make sense. -/ let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N}, have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x, { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩, exact le_of_lt (hR m n) }, have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))), { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) }, -- Prove that it bounds the distances of points in the Cauchy sequence have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ real.Sup (S N) := λ m n N hm hn, real.le_Sup _ (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩, have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩, have S0 := λ n, real.le_Sup _ (hS n) (S0m n), -- Prove that it tends to `0`, by using the Cauchy property of `s` refine ⟨λ N, real.Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩, refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _), rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)], refine lt_of_le_of_lt (real.Sup_le_ub _ ⟨_, S0m _⟩ _) (half_lt_self ε0), rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩, exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn')) end, λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩ end cauchy_seq def metric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, edist := λ x y, edist (f x) (f y), edist_dist := λ x y, edist_dist _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced subtype.val (λ x y, subtype.eq) t theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist x.1 y.1 := rfl section nnreal instance : metric_space nnreal := by unfold nnreal; apply_instance lemma nnreal.dist_eq (a b : nnreal) : dist a b = abs ((a:ℝ) - b) := rfl lemma nnreal.nndist_eq (a b : nnreal) : nndist a b = max (a - b) (b - a) := begin wlog h : a ≤ b, { apply nnreal.coe_eq.1, rw [nnreal.sub_eq_zero h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq, nnreal.coe_sub h, abs, neg_sub], apply max_eq_right, linarith [nnreal.coe_le.2 h] }, rwa [nndist_comm, max_comm] end end nnreal section prod instance prod.metric_space_max [metric_space β] : metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_dist := assume x y, begin have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h, rw [edist_dist, edist_dist, this.map_max.symm] end, uniformity_dist := begin refine uniformity_prod.trans _, simp [uniformity_dist, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.dist_eq [metric_space β] {x y : α × β} : dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl end prod theorem uniform_continuous_dist' : uniform_continuous (λp:α×α, dist p.1 p.2) := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous_dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := uniform_continuous_dist'.comp (hf.prod_mk hg) theorem continuous_dist' : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist'.continuous theorem continuous_dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := continuous_dist'.comp (hf.prod_mk hg) theorem tendsto_dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) := have tendsto (λp:α×α, dist p.1 p.2) (𝓝 (a, b)) (𝓝 (dist a b)), from continuous_iff_continuous_at.mp continuous_dist' (a, b), tendsto.comp (by rw [nhds_prod_eq] at this; exact this) (hf.prod_mk hg) lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a := have h₁ : ∀ε, (λa', dist a' a) ⁻¹' ball 0 ε ⊆ ball a ε, by simp [subset_def, real.dist_0_eq_abs], have h₂ : tendsto (λa', dist a' a) (𝓝 a) (𝓝 (dist a a)), from tendsto_dist tendsto_id tendsto_const_nhds, le_antisymm (by simp [h₁, nhds_eq, infi_le_infi, principal_mono, -le_principal_iff, -le_infi_iff]) (by simpa [map_le_iff_le_comap.symm, tendsto] using h₂) lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] lemma uniform_continuous_nndist' : uniform_continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_subtype_mk uniform_continuous_dist' _ lemma continuous_nndist' : continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_nndist'.continuous lemma continuous_nndist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) := continuous_nndist'.comp (hf.prod_mk hg) lemma tendsto_nndist' (a b :α) : tendsto (λp:α×α, nndist p.1 p.2) (filter.prod (𝓝 a) (𝓝 b)) (𝓝 (nndist a b)) := by rw [← nhds_prod_eq]; exact continuous_iff_continuous_at.1 continuous_nndist' _ namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_dist continuous_id continuous_const) continuous_const /-- ε-characterization of the closure in metric spaces-/ theorem mem_closure_iff' {α : Type u} [metric_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := ⟨begin intros ha ε hε, have A : ball a ε ∩ s ≠ ∅ := mem_closure_iff.1 ha _ is_open_ball (mem_ball_self hε), cases ne_empty_iff_exists_mem.1 A with b hb, simp, exact ⟨b, ⟨hb.2, by have B := hb.1; simpa [mem_ball'] using B⟩⟩ end, begin intros H, apply mem_closure_iff.2, intros o ho ao, rcases is_open_iff.1 ho a ao with ⟨ε, ⟨εpos, hε⟩⟩, rcases H ε εpos with ⟨b, ⟨bs, bdist⟩⟩, have B : b ∈ o ∩ s := ⟨hε (by simpa [dist_comm]), bs⟩, apply ne_empty_of_mem B end⟩ lemma mem_closure_range_iff {α : Type u} [metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε := iff.intro ( assume ha ε hε, let ⟨b, ⟨hb, hab⟩⟩ := metric.mem_closure_iff'.1 ha ε hε in let ⟨k, hk⟩ := mem_range.1 hb in ⟨k, by { rw hk, exact hab }⟩ ) ( assume h, metric.mem_closure_iff'.2 (assume ε hε, let ⟨k, hk⟩ := h ε hε in ⟨e k, ⟨mem_range.2 ⟨k, rfl⟩, hk⟩⟩) ) lemma mem_closure_range_iff_nat {α : Type u} [metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) := ⟨assume ha n, mem_closure_range_iff.1 ha (1 / ((n : ℝ) + 1)) nat.one_div_pos_of_nat, assume h, mem_closure_range_iff.2 $ assume ε hε, let ⟨n, hn⟩ := exists_nat_one_div_lt hε in let ⟨k, hk⟩ := h n in ⟨k, calc dist a (e k) < 1 / ((n : ℝ) + 1) : hk ... < ε : hn⟩⟩ theorem mem_of_closed' {α : Type u} [metric_space α] {s : set α} (hs : is_closed s) {a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := by simpa only [closure_eq_of_is_closed hs] using @mem_closure_iff' _ _ s a end metric section pi open finset lattice variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] /-- A finite product of metric spaces is a metric space, with the sup distance. -/ instance metric_space_pi : metric_space (Πb, π b) := begin /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ refine emetric_space.to_metric_space_of_dist (λf g, ((sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)) _ _, show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤, { assume x y, rw ← lt_top_iff_ne_top, have : (⊥ : ennreal) < ⊤ := ennreal.coe_lt_top, simp [edist, this], assume b, rw lt_top_iff_ne_top, exact edist_ne_top (x b) (y b) }, show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) = ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))), { assume x y, have : sup univ (λ (b : β), edist (x b) (y b)) = ↑(sup univ (λ (b : β), nndist (x b) (y b))), { simp [edist_nndist], refine eq.symm (comp_sup_eq_sup_comp _ _ _), exact (assume x y h, ennreal.coe_le_coe.2 h), refl }, rw this, refl } end lemma dist_pi_def (f g : Πb, π b) : dist f g = (sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) : dist f g < r ↔ ∀b, dist (f b) (g b) < r := begin lift r to nnreal using le_of_lt hr, rw_mod_cast [dist_pi_def, finset.sup_lt_iff], { simp [nndist], refl }, { exact hr } end lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) : dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r := begin lift r to nnreal using hr, rw_mod_cast [dist_pi_def, finset.sup_le_iff], simp [nndist], refl end /-- An open ball in a product space is a product of open balls. The assumption `0 < r` is necessary for the case of the empty product. -/ lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) : ball x r = { y | ∀b, y b ∈ ball (x b) r } := by { ext p, simp [dist_pi_lt_iff hr] } /-- A closed ball in a product space is a product of closed balls. The assumption `0 ≤ r` is necessary for the case of the empty product. -/ lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) : closed_ball x r = { y | ∀b, y b ∈ closed_ball (x b) r } := by { ext p, simp [dist_pi_le_iff hr] } end pi section compact /-- Any compact set in a metric space can be covered by finitely many balls of a given positive radius -/ lemma finite_cover_balls_of_compact {α : Type u} [metric_space α] {s : set α} (hs : compact s) {e : ℝ} (he : 0 < e) : ∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e := begin apply hs.elim_finite_subcover_image, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end alias finite_cover_balls_of_compact ← compact.finite_cover_balls end compact section proper_space open metric /-- A metric space is proper if all closed balls are compact. -/ class proper_space (α : Type u) [metric_space α] : Prop := (compact_ball : ∀x:α, ∀r, compact (closed_ball x r)) /-- If all closed balls of large enough radius are compact, then the space is proper. Especially useful when the lower bound for the radius is 0. -/ lemma proper_space_of_compact_closed_ball_of_le (R : ℝ) (h : ∀x:α, ∀r, R ≤ r → compact (closed_ball x r)) : proper_space α := ⟨begin assume x r, by_cases hr : R ≤ r, { exact h x r hr }, { have : closed_ball x r = closed_ball x R ∩ closed_ball x r, { symmetry, apply inter_eq_self_of_subset_right, exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) }, rw this, exact (h x R (le_refl _)).inter_right is_closed_ball } end⟩ /- A compact metric space is proper -/ @[priority 100] -- see Note [lower instance priority] instance proper_of_compact [compact_space α] : proper_space α := ⟨assume x r, compact_of_is_closed_subset compact_univ is_closed_ball (subset_univ _)⟩ /-- A proper space is locally compact -/ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_proper [proper_space α] : locally_compact_space α := begin apply locally_compact_of_compact_nhds, intros x, existsi closed_ball x 1, split, { apply mem_nhds_iff.2, existsi (1 : ℝ), simp, exact ⟨zero_lt_one, ball_subset_closed_ball⟩ }, { apply proper_space.compact_ball } end /-- A proper space is complete -/ @[priority 100] -- see Note [lower instance priority] instance complete_of_proper [proper_space α] : complete_space α := ⟨begin intros f hf, /- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial. -/ have A : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one, rcases A with ⟨t, ⟨t_fset, ht⟩⟩, rcases inhabited_of_mem_sets hf.1 t_fset with ⟨x, xt⟩, have : t ⊆ closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt), have : closed_ball x 1 ∈ f := f.sets_of_superset t_fset this, rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this) with ⟨y, _, hy⟩, exact ⟨y, hy⟩ end⟩ /-- A proper metric space is separable, and therefore second countable. Indeed, any ball is compact, and therefore admits a countable dense subset. Taking a countable union over the balls centered at a fixed point and with integer radius, one obtains a countable set which is dense in the whole space. -/ @[priority 100] -- see Note [lower instance priority] instance second_countable_of_proper [proper_space α] : second_countable_topology α := begin /- We show that the space admits a countable dense subset. The case where the space is empty is special, and trivial. -/ have A : (univ : set α) = ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) := assume H, ⟨∅, ⟨by simp, by simp; exact H.symm⟩⟩, have B : (univ : set α) ≠ ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) := begin /- When the space is not empty, we take a point `x` in the space, and then a countable set `T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set `t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union of countable sets, and dense in the space by construction. -/ assume non_empty, rcases ne_empty_iff_exists_mem.1 non_empty with ⟨x, x_univ⟩, choose T a using show ∀ (r:ℝ), ∃ t ⊆ closed_ball x r, (countable (t : set α) ∧ closed_ball x r = closure t), from assume r, emetric.countable_closure_of_compact (proper_space.compact_ball _ _), let t := (⋃n:ℕ, T (n : ℝ)), have T₁ : countable t := by finish [countable_Union], have T₂ : closure t ⊆ univ := by simp, have T₃ : univ ⊆ closure t := begin intros y y_univ, rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩, have h : y ∈ closed_ball x (n : ℝ) := by simp; apply le_of_lt n_large, have h' : closed_ball x (n : ℝ) = closure (T (n : ℝ)) := by finish, have : y ∈ closure (T (n : ℝ)) := by rwa h' at h, show y ∈ closure t, from mem_of_mem_of_subset this (by apply closure_mono; apply subset_Union (λ(n:ℕ), T (n:ℝ))), end, exact ⟨t, ⟨T₁, subset.antisymm T₂ T₃⟩⟩ end, haveI : separable_space α := ⟨by_cases A B⟩, apply emetric.second_countable_of_separable, end /-- A finite product of proper spaces is proper. -/ instance pi_proper_space {π : β → Type*} [fintype β] [∀b, metric_space (π b)] [h : ∀b, proper_space (π b)] : proper_space (Πb, π b) := begin refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _), rw closed_ball_pi _ hr, apply compact_pi_infinite (λb, _), apply (h b).compact_ball end end proper_space namespace metric section second_countable open topological_space /-- A metric space is second countable if, for every ε > 0, there is a countable set which is ε-dense. -/ lemma second_countable_of_almost_dense_set (H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) : second_countable_topology α := begin choose T T_dense using H, have I1 : ∀n:ℕ, (n:ℝ) + 1 > 0 := λn, lt_of_lt_of_le zero_lt_one (le_add_of_nonneg_left (nat.cast_nonneg _)), have I : ∀n:ℕ, (n+1 : ℝ)⁻¹ > 0 := λn, inv_pos'.2 (I1 n), let t := ⋃n:ℕ, T (n+1)⁻¹ (I n), have count_t : countable t := by finish [countable_Union], have clos_t : closure t = univ, { refine subset.antisymm (subset_univ _) (λx xuniv, mem_closure_iff'.2 (λε εpos, _)), rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩, have : ε⁻¹ < n + 1 := lt_of_lt_of_le hn (le_add_of_nonneg_right zero_le_one), have nε : ((n:ℝ)+1)⁻¹ < ε := (inv_lt (I1 n) εpos).2 this, rcases (T_dense (n+1)⁻¹ (I n)).2 x with ⟨y, yT, Dxy⟩, have : y ∈ t := mem_of_mem_of_subset yT (by apply subset_Union (λ (n:ℕ), T (n+1)⁻¹ (I n))), exact ⟨y, this, lt_of_le_of_lt Dxy nε⟩ }, haveI : separable_space α := ⟨⟨t, ⟨count_t, clos_t⟩⟩⟩, exact emetric.second_countable_of_separable α end /-- A metric space space is second countable if one can reconstruct up to any ε>0 any element of the space from countably many data. -/ lemma second_countable_of_countable_discretization {α : Type u} [metric_space α] (H : ∀ε > (0 : ℝ), ∃ (β : Type u) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin classical, by_cases hs : (univ : set α) = ∅, { haveI : compact_space α := ⟨by rw hs; exact compact_empty⟩, by apply_instance }, rcases exists_mem_of_ne_empty hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, let Finv := function.inv_fun F, refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩, let x' := Finv (F x), have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩, exact ⟨x', mem_range_self _, hF _ _ this.symm⟩ end end second_countable end metric lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂ namespace metric /-- Boundedness of a subset of a metric space. We formulate the definition to work even in the empty space. -/ def bounded (s : set α) : Prop := ∃C, ∀x y ∈ s, dist x y ≤ C section bounded variables {x : α} {s t : set α} {r : ℝ} @[simp] lemma bounded_empty : bounded (∅ : set α) := ⟨0, by simp⟩ lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s := ⟨λ h _ _, h, λ H, begin classical, by_cases s = ∅, { subst s, exact ⟨0, by simp⟩ }, { rcases exists_mem_of_ne_empty h with ⟨x, hx⟩, exact H x hx } end⟩ /-- Subsets of a bounded set are also bounded -/ lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y z hy hz, begin simp only [mem_closed_ball] at *, calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add hy hz end⟩ /-- Open balls are bounded -/ lemma bounded_ball : bounded (ball x r) := bounded_closed_ball.subset ball_subset_closed_ball /-- Given a point, a bounded subset is included in some ball around this point -/ lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r := begin split; rintro ⟨C, hC⟩, { classical, by_cases s = ∅, { subst s, exact ⟨0, by simp⟩ }, { rcases exists_mem_of_ne_empty h with ⟨x, hx⟩, exact ⟨C + dist x c, λ y hy, calc dist y c ≤ dist y x + dist x c : dist_triangle _ _ _ ... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } }, { exact bounded_closed_ball.subset hC } end /-- The union of two bounded sets is bounded iff each of the sets is bounded -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩, begin rintro ⟨hs, ht⟩, refine bounded_iff_mem_bounded.2 (λ x _, _), rw bounded_iff_subset_ball x at hs ht ⊢, rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩, exact ⟨max Cs Ct, union_subset (subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _) (subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩, end⟩ /-- A finite union of bounded sets is bounded -/ lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) : bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) := finite.induction_on H (by simp) $ λ x I _ _ IH, by simp [or_imp_distrib, forall_and_distrib, IH] /-- A compact set is bounded -/ lemma bounded_of_compact {s : set α} (h : compact s) : bounded s := -- We cover the compact set by finitely many balls of radius 1, -- and then argue that a finite union of bounded sets is bounded let ⟨t, ht, fint, subs⟩ := finite_cover_balls_of_compact h zero_lt_one in bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball alias bounded_of_compact ← compact.bounded /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : finite s) : bounded s := h.compact.bounded /-- A singleton is bounded -/ lemma bounded_singleton {x : α} : bounded ({x} : set α) := bounded_of_finite $ finite_singleton _ /-- Characterization of the boundedness of the range of a function -/ lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C := exists_congr $ λ C, ⟨ λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩ /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := compact_univ.bounded.subset (subset_univ _) /-- In a proper space, a set is compact if and only if it is closed and bounded -/ lemma compact_iff_closed_bounded [proper_space α] : compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨closed_of_compact _ h, h.bounded⟩, begin rintro ⟨hc, hb⟩, classical, by_cases s = ∅, {simp [h, compact_empty]}, rcases exists_mem_of_ne_empty h with ⟨x, hx⟩, rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩, exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr end⟩ /-- The image of a proper space under an expanding onto map is proper. -/ lemma proper_image_of_proper [proper_space α] [metric_space β] (f : α → β) (f_cont : continuous f) (hf : range f = univ) (C : ℝ) (hC : ∀x y, dist x y ≤ C * dist (f x) (f y)) : proper_space β := begin apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _), let K := f ⁻¹' (closed_ball x₀ r), have A : is_closed K := continuous_iff_is_closed.1 f_cont (closed_ball x₀ r) (is_closed_ball), have B : bounded K := ⟨max C 0 * (r + r), λx y hx hy, calc dist x y ≤ C * dist (f x) (f y) : hC x y ... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left _ _) (dist_nonneg) ... ≤ max C 0 * (dist (f x) x₀ + dist (f y) x₀) : mul_le_mul_of_nonneg_left (dist_triangle_right (f x) (f y) x₀) (le_max_right _ _) ... ≤ max C 0 * (r + r) : begin simp only [mem_closed_ball, mem_preimage] at hx hy, exact mul_le_mul_of_nonneg_left (add_le_add hx hy) (le_max_right _ _) end⟩, have : compact K := compact_iff_closed_bounded.2 ⟨A, B⟩, have C : compact (f '' K) := this.image f_cont, have : f '' K = closed_ball x₀ r, by { rw image_preimage_eq_of_subset, rw hf, exact subset_univ _ }, rwa this at C end end bounded section diam variables {s : set α} {x y : α} /-- The diameter of a set in a metric space. To get controllable behavior even when the diameter should be infinite, we express it in terms of the emetric.diameter -/ def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s) /-- The diameter of a set is always nonnegative -/ lemma diam_nonneg : 0 ≤ diam s := by simp [diam] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := by simp [diam] /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := by simp [diam] /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_diam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := begin classical, by_cases hs : s = ∅, { simp [hs] }, { rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hx⟩, split, { assume bs, rcases (bounded_iff_subset_ball x).1 bs with ⟨r, hr⟩, have r0 : 0 ≤ r := by simpa [closed_ball] using hr hx, have : emetric.diam s < ⊤ := calc emetric.diam s ≤ emetric.diam (emetric.closed_ball x (ennreal.of_real r)) : by rw emetric_closed_ball r0; exact emetric.diam_mono hr ... ≤ 2 * (ennreal.of_real r) : emetric.diam_closed_ball ... < ⊤ : begin apply ennreal.lt_top_iff_ne_top.2, simp [ennreal.mul_eq_top], end, exact ennreal.lt_top_iff_ne_top.1 this }, { assume ds, have : s ⊆ closed_ball x (ennreal.to_real (emetric.diam s)), { rw [← emetric_closed_ball ennreal.to_real_nonneg, ennreal.of_real_to_real ds], exact λy hy, emetric.edist_le_diam_of_mem hy hx }, exact bounded.subset this (bounded_closed_ball) }} end /-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`. This lemma makes it possible to avoid side conditions in some situations -/ lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 := begin simp only [bounded_iff_diam_ne_top, not_not, ne.def] at h, simp [diam, h] end /-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/ lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t := begin unfold diam, rw ennreal.to_real_le_to_real (bounded_iff_diam_ne_top.1 (bounded.subset h ht)) (bounded_iff_diam_ne_top.1 ht), exact emetric.diam_mono h end /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := begin rw [diam, dist_edist], rw ennreal.to_real_le_to_real (edist_ne_top _ _) (bounded_iff_diam_ne_top.1 h), exact emetric.edist_le_diam_of_mem hx hy end /-- If the distance between any two points in a set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {d : real} (hd : d ≥ 0) (h : ∀x y ∈ s, dist x y ≤ d) : diam s ≤ d := begin have I : emetric.diam s ≤ ennreal.of_real d, { refine emetric.diam_le_of_forall_edist_le (λx y hx hy, _), rw [edist_dist], exact ennreal.of_real_le_of_real (h x y hx hy) }, have A : emetric.diam s ≠ ⊤ := ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt I (ennreal.lt_top_iff_ne_top.2 (by simp))), rw [← ennreal.to_real_of_real hd, diam, ennreal.to_real_le_to_real A], { exact I }, { simp } end /-- The diameter of a union is controlled by the sum of the diameters, and the distance between any two points in each of the sets. This lemma is true without any side condition, since it is obviously true if `s ∪ t` is unbounded. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t := have I1 : ¬(bounded (s ∪ t)) → diam (s ∪ t) ≤ diam s + dist x y + diam t := λh, calc diam (s ∪ t) = 0 + 0 + 0 : by simp [diam_eq_zero_of_unbounded h] ... ≤ diam s + dist x y + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) diam_nonneg, have I2 : (bounded (s ∪ t)) → diam (s ∪ t) ≤ diam s + dist x y + diam t := λh, begin have : bounded s := bounded.subset (subset_union_left _ _) h, have : bounded t := bounded.subset (subset_union_right _ _) h, have A : ∀a ∈ s, ∀b ∈ t, dist a b ≤ diam s + dist x y + diam t := λa ha b hb, calc dist a b ≤ dist a x + dist x y + dist y b : dist_triangle4 _ _ _ _ ... ≤ diam s + dist x y + diam t : add_le_add (add_le_add (dist_le_diam_of_mem ‹bounded s› ha xs) (le_refl _)) (dist_le_diam_of_mem ‹bounded t› yt hb), have B : ∀a b ∈ s ∪ t, dist a b ≤ diam s + dist x y + diam t := λa b ha hb, begin cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc dist a b ≤ diam s : dist_le_diam_of_mem ‹bounded s› h'a h'b ... = diam s + (0 + 0) : by simp ... ≤ diam s + (dist x y + diam t) : add_le_add (le_refl _) (add_le_add dist_nonneg diam_nonneg) ... = diam s + dist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] }, { exact A a h'a b h'b }, { have Z := A b h'b a h'a, rwa [dist_comm] at Z }, { calc dist a b ≤ diam t : dist_le_diam_of_mem ‹bounded t› h'a h'b ... = (0 + 0) + diam t : by simp ... ≤ (diam s + dist x y) + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) (le_refl _) } end, have C : 0 ≤ diam s + dist x y + diam t := calc 0 = 0 + 0 + 0 : by simp ... ≤ diam s + dist x y + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) diam_nonneg, exact diam_le_of_forall_dist_le C B end, classical.by_cases I2 I1 /-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/ lemma diam_union' {t : set α} (h : s ∩ t ≠ ∅) : diam (s ∪ t) ≤ diam s + diam t := begin rcases ne_empty_iff_exists_mem.1 h with ⟨x, ⟨xs, xt⟩⟩, simpa using diam_union xs xt end /-- The diameter of a closed ball of radius `r` is at most `2 r`. -/ lemma diam_closed_ball {r : ℝ} (h : r ≥ 0) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg (by norm_num) h) $ λa b ha hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] /-- The diameter of a ball of radius `r` is at most `2 r`. -/ lemma diam_ball {r : ℝ} (h : r ≥ 0) : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h) end diam end metric
fc636c9013badd14325bb8453ff8006530e8b088
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/gen_bug.lean
66e30f56543c371fed77ee751814e9635e8317d4
[ "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
425
lean
import logic set_option pp.notation false set_option pp.implicit true theorem tst (A B : Type) (a : A) (b : B) : a == b → b == a := begin intro H, generalize B, -- Should produce an error intro B', apply (heq.symm H), end theorem tst2 (A B : Type) (a : A) (b : B) : a == b → b == a := begin generalize a, generalize b, generalize B, intro B', intro b, intro a, intro H, apply (heq.symm H), end
672711ec692fa4ff0b4adfaac1679ca96a7cf7ec
4727251e0cd73359b15b664c3170e5d754078599
/src/order/directed.lean
11f44fa57d2206d2f9396320aaa52d62d40351b7
[ "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
6,965
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 -/ import data.set.basic import order.lattice import order.max /-! # Directed indexed families and sets This file defines directed indexed families and directed sets. An indexed family/set is directed iff each pair of elements has a shared upper bound. ## Main declarations * `directed r f`: Predicate stating that the indexed family `f` is `r`-directed. * `directed_on r s`: Predicate stating that the set `s` is `r`-directed. * `is_directed α r`: Prop-valued mixin stating that `α` is `r`-directed. Follows the style of the unbundled relation classes such as `is_total`. -/ open function universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} (r s : α → α → Prop) local infix ` ≼ ` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed (f : ι → α) := ∀ x y, ∃ z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃ z ∈ s, x ≼ z ∧ y ≼ z variables {r} theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) := by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl) alias directed_on_iff_directed ↔ directed_on.directed_coe _ theorem directed_on_image {s} {f : β → α} : directed_on r (f '' s) ↔ directed_on (f ⁻¹'o r) s := by simp only [directed_on, set.ball_image_iff, set.bex_image_iff, order.preimage] theorem directed_on.mono {s : set α} (h : directed_on r s) {r' : α → α → Prop} (H : ∀ {a b}, r a b → r' a b) : directed_on r' s := λ x hx y hy, let ⟨z, zs, xz, yz⟩ := h x hx y hy in ⟨z, zs, H xz, H yz⟩ theorem directed_comp {ι} {f : ι → β} {g : β → α} : directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl theorem directed.mono {s : α → α → Prop} {ι} {f : ι → α} (H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f := λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩ theorem directed.mono_comp {ι} {rb : β → β → Prop} {g : α → β} {f : ι → α} (hg : ∀ ⦃x y⦄, x ≼ y → rb (g x) (g y)) (hf : directed r f) : directed rb (g ∘ f) := directed_comp.2 $ hf.mono hg /-- A monotone function on a sup-semilattice is directed. -/ lemma directed_of_sup [semilattice_sup α] {f : α → β} {r : β → β → Prop} (H : ∀ ⦃i j⦄, i ≤ j → r (f i) (f j)) : directed r f := λ a b, ⟨a ⊔ b, H le_sup_left, H le_sup_right⟩ lemma monotone.directed_le [semilattice_sup α] [preorder β] {f : α → β} : monotone f → directed (≤) f := directed_of_sup lemma directed.extend_bot [preorder α] [order_bot α] {e : ι → β} {f : ι → α} (hf : directed (≤) f) (he : function.injective e) : directed (≤) (function.extend e f ⊥) := begin intros a b, rcases (em (∃ i, e i = a)).symm with ha | ⟨i, rfl⟩, { use b, simp [function.extend_apply' _ _ _ ha] }, rcases (em (∃ i, e i = b)).symm with hb | ⟨j, rfl⟩, { use e i, simp [function.extend_apply' _ _ _ hb] }, rcases hf i j with ⟨k, hi, hj⟩, use (e k), simp only [function.extend_apply he, *, true_and] end /-- An antitone function on an inf-semilattice is directed. -/ lemma directed_of_inf [semilattice_inf α] {r : β → β → Prop} {f : α → β} (hf : ∀ a₁ a₂, a₁ ≤ a₂ → r (f a₂) (f a₁)) : directed r f := λ x y, ⟨x ⊓ y, hf _ _ inf_le_left, hf _ _ inf_le_right⟩ /-- `is_directed α r` states that for any elements `a`, `b` there exists an element `c` such that `r a c` and `r b c`. -/ class is_directed (α : Type*) (r : α → α → Prop) : Prop := (directed (a b : α) : ∃ c, r a c ∧ r b c) lemma directed_of (r : α → α → Prop) [is_directed α r] (a b : α) : ∃ c, r a c ∧ r b c := is_directed.directed _ _ lemma directed_id [is_directed α r] : directed r id := by convert directed_of r lemma directed_id_iff : directed r id ↔ is_directed α r := ⟨λ h, ⟨h⟩, @directed_id _ _⟩ lemma directed_on_univ [is_directed α r] : directed_on r set.univ := λ a _ b _, let ⟨c, hc⟩ := directed_of r a b in ⟨c, trivial, hc⟩ lemma directed_on_univ_iff : directed_on r set.univ ↔ is_directed α r := ⟨λ h, ⟨λ a b, let ⟨c, _, hc⟩ := h a trivial b trivial in ⟨c, hc⟩⟩, @directed_on_univ _ _⟩ @[priority 100] -- see Note [lower instance priority] instance is_total.to_is_directed [is_total α r] : is_directed α r := ⟨λ a b, or.cases_on (total_of r a b) (λ h, ⟨b, h, refl _⟩) (λ h, ⟨a, refl _, h⟩)⟩ lemma is_directed_mono [is_directed α r] (h : ∀ ⦃a b⦄, r a b → s a b) : is_directed α s := ⟨λ a b, let ⟨c, ha, hb⟩ := is_directed.directed a b in ⟨c, h ha, h hb⟩⟩ lemma exists_ge_ge [has_le α] [is_directed α (≤)] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c := directed_of (≤) a b lemma exists_le_le [has_le α] [is_directed α (swap (≤))] (a b : α) : ∃ c, c ≤ a ∧ c ≤ b := directed_of (swap (≤)) a b instance order_dual.is_directed_ge [has_le α] [is_directed α (≤)] : is_directed αᵒᵈ (swap (≤)) := by assumption instance order_dual.is_directed_le [has_le α] [is_directed α (swap (≤))] : is_directed αᵒᵈ (≤) := by assumption section preorder variables [preorder α] {a : α} protected lemma is_min.is_bot [is_directed α (swap (≤))] (h : is_min a) : is_bot a := λ b, let ⟨c, hca, hcb⟩ := exists_le_le a b in (h hca).trans hcb protected lemma is_max.is_top [is_directed α (≤)] (h : is_max a) : is_top a := λ b, let ⟨c, hac, hbc⟩ := exists_ge_ge a b in hbc.trans $ h hac lemma is_bot_iff_is_min [is_directed α (swap (≤))] : is_bot a ↔ is_min a := ⟨is_bot.is_min, is_min.is_bot⟩ lemma is_top_iff_is_max [is_directed α (≤)] : is_top a ↔ is_max a := ⟨is_top.is_max, is_max.is_top⟩ end preorder @[priority 100] -- see Note [lower instance priority] instance semilattice_sup.to_is_directed_le [semilattice_sup α] : is_directed α (≤) := ⟨λ a b, ⟨a ⊔ b, le_sup_left, le_sup_right⟩⟩ @[priority 100] -- see Note [lower instance priority] instance semilattice_inf.to_is_directed_ge [semilattice_inf α] : is_directed α (swap (≤)) := ⟨λ a b, ⟨a ⊓ b, inf_le_left, inf_le_right⟩⟩ @[priority 100] -- see Note [lower instance priority] instance order_top.to_is_directed_le [has_le α] [order_top α] : is_directed α (≤) := ⟨λ a b, ⟨⊤, le_top, le_top⟩⟩ @[priority 100] -- see Note [lower instance priority] instance order_bot.to_is_directed_ge [has_le α] [order_bot α] : is_directed α (swap (≤)) := ⟨λ a b, ⟨⊥, bot_le, bot_le⟩⟩
a104b5c902c03e7427ec0eb366b1700c83a3448a
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/PrettyPrinter/Delaborator/TopDownAnalyze.lean
3b1134f7e623af4f12879a9000915aea35a03e66
[ "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
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
27,137
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Lean.Data.RBMap import Lean.Meta.SynthInstance import Lean.Util.FindMVar import Lean.Util.FindLevelMVar import Lean.Util.CollectLevelParams import Lean.Util.ReplaceLevel import Lean.PrettyPrinter.Delaborator.Options import Lean.PrettyPrinter.Delaborator.SubExpr import Lean.Elab.Config /-! The top-down analyzer is an optional preprocessor to the delaborator that aims to determine the minimal annotations necessary to ensure that the delaborated expression can be re-elaborated correctly. Currently, the top-down analyzer is neither sound nor complete: there may be edge-cases in which the expression can still not be re-elaborated correctly, and it may also add many annotations that are not strictly necessary. -/ namespace Lean open Meta SubExpr register_builtin_option pp.analyze : Bool := { defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) determine annotations sufficient to ensure round-tripping" } register_builtin_option pp.analyze.checkInstances : Bool := { -- TODO: It would be great to make this default to `true`, but currently, `MessageData` does not -- include the `LocalInstances`, so this will be very over-aggressive in inserting instances -- that would otherwise be easy to synthesize. We may consider threading the instances in the future, -- or at least tracking a bool for whether the instances have been lost. defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) confirm that instances can be re-synthesized" } register_builtin_option pp.analyze.typeAscriptions : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) add type ascriptions when deemed necessary" } register_builtin_option pp.analyze.trustSubst : Bool := { defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) always 'pretend' applications that can delab to ▸ are 'regular'" } register_builtin_option pp.analyze.trustOfNat : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) always 'pretend' `OfNat.ofNat` applications can elab bottom-up" } register_builtin_option pp.analyze.trustOfScientific : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) always 'pretend' `OfScientific.ofScientific` applications can elab bottom-up" } -- TODO: this is an arbitrary special case of a more general principle. register_builtin_option pp.analyze.trustSubtypeMk : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) assume the implicit arguments of Subtype.mk can be inferred" } register_builtin_option pp.analyze.trustId : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) always assume an implicit `fun x => x` can be inferred" } register_builtin_option pp.analyze.trustKnownFOType2TypeHOFuns : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) omit higher-order functions whose values seem to be knownType2Type" } register_builtin_option pp.analyze.omitMax : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) omit universe `max` annotations (these constraints can actually hurt)" } register_builtin_option pp.analyze.knowsType : Bool := { defValue := true group := "pp.analyze" descr := "(pretty printer analyzer) assume the type of the original expression is known" } register_builtin_option pp.analyze.explicitHoles : Bool := { defValue := false group := "pp.analyze" descr := "(pretty printer analyzer) use `_` for explicit arguments that can be inferred" } def getPPAnalyze (o : Options) : Bool := o.get pp.analyze.name pp.analyze.defValue def getPPAnalyzeCheckInstances (o : Options) : Bool := o.get pp.analyze.checkInstances.name pp.analyze.checkInstances.defValue def getPPAnalyzeTypeAscriptions (o : Options) : Bool := o.get pp.analyze.typeAscriptions.name pp.analyze.typeAscriptions.defValue def getPPAnalyzeTrustSubst (o : Options) : Bool := o.get pp.analyze.trustSubst.name pp.analyze.trustSubst.defValue def getPPAnalyzeTrustOfNat (o : Options) : Bool := o.get pp.analyze.trustOfNat.name pp.analyze.trustOfNat.defValue def getPPAnalyzeTrustOfScientific (o : Options) : Bool := o.get pp.analyze.trustOfScientific.name pp.analyze.trustOfScientific.defValue def getPPAnalyzeTrustId (o : Options) : Bool := o.get pp.analyze.trustId.name pp.analyze.trustId.defValue def getPPAnalyzeTrustSubtypeMk (o : Options) : Bool := o.get pp.analyze.trustSubtypeMk.name pp.analyze.trustSubtypeMk.defValue def getPPAnalyzeTrustKnownFOType2TypeHOFuns (o : Options) : Bool := o.get pp.analyze.trustKnownFOType2TypeHOFuns.name pp.analyze.trustKnownFOType2TypeHOFuns.defValue def getPPAnalyzeOmitMax (o : Options) : Bool := o.get pp.analyze.omitMax.name pp.analyze.omitMax.defValue def getPPAnalyzeKnowsType (o : Options) : Bool := o.get pp.analyze.knowsType.name pp.analyze.knowsType.defValue def getPPAnalyzeExplicitHoles (o : Options) : Bool := o.get pp.analyze.explicitHoles.name pp.analyze.explicitHoles.defValue def getPPAnalysisSkip (o : Options) : Bool := o.get `pp.analysis.skip false def getPPAnalysisHole (o : Options) : Bool := o.get `pp.analysis.hole false def getPPAnalysisNamedArg (o : Options) : Bool := o.get `pp.analysis.namedArg false def getPPAnalysisLetVarType (o : Options) : Bool := o.get `pp.analysis.letVarType false def getPPAnalysisNeedsType (o : Options) : Bool := o.get `pp.analysis.needsType false def getPPAnalysisBlockImplicit (o : Options) : Bool := o.get `pp.analysis.blockImplicit false namespace PrettyPrinter.Delaborator def returnsPi (motive : Expr) : MetaM Bool := do lambdaTelescope motive fun _ b => return b.isForall def isNonConstFun (motive : Expr) : MetaM Bool := do match motive with | Expr.lam _ _ b _ => isNonConstFun b | _ => return motive.hasLooseBVars def isSimpleHOFun (motive : Expr) : MetaM Bool := return not (← returnsPi motive) && not (← isNonConstFun motive) def isType2Type (motive : Expr) : MetaM Bool := do match ← inferType motive with | Expr.forallE _ (Expr.sort ..) (Expr.sort ..) .. => return true | _ => return false def isFOLike (motive : Expr) : MetaM Bool := do let f := motive.getAppFn return f.isFVar || f.isConst def isIdLike (arg : Expr) : Bool := -- TODO: allow `id` constant as well? match arg with | Expr.lam _ _ (Expr.bvar ..) .. => true | _ => false def isStructureInstance (e : Expr) : MetaM Bool := do match e.isConstructorApp? (← getEnv) with | some s => return isStructure (← getEnv) s.induct | none => return false namespace TopDownAnalyze partial def hasMVarAtCurrDepth (e : Expr) : MetaM Bool := do let mctx ← getMCtx return Option.isSome <| e.findMVar? fun mvarId => match mctx.findDecl? mvarId with | some mdecl => mdecl.depth == mctx.depth | _ => false partial def hasLevelMVarAtCurrDepth (e : Expr) : MetaM Bool := do let mctx ← getMCtx return Option.isSome <| e.findLevelMVar? fun mvarId => mctx.findLevelDepth? mvarId == some mctx.depth private def valUnknown (e : Expr) : MetaM Bool := do hasMVarAtCurrDepth (← instantiateMVars e) private def typeUnknown (e : Expr) : MetaM Bool := do valUnknown (← inferType e) def isHBinOp (e : Expr) : Bool := Id.run do -- TODO: instead of tracking these explicitly, -- consider a more general solution that checks for defaultInstances if e.getAppNumArgs != 6 then return false let f := e.getAppFn if !f.isConst then return false -- Note: we leave out `HPow.hPow because we expect its homogeneous -- version will change soon let ops := #[ `HOr.hOr, `HXor.hXor, `HAnd.hAnd, `HAppend.hAppend, `HOrElse.hOrElse, `HAndThen.hAndThen, `HAdd.hAdd, `HSub.hSub, `HMul.hMul, `HDiv.hDiv, `HMod.hMod, `HShiftLeft.hShiftLeft, `HShiftRight] ops.any fun op => op == f.constName! def replaceLPsWithVars (e : Expr) : MetaM Expr := do if !e.hasLevelParam then return e let lps := collectLevelParams {} e |>.params let mut replaceMap : HashMap Name Level := {} for lp in lps do replaceMap := replaceMap.insert lp (← mkFreshLevelMVar) return e.replaceLevel fun | Level.param n .. => replaceMap.find! n | l => if !l.hasParam then some l else none def isDefEqAssigning (t s : Expr) : MetaM Bool := do withReader (fun ctx => { ctx with config := { ctx.config with assignSyntheticOpaque := true }}) $ Meta.isDefEq t s def checkpointDefEq (t s : Expr) : MetaM Bool := do Meta.checkpointDefEq (mayPostpone := false) do isDefEqAssigning t s def isHigherOrder (type : Expr) : MetaM Bool := do forallTelescopeReducing type fun xs b => return xs.size > 0 && b.isSort def isFunLike (e : Expr) : MetaM Bool := do forallTelescopeReducing (← inferType e) fun xs _ => return xs.size > 0 def isSubstLike (e : Expr) : Bool := e.isAppOfArity ``Eq.ndrec 6 || e.isAppOfArity ``Eq.rec 6 def nameNotRoundtrippable (n : Name) : Bool := n.hasMacroScopes || isPrivateName n || containsNum n where containsNum | Name.str p .. => containsNum p | Name.num .. => true | Name.anonymous => false def mvarName (mvar : Expr) : MetaM Name := return (← mvar.mvarId!.getDecl).userName def containsBadMax : Level → Bool | Level.succ u .. => containsBadMax u | Level.max u v .. => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v | Level.imax u v .. => (u.hasParam && v.hasParam) || containsBadMax u || containsBadMax v | _ => false open SubExpr structure Context where knowsType : Bool knowsLevel : Bool -- only constants look at this inBottomUp : Bool := false parentIsApp : Bool := false subExpr : SubExpr deriving Inhabited structure State where annotations : OptionsPerPos := {} postponed : Array (Expr × Expr) := #[] -- not currently used abbrev AnalyzeM := ReaderT Context (StateRefT State MetaM) instance (priority := low) : MonadReaderOf SubExpr AnalyzeM where read := Context.subExpr <$> read instance (priority := low) : MonadWithReaderOf SubExpr AnalyzeM where withReader f x := fun ctx => x { ctx with subExpr := f ctx.subExpr } def tryUnify (e₁ e₂ : Expr) : AnalyzeM Unit := do try let r ← isDefEqAssigning e₁ e₂ if !r then modify fun s => { s with postponed := s.postponed.push (e₁, e₂) } pure () catch _ => modify fun s => { s with postponed := s.postponed.push (e₁, e₂) } partial def inspectOutParams (arg mvar : Expr) : AnalyzeM Unit := do let argType ← inferType arg -- HAdd α α α let mvarType ← inferType mvar let fType ← inferType argType.getAppFn -- Type → Type → outParam Type let mType ← inferType mvarType.getAppFn inspectAux fType mType 0 argType.getAppArgs mvarType.getAppArgs where inspectAux (fType mType : Expr) (i : Nat) (args mvars : Array Expr) := do let fType ← whnf fType let mType ← whnf mType if not (i < args.size) then return () match fType, mType with | Expr.forallE _ fd fb _, Expr.forallE _ _ mb _ => do -- TODO: do I need to check (← okBottomUp? args[i] mvars[i] fuel).isSafe here? -- if so, I'll need to take a callback if fd.isOutParam then tryUnify (args[i]!) (mvars[i]!) inspectAux (fb.instantiate1 args[i]!) (mb.instantiate1 mvars[i]!) (i+1) args mvars | _, _ => return () partial def isTrivialBottomUp (e : Expr) : AnalyzeM Bool := do let opts ← getOptions return e.isFVar || e.isConst || e.isMVar || e.isNatLit || e.isStringLit || e.isSort || (getPPAnalyzeTrustOfNat opts && e.isAppOfArity ``OfNat.ofNat 3) || (getPPAnalyzeTrustOfScientific opts && e.isAppOfArity ``OfScientific.ofScientific 5) partial def canBottomUp (e : Expr) (mvar? : Option Expr := none) (fuel : Nat := 10) : AnalyzeM Bool := do -- Here we check if `e` can be safely elaborated without its expected type. -- These are incomplete (and possibly unsound) heuristics. -- TODO: do I need to snapshot the state before calling this? match fuel with | 0 => return false | fuel + 1 => if ← isTrivialBottomUp e then return true let f := e.getAppFn if !f.isConst && !f.isFVar then return false let args := e.getAppArgs let fType ← replaceLPsWithVars (← inferType e.getAppFn) let (mvars, bInfos, resultType) ← forallMetaBoundedTelescope fType e.getAppArgs.size for i in [:mvars.size] do if bInfos[i]! == BinderInfo.instImplicit then inspectOutParams args[i]! mvars[i]! else if bInfos[i]! == BinderInfo.default then if ← isTrivialBottomUp args[i]! then tryUnify args[i]! mvars[i]! else if ← typeUnknown mvars[i]! <&&> canBottomUp args[i]! (some mvars[i]!) fuel then tryUnify args[i]! mvars[i]! if ← (pure (isHBinOp e) <&&> (valUnknown mvars[0]! <||> valUnknown mvars[1]!)) then tryUnify mvars[0]! mvars[1]! if mvar?.isSome then tryUnify resultType (← inferType mvar?.get!) return !(← valUnknown resultType) def withKnowing (knowsType knowsLevel : Bool) (x : AnalyzeM α) : AnalyzeM α := do withReader (fun ctx => { ctx with knowsType := knowsType, knowsLevel := knowsLevel }) x builtin_initialize analyzeFailureId : InternalExceptionId ← registerInternalExceptionId `analyzeFailure def checkKnowsType : AnalyzeM Unit := do if not (← read).knowsType then throw $ Exception.internal analyzeFailureId def annotateBoolAt (n : Name) (pos : Pos) : AnalyzeM Unit := do let opts := (← get).annotations.findD pos {} |>.setBool n true trace[pp.analyze.annotate] "{pos} {n}" modify fun s => { s with annotations := s.annotations.insert pos opts } def annotateBool (n : Name) : AnalyzeM Unit := do annotateBoolAt n (← getPos) structure App.Context where f : Expr fType : Expr args : Array Expr mvars : Array Expr bInfos : Array BinderInfo forceRegularApp : Bool structure App.State where bottomUps : Array Bool higherOrders : Array Bool funBinders : Array Bool provideds : Array Bool namedArgs : Array Name := #[] abbrev AnalyzeAppM := ReaderT App.Context (StateT App.State AnalyzeM) mutual partial def analyze (parentIsApp : Bool := false) : AnalyzeM Unit := do checkMaxHeartbeats "Delaborator.topDownAnalyze" trace[pp.analyze] "{(← read).knowsType}.{(← read).knowsLevel}" let e ← getExpr let opts ← getOptions if ← (pure !e.isAtomic) <&&> pure !(getPPProofs opts) <&&> (try Meta.isProof e catch _ => pure false) then if getPPProofsWithType opts then withType $ withKnowing true true $ analyze return () else withReader (fun ctx => { ctx with parentIsApp := parentIsApp }) do match (← getExpr) with | Expr.app .. => analyzeApp | Expr.forallE .. => analyzePi | Expr.lam .. => analyzeLam | Expr.const .. => analyzeConst | Expr.sort .. => analyzeSort | Expr.proj .. => analyzeProj | Expr.fvar .. => analyzeFVar | Expr.mdata .. => analyzeMData | Expr.letE .. => analyzeLet | Expr.lit .. => pure () | Expr.mvar .. => pure () | Expr.bvar .. => pure () where analyzeApp := do let mut willKnowType := (← read).knowsType if !(← read).knowsType && !(← canBottomUp (← getExpr)) then annotateBool `pp.analysis.needsType withType $ withKnowing true false $ analyze willKnowType := true else if ← (pure !(← read).knowsType <||> pure (← read).inBottomUp) <&&> isStructureInstance (← getExpr) then withType do annotateBool `pp.structureInstanceTypes withKnowing true false $ analyze willKnowType := true withKnowing willKnowType true $ analyzeAppStaged (← getExpr).getAppFn (← getExpr).getAppArgs analyzeAppStaged (f : Expr) (args : Array Expr) : AnalyzeM Unit := do let fType ← replaceLPsWithVars (← inferType f) let (mvars, bInfos, resultType) ← forallMetaBoundedTelescope fType args.size let rest := args.extract mvars.size args.size let args := args.shrink mvars.size -- Unify with the expected type if (← read).knowsType then tryUnify (← inferType (mkAppN f args)) resultType let forceRegularApp : Bool := (getPPAnalyzeTrustSubst (← getOptions) && isSubstLike (← getExpr)) || (getPPAnalyzeTrustSubtypeMk (← getOptions) && (← getExpr).isAppOfArity ``Subtype.mk 4) analyzeAppStagedCore { f, fType, args, mvars, bInfos, forceRegularApp } |>.run' { bottomUps := mkArray args.size false, higherOrders := mkArray args.size false, provideds := mkArray args.size false, funBinders := mkArray args.size false } if not rest.isEmpty then -- Note: this shouldn't happen for type-correct terms if !args.isEmpty then analyzeAppStaged (mkAppN f args) rest maybeAddBlockImplicit : AnalyzeM Unit := do -- See `MonadLift.noConfusion for an example where this is necessary. if !(← read).parentIsApp then let type ← inferType (← getExpr) if type.isForall && type.bindingInfo! == BinderInfo.implicit then annotateBool `pp.analysis.blockImplicit analyzeConst : AnalyzeM Unit := do let Expr.const _ ls .. ← getExpr | unreachable! if !(← read).knowsLevel && !ls.isEmpty then -- TODO: this is a very crude heuristic, motivated by https://github.com/leanprover/lean4/issues/590 unless getPPAnalyzeOmitMax (← getOptions) && ls.any containsBadMax do annotateBool `pp.universes maybeAddBlockImplicit analyzePi : AnalyzeM Unit := do withBindingDomain $ withKnowing true false analyze withBindingBody Name.anonymous analyze analyzeLam : AnalyzeM Unit := do if !(← read).knowsType then annotateBool `pp.funBinderTypes withBindingDomain $ withKnowing true false analyze withBindingBody Name.anonymous analyze analyzeLet : AnalyzeM Unit := do let Expr.letE _ _ v _ .. ← getExpr | unreachable! if !(← canBottomUp v) then annotateBool `pp.analysis.letVarType withLetVarType $ withKnowing true false analyze withLetValue $ withKnowing true true analyze else withReader (fun ctx => { ctx with inBottomUp := true }) do withLetValue $ withKnowing true true analyze withLetBody analyze analyzeSort : AnalyzeM Unit := pure () analyzeProj : AnalyzeM Unit := withProj analyze analyzeFVar : AnalyzeM Unit := maybeAddBlockImplicit analyzeMData : AnalyzeM Unit := withMDataExpr analyze partial def analyzeAppStagedCore : AnalyzeAppM Unit := do collectBottomUps checkOutParams collectHigherOrders hBinOpHeuristic collectTrivialBottomUps discard <| processPostponed (mayPostpone := true) applyFunBinderHeuristic analyzeFn for i in [:(← read).args.size] do analyzeArg i maybeSetExplicit where collectBottomUps := do let { args, mvars, bInfos, ..} ← read for target in [fun _ => none, fun i => some mvars[i]!] do for i in [:args.size] do if bInfos[i]! == BinderInfo.default then if ← typeUnknown mvars[i]! <&&> canBottomUp args[i]! (target i) then tryUnify args[i]! mvars[i]! modify fun s => { s with bottomUps := s.bottomUps.set! i true } checkOutParams := do let { args, mvars, bInfos, ..} ← read for i in [:args.size] do if bInfos[i]! == BinderInfo.instImplicit then inspectOutParams args[i]! mvars[i]! collectHigherOrders := do let { args, mvars, bInfos, ..} ← read for i in [:args.size] do if not (bInfos[i]! == BinderInfo.implicit || bInfos[i]! == BinderInfo.strictImplicit) then continue if not (← isHigherOrder (← inferType args[i]!)) then continue if getPPAnalyzeTrustId (← getOptions) && isIdLike args[i]! then continue if getPPAnalyzeTrustKnownFOType2TypeHOFuns (← getOptions) && not (← valUnknown mvars[i]!) && (← isType2Type (args[i]!)) && (← isFOLike (args[i]!)) then continue tryUnify args[i]! mvars[i]! modify fun s => { s with higherOrders := s.higherOrders.set! i true } hBinOpHeuristic := do let { mvars, ..} ← read if ← (pure (isHBinOp (← getExpr)) <&&> (valUnknown mvars[0]! <||> valUnknown mvars[1]!)) then tryUnify mvars[0]! mvars[1]! collectTrivialBottomUps := do -- motivation: prevent levels from printing in -- Boo.mk : {α : Type u_1} → {β : Type u_2} → α → β → Boo.{u_1, u_2} α β let { args, mvars, bInfos, ..} ← read for i in [:args.size] do if bInfos[i]! == BinderInfo.default then if ← valUnknown mvars[i]! <&&> isTrivialBottomUp args[i]! then tryUnify args[i]! mvars[i]! modify fun s => { s with bottomUps := s.bottomUps.set! i true } applyFunBinderHeuristic := do let { args, mvars, bInfos, .. } ← read let rec core (argIdx : Nat) (mvarType : Expr) : AnalyzeAppM Bool := do match ← getExpr, mvarType with | Expr.lam .., Expr.forallE _ t b .. => let mut annotated := false for i in [:argIdx] do if ← pure (bInfos[i]! == BinderInfo.implicit) <&&> valUnknown mvars[i]! <&&> withNewMCtxDepth (checkpointDefEq t mvars[i]!) then annotateBool `pp.funBinderTypes tryUnify args[i]! mvars[i]! -- Note: currently we always analyze the lambda binding domains in `analyzeLam` -- (so we don't need to analyze it again here) annotated := true break let annotatedBody ← withBindingBody Name.anonymous (core argIdx b) return annotated || annotatedBody | _, _ => return false for i in [:args.size] do if bInfos[i]! == BinderInfo.default then let b ← withNaryArg i (core i (← inferType mvars[i]!)) if b then modify fun s => { s with funBinders := s.funBinders.set! i true } analyzeFn := do -- Now, if this is the first staging, analyze the n-ary function without expected type let {f, fType, forceRegularApp ..} ← read if !f.isApp then withKnowing false (forceRegularApp || !(← hasLevelMVarAtCurrDepth (← instantiateMVars fType))) $ withNaryFn (analyze (parentIsApp := true)) annotateNamedArg (n : Name) : AnalyzeAppM Unit := do annotateBool `pp.analysis.namedArg modify fun s => { s with namedArgs := s.namedArgs.push n } analyzeArg (i : Nat) := do let { f, args, mvars, bInfos, forceRegularApp ..} ← read let { bottomUps, higherOrders, funBinders, ..} ← get let arg := args[i]! let argType ← inferType arg let processNaturalImplicit : AnalyzeAppM Unit := do if (← valUnknown mvars[i]! <||> pure higherOrders[i]!) && !forceRegularApp then annotateNamedArg (← mvarName mvars[i]!) modify fun s => { s with provideds := s.provideds.set! i true } else annotateBool `pp.analysis.skip withNaryArg (f.getAppNumArgs + i) do withTheReader Context (fun ctx => { ctx with inBottomUp := ctx.inBottomUp || bottomUps[i]! }) do match bInfos[i]! with | BinderInfo.default => if ← pure (getPPAnalyzeExplicitHoles (← getOptions)) <&&> pure !(← valUnknown mvars[i]!) <&&> pure !(← readThe Context).inBottomUp <&&> pure !(← isFunLike arg) <&&> pure !funBinders[i]! <&&> checkpointDefEq mvars[i]! arg then annotateBool `pp.analysis.hole else modify fun s => { s with provideds := s.provideds.set! i true } | BinderInfo.implicit => processNaturalImplicit | BinderInfo.strictImplicit => processNaturalImplicit | BinderInfo.instImplicit => -- Note: apparently checking valUnknown here is not sound, because the elaborator -- will not happily assign instImplicits that it cannot synthesize let mut provided := true if !getPPInstances (← getOptions) then annotateBool `pp.analysis.skip provided := false else if getPPAnalyzeCheckInstances (← getOptions) then let instResult ← try trySynthInstance argType catch _ => pure LOption.undef match instResult with | LOption.some inst => if ← checkpointDefEq inst arg then annotateBool `pp.analysis.skip; provided := false else annotateNamedArg (← mvarName mvars[i]!) | _ => annotateNamedArg (← mvarName mvars[i]!) else annotateBool `pp.analysis.skip; provided := false modify fun s => { s with provideds := s.provideds.set! i provided } | BinderInfo.auxDecl => pure () if (← get).provideds[i]! then withKnowing (not (← typeUnknown mvars[i]!)) true analyze tryUnify mvars[i]! args[i]! maybeSetExplicit := do let { f, args, bInfos, ..} ← read if (← get).namedArgs.any nameNotRoundtrippable then annotateBool `pp.explicit for i in [:args.size] do if !(← get).provideds[i]! then withNaryArg (f.getAppNumArgs + i) do annotateBool `pp.analysis.hole if bInfos[i]! == BinderInfo.instImplicit && getPPInstanceTypes (← getOptions) then withType (withKnowing true false analyze) end end TopDownAnalyze open TopDownAnalyze SubExpr def topDownAnalyze (e : Expr) : MetaM OptionsPerPos := do let s₀ ← get withTraceNode `pp.analyze (fun _ => return e) do withReader (fun ctx => { ctx with config := Elab.Term.setElabConfig ctx.config }) do let ϕ : AnalyzeM OptionsPerPos := do withNewMCtxDepth analyze; pure (← get).annotations try let knowsType := getPPAnalyzeKnowsType (← getOptions) ϕ { knowsType := knowsType, knowsLevel := knowsType, subExpr := mkRoot e } |>.run' { : TopDownAnalyze.State } catch e => trace[pp.analyze.error] "failed {e.toMessageData}" pure {} finally set s₀ builtin_initialize registerTraceClass `pp.analyze registerTraceClass `pp.analyze.annotate (inherited := true) registerTraceClass `pp.analyze.tryUnify (inherited := true) registerTraceClass `pp.analyze.error (inherited := true) end Lean.PrettyPrinter.Delaborator
d54e94942bbf17fb7450a63ee7d56f91733057f9
63abd62053d479eae5abf4951554e1064a4c45b4
/src/order/filter/at_top_bot.lean
6e491df8caafeaf3b5376025bc206726bc2035be
[ "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
41,918
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, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import order.filter.bases import data.finset.preimage /-! # `at_top` and `at_bot` filters on preorded sets, monoids and groups. In this file we define the filters * `at_top`: corresponds to `n → +∞`; * `at_bot`: corresponds to `n → -∞`. Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”. -/ variables {ι ι' α β γ : Type*} open set open_locale classical filter big_operators namespace filter /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, 𝓟 {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, 𝓟 {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ lemma Ioi_mem_at_top [preorder α] [no_top_order α] (x : α) : Ioi x ∈ (at_top : filter α) := let ⟨z, hz⟩ := no_top x in mem_sets_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ := mem_infi_sets a $ subset.refl _ lemma Iio_mem_at_bot [preorder α] [no_bot_order α] (x : α) : Iio x ∈ (at_bot : filter α) := let ⟨z, hz⟩ := no_bot x in mem_sets_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := has_basis_infi_principal (directed_of_sup $ λ a b, Ici_subset_Ici.2) lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := ⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩ lemma at_bot_basis [nonempty α] [semilattice_inf α] : (@at_bot α _).has_basis (λ _, true) Iic := @at_top_basis (order_dual α) _ _ lemma at_bot_basis' [semilattice_inf α] (a : α) : (@at_bot α _).has_basis (λ x, x ≤ a) Iic := @at_top_basis' (order_dual α) _ _ @[instance] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) := at_top_basis.ne_bot_iff.2 $ λ a _, nonempty_Ici @[instance] lemma at_bot_ne_bot [nonempty α] [semilattice_inf α] : ne_bot (at_bot : filter α) := @at_top_ne_bot (order_dual α) _ _ @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := at_top_basis.mem_iff.trans $ exists_congr $ λ _, exists_const _ @[simp] lemma mem_at_bot_sets [nonempty α] [semilattice_inf α] {s : set α} : s ∈ (at_bot : filter α) ↔ ∃a:α, ∀b≤a, b ∈ s := @mem_at_top_sets (order_dual α) _ _ _ @[simp] lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) := mem_at_top_sets @[simp] lemma eventually_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ b ≤ a, p b) := mem_at_bot_sets lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a lemma eventually_le_at_bot [preorder α] (a : α) : ∀ᶠ x in at_bot, x ≤ a := mem_at_bot a lemma eventually_gt_at_top [preorder α] [no_top_order α] (a : α) : ∀ᶠ x in at_top, a < x := Ioi_mem_at_top a lemma eventually_lt_at_bot [preorder α] [no_bot_order α] (a : α) : ∀ᶠ x in at_bot, x < a := Iio_mem_at_bot a lemma at_top_basis_Ioi [nonempty α] [semilattice_sup α] [no_top_order α] : (@at_top α _).has_basis (λ _, true) Ioi := at_top_basis.to_has_basis (λ a ha, ⟨a, ha, Ioi_subset_Ici_self⟩) $ λ a ha, (no_top a).imp $ λ b hb, ⟨ha, Ici_subset_Ioi.2 hb⟩ lemma at_top_countable_basis [nonempty α] [semilattice_sup α] [encodable α] : has_countable_basis (at_top : filter α) (λ _, true) Ici := { countable := countable_encodable _, .. at_top_basis } lemma at_bot_countable_basis [nonempty α] [semilattice_inf α] [encodable α] : has_countable_basis (at_bot : filter α) (λ _, true) Iic := { countable := countable_encodable _, .. at_bot_basis } lemma is_countably_generated_at_top [nonempty α] [semilattice_sup α] [encodable α] : (at_top : filter $ α).is_countably_generated := at_top_countable_basis.is_countably_generated lemma is_countably_generated_at_bot [nonempty α] [semilattice_inf α] [encodable α] : (at_bot : filter $ α).is_countably_generated := at_bot_countable_basis.is_countably_generated lemma order_top.at_top_eq (α) [order_top α] : (at_top : filter α) = pure ⊤ := le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique) (le_infi $ λ b, le_principal_iff.2 le_top) lemma order_bot.at_bot_eq (α) [order_bot α] : (at_bot : filter α) = pure ⊥ := @order_top.at_top_eq (order_dual α) _ lemma tendsto_at_top_pure [order_top α] (f : α → β) : tendsto f at_top (pure $ f ⊤) := (order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _ lemma tendsto_at_bot_pure [order_bot α] (f : α → β) : tendsto f at_bot (pure $ f ⊥) := @tendsto_at_top_pure (order_dual α) _ _ _ lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b := eventually_at_top.mp h lemma eventually.exists_forall_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_bot, p x) : ∃ a, ∀ b ≤ a, p b := eventually_at_bot.mp h lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) := by simp [at_top_basis.frequently_iff] lemma frequently_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b ≤ a, p b) := @frequently_at_top (order_dual α) _ _ _ lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_top_order α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) := by simp [at_top_basis_Ioi.frequently_iff] lemma frequently_at_bot' [semilattice_inf α] [nonempty α] [no_bot_order α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b < a, p b) := @frequently_at_top' (order_dual α) _ _ _ _ lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b := frequently_at_top.mp h lemma frequently.forall_exists_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_bot, p x) : ∀ a, ∃ b ≤ a, p b := frequently_at_bot.mp h lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) := (at_top_basis.map _).eq_infi lemma map_at_bot_eq [nonempty α] [semilattice_inf α] {f : α → β} : at_bot.map f = (⨅a, 𝓟 $ f '' {a' | a' ≤ a}) := @map_at_top_eq (order_dual α) _ _ _ _ lemma tendsto_at_top [preorder β] {m : α → β} {f : filter α} : tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) := by simp only [at_top, tendsto_infi, tendsto_principal, mem_set_of_eq] lemma tendsto_at_bot [preorder β] {m : α → β} {f : filter α} : tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) := @tendsto_at_top α (order_dual β) _ m f lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, tendsto_at_top.2 $ λ b, mp_sets (tendsto_at_top.1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_bot_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₂ l at_bot → tendsto f₁ l at_bot := @tendsto_at_top_mono' _ (order_dual β) _ _ _ _ h lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto f l at_top → tendsto g l at_top := tendsto_at_top_mono' l $ eventually_of_forall h lemma tendsto_at_bot_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto g l at_bot → tendsto f l at_bot := @tendsto_at_top_mono _ (order_dual β) _ _ _ _ h /-! ### Sequences -/ lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U := by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl lemma inf_map_at_bot_ne_bot_iff [semilattice_inf α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_bot)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≤ N, u n ∈ U := @inf_map_at_top_ne_bot_iff (order_dual α) _ _ _ _ _ lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin choose u hu using h, cases forall_and_distrib.mp hu with hu hu', exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono.nat (λ n, hu _), λ n, hu' _⟩, end lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin rw frequently_at_top' at h, exact extraction_of_frequently_at_top' h, end lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := extraction_of_frequently_at_top h.frequently lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b ≤ u a' := begin have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x := (eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b), haveI : nonempty α := ⟨a⟩, rcases this.exists with ⟨a', ha, hb⟩, exact ⟨a', ha, hb⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_le_of_tendsto_at_bot [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' ≤ b := @exists_le_of_tendsto_at_top _ (order_dual β) _ _ _ h lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_top_order β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b < u a' := begin cases no_top b with b' hb', rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩, exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_lt_of_tendsto_at_bot [semilattice_sup α] [preorder β] [no_bot_order β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' < b := @exists_lt_of_tendsto_at_top _ (order_dual β) _ _ _ _ h /-- If `u` is a sequence which is unbounded above, then after any point, it reaches a value strictly greater than all previous values. -/ lemma high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n := begin intros N, let A := finset.image u (finset.range $ N+1), -- A = {u 0, ..., u N} have Ane : A.nonempty, from ⟨u 0, finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.zero_lt_succ _)⟩, let M := finset.max' A Ane, have ex : ∃ n ≥ N, M < u n, from exists_lt_of_tendsto_at_top hu _ _, obtain ⟨n, hnN, hnM, hn_min⟩ : ∃ n, N ≤ n ∧ M < u n ∧ ∀ k, N ≤ k → k < n → u k ≤ M, { use nat.find ex, rw ← and_assoc, split, { simpa using nat.find_spec ex }, { intros k hk hk', simpa [hk] using nat.find_min ex hk' } }, use [n, hnN], intros k hk, by_cases H : k ≤ N, { have : u k ∈ A, from finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.lt_succ_of_le H), have : u k ≤ M, from finset.le_max' A (u k) this, exact lt_of_le_of_lt this hnM }, { push_neg at H, calc u k ≤ M : hn_min k (le_of_lt H) hk ... < u n : hnM }, end /-- If `u` is a sequence which is unbounded below, then after any point, it reaches a value strictly smaller than all previous values. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∀ N, ∃ n ≥ N, ∀ k < n, u n < u k := @high_scores (order_dual β) _ _ _ hu /-- If `u` is a sequence which is unbounded above, then it `frequently` reaches a value strictly greater than all previous values. -/ lemma frequently_high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n := by simpa [frequently_at_top] using high_scores hu /-- If `u` is a sequence which is unbounded below, then it `frequently` reaches a value strictly smaller than all previous values. -/ lemma frequently_low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∃ᶠ n in at_top, ∀ k < n, u n < u k := @frequently_high_scores (order_dual β) _ _ _ hu lemma strict_mono_subseq_of_tendsto_at_top {β : Type*} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in ⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩ lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id) lemma strict_mono_tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) : tendsto φ at_top at_top := tendsto_at_top_mono h.id_le tendsto_id section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg lemma tendsto_at_bot_add_nonpos_left' (hf : ∀ᶠ x in l, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg lemma tendsto_at_bot_add_nonpos_left (hf : ∀ x, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_bot_add_nonpos_right' (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg) lemma tendsto_at_bot_add_nonpos_right (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (tendsto_at_top.mp hf 0) hg lemma tendsto_at_bot_add (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add _ (order_dual β) _ _ _ _ hf hg end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (C + b)).mono (λ x, le_of_add_le_add_left) lemma tendsto_at_bot_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (b + C)).mono (λ x, le_of_add_le_add_right) lemma tendsto_at_bot_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h) lemma tendsto_at_bot_of_add_bdd_below_left' (C) (hC : ∀ᶠ x in l, C ≤ f x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_left (C) (hC : ∀ x, C ≤ f x) : tendsto (λ x, f x + g x) l at_bot → tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left _ (order_dual β) _ _ _ _ C hC lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h) lemma tendsto_at_bot_of_add_bdd_below_right' (C) (hC : ∀ᶠ x in l, C ≤ g x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' C (univ_mem_sets' hC) lemma tendsto_at_bot_of_add_bdd_below_right (C) (hC : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_bot → tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right _ (order_dual β) _ _ _ _ C hC end ordered_cancel_add_comm_monoid section ordered_group variables [ordered_add_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simpa) (by simpa) lemma tendsto_at_bot_add_left_of_ge' (C : β) (hf : ∀ᶠ x in l, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_bot_add_left_of_ge (C : β) (hf : ∀ x, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_bot_add_right_of_ge' (C : β) (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_bot_add_right_of_ge (C : β) (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_bot_add_const_left (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, C + f x) l at_bot := @tendsto_at_top_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) lemma tendsto_at_bot_add_const_right (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, f x + C) l at_bot := @tendsto_at_top_add_const_right _ (order_dual β) _ _ _ C hf end ordered_group section linear_ordered_semiring variables [ordered_semiring α] {l : filter β} {f g : β → α} lemma tendsto_at_top_mul_at_top (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_top := begin refine tendsto_at_top_mono' _ _ hg, filter_upwards [hg (eventually_ge_at_top 0), hf (eventually_ge_at_top 1)], exact λ x, le_mul_of_one_le_left end end linear_ordered_semiring open_locale filter lemma tendsto_at_top' [nonempty α] [semilattice_sup α] {f : α → β} {l : filter β} : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] {f : α → β} {l : filter β} : tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) := @tendsto_at_top' (order_dual α) _ _ _ _ _ theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl theorem tendsto_at_bot_principal [nonempty β] [semilattice_inf β] {f : β → α} {s : set α} : tendsto f at_bot (𝓟 s) ↔ ∃N, ∀n≤N, f n ∈ s := @tendsto_at_top_principal _ (order_dual β) _ _ _ _ /-- A function `f` grows to `+∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a := @tendsto_at_top_at_top (order_dual α) β _ _ _ f lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b := @tendsto_at_top_at_top (order_dual α) (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, b ≤ f a) : tendsto f at_top at_top := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha') lemma tendsto_at_bot_at_bot_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, f a ≤ b) : tendsto f at_bot at_bot := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_bot a) $ λ a' ha', le_trans (hf ha') ha lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := tendsto_at_top_at_top.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ lemma tendsto_at_bot_at_bot_iff_of_monotone [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_bot at_bot ↔ ∀ b : β, ∃ a : α, f a ≤ b := tendsto_at_bot_at_bot.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans (hf ha') h⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top alias tendsto_at_bot_at_bot_of_monotone ← monotone.tendsto_at_bot_at_bot alias tendsto_at_top_at_top_iff_of_monotone ← monotone.tendsto_at_top_at_top_iff alias tendsto_at_bot_at_bot_iff_of_monotone ← monotone.tendsto_at_bot_at_bot_iff lemma tendsto_at_top_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin refine ⟨_, (tendsto_at_top_at_top_of_monotone (λ b₁ b₂, (hm b₁ b₂).2) hu).comp⟩, rw [tendsto_at_top, tendsto_at_top], exact λ hc b, (hc (e b)).mono (λ a, (hm b (f a)).1) end /-- A function `f` goes to `-∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_bot_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, e b ≤ c) : tendsto (e ∘ f) l at_bot ↔ tendsto f l at_bot := @tendsto_at_top_embedding α (order_dual β) (order_dual γ) _ _ f e l (function.swap hm) hu lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range lemma at_top_finset_eq_infi : (at_top : filter $ finset α) = ⨅ x : α, 𝓟 (Ici {x}) := begin refine le_antisymm (le_infi (λ i, le_principal_iff.2 $ mem_at_top {i})) _, refine le_infi (λ s, le_principal_iff.2 $ mem_infi_iff.2 _), refine ⟨↑s, s.finite_to_set, _, λ i, mem_principal_self _, _⟩, simp only [subset_def, mem_Inter, set_coe.forall, mem_Ici, finset.le_iff_subset, finset.mem_singleton, finset.subset_iff, forall_eq], dsimp, exact λ t, id end /-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then `tendsto f at_top at_top`. -/ lemma tendsto_at_top_finset_of_monotone [preorder β] {f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) : tendsto f at_top at_top := begin simp only [at_top_finset_eq_infi, tendsto_infi, tendsto_principal], intro a, rcases h' a with ⟨b, hb⟩, exact eventually.mono (mem_at_top b) (λ b' hb', le_trans (finset.singleton_subset_iff.2 hb) (h hb')), end alias tendsto_at_top_finset_of_monotone ← monotone.tendsto_at_top_finset lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) : tendsto (finset.image j) at_top at_top := (finset.image_mono j).tendsto_at_top_finset $ assume a, ⟨{i a}, by simp only [finset.image_singleton, h a, finset.mem_singleton]⟩ lemma tendsto_finset_preimage_at_top_at_top {f : α → β} (hf : function.injective f) : tendsto (λ s : finset β, s.preimage f (hf.inj_on _)) at_top at_top := (finset.monotone_preimage hf).tendsto_at_top_finset $ λ x, ⟨{f x}, finset.mem_preimage.2 $ finset.mem_singleton_self _⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] : (at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) := begin by_cases ne : nonempty β₁ ∧ nonempty β₂, { cases ne, resetI, simp [at_top, prod_infi_left, prod_infi_right, infi_prod], exact infi_comm }, { rw not_and_distrib at ne, cases ne; { have : ¬ (nonempty (β₁ × β₂)), by simp [ne], rw [at_top.filter_eq_bot_of_not_nonempty ne, at_top.filter_eq_bot_of_not_nonempty this], simp only [bot_prod, prod_bot] } } end lemma prod_at_bot_at_bot_eq {β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] : (at_bot : filter β₁) ×ᶠ (at_bot : filter β₂) = (at_bot : filter (β₁ × β₂)) := @prod_at_top_at_top_eq (order_dual β₁) (order_dual β₂) _ _ lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] lemma prod_map_at_bot_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_bot) ×ᶠ (map u₂ at_bot) = map (prod.map u₁ u₂) at_bot := @prod_map_at_top_eq _ _ (order_dual β₁) (order_dual β₂) _ _ _ _ /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin refine le_antisymm (hf.tendsto_at_top_at_top $ λ b, ⟨g (b ⊔ b'), le_sup_left.trans $ hgi _ le_sup_right⟩) _, rw [@map_at_top_eq _ _ ⟨g b'⟩], refine le_infi (λ a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 $ λ b hb, _), rw [mem_set_of_eq, sup_le_iff] at hb, exact ⟨g b, (gc _ _ hb.2).1 hb.1, le_antisymm ((gc _ _ hb.2).2 (le_refl _)) (hgi _ hb.2)⟩ end lemma map_at_bot_eq_of_gc [semilattice_inf α] [semilattice_inf β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≤b', b ≤ f a ↔ g b ≤ a) (hgi : ∀b≤b', f (g b) ≤ b) : map f at_bot = at_bot := @map_at_top_eq_of_gc (order_dual α) (order_dual β) _ _ _ _ _ hf.order_dual gc hgi lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : 0 < k) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded above, then `tendsto u at_top at_top`. -/ lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) : tendsto u at_top at_top := begin apply h.tendsto_at_top_at_top, intro b, rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩, exact ⟨N, le_of_lt hN⟩, end /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded below, then `tendsto u at_bot at_bot`. -/ lemma tendsto_at_bot_at_bot_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_below (range u)) : tendsto u at_bot at_bot := @tendsto_at_top_at_top_of_monotone' (order_dual ι) (order_dual α) _ _ _ h.order_dual H lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_top at_top) : ¬ bdd_above (range f) := begin rintros ⟨M, hM⟩, cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha, apply lt_irrefl M, calc M < f a : ha a (le_refl _) ... ≤ M : hM (set.mem_range_self a) end lemma unbounded_of_tendsto_at_bot [nonempty α] [semilattice_sup α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_top at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top _ (order_dual β) _ _ _ _ _ h lemma unbounded_of_tendsto_at_top' [nonempty α] [semilattice_inf α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_bot at_top) : ¬ bdd_above (range f) := @unbounded_of_tendsto_at_top (order_dual α) _ _ _ _ _ _ h lemma unbounded_of_tendsto_at_bot' [nonempty α] [semilattice_inf α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_bot at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top (order_dual α) (order_dual β) _ _ _ _ _ h /-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then it tends to `at_top` along `at_top`. -/ lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) : tendsto u at_top at_top := h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists /-- If a monotone function `u : ι → α` tends to `at_bot` along *some* non-trivial filter `l`, then it tends to `at_bot` along `at_bot`. -/ lemma tendsto_at_bot_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_bot) : tendsto u at_bot at_bot := @tendsto_at_top_of_monotone_of_filter (order_dual ι) (order_dual α) _ _ _ _ h.order_dual _ hu lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_top) : tendsto u at_top at_top := tendsto_at_top_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_at_bot_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_bot) : tendsto u at_bot at_bot := tendsto_at_bot_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_neg_at_top_at_bot [ordered_add_comm_group α] : tendsto (has_neg.neg : α → α) at_top at_bot := begin simp only [tendsto_at_bot, neg_le], exact λ b, eventually_ge_at_top _ end lemma tendsto_neg_at_bot_at_top [ordered_add_comm_group α] : tendsto (has_neg.neg : α → α) at_bot at_top := @tendsto_neg_at_top_at_bot (order_dual α) _ /-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with `at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of `Π b in s, f b` as `s → at_top` with the similar set for `g`. -/ @[to_additive] lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) : at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) := 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_antimono_basis.tendsto [semilattice_sup ι] [nonempty ι] {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : l.has_antimono_basis p s) {φ : ι → α} (h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l := (at_top_basis.tendsto_iff hl.to_has_basis).2 $ assume i hi, ⟨i, trivial, λ j hij, hl.decreasing hi (hl.mono hij hi) hij (h j)⟩ namespace is_countably_generated /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l, from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩, begin rcases hcb.exists_antimono_basis with ⟨g, gbasis, gmon, -⟩, contrapose, simp only [not_forall, gbasis.tendsto_left_iff, exists_const, not_exists, not_imp], rintro ⟨B, hBl, hfBk⟩, choose x h using hfBk, use x, split, { exact (at_top_basis.tendsto_iff gbasis).2 (λ i _, ⟨i, trivial, λ j hj, gmon trivial trivial hj (h j).1⟩) }, { simp only [tendsto_at_top', (∘), not_forall, not_exists], use [B, hBl], intro i, use [i, (le_refl _)], apply (h i).right }, end lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := hcb.tendsto_iff_seq_tendsto.2 lemma subseq_tendsto {f : filter α} (hf : is_countably_generated f) {u : ℕ → α} (hx : ne_bot (f ⊓ map u at_top)) : ∃ (θ : ℕ → ℕ), (strict_mono θ) ∧ (tendsto (u ∘ θ) at_top f) := begin rcases hf.exists_antimono_basis with ⟨B, h⟩, have : ∀ N, ∃ n ≥ N, u n ∈ B N, from λ N, filter.inf_map_at_top_ne_bot_iff.mp hx _ (h.to_has_basis.mem_of_mem trivial) N, choose φ hφ using this, cases forall_and_distrib.mp hφ with φ_ge φ_in, have lim_uφ : tendsto (u ∘ φ) at_top f, from h.tendsto φ_in, have lim_φ : tendsto φ at_top at_top, from (tendsto_at_top_mono φ_ge tendsto_id), obtain ⟨ψ, hψ, hψφ⟩ : ∃ ψ : ℕ → ℕ, strict_mono ψ ∧ strict_mono (φ ∘ ψ), from strict_mono_subseq_of_tendsto_at_top lim_φ, exact ⟨φ ∘ ψ, hψφ, lim_uφ.comp $ strict_mono_tendsto_at_top hψ⟩, end end is_countably_generated end filter open filter finset /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters `at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide. The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ @[to_additive] lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β} (hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) : map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top := begin apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _), { refine ⟨s.preimage g (hg.inj_on _), λ t ht, _⟩, refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩, rw [← finset.prod_image (hg.inj_on _)], refine (prod_subset (subset_union_left _ _) _).symm, simp only [finset.mem_union, finset.mem_image], refine λ y hy hyt, hf y (mt _ hyt), rintros ⟨x, rfl⟩, exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ }, { refine ⟨s.image g, λ t ht, _⟩, simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)], exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ } end /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide. This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ add_decl_doc function.injective.map_at_top_finset_sum_eq
9b491c9bebb856ad266b2a18e053affc1437ffa6
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/ring_theory/adjoin_root.lean
35b5284da12d1ef1eb4822b7b1c3fa47c3afd9d1
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
3,649
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes Adjoining roots of polynomials -/ import data.polynomial ring_theory.principal_ideal_domain noncomputable theory universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open polynomial ideal def adjoin_root [comm_ring α] (f : polynomial α) : Type u := ideal.quotient (span {f} : ideal (polynomial α)) namespace adjoin_root section comm_ring variables [comm_ring α] (f : polynomial α) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ instance : decidable_eq (adjoin_root f) := classical.dec_eq _ variable {f} def mk : polynomial α → adjoin_root f := ideal.quotient.mk _ def root : adjoin_root f := mk X def of (x : α) : adjoin_root f := mk (C x) instance adjoin_root.has_coe_t : has_coe_t α (adjoin_root f) := ⟨of⟩ instance mk.is_ring_hom : is_ring_hom (mk : polynomial α → adjoin_root f) := ideal.quotient.is_ring_hom_mk _ @[simp] lemma mk_self : (mk f : adjoin_root f) = 0 := quotient.sound' (mem_span_singleton.2 $ by simp) instance : is_ring_hom (coe : α → adjoin_root f) := @is_ring_hom.comp _ _ _ _ C _ _ _ mk mk.is_ring_hom lemma eval₂_root (f : polynomial α) : f.eval₂ coe (root : adjoin_root f) = 0 := quotient.induction_on' (root : adjoin_root f) (λ (g : polynomial α) (hg : mk g = mk X), show finsupp.sum f (λ (e : ℕ) (a : α), mk (C a) * mk g ^ e) = 0, by simp only [hg, (is_semiring_hom.map_pow (mk : polynomial α → adjoin_root f) _ _).symm, (is_ring_hom.map_mul (mk : polynomial α → adjoin_root f)).symm]; rw [finsupp.sum, finset.sum_hom (mk : polynomial α → adjoin_root f), show finset.sum _ _ = _, from sum_C_mul_X_eq _, mk_self]) (show (root : adjoin_root f) = mk X, from rfl) lemma is_root_root (f : polynomial α) : is_root (f.map coe) (root : adjoin_root f) := by rw [is_root, eval_map, eval₂_root] variables [comm_ring β] def lift (i : α → β) [is_ring_hom i] (x : β) (h : f.eval₂ i x = 0) : (adjoin_root f) → β := ideal.quotient.lift _ (eval₂ i x) $ λ g H, begin simp [mem_span_singleton] at H, cases H with y H, rw [H, eval₂_mul], simp [h] end variables {i : α → β} [is_ring_hom i] {a : β} {h : f.eval₂ i a = 0} @[simp] lemma lift_mk {g : polynomial α} : lift i a h (mk g) = g.eval₂ i a := ideal.quotient.lift_mk @[simp] lemma lift_root : lift i a h root = a := by simp [root, h] @[simp] lemma lift_of {x : α} : lift i a h x = i x := by show lift i a h (ideal.quotient.mk _ (C x)) = i x; convert ideal.quotient.lift_mk; simp instance is_ring_hom_lift : is_ring_hom (lift i a h) := by unfold lift; apply_instance end comm_ring variables [discrete_field α] {f : polynomial α} [irreducible f] instance is_maximal_span : is_maximal (span {f} : ideal (polynomial α)) := principal_ideal_domain.is_maximal_of_irreducible ‹irreducible f› noncomputable instance field : discrete_field (adjoin_root f) := ideal.quotient.field (span {f} : ideal (polynomial α)) instance : is_field_hom (coe : α → adjoin_root f) := by apply_instance instance lift_is_field_hom [field β] {i : α → β} [is_ring_hom i] {a : β} {h : f.eval₂ i a = 0} : is_field_hom (lift i a h) := by apply_instance lemma coe_injective : function.injective (coe : α → adjoin_root f) := is_field_hom.injective _ lemma mul_div_root_cancel (f : polynomial α) [irreducible f] : (X - C (root : adjoin_root f)) * (f.map coe / (X - C root)) = f.map coe := mul_div_eq_iff_is_root.2 $ is_root_root _ end adjoin_root
02a15b36175ebf5ce8cf090fa5f1762b36d927cc
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/max/level10.lean
b14dd4bb4e1a4243e65d77d05a552e55641c4f89
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
739
lean
import game.max.level09 -- hide open_locale classical -- hide noncomputable theory -- hide namespace xena -- hide /- # Chapter ? : Max ## Level 10 And finally `lt_max_iff`. -/ /- Lemma If $a$, $b$, $c$ are real numbers, then $a<\max(b,c)$ iff ($a<b$ or $a<c$). -/ theorem lt_max_iff {a b c : ℝ} : a < max b c ↔ a < b ∨ a < c := begin split, { intro ha, cases le_total b c with hbc hcb, { rw max_eq_right hbc at ha, right, assumption, }, { rw max_eq_left hcb at ha, left, assumption } }, { intro habc, cases habc with hab hac, { apply lt_of_lt_of_le hab, apply le_max_left}, { apply lt_of_lt_of_le hac, apply le_max_right}, } end end xena --hide
08fae2dd3f584f3caf7fe8ada5a539e4eef1baea
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/ring_theory/ideal/basic.lean
11659e978ea263d274cfe736ed5ab90699422cd2
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
32,116
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Mario Carneiro -/ import algebra.associated import linear_algebra.basic import order.zorn /-! # Ideals over a ring This file defines `ideal R`, the type of ideals over a commutative ring `R`. ## Implementation notes `ideal R` is implemented using `submodule R R`, where `•` is interpreted as `*`. ## TODO Support one-sided ideals, and ideals over non-commutative rings. See `algebra.ring_quot` for quotients of non-commutative rings. -/ universes u v w variables {α : Type u} {β : Type v} open set function open_locale classical big_operators /-- Ideal in a commutative ring is an additive subgroup `s` such that `a * b ∈ s` whenever `b ∈ s`. -/ @[reducible] def ideal (R : Type u) [comm_ring R] := submodule R R namespace ideal variables [comm_ring α] (I : ideal α) {a b : α} protected lemma zero_mem : (0 : α) ∈ I := I.zero_mem protected lemma add_mem : a ∈ I → b ∈ I → a + b ∈ I := I.add_mem lemma neg_mem_iff : -a ∈ I ↔ a ∈ I := I.neg_mem_iff lemma add_mem_iff_left : b ∈ I → (a + b ∈ I ↔ a ∈ I) := I.add_mem_iff_left lemma add_mem_iff_right : a ∈ I → (a + b ∈ I ↔ b ∈ I) := I.add_mem_iff_right protected lemma sub_mem : a ∈ I → b ∈ I → a - b ∈ I := I.sub_mem lemma mul_mem_left : b ∈ I → a * b ∈ I := I.smul_mem _ lemma mul_mem_right (h : a ∈ I) : a * b ∈ I := mul_comm b a ▸ I.mul_mem_left h end ideal variables {a b : α} -- A separate namespace definition is needed because the variables were historically in a different order namespace ideal variables [comm_ring α] (I : ideal α) @[ext] lemma ext {I J : ideal α} (h : ∀ x, x ∈ I ↔ x ∈ J) : I = J := submodule.ext h theorem eq_top_of_unit_mem (x y : α) (hx : x ∈ I) (h : y * x = 1) : I = ⊤ := eq_top_iff.2 $ λ z _, calc z = z * (y * x) : by simp [h] ... = (z * y) * x : eq.symm $ mul_assoc z y x ... ∈ I : I.mul_mem_left hx theorem eq_top_of_is_unit_mem {x} (hx : x ∈ I) (h : is_unit x) : I = ⊤ := let ⟨y, hy⟩ := is_unit_iff_exists_inv'.1 h in eq_top_of_unit_mem I x y hx hy theorem eq_top_iff_one : I = ⊤ ↔ (1:α) ∈ I := ⟨by rintro rfl; trivial, λ h, eq_top_of_unit_mem _ _ 1 h (by simp)⟩ theorem ne_top_iff_one : I ≠ ⊤ ↔ (1:α) ∉ I := not_congr I.eq_top_iff_one @[simp] theorem unit_mul_mem_iff_mem {x y : α} (hy : is_unit y) : y * x ∈ I ↔ x ∈ I := begin refine ⟨λ h, _, λ h, I.smul_mem y h⟩, obtain ⟨y', hy'⟩ := is_unit_iff_exists_inv.1 hy, have := I.smul_mem y' h, rwa [smul_eq_mul, ← mul_assoc, mul_comm y' y, hy', one_mul] at this, end @[simp] theorem mul_unit_mem_iff_mem {x y : α} (hy : is_unit y) : x * y ∈ I ↔ x ∈ I := mul_comm y x ▸ unit_mul_mem_iff_mem I hy /-- The ideal generated by a subset of a ring -/ def span (s : set α) : ideal α := submodule.span α s lemma subset_span {s : set α} : s ⊆ span s := submodule.subset_span lemma span_le {s : set α} {I} : span s ≤ I ↔ s ⊆ I := submodule.span_le lemma span_mono {s t : set α} : s ⊆ t → span s ≤ span t := submodule.span_mono @[simp] lemma span_eq : span (I : set α) = I := submodule.span_eq _ @[simp] lemma span_singleton_one : span (1 : set α) = ⊤ := (eq_top_iff_one _).2 $ subset_span $ mem_singleton _ lemma mem_span_insert {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃ a (z ∈ span s), x = a * y + z := submodule.mem_span_insert lemma mem_span_insert' {s : set α} {x y} : x ∈ span (insert y s) ↔ ∃a, x + a * y ∈ span s := submodule.mem_span_insert' lemma mem_span_singleton' {x y : α} : x ∈ span ({y} : set α) ↔ ∃ a, a * y = x := submodule.mem_span_singleton lemma mem_span_singleton {x y : α} : x ∈ span ({y} : set α) ↔ y ∣ x := mem_span_singleton'.trans $ exists_congr $ λ _, by rw [eq_comm, mul_comm] lemma span_singleton_le_span_singleton {x y : α} : span ({x} : set α) ≤ span ({y} : set α) ↔ y ∣ x := span_le.trans $ singleton_subset_iff.trans mem_span_singleton lemma span_singleton_eq_span_singleton {α : Type u} [integral_domain α] {x y : α} : span ({x} : set α) = span ({y} : set α) ↔ associated x y := begin rw [←dvd_dvd_iff_associated, le_antisymm_iff, and_comm], apply and_congr; rw span_singleton_le_span_singleton, end lemma span_eq_bot {s : set α} : span s = ⊥ ↔ ∀ x ∈ s, (x:α) = 0 := submodule.span_eq_bot @[simp] lemma span_singleton_eq_bot {x} : span ({x} : set α) = ⊥ ↔ x = 0 := submodule.span_singleton_eq_bot @[simp] lemma span_zero : span (0 : set α) = ⊥ := by rw [←set.singleton_zero, span_singleton_eq_bot] lemma span_singleton_eq_top {x} : span ({x} : set α) = ⊤ ↔ is_unit x := by rw [is_unit_iff_dvd_one, ← span_singleton_le_span_singleton, singleton_one, span_singleton_one, eq_top_iff] lemma span_singleton_mul_right_unit {a : α} (h2 : is_unit a) (x : α) : span ({x * a} : set α) = span {x} := begin apply le_antisymm, { rw span_singleton_le_span_singleton, use a}, { rw span_singleton_le_span_singleton, rw is_unit.mul_right_dvd h2} end lemma span_singleton_mul_left_unit {a : α} (h2 : is_unit a) (x : α) : span ({a * x} : set α) = span {x} := by rw [mul_comm, span_singleton_mul_right_unit h2] /-- The ideal generated by an arbitrary binary relation. -/ def of_rel (r : α → α → Prop) : ideal α := submodule.span α { x | ∃ (a b) (h : r a b), x = a - b } /-- An ideal `P` of a ring `R` is prime if `P ≠ R` and `xy ∈ P → x ∈ P ∨ y ∈ P` -/ @[class] def is_prime (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I theorem is_prime.mem_or_mem {I : ideal α} (hI : I.is_prime) : ∀ {x y : α}, x * y ∈ I → x ∈ I ∨ y ∈ I := hI.2 theorem is_prime.mem_or_mem_of_mul_eq_zero {I : ideal α} (hI : I.is_prime) {x y : α} (h : x * y = 0) : x ∈ I ∨ y ∈ I := hI.2 (h.symm ▸ I.zero_mem) theorem is_prime.mem_of_pow_mem {I : ideal α} (hI : I.is_prime) {r : α} (n : ℕ) (H : r^n ∈ I) : r ∈ I := begin induction n with n ih, { exact (mt (eq_top_iff_one _).2 hI.1).elim H }, exact or.cases_on (hI.mem_or_mem H) id ih end lemma not_is_prime_iff {I : ideal α} : ¬ I.is_prime ↔ I = ⊤ ∨ ∃ (x ∉ I) (y ∉ I), x * y ∈ I := begin simp_rw [ideal.is_prime, not_and_distrib, ne.def, not_not, not_forall, not_or_distrib], exact or_congr iff.rfl ⟨λ ⟨x, y, hxy, hx, hy⟩, ⟨x, hx, y, hy, hxy⟩, λ ⟨x, hx, y, hy, hxy⟩, ⟨x, y, hxy, hx, hy⟩⟩ end theorem zero_ne_one_of_proper {I : ideal α} (h : I ≠ ⊤) : (0:α) ≠ 1 := λ hz, I.ne_top_iff_one.1 h $ hz ▸ I.zero_mem theorem span_singleton_prime {p : α} (hp : p ≠ 0) : is_prime (span ({p} : set α)) ↔ prime p := by simp [is_prime, prime, span_singleton_eq_top, hp, mem_span_singleton] lemma bot_prime {R : Type*} [integral_domain R] : (⊥ : ideal R).is_prime := ⟨λ h, one_ne_zero (by rwa [ideal.eq_top_iff_one, submodule.mem_bot] at h), λ x y h, mul_eq_zero.mp (by simpa only [submodule.mem_bot] using h)⟩ /-- An ideal is maximal if it is maximal in the collection of proper ideals. -/ @[class] def is_maximal (I : ideal α) : Prop := I ≠ ⊤ ∧ ∀ J, I < J → J = ⊤ theorem is_maximal_iff {I : ideal α} : I.is_maximal ↔ (1:α) ∉ I ∧ ∀ (J : ideal α) x, I ≤ J → x ∉ I → x ∈ J → (1:α) ∈ J := and_congr I.ne_top_iff_one $ forall_congr $ λ J, by rw [lt_iff_le_not_le]; exact ⟨λ H x h hx₁ hx₂, J.eq_top_iff_one.1 $ H ⟨h, not_subset.2 ⟨_, hx₂, hx₁⟩⟩, λ H ⟨h₁, h₂⟩, let ⟨x, xJ, xI⟩ := not_subset.1 h₂ in J.eq_top_iff_one.2 $ H x h₁ xI xJ⟩ theorem is_maximal.eq_of_le {I J : ideal α} (hI : I.is_maximal) (hJ : J ≠ ⊤) (IJ : I ≤ J) : I = J := eq_iff_le_not_lt.2 ⟨IJ, λ h, hJ (hI.2 _ h)⟩ theorem is_maximal.exists_inv {I : ideal α} (hI : I.is_maximal) {x} (hx : x ∉ I) : ∃ y, y * x - 1 ∈ I := begin cases is_maximal_iff.1 hI with H₁ H₂, rcases mem_span_insert'.1 (H₂ (span (insert x I)) x (set.subset.trans (subset_insert _ _) subset_span) hx (subset_span (mem_insert _ _))) with ⟨y, hy⟩, rw [span_eq, ← neg_mem_iff, add_comm, neg_add', neg_mul_eq_neg_mul] at hy, exact ⟨-y, hy⟩ end theorem is_maximal.is_prime {I : ideal α} (H : I.is_maximal) : I.is_prime := ⟨H.1, λ x y hxy, or_iff_not_imp_left.2 $ λ hx, begin cases H.exists_inv hx with z hz, have := I.mul_mem_left hz, rw [mul_sub, mul_one, mul_comm, mul_assoc] at this, exact I.neg_mem_iff.1 ((I.add_mem_iff_right $ I.mul_mem_left hxy).1 this) end⟩ @[priority 100] -- see Note [lower instance priority] instance is_maximal.is_prime' (I : ideal α) : ∀ [H : I.is_maximal], I.is_prime := is_maximal.is_prime /-- Krull's theorem: if `I` is an ideal that is not the whole ring, then it is included in some maximal ideal. -/ theorem exists_le_maximal (I : ideal α) (hI : I ≠ ⊤) : ∃ M : ideal α, M.is_maximal ∧ I ≤ M := begin rcases zorn.zorn_partial_order₀ { J : ideal α | J ≠ ⊤ } _ I hI with ⟨M, M0, IM, h⟩, { refine ⟨M, ⟨M0, λ J hJ, by_contradiction $ λ J0, _⟩, IM⟩, cases h J J0 (le_of_lt hJ), exact lt_irrefl _ hJ }, { intros S SC cC I IS, refine ⟨Sup S, λ H, _, λ _, le_Sup⟩, obtain ⟨J, JS, J0⟩ : ∃ J ∈ S, (1 : α) ∈ J, from (submodule.mem_Sup_of_directed ⟨I, IS⟩ cC.directed_on).1 ((eq_top_iff_one _).1 H), exact SC JS ((eq_top_iff_one _).2 J0) } end /-- Krull's theorem: a nontrivial ring has a maximal ideal. -/ theorem exists_maximal [nontrivial α] : ∃ M : ideal α, M.is_maximal := let ⟨I, ⟨hI, _⟩⟩ := exists_le_maximal (⊥ : ideal α) submodule.bot_ne_top in ⟨I, hI⟩ /-- If P is not properly contained in any maximal ideal then it is not properly contained in any proper ideal -/ lemma maximal_of_no_maximal {R : Type u} [comm_ring R] {P : ideal R} (hmax : ∀ m : ideal R, P < m → ¬is_maximal m) (J : ideal R) (hPJ : P < J) : J = ⊤ := begin by_contradiction hnonmax, rcases exists_le_maximal J hnonmax with ⟨M, hM1, hM2⟩, exact hmax M (lt_of_lt_of_le hPJ hM2) hM1, end theorem mem_span_pair {x y z : α} : z ∈ span ({x, y} : set α) ↔ ∃ a b, a * x + b * y = z := by simp [mem_span_insert, mem_span_singleton', @eq_comm _ _ z] lemma span_singleton_lt_span_singleton [integral_domain β] {x y : β} : span ({x} : set β) < span ({y} : set β) ↔ dvd_not_unit y x := by rw [lt_iff_le_not_le, span_singleton_le_span_singleton, span_singleton_le_span_singleton, dvd_and_not_dvd_iff] lemma factors_decreasing [integral_domain β] (b₁ b₂ : β) (h₁ : b₁ ≠ 0) (h₂ : ¬ is_unit b₂) : span ({b₁ * b₂} : set β) < span {b₁} := lt_of_le_not_le (ideal.span_le.2 $ singleton_subset_iff.2 $ ideal.mem_span_singleton.2 ⟨b₂, rfl⟩) $ λ h, h₂ $ is_unit_of_dvd_one _ $ (mul_dvd_mul_iff_left h₁).1 $ by rwa [mul_one, ← ideal.span_singleton_le_span_singleton] /-- The quotient `R/I` of a ring `R` by an ideal `I`. -/ def quotient (I : ideal α) := I.quotient namespace quotient variables {I} {x y : α} instance (I : ideal α) : has_one I.quotient := ⟨submodule.quotient.mk 1⟩ instance (I : ideal α) : has_mul I.quotient := ⟨λ a b, quotient.lift_on₂' a b (λ a b, submodule.quotient.mk (a * b)) $ λ a₁ a₂ b₁ b₂ h₁ h₂, quot.sound $ begin refine calc a₁ * a₂ - b₁ * b₂ = a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁ : _ ... ∈ I : I.add_mem (I.mul_mem_left h₁) (I.mul_mem_right h₂), rw [mul_sub, sub_mul, sub_add_sub_cancel, mul_comm, mul_comm b₁] end⟩ instance (I : ideal α) : comm_ring I.quotient := { mul := (*), one := 1, mul_assoc := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (mul_assoc a b c), mul_comm := λ a b, quotient.induction_on₂' a b $ λ a b, congr_arg submodule.quotient.mk (mul_comm a b), one_mul := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (one_mul a), mul_one := λ a, quotient.induction_on' a $ λ a, congr_arg submodule.quotient.mk (mul_one a), left_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (left_distrib a b c), right_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg submodule.quotient.mk (right_distrib a b c), ..submodule.quotient.add_comm_group I } /-- The ring homomorphism from a ring `R` to a quotient ring `R/I`. -/ def mk (I : ideal α) : α →+* I.quotient := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ instance : inhabited (quotient I) := ⟨mk I 37⟩ protected theorem eq : mk I x = mk I y ↔ x - y ∈ I := submodule.quotient.eq I @[simp] theorem mk_eq_mk (x : α) : (submodule.quotient.mk x : quotient I) = mk I x := rfl lemma eq_zero_iff_mem {I : ideal α} : mk I a = 0 ↔ a ∈ I := by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq' theorem zero_eq_one_iff {I : ideal α} : (0 : I.quotient) = 1 ↔ I = ⊤ := eq_comm.trans $ eq_zero_iff_mem.trans (eq_top_iff_one _).symm theorem zero_ne_one_iff {I : ideal α} : (0 : I.quotient) ≠ 1 ↔ I ≠ ⊤ := not_congr zero_eq_one_iff protected theorem nontrivial {I : ideal α} (hI : I ≠ ⊤) : nontrivial I.quotient := ⟨⟨0, 1, zero_ne_one_iff.2 hI⟩⟩ lemma mk_surjective : function.surjective (mk I) := λ y, quotient.induction_on' y (λ x, exists.intro x rfl) instance (I : ideal α) [hI : I.is_prime] : integral_domain I.quotient := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, quotient.induction_on₂' a b $ λ a b hab, (hI.mem_or_mem (eq_zero_iff_mem.1 hab)).elim (or.inl ∘ eq_zero_iff_mem.2) (or.inr ∘ eq_zero_iff_mem.2), .. quotient.comm_ring I, .. quotient.nontrivial hI.1 } lemma is_integral_domain_iff_prime (I : ideal α) : is_integral_domain I.quotient ↔ I.is_prime := ⟨ λ ⟨h1, h2, h3⟩, ⟨zero_ne_one_iff.1 $ @zero_ne_one _ _ ⟨h1⟩, λ x y h, by { simp only [←eq_zero_iff_mem, (mk I).map_mul] at ⊢ h, exact h3 _ _ h}⟩, λ h, by exactI integral_domain.to_is_integral_domain I.quotient⟩ lemma exists_inv {I : ideal α} [hI : I.is_maximal] : ∀ {a : I.quotient}, a ≠ 0 → ∃ b : I.quotient, a * b = 1 := begin rintro ⟨a⟩ h, cases hI.exists_inv (mt eq_zero_iff_mem.2 h) with b hb, rw [mul_comm] at hb, exact ⟨mk _ b, quot.sound hb⟩ end /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications -/ protected noncomputable def field (I : ideal α) [hI : I.is_maximal] : field I.quotient := { inv := λ a, if ha : a = 0 then 0 else classical.some (exists_inv ha), mul_inv_cancel := λ a (ha : a ≠ 0), show a * dite _ _ _ = _, by rw dif_neg ha; exact classical.some_spec (exists_inv ha), inv_zero := dif_pos rfl, ..quotient.integral_domain I } /-- If the quotient by an ideal is a field, then the ideal is maximal. -/ theorem maximal_of_is_field (I : ideal α) (hqf : is_field I.quotient) : I.is_maximal := begin apply ideal.is_maximal_iff.2, split, { intro h, rcases hqf.exists_pair_ne with ⟨⟨x⟩, ⟨y⟩, hxy⟩, exact hxy (ideal.quotient.eq.2 (mul_one (x - y) ▸ I.mul_mem_left h)) }, { intros J x hIJ hxnI hxJ, rcases hqf.mul_inv_cancel (mt ideal.quotient.eq_zero_iff_mem.1 hxnI) with ⟨⟨y⟩, hy⟩, rw [← zero_add (1 : α), ← sub_self (x * y), sub_add], refine J.sub_mem (J.mul_mem_right hxJ) (hIJ (ideal.quotient.eq.1 hy)) } end /-- The quotient of a ring by an ideal is a field iff the ideal is maximal. -/ theorem maximal_ideal_iff_is_field_quotient (I : ideal α) : I.is_maximal ↔ is_field I.quotient := ⟨λ h, @field.to_is_field I.quotient (@ideal.quotient.field _ _ I h), λ h, maximal_of_is_field I h⟩ variable [comm_ring β] /-- Given a ring homomorphism `f : α →+* β` sending all elements of an ideal to zero, lift it to the quotient by this ideal. -/ def lift (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : quotient S →+* β := { to_fun := λ x, quotient.lift_on' x f $ λ (a b) (h : _ ∈ _), eq_of_sub_eq_zero $ by rw [← f.map_sub, H _ h], map_one' := f.map_one, map_zero' := f.map_zero, map_add' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_add, map_mul' := λ a₁ a₂, quotient.induction_on₂' a₁ a₂ f.map_mul } @[simp] lemma lift_mk (S : ideal α) (f : α →+* β) (H : ∀ (a : α), a ∈ S → f a = 0) : lift S f H (mk S a) = f a := rfl end quotient section lattice variables {R : Type u} [comm_ring R] lemma mem_sup_left {S T : ideal R} : ∀ {x : R}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left lemma mem_sup_right {S T : ideal R} : ∀ {x : R}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right lemma mem_supr_of_mem {ι : Type*} {S : ι → ideal R} (i : ι) : ∀ {x : R}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ lemma mem_Sup_of_mem {S : set (ideal R)} {s : ideal R} (hs : s ∈ S) : ∀ {x : R}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs theorem mem_Inf {s : set (ideal R)} {x : R} : x ∈ Inf s ↔ ∀ ⦃I⦄, I ∈ s → x ∈ I := ⟨λ hx I his, hx I ⟨I, infi_pos his⟩, λ H I ⟨J, hij⟩, hij ▸ λ S ⟨hj, hS⟩, hS ▸ H hj⟩ @[simp] lemma mem_inf {I J : ideal R} {x : R} : x ∈ I ⊓ J ↔ x ∈ I ∧ x ∈ J := iff.rfl @[simp] lemma mem_infi {ι : Type*} {I : ι → ideal R} {x : R} : x ∈ infi I ↔ ∀ i, x ∈ I i := submodule.mem_infi _ @[simp] lemma mem_bot {x : R} : x ∈ (⊥ : ideal R) ↔ x = 0 := submodule.mem_bot _ end lattice /-- All ideals in a field are trivial. -/ lemma eq_bot_or_top {K : Type u} [field K] (I : ideal K) : I = ⊥ ∨ I = ⊤ := begin rw or_iff_not_imp_right, change _ ≠ _ → _, rw ideal.ne_top_iff_one, intro h1, rw eq_bot_iff, intros r hr, by_cases H : r = 0, {simpa}, simpa [H, h1] using submodule.smul_mem I r⁻¹ hr, end lemma eq_bot_of_prime {K : Type u} [field K] (I : ideal K) [h : I.is_prime] : I = ⊥ := or_iff_not_imp_right.mp I.eq_bot_or_top h.1 lemma bot_is_maximal {K : Type u} [field K] : is_maximal (⊥ : ideal K) := ⟨λ h, absurd ((eq_top_iff_one (⊤ : ideal K)).mp rfl) (by rw ← h; simp), λ I hI, or_iff_not_imp_left.mp (eq_bot_or_top I) (ne_of_gt hI)⟩ section pi variables (ι : Type v) /-- `I^n` as an ideal of `R^n`. -/ def pi : ideal (ι → α) := { carrier := { x | ∀ i, x i ∈ I }, zero_mem' := λ i, submodule.zero_mem _, add_mem' := λ a b ha hb i, submodule.add_mem _ (ha i) (hb i), smul_mem' := λ a b hb i, ideal.mul_mem_left _ (hb i) } lemma mem_pi (x : ι → α) : x ∈ I.pi ι ↔ ∀ i, x i ∈ I := iff.rfl /-- `R^n/I^n` is a `R/I`-module. -/ instance module_pi : module (I.quotient) (I.pi ι).quotient := begin refine { smul := λ c m, quotient.lift_on₂' c m (λ r m, submodule.quotient.mk $ r • m) _, .. }, { intros c₁ m₁ c₂ m₂ hc hm, change c₁ - c₂ ∈ I at hc, change m₁ - m₂ ∈ (I.pi ι) at hm, apply ideal.quotient.eq.2, have : c₁ • (m₂ - m₁) ∈ I.pi ι, { rw ideal.mem_pi, intro i, simp only [smul_eq_mul, pi.smul_apply, pi.sub_apply], apply ideal.mul_mem_left, rw ←ideal.neg_mem_iff, simpa only [neg_sub] using hm i }, rw [←ideal.add_mem_iff_left (I.pi ι) this, sub_eq_add_neg, add_comm, ←add_assoc, ←smul_add, sub_add_cancel, ←sub_eq_add_neg, ←sub_smul, ideal.mem_pi], exact λ i, ideal.mul_mem_right _ hc }, all_goals { rintro ⟨a⟩ ⟨b⟩ ⟨c⟩ <|> rintro ⟨a⟩, simp only [(•), submodule.quotient.quot_mk_eq_mk, ideal.quotient.mk_eq_mk], change ideal.quotient.mk _ _ = ideal.quotient.mk _ _, congr' with i, simp [mul_assoc, mul_add, add_mul] } end /-- `R^n/I^n` is isomorphic to `(R/I)^n` as an `R/I`-module. -/ noncomputable def pi_quot_equiv : (I.pi ι).quotient ≃ₗ[I.quotient] (ι → I.quotient) := { to_fun := λ x, quotient.lift_on' x (λ f i, ideal.quotient.mk I (f i)) $ λ a b hab, funext (λ i, ideal.quotient.eq.2 (hab i)), map_add' := by { rintros ⟨_⟩ ⟨_⟩, refl }, map_smul' := by { rintros ⟨_⟩ ⟨_⟩, refl }, inv_fun := λ x, ideal.quotient.mk (I.pi ι) $ λ i, quotient.out' (x i), left_inv := begin rintro ⟨x⟩, exact ideal.quotient.eq.2 (λ i, ideal.quotient.eq.1 (quotient.out_eq' _)) end, right_inv := begin intro x, ext i, obtain ⟨r, hr⟩ := @quot.exists_rep _ _ (x i), simp_rw ←hr, convert quotient.out_eq' _ end } /-- If `f : R^n → R^m` is an `R`-linear map and `I ⊆ R` is an ideal, then the image of `I^n` is contained in `I^m`. -/ lemma map_pi {ι} [fintype ι] {ι' : Type w} (x : ι → α) (hi : ∀ i, x i ∈ I) (f : (ι → α) →ₗ[α] (ι' → α)) (i : ι') : f x i ∈ I := begin rw pi_eq_sum_univ x, simp only [finset.sum_apply, smul_eq_mul, linear_map.map_sum, pi.smul_apply, linear_map.map_smul], exact submodule.sum_mem _ (λ j hj, ideal.mul_mem_right _ (hi j)) end end pi end ideal namespace ring variables {R : Type*} [comm_ring R] lemma not_is_field_of_subsingleton {R : Type*} [ring R] [subsingleton R] : ¬ is_field R := λ ⟨⟨x, y, hxy⟩, _, _⟩, hxy (subsingleton.elim x y) lemma exists_not_is_unit_of_not_is_field [nontrivial R] (hf : ¬ is_field R) : ∃ x ≠ (0 : R), ¬ is_unit x := begin have : ¬ _ := λ h, hf ⟨exists_pair_ne R, mul_comm, h⟩, simp_rw is_unit_iff_exists_inv, push_neg at ⊢ this, obtain ⟨x, hx, not_unit⟩ := this, exact ⟨x, hx, not_unit⟩ end lemma not_is_field_iff_exists_ideal_bot_lt_and_lt_top [nontrivial R] : ¬ is_field R ↔ ∃ I : ideal R, ⊥ < I ∧ I < ⊤ := begin split, { intro h, obtain ⟨x, nz, nu⟩ := exists_not_is_unit_of_not_is_field h, use ideal.span {x}, rw [bot_lt_iff_ne_bot, lt_top_iff_ne_top], exact ⟨mt ideal.span_singleton_eq_bot.mp nz, mt ideal.span_singleton_eq_top.mp nu⟩ }, { rintros ⟨I, bot_lt, lt_top⟩ hf, obtain ⟨x, mem, ne_zero⟩ := submodule.exists_of_lt bot_lt, rw submodule.mem_bot at ne_zero, obtain ⟨y, hy⟩ := hf.mul_inv_cancel ne_zero, rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ← hy] at lt_top, exact lt_top (ideal.mul_mem_right _ mem), } end lemma not_is_field_iff_exists_prime [nontrivial R] : ¬ is_field R ↔ ∃ p : ideal R, p ≠ ⊥ ∧ p.is_prime := not_is_field_iff_exists_ideal_bot_lt_and_lt_top.trans ⟨λ ⟨I, bot_lt, lt_top⟩, let ⟨p, hp, le_p⟩ := I.exists_le_maximal (lt_top_iff_ne_top.mp lt_top) in ⟨p, bot_lt_iff_ne_bot.mp (lt_of_lt_of_le bot_lt le_p), hp.is_prime⟩, λ ⟨p, ne_bot, prime⟩, ⟨p, bot_lt_iff_ne_bot.mpr ne_bot, lt_top_iff_ne_top.mpr prime.1⟩⟩ end ring namespace ideal /-- Maximal ideals in a non-field are nontrivial. -/ variables {R : Type u} [comm_ring R] [nontrivial R] lemma bot_lt_of_maximal (M : ideal R) [hm : M.is_maximal] (non_field : ¬ is_field R) : ⊥ < M := begin rcases (ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top.1 non_field) with ⟨I, Ibot, Itop⟩, split, finish, intro mle, apply @irrefl _ (<) _ (⊤ : ideal R), have : M = ⊥ := eq_bot_iff.mpr mle, rw this at *, rwa hm.2 I Ibot at Itop, end end ideal /-- The set of non-invertible elements of a monoid. -/ def nonunits (α : Type u) [monoid α] : set α := { a | ¬is_unit a } @[simp] theorem mem_nonunits_iff [comm_monoid α] : a ∈ nonunits α ↔ ¬ is_unit a := iff.rfl theorem mul_mem_nonunits_right [comm_monoid α] : b ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_right theorem mul_mem_nonunits_left [comm_monoid α] : a ∈ nonunits α → a * b ∈ nonunits α := mt is_unit_of_mul_is_unit_left theorem zero_mem_nonunits [semiring α] : 0 ∈ nonunits α ↔ (0:α) ≠ 1 := not_congr is_unit_zero_iff @[simp] theorem one_not_mem_nonunits [monoid α] : (1:α) ∉ nonunits α := not_not_intro is_unit_one theorem coe_subset_nonunits [comm_ring α] {I : ideal α} (h : I ≠ ⊤) : (I : set α) ⊆ nonunits α := λ x hx hu, h $ I.eq_top_of_is_unit_mem hx hu lemma exists_max_ideal_of_mem_nonunits [comm_ring α] (h : a ∈ nonunits α) : ∃ I : ideal α, I.is_maximal ∧ a ∈ I := begin have : ideal.span ({a} : set α) ≠ ⊤, { intro H, rw ideal.span_singleton_eq_top at H, contradiction }, rcases ideal.exists_le_maximal _ this with ⟨I, Imax, H⟩, use [I, Imax], apply H, apply ideal.subset_span, exact set.mem_singleton a end /-- A commutative ring is local if it has a unique maximal ideal. Note that `local_ring` is a predicate. -/ class local_ring (α : Type u) [comm_ring α] extends nontrivial α : Prop := (is_local : ∀ (a : α), (is_unit a) ∨ (is_unit (1 - a))) namespace local_ring variables [comm_ring α] [local_ring α] lemma is_unit_or_is_unit_one_sub_self (a : α) : (is_unit a) ∨ (is_unit (1 - a)) := is_local a lemma is_unit_of_mem_nonunits_one_sub_self (a : α) (h : (1 - a) ∈ nonunits α) : is_unit a := or_iff_not_imp_right.1 (is_local a) h lemma is_unit_one_sub_self_of_mem_nonunits (a : α) (h : a ∈ nonunits α) : is_unit (1 - a) := or_iff_not_imp_left.1 (is_local a) h lemma nonunits_add {x y} (hx : x ∈ nonunits α) (hy : y ∈ nonunits α) : x + y ∈ nonunits α := begin rintros ⟨u, hu⟩, apply hy, suffices : is_unit ((↑u⁻¹ : α) * y), { rcases this with ⟨s, hs⟩, use u * s, convert congr_arg (λ z, (u : α) * z) hs, rw ← mul_assoc, simp }, rw show (↑u⁻¹ * y) = (1 - ↑u⁻¹ * x), { rw eq_sub_iff_add_eq, replace hu := congr_arg (λ z, (↑u⁻¹ : α) * z) hu.symm, simpa [mul_add, add_comm] using hu }, apply is_unit_one_sub_self_of_mem_nonunits, exact mul_mem_nonunits_right hx end variable (α) /-- The ideal of elements that are not units. -/ def maximal_ideal : ideal α := { carrier := nonunits α, zero_mem' := zero_mem_nonunits.2 $ zero_ne_one, add_mem' := λ x y hx hy, nonunits_add hx hy, smul_mem' := λ a x, mul_mem_nonunits_right } instance maximal_ideal.is_maximal : (maximal_ideal α).is_maximal := begin rw ideal.is_maximal_iff, split, { intro h, apply h, exact is_unit_one }, { intros I x hI hx H, erw not_not at hx, rcases hx with ⟨u,rfl⟩, simpa using I.smul_mem ↑u⁻¹ H } end lemma maximal_ideal_unique : ∃! I : ideal α, I.is_maximal := ⟨maximal_ideal α, maximal_ideal.is_maximal α, λ I hI, hI.eq_of_le (maximal_ideal.is_maximal α).1 $ λ x hx, hI.1 ∘ I.eq_top_of_is_unit_mem hx⟩ variable {α} lemma eq_maximal_ideal {I : ideal α} (hI : I.is_maximal) : I = maximal_ideal α := unique_of_exists_unique (maximal_ideal_unique α) hI $ maximal_ideal.is_maximal α lemma le_maximal_ideal {J : ideal α} (hJ : J ≠ ⊤) : J ≤ maximal_ideal α := begin rcases ideal.exists_le_maximal J hJ with ⟨M, hM1, hM2⟩, rwa ←eq_maximal_ideal hM1 end @[simp] lemma mem_maximal_ideal (x) : x ∈ maximal_ideal α ↔ x ∈ nonunits α := iff.rfl end local_ring lemma local_of_nonunits_ideal [comm_ring α] (hnze : (0:α) ≠ 1) (h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : local_ring α := { exists_pair_ne := ⟨0, 1, hnze⟩, is_local := λ x, or_iff_not_imp_left.mpr $ λ hx, begin by_contra H, apply h _ _ hx H, simp [-sub_eq_add_neg, add_sub_cancel'_right] end } lemma local_of_unique_max_ideal [comm_ring α] (h : ∃! I : ideal α, I.is_maximal) : local_ring α := local_of_nonunits_ideal (let ⟨I, Imax, _⟩ := h in (λ (H : 0 = 1), Imax.1 $ I.eq_top_iff_one.2 $ H ▸ I.zero_mem)) $ λ x y hx hy H, let ⟨I, Imax, Iuniq⟩ := h in let ⟨Ix, Ixmax, Hx⟩ := exists_max_ideal_of_mem_nonunits hx in let ⟨Iy, Iymax, Hy⟩ := exists_max_ideal_of_mem_nonunits hy in have xmemI : x ∈ I, from ((Iuniq Ix Ixmax) ▸ Hx), have ymemI : y ∈ I, from ((Iuniq Iy Iymax) ▸ Hy), Imax.1 $ I.eq_top_of_is_unit_mem (I.add_mem xmemI ymemI) H lemma local_of_unique_nonzero_prime (R : Type u) [comm_ring R] (h : ∃! P : ideal R, P ≠ ⊥ ∧ ideal.is_prime P) : local_ring R := local_of_unique_max_ideal begin rcases h with ⟨P, ⟨hPnonzero, hPnot_top, _⟩, hPunique⟩, refine ⟨P, ⟨hPnot_top, _⟩, λ M hM, hPunique _ ⟨_, ideal.is_maximal.is_prime hM⟩⟩, { refine ideal.maximal_of_no_maximal (λ M hPM hM, ne_of_lt hPM _), exact (hPunique _ ⟨ne_bot_of_gt hPM, ideal.is_maximal.is_prime hM⟩).symm }, { rintro rfl, exact hPnot_top (hM.2 P (bot_lt_iff_ne_bot.2 hPnonzero)) }, end lemma local_of_surjective {A B : Type*} [comm_ring A] [local_ring A] [comm_ring B] [nontrivial B] (f : A →+* B) (hf : function.surjective f) : local_ring B := { is_local := begin intros b, obtain ⟨a, rfl⟩ := hf b, apply (local_ring.is_unit_or_is_unit_one_sub_self a).imp f.is_unit_map _, rw [← f.map_one, ← f.map_sub], apply f.is_unit_map, end, .. ‹nontrivial B› } /-- A local ring homomorphism is a homomorphism between local rings such that the image of the maximal ideal of the source is contained within the maximal ideal of the target. -/ class is_local_ring_hom [semiring α] [semiring β] (f : α →+* β) : Prop := (map_nonunit : ∀ a, is_unit (f a) → is_unit a) instance is_local_ring_hom_id (A : Type*) [semiring A] : is_local_ring_hom (ring_hom.id A) := { map_nonunit := λ a, id } @[simp] lemma is_unit_map_iff {A B : Type*} [semiring A] [semiring B] (f : A →+* B) [is_local_ring_hom f] (a) : is_unit (f a) ↔ is_unit a := ⟨is_local_ring_hom.map_nonunit a, f.is_unit_map⟩ instance is_local_ring_hom_comp {A B C : Type*} [semiring A] [semiring B] [semiring C] (g : B →+* C) (f : A →+* B) [is_local_ring_hom g] [is_local_ring_hom f] : is_local_ring_hom (g.comp f) := { map_nonunit := λ a, is_local_ring_hom.map_nonunit a ∘ is_local_ring_hom.map_nonunit (f a) } @[simp] lemma is_unit_of_map_unit [semiring α] [semiring β] (f : α →+* β) [is_local_ring_hom f] (a) (h : is_unit (f a)) : is_unit a := is_local_ring_hom.map_nonunit a h theorem of_irreducible_map [semiring α] [semiring β] (f : α →+* β) [h : is_local_ring_hom f] {x : α} (hfx : irreducible (f x)) : irreducible x := ⟨λ h, hfx.1 $ is_unit.map f.to_monoid_hom h, λ p q hx, let ⟨H⟩ := h in or.imp (H p) (H q) $ hfx.2 _ _ $ f.map_mul p q ▸ congr_arg f hx⟩ section open local_ring variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β] variables (f : α →+* β) [is_local_ring_hom f] lemma map_nonunit (a) (h : a ∈ maximal_ideal α) : f a ∈ maximal_ideal β := λ H, h $ is_unit_of_map_unit f a H end namespace local_ring variables [comm_ring α] [local_ring α] [comm_ring β] [local_ring β] variable (α) /-- The residue field of a local ring is the quotient of the ring by its maximal ideal. -/ def residue_field := (maximal_ideal α).quotient noncomputable instance residue_field.field : field (residue_field α) := ideal.quotient.field (maximal_ideal α) noncomputable instance : inhabited (residue_field α) := ⟨37⟩ /-- The quotient map from a local ring to its residue field. -/ def residue : α →+* (residue_field α) := ideal.quotient.mk _ namespace residue_field variables {α β} /-- The map on residue fields induced by a local homomorphism between local rings -/ noncomputable def map (f : α →+* β) [is_local_ring_hom f] : residue_field α →+* residue_field β := ideal.quotient.lift (maximal_ideal α) ((ideal.quotient.mk _).comp f) $ λ a ha, begin erw ideal.quotient.eq_zero_iff_mem, exact map_nonunit f a ha end end residue_field end local_ring namespace field variables [field α] @[priority 100] -- see Note [lower instance priority] instance : local_ring α := { is_local := λ a, if h : a = 0 then or.inr (by rw [h, sub_zero]; exact is_unit_one) else or.inl $ is_unit_of_mul_eq_one a a⁻¹ $ div_self h } end field
7b92eb8abae96272c96f49ebe585c972869fd4c3
bdb33f8b7ea65f7705fc342a178508e2722eb851
/data/num/lemmas.lean
113604ae8f631681e6fd65e86062359243b13163
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
37,513
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Properties of the binary representation of integers. -/ import data.num.basic data.num.bitwise algebra.order tactic.interactive data.int.basic namespace pos_num variables {α : Type*} @[simp] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : pos_num) : α) = 1 := rfl theorem one_add (n : pos_num) : 1 + n = succ n := by cases n; refl @[simp] theorem cast_bit0 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit0 : α) = _root_.bit0 n := rfl @[simp] theorem cast_bit1 [has_zero α] [has_one α] [has_add α] (n : pos_num) : (n.bit1 : α) = _root_.bit1 n := rfl @[simp] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : pos_num, ((n : ℕ) : α) = n | 1 := nat.cast_one | (bit0 p) := (nat.cast_bit0 _).trans $ congr_arg _root_.bit0 p.cast_to_nat | (bit1 p) := (nat.cast_bit1 _).trans $ congr_arg _root_.bit1 p.cast_to_nat @[simp] theorem cast_to_int [add_group α] [has_one α] (n : pos_num) : ((n : ℤ) : α) = n := by rw [← cast_to_nat, int.nat_cast_eq_coe_nat, int.cast_coe_nat, cast_to_nat] theorem succ_to_nat : ∀ n, (succ n : ℕ) = n + 1 | 1 := rfl | (bit0 p) := rfl | (bit1 p) := (congr_arg _root_.bit0 (succ_to_nat p)).trans $ show ↑p + 1 + ↑p + 1 = ↑p + ↑p + 1 + 1, by simp theorem add_one (n : pos_num) : n + 1 = succ n := by cases n; refl @[simp] theorem add_to_nat : ∀ m n, ((m + n : pos_num) : ℕ) = m + n | 1 b := by rw [one_add b, succ_to_nat, add_comm]; refl | a 1 := by rw [add_one a, succ_to_nat]; refl | (bit0 a) (bit0 b) := (congr_arg _root_.bit0 (add_to_nat a b)).trans $ show ((a + b) + (a + b) : ℕ) = (a + a) + (b + b), by simp | (bit0 a) (bit1 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a) + (b + b + 1), by simp | (bit1 a) (bit0 b) := (congr_arg _root_.bit1 (add_to_nat a b)).trans $ show ((a + b) + (a + b) + 1 : ℕ) = (a + a + 1) + (b + b), by simp | (bit1 a) (bit1 b) := show (succ (a + b) + succ (a + b) : ℕ) = (a + a + 1) + (b + b + 1), by rw [succ_to_nat, add_to_nat]; simp theorem add_succ : ∀ (m n : pos_num), m + succ n = succ (m + n) | 1 b := by simp [one_add] | (bit0 a) 1 := congr_arg bit0 (add_one a) | (bit1 a) 1 := congr_arg bit1 (add_one a) | (bit0 a) (bit0 b) := rfl | (bit0 a) (bit1 b) := congr_arg bit0 (add_succ a b) | (bit1 a) (bit0 b) := rfl | (bit1 a) (bit1 b) := congr_arg bit1 (add_succ a b) theorem bit0_of_bit0 : Π n, _root_.bit0 n = bit0 n | 1 := rfl | (bit0 p) := congr_arg bit0 (bit0_of_bit0 p) | (bit1 p) := show bit0 (succ (_root_.bit0 p)) = _, by rw bit0_of_bit0; refl theorem bit1_of_bit1 (n : pos_num) : _root_.bit1 n = bit1 n := show _root_.bit0 n + 1 = bit1 n, by rw [add_one, bit0_of_bit0]; refl @[simp] theorem mul_to_nat (m) : ∀ n, ((m * n : pos_num) : ℕ) = m * n | 1 := (mul_one _).symm | (bit0 p) := show (↑(m * p) + ↑(m * p) : ℕ) = ↑m * (p + p), by rw [mul_to_nat, left_distrib] | (bit1 p) := (add_to_nat (bit0 (m * p)) m).trans $ show (↑(m * p) + ↑(m * p) + ↑m : ℕ) = ↑m * (p + p) + m, by rw [mul_to_nat, left_distrib] theorem to_nat_pos : ∀ n : pos_num, (n : ℕ) > 0 | 1 := zero_lt_one | (bit0 p) := let h := to_nat_pos p in add_pos h h | (bit1 p) := nat.succ_pos _ theorem cmp_to_nat_lemma {m n : pos_num} : (m:ℕ) < n → (bit1 m : ℕ) < bit0 n := show (m:ℕ) < n → (m + m + 1 + 1 : ℕ) ≤ n + n, by intro h; rw [nat.add_right_comm m m 1, add_assoc]; exact add_le_add h h theorem cmp_swap (m) : ∀n, (cmp m n).swap = cmp n m := by induction m with m IH m IH; intro n; cases n with n n; try {unfold cmp}; try {refl}; rw ←IH; cases cmp m n; refl theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 1 1 := rfl | (bit0 a) 1 := let h : (1:ℕ) ≤ a := to_nat_pos a in add_le_add h h | (bit1 a) 1 := nat.succ_lt_succ $ to_nat_pos $ bit0 a | 1 (bit0 b) := let h : (1:ℕ) ≤ b := to_nat_pos b in add_le_add h h | 1 (bit1 b) := nat.succ_lt_succ $ to_nat_pos $ bit0 b | (bit0 a) (bit0 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact add_lt_add this this }, { rw this }, { exact add_lt_add this this } end | (bit0 a) (bit1 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.le_succ_of_le (add_lt_add this this) }, { rw this, apply nat.lt_succ_self }, { exact cmp_to_nat_lemma this } end | (bit1 a) (bit0 b) := begin dsimp [cmp], have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact cmp_to_nat_lemma this }, { rw this, apply nat.lt_succ_self }, { exact nat.le_succ_of_le (add_lt_add this this) }, end | (bit1 a) (bit1 b) := begin have := cmp_to_nat a b, revert this, cases cmp a b; dsimp; intro, { exact nat.succ_lt_succ (add_lt_add this this) }, { rw this }, { exact nat.succ_lt_succ (add_lt_add this this) } end @[simp] theorem lt_to_nat {m n : pos_num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[simp] theorem le_to_nat {m n : pos_num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end pos_num namespace num variables {α : Type*} open pos_num theorem add_zero (n : num) : n + 0 = n := by cases n; refl theorem zero_add (n : num) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : num, n + 1 = succ n | 0 := rfl | (pos p) := by cases p; refl theorem add_succ : ∀ (m n : num), m + succ n = succ (m + n) | 0 n := by simp [zero_add] | (pos p) 0 := show pos (p + 1) = succ (pos p + 0), by rw [pos_num.add_one, add_zero]; refl | (pos p) (pos q) := congr_arg pos (pos_num.add_succ _ _) @[simp] theorem add_of_nat (m) : ∀ n, ((m + n : ℕ) : num) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) + 1 : num) = m + (↑ n + 1), by rw [add_one, add_one, add_succ, add_of_nat] theorem bit0_of_bit0 : ∀ n : num, bit0 n = n.bit0 | 0 := rfl | (pos p) := congr_arg pos p.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : num, bit1 n = n.bit1 | 0 := rfl | (pos p) := congr_arg pos p.bit1_of_bit1 @[simp] theorem cast_zero [has_zero α] [has_one α] [has_add α] : ((0 : num) : α) = 0 := rfl @[simp] theorem cast_one [has_zero α] [has_one α] [has_add α] : ((1 : num) : α) = 1 := rfl theorem succ'_to_nat : ∀ n, (succ' n : ℕ) = n + 1 | 0 := (_root_.zero_add _).symm | (pos p) := pos_num.succ_to_nat _ theorem succ_to_nat (n) : (succ n : ℕ) = n + 1 := succ'_to_nat n @[simp] theorem cast_to_nat [add_monoid α] [has_one α] : ∀ n : num, ((n : ℕ) : α) = n | 0 := nat.cast_zero | (pos p) := p.cast_to_nat @[simp] theorem cast_to_int [add_group α] [has_one α] (n : num) : ((n : ℤ) : α) = n := by rw [← cast_to_nat, int.nat_cast_eq_coe_nat, int.cast_coe_nat, cast_to_nat] @[simp] theorem to_of_nat : Π (n : ℕ), ((n : num) : ℕ) = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, add_one, succ_to_nat, to_of_nat] theorem of_nat_inj {m n : ℕ} : (m : num) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse to_of_nat h, congr_arg _⟩ @[simp] theorem add_to_nat : ∀ m n, ((m + n : num) : ℕ) = m + n | 0 0 := rfl | 0 (pos q) := (_root_.zero_add _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.add_to_nat _ _ @[simp] theorem mul_to_nat : ∀ m n, ((m * n : num) : ℕ) = m * n | 0 0 := rfl | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := rfl | (pos p) (pos q) := pos_num.mul_to_nat _ _ theorem cmp_to_nat : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℕ) < n) (m = n) ((m:ℕ) > n) : Prop) | 0 0 := rfl | 0 (pos b) := to_nat_pos _ | (pos a) 0 := to_nat_pos _ | (pos a) (pos b) := by { have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b, exacts [id, congr_arg pos, id] } @[simp] theorem lt_to_nat {m n : num} : (m:ℕ) < n ↔ m < n := show (m:ℕ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_nat m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[simp] theorem le_to_nat {m n : num} : (m:ℕ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_nat end num namespace pos_num @[simp] theorem of_to_nat : Π (n : pos_num), ((n : ℕ) : num) = num.pos n | 1 := rfl | (bit0 p) := show ↑(p + p : ℕ) = num.pos p.bit0, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit0_of_bit0 | (bit1 p) := show ((p + p : ℕ) : num) + 1 = num.pos p.bit1, by rw [num.add_of_nat, of_to_nat]; exact congr_arg num.pos p.bit1_of_bit1 end pos_num namespace num @[simp] theorem of_to_nat : Π (n : num), ((n : ℕ) : num) = n | 0 := rfl | (pos p) := p.of_to_nat theorem to_nat_inj {m n : num} : (m : ℕ) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse of_to_nat h, congr_arg _⟩ meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp}] instance : comm_semiring num := by refine { add := (+), zero := 0, zero_add := zero_add, add_zero := add_zero, mul := (*), one := 1, .. }; try {transfer}; simp [mul_add, mul_left_comm, mul_comm] instance : ordered_cancel_comm_monoid num := { add_left_cancel := by {intros a b c, transfer_rw, apply add_left_cancel}, add_right_cancel := by {intros a b c, transfer_rw, apply add_right_cancel}, lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, le_of_add_le_add_left := by {intros a b c, transfer_rw, apply le_of_add_le_add_left}, ..num.comm_semiring } instance : decidable_linear_ordered_semiring num := { le_total := by {intros a b, transfer_rw, apply le_total}, zero_lt_one := dec_trivial, mul_le_mul_of_nonneg_left := by {intros a b c, transfer_rw, apply mul_le_mul_of_nonneg_left}, mul_le_mul_of_nonneg_right := by {intros a b c, transfer_rw, apply mul_le_mul_of_nonneg_right}, mul_lt_mul_of_pos_left := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_left}, mul_lt_mul_of_pos_right := by {intros a b c, transfer_rw, apply mul_lt_mul_of_pos_right}, decidable_lt := num.decidable_lt, decidable_le := num.decidable_le, decidable_eq := num.decidable_eq, ..num.comm_semiring, ..num.ordered_cancel_comm_monoid } end num namespace pos_num variables {α : Type*} open num theorem to_nat_inj {m n : pos_num} : (m : ℕ) = n ↔ m = n := ⟨λ h, num.pos.inj $ by rw [← pos_num.of_to_nat, ← pos_num.of_to_nat, h], congr_arg _⟩ theorem pred'_to_nat : ∀ n, (pred' n : ℕ) = nat.pred n | 1 := rfl | (bit0 n) := have nat.succ ↑(pred' n) = ↑n, by rw [pred'_to_nat n, nat.succ_pred_eq_of_pos (to_nat_pos n)], match pred' n, this : ∀ k : num, nat.succ ↑k = ↑n → ↑(num.cases_on k 1 bit1 : pos_num) = nat.pred (_root_.bit0 n) with | 0, (h : ((1:num):ℕ) = n) := by rw ← to_nat_inj.1 h; refl | num.pos p, (h : nat.succ ↑p = n) := by rw ← h; exact (nat.succ_add p p).symm end | (bit1 n) := rfl @[simp] theorem pred'_succ' (n) : pred' (succ' n) = n := num.to_nat_inj.1 $ by rw [pred'_to_nat, succ'_to_nat, nat.add_one, nat.pred_succ] @[simp] theorem succ'_pred' (n) : succ' (pred' n) = n := to_nat_inj.1 $ by rw [succ'_to_nat, pred'_to_nat, nat.add_one, nat.succ_pred_eq_of_pos (to_nat_pos _)] theorem size_to_nat : ∀ n, (size n : ℕ) = nat.size n | 1 := nat.size_one.symm | (bit0 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit0, nat.size_bit0 $ ne_of_gt $ to_nat_pos n] | (bit1 n) := by rw [size, succ_to_nat, size_to_nat, cast_bit1, nat.size_bit1] meta def transfer_rw : tactic unit := `[repeat {rw ← to_nat_inj <|> rw ← lt_to_nat <|> rw ← le_to_nat}, repeat {rw add_to_nat <|> rw mul_to_nat <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [mul_comm, mul_left_comm]}] instance : add_comm_semigroup pos_num := by refine {add := (+), ..}; transfer instance : comm_monoid pos_num := by refine {mul := (*), one := 1, ..}; transfer instance : distrib pos_num := by refine {add := (+), mul := (*), ..}; {transfer, simp [mul_add, mul_comm]} instance : decidable_linear_order pos_num := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance } @[simp] theorem cast_to_num (n : pos_num) : ↑n = num.pos n := by rw [← cast_to_nat, ← of_to_nat n] theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; refl @[simp] theorem cast_add [add_monoid α] [has_one α] (m n) : ((m + n : pos_num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp] theorem cast_succ [add_monoid α] [has_one α] (n : pos_num) : (succ n : α) = n + 1 := by rw [← add_one, cast_add, cast_one] theorem one_le_cast [linear_ordered_semiring α] (n : pos_num) : (1 : α) ≤ n := by rw [← cast_to_nat, ← nat.cast_one, nat.cast_le]; apply to_nat_pos theorem cast_pos [linear_ordered_semiring α] (n : pos_num) : (n : α) > 0 := lt_of_lt_of_le zero_lt_one (one_le_cast n) @[simp] theorem cast_mul [semiring α] (m n) : ((m * n : pos_num) : α) = m * n := by rw [← cast_to_nat, mul_to_nat, nat.cast_mul, cast_to_nat, cast_to_nat] theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp] theorem cast_lt [linear_ordered_semiring α] {m n : pos_num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp] theorem cast_le [linear_ordered_semiring α] {m n : pos_num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp] theorem cast_inj [linear_ordered_semiring α] {m n : pos_num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] end pos_num namespace num variables {α : Type*} open pos_num theorem bit_to_nat (b n) : (bit b n : ℕ) = nat.bit b n := by cases b; cases n; refl theorem cast_succ' [add_monoid α] [has_one α] (n) : (succ' n : α) = n + 1 := by rw [← pos_num.cast_to_nat, succ'_to_nat, nat.cast_add_one, cast_to_nat] theorem cast_succ [add_monoid α] [has_one α] (n) : (succ n : α) = n + 1 := cast_succ' n @[simp] theorem cast_add [semiring α] (m n) : ((m + n : num) : α) = m + n := by rw [← cast_to_nat, add_to_nat, nat.cast_add, cast_to_nat, cast_to_nat] @[simp] theorem cast_mul [semiring α] : ∀ m n, ((m * n : num) : α) = m * n | 0 0 := (zero_mul _).symm | 0 (pos q) := (zero_mul _).symm | (pos p) 0 := (mul_zero _).symm | (pos p) (pos q) := pos_num.cast_mul _ _ theorem zneg_to_znum (n : num) : -n.to_znum = n.to_znum_neg := by cases n; refl theorem zneg_to_znum_neg (n : num) : -n.to_znum_neg = n.to_znum := by cases n; refl @[simp] theorem cast_to_znum [has_zero α] [has_one α] [has_add α] [has_neg α] : ∀ n : num, (n.to_znum : α) = n | 0 := rfl | (num.pos p) := rfl @[simp] theorem cast_to_znum_neg [add_group α] [has_one α] : ∀ n : num, (n.to_znum_neg : α) = -n | 0 := neg_zero.symm | (num.pos p) := rfl @[simp] theorem add_to_znum (m n : num) : num.to_znum (m + n) = m.to_znum + n.to_znum := by cases m; cases n; refl end num namespace pos_num open num theorem pred_to_nat {n : pos_num} (h : n > 1) : (pred n : ℕ) = nat.pred n := begin unfold pred, have := pred'_to_nat n, cases e : pred' n, { have : (1:ℕ) ≤ nat.pred n := nat.pred_le_pred ((@cast_lt ℕ _ _ _).2 h), rw [← pred'_to_nat, e] at this, exact absurd this dec_trivial }, { rw [← pred'_to_nat, e], refl } end theorem sub'_one (a : pos_num) : sub' a 1 = (pred' a).to_znum := by cases a; refl theorem one_sub' (a : pos_num) : sub' 1 a = (pred' a).to_znum_neg := by cases a; refl theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial end pos_num namespace num variables {α : Type*} open pos_num theorem pred_to_nat : ∀ (n : num), (pred n : ℕ) = nat.pred n | 0 := rfl | (pos p) := by rw [pred, pos_num.pred'_to_nat]; refl theorem ppred_to_nat : ∀ (n : num), coe <$> ppred n = nat.ppred n | 0 := rfl | (pos p) := by rw [ppred, option.map_some, nat.ppred_eq_some.2]; rw [pos_num.pred'_to_nat, nat.succ_pred_eq_of_pos (pos_num.to_nat_pos _)]; refl theorem cmp_swap (m n) : (cmp m n).swap = cmp n m := by cases m; cases n; try {unfold cmp}; try {refl}; apply pos_num.cmp_swap theorem cmp_eq (m n) : cmp m n = ordering.eq ↔ m = n := begin have := cmp_to_nat m n, cases cmp m n; simp at this ⊢; try {exact this}; { simp [show m ≠ n, from λ e, by rw e at this; exact lt_irrefl _ this] } end @[simp] theorem cast_lt [linear_ordered_semiring α] {m n : num} : (m:α) < n ↔ m < n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_lt, lt_to_nat] @[simp] theorem cast_le [linear_ordered_semiring α] {m n : num} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp] theorem cast_inj [linear_ordered_semiring α] {m n : num} : (m:α) = n ↔ m = n := by rw [← cast_to_nat m, ← cast_to_nat n, nat.cast_inj, to_nat_inj] theorem lt_iff_cmp {m n} : m < n ↔ cmp m n = ordering.lt := iff.rfl theorem le_iff_cmp {m n} : m ≤ n ↔ cmp m n ≠ ordering.gt := not_congr $ lt_iff_cmp.trans $ by rw ← cmp_swap; cases cmp m n; exact dec_trivial theorem bitwise_to_nat {f : num → num → num} {g : bool → bool → bool} (p : pos_num → pos_num → num) (gff : g ff ff = ff) (f00 : f 0 0 = 0) (f0n : ∀ n, f 0 (pos n) = cond (g ff tt) (pos n) 0) (fn0 : ∀ n, f (pos n) 0 = cond (g tt ff) (pos n) 0) (fnn : ∀ m n, f (pos m) (pos n) = p m n) (p11 : p 1 1 = cond (g tt tt) 1 0) (p1b : ∀ b n, p 1 (pos_num.bit b n) = bit (g tt b) (cond (g ff tt) (pos n) 0)) (pb1 : ∀ a m, p (pos_num.bit a m) 1 = bit (g a tt) (cond (g tt ff) (pos m) 0)) (pbb : ∀ a b m n, p (pos_num.bit a m) (pos_num.bit b n) = bit (g a b) (p m n)) : ∀ m n : num, (f m n : ℕ) = nat.bitwise g m n := begin intros, cases m with m; cases n with n; try { change zero with 0 }; try { change ((0:num):ℕ) with 0 }, { rw [f00, nat.bitwise_zero]; refl }, { unfold nat.bitwise, rw [f0n, nat.binary_rec_zero], cases g ff tt; refl }, { unfold nat.bitwise, generalize h : (pos m : ℕ) = m', revert h, apply nat.bit_cases_on m' _, intros b m' h, rw [fn0, nat.binary_rec_eq, nat.binary_rec_zero, ←h], cases g tt ff; refl, apply nat.bitwise_bit_aux gff }, { rw fnn, have : ∀b (n : pos_num), (cond b ↑n 0 : ℕ) = ↑(cond b (pos n) 0 : num) := by intros; cases b; refl, induction m with m IH m IH generalizing n; cases n with n n, any_goals { change one with 1 }, any_goals { change pos 1 with 1 }, any_goals { change pos_num.bit0 with pos_num.bit ff }, any_goals { change pos_num.bit1 with pos_num.bit tt }, any_goals { change ((1:num):ℕ) with nat.bit tt 0 }, all_goals { repeat { rw show ∀ b n, (pos (pos_num.bit b n) : ℕ) = nat.bit b ↑n, by intros; cases b; refl }, rw nat.bitwise_bit }, any_goals { assumption }, any_goals { rw [nat.bitwise_zero, p11], cases g tt tt; refl }, any_goals { rw [nat.bitwise_zero_left, this, ← bit_to_nat, p1b] }, any_goals { rw [nat.bitwise_zero_right _ gff, this, ← bit_to_nat, pb1] }, all_goals { rw [← show ∀ n, ↑(p m n) = nat.bitwise g ↑m ↑n, from IH], rw [← bit_to_nat, pbb] } } end @[simp] theorem lor_to_nat : ∀ m n, (lor m n : ℕ) = nat.lor m n := by apply bitwise_to_nat (λx y, pos (pos_num.lor x y)); intros; try {cases a}; try {cases b}; refl @[simp] theorem land_to_nat : ∀ m n, (land m n : ℕ) = nat.land m n := by apply bitwise_to_nat pos_num.land; intros; try {cases a}; try {cases b}; refl @[simp] theorem ldiff_to_nat : ∀ m n, (ldiff m n : ℕ) = nat.ldiff m n := by apply bitwise_to_nat pos_num.ldiff; intros; try {cases a}; try {cases b}; refl @[simp] theorem lxor_to_nat : ∀ m n, (lxor m n : ℕ) = nat.lxor m n := by apply bitwise_to_nat pos_num.lxor; intros; try {cases a}; try {cases b}; refl @[simp] theorem shiftl_to_nat (m n) : (shiftl m n : ℕ) = nat.shiftl m n := begin cases m; dunfold shiftl, {symmetry, apply nat.zero_shiftl}, induction n with n IH, {refl}, simp [pos_num.shiftl, nat.shiftl_succ], rw ←IH, refl end @[simp] theorem shiftr_to_nat (m n) : (shiftr m n : ℕ) = nat.shiftr m n := begin cases m with m; dunfold shiftr, {symmetry, apply nat.zero_shiftr}, induction n with n IH generalizing m, {cases m; refl}, cases m with m m; dunfold pos_num.shiftr, { rw [nat.shiftr_eq_div_pow], symmetry, apply nat.div_eq_of_lt, exact @nat.pow_lt_pow_of_lt_right 2 dec_trivial 0 (n+1) (nat.succ_pos _) }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit1 m) (n+1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit1 ↑m : ℕ) with nat.bit tt m, rw nat.div2_bit }, { transitivity, apply IH, change nat.shiftr m n = nat.shiftr (bit0 m) (n + 1), rw [add_comm n 1, nat.shiftr_add], apply congr_arg (λx, nat.shiftr x n), unfold nat.shiftr, change (bit0 ↑m : ℕ) with nat.bit ff m, rw nat.div2_bit } end @[simp] theorem test_bit_to_nat (m n) : test_bit m n = nat.test_bit m n := begin cases m with m; unfold test_bit nat.test_bit, { change (zero : nat) with 0, rw nat.zero_shiftr, refl }, induction n with n IH generalizing m; cases m; dunfold pos_num.test_bit, {refl}, { exact (nat.bodd_bit _ _).symm }, { exact (nat.bodd_bit _ _).symm }, { change ff = nat.bodd (nat.shiftr 1 (n + 1)), rw [add_comm, nat.shiftr_add], change nat.shiftr 1 1 with 0, rw nat.zero_shiftr; refl }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit tt m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, { change pos_num.test_bit m n = nat.bodd (nat.shiftr (nat.bit ff m) (n + 1)), rw [add_comm, nat.shiftr_add], unfold nat.shiftr, rw nat.div2_bit, apply IH }, end end num namespace znum variables {α : Type*} open pos_num @[simp] theorem cast_zero [has_zero α] [has_one α] [has_add α] [has_neg α] : ((0 : znum) : α) = 0 := rfl @[simp] theorem cast_one [has_zero α] [has_one α] [has_add α] [has_neg α] : ((1 : znum) : α) = 1 := rfl @[simp] theorem cast_pos [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (pos n : α) = n := rfl @[simp] theorem cast_neg [has_zero α] [has_one α] [has_add α] [has_neg α] (n : pos_num) : (neg n : α) = -n := rfl @[simp] theorem cast_zneg [add_group α] [has_one α] : ∀ n, ((-n : znum) : α) = -n | 0 := neg_zero.symm | (pos p) := rfl | (neg p) := (neg_neg _).symm theorem neg_zero : (-0 : znum) = 0 := rfl theorem zneg_pos (n : pos_num) : -pos n = neg n := rfl theorem zneg_neg (n : pos_num) : -neg n = pos n := rfl theorem zneg_zneg (n : znum) : - -n = n := by cases n; refl theorem zneg_bit1 (n : znum) : -n.bit1 = (-n).bitm1 := by cases n; refl theorem zneg_bitm1 (n : znum) : -n.bitm1 = (-n).bit1 := by cases n; refl theorem zneg_succ (n : znum) : -n.succ = (-n).pred := by cases n; try {refl}; rw [succ, num.zneg_to_znum_neg]; refl theorem zneg_pred (n : znum) : -n.pred = (-n).succ := by rw [← zneg_zneg (succ (-n)), zneg_succ, zneg_zneg] @[simp] theorem neg_of_int : ∀ n, ((-n : ℤ) : znum) = -n | (n+1:ℕ) := rfl | 0 := rfl | -[1+n] := (zneg_zneg _).symm @[simp] theorem cast_to_int [add_group α] [has_one α] : ∀ n : znum, ((n : ℤ) : α) = n | 0 := rfl | (pos p) := by rw [cast_pos, cast_pos, pos_num.cast_to_int] | (neg p) := by rw [cast_neg, cast_neg, int.cast_neg, pos_num.cast_to_int] theorem bit0_of_bit0 : ∀ n : znum, _root_.bit0 n = n.bit0 | 0 := rfl | (pos a) := congr_arg pos a.bit0_of_bit0 | (neg a) := congr_arg neg a.bit0_of_bit0 theorem bit1_of_bit1 : ∀ n : znum, _root_.bit1 n = n.bit1 | 0 := rfl | (pos a) := congr_arg pos a.bit1_of_bit1 | (neg a) := show pos_num.sub' 1 (_root_.bit0 a) = _, by rw [pos_num.one_sub', a.bit0_of_bit0]; refl @[simp] theorem cast_bit0 [add_group α] [has_one α] : ∀ n : znum, (n.bit0 : α) = bit0 n | 0 := (add_zero _).symm | (pos p) := by rw [znum.bit0, cast_pos, cast_pos]; refl | (neg p) := by rw [znum.bit0, cast_neg, cast_neg, pos_num.cast_bit0, _root_.bit0, _root_.bit0, neg_add_rev] @[simp] theorem cast_bit1 [add_group α] [has_one α] : ∀ n : znum, (n.bit1 : α) = bit1 n | 0 := by simp [znum.bit1, _root_.bit1, _root_.bit0] | (pos p) := by rw [znum.bit1, cast_pos, cast_pos]; refl | (neg p) := begin rw [znum.bit1, cast_neg, cast_neg], cases e : pred' p; have : p = _ := (succ'_pred' p).symm.trans (congr_arg num.succ' e), { change p=1 at this, subst p, simp [_root_.bit1, _root_.bit0] }, { rw [num.succ'] at this, subst p, have : (↑(-↑a:ℤ) : α) = -1 + ↑(-↑a + 1 : ℤ), {simp}, simpa [_root_.bit1, _root_.bit0, -add_comm] }, end @[simp] theorem cast_bitm1 [add_group α] [has_one α] (n : znum) : (n.bitm1 : α) = bit0 n - 1 := begin conv { to_lhs, rw ← zneg_zneg n }, rw [← zneg_bit1, cast_zneg, cast_bit1], have : ((-1 + n + n : ℤ) : α) = (n + n + -1 : ℤ), {simp}, simpa [_root_.bit1, _root_.bit0, -add_comm] end theorem add_zero (n : znum) : n + 0 = n := by cases n; refl theorem zero_add (n : znum) : 0 + n = n := by cases n; refl theorem add_one : ∀ n : znum, n + 1 = succ n | 0 := rfl | (pos p) := congr_arg pos p.add_one | (neg p) := by cases p; refl end znum namespace pos_num variables {α : Type*} theorem cast_to_znum : ∀ n : pos_num, (n : znum) = znum.pos n | 1 := rfl | (bit0 p) := (znum.bit0_of_bit0 p).trans $ congr_arg _ (cast_to_znum p) | (bit1 p) := (znum.bit1_of_bit1 p).trans $ congr_arg _ (cast_to_znum p) theorem cast_sub' [add_group α] [has_one α] : ∀ m n : pos_num, (sub' m n : α) = m - n | a 1 := by rw [sub'_one, num.cast_to_znum, ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | 1 b := by rw [one_sub', num.cast_to_znum_neg, ← neg_sub, neg_inj', ← num.cast_to_nat, pred'_to_nat, ← nat.sub_one]; simp [pos_num.cast_pos] | (bit0 a) (bit0 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((a + -b + (a + -b) : ℤ) : α) = a + a + (-b + -b), {simp}, simpa [_root_.bit0, -add_left_comm] end | (bit0 a) (bit1 b) := begin rw [sub', znum.cast_bitm1, cast_sub'], have : ((-b + (a + (-b + -1)) : ℤ) : α) = (a + -1 + (-b + -b):ℤ), {simp}, simpa [_root_.bit1, _root_.bit0, -add_left_comm, -add_comm] end | (bit1 a) (bit0 b) := begin rw [sub', znum.cast_bit1, cast_sub'], have : ((-b + (a + (-b + 1)) : ℤ) : α) = (a + 1 + (-b + -b):ℤ), {simp}, simpa [_root_.bit1, _root_.bit0, -add_left_comm, -add_comm] end | (bit1 a) (bit1 b) := begin rw [sub', znum.cast_bit0, cast_sub'], have : ((-b + (a + -b) : ℤ) : α) = a + (-b + -b), {simp}, simpa [_root_.bit1, _root_.bit0, -add_left_comm, add_neg_cancel_left] end end pos_num namespace num variables {α : Type*} theorem cast_sub' [add_group α] [has_one α] : ∀ m n : num, (sub' m n : α) = m - n | 0 0 := (sub_zero _).symm | (pos a) 0 := (sub_zero _).symm | 0 (pos b) := (zero_sub _).symm | (pos a) (pos b) := pos_num.cast_sub' _ _ @[simp] theorem of_nat_to_znum : ∀ n : ℕ, num.to_znum n = n | 0 := rfl | (n+1) := by rw [nat.cast_add_one, nat.cast_add_one, znum.add_one, add_one, ← of_nat_to_znum]; cases (n:num); refl @[simp] theorem of_nat_to_znum_neg (n : ℕ) : num.to_znum_neg n = -n := by rw [← of_nat_to_znum, zneg_to_znum] end num namespace znum variables {α : Type*} @[simp] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : znum) : α) = m + n | 0 a := by cases a; exact (_root_.zero_add _).symm | b 0 := by cases b; exact (_root_.add_zero _).symm | (pos a) (pos b) := pos_num.cast_add _ _ | (pos a) (neg b) := pos_num.cast_sub' _ _ | (neg a) (pos b) := (pos_num.cast_sub' _ _).trans $ show ↑b + -↑a = -↑a + ↑b, by rw [← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_neg, ← int.cast_add (-a)]; simp | (neg a) (neg b) := show -(↑(a + b) : α) = -a + -b, by rw [ pos_num.cast_add, neg_eq_iff_neg_eq, neg_add_rev, neg_neg, neg_neg, ← pos_num.cast_to_int a, ← pos_num.cast_to_int b, ← int.cast_add]; simp @[simp] theorem cast_succ [add_group α] [has_one α] (n) : ((succ n : znum) : α) = n + 1 := by rw [← add_one, cast_add, cast_one] @[simp] theorem mul_to_int : ∀ m n, ((m * n : znum) : ℤ) = m * n | 0 a := by cases a; exact (_root_.zero_mul _).symm | b 0 := by cases b; exact (_root_.mul_zero _).symm | (pos a) (pos b) := pos_num.cast_mul a b | (pos a) (neg b) := show -↑(a * b) = ↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_eq_mul_neg] | (neg a) (pos b) := show -↑(a * b) = -↑a * ↑b, by rw [pos_num.cast_mul, neg_mul_eq_neg_mul] | (neg a) (neg b) := show ↑(a * b) = -↑a * -↑b, by rw [pos_num.cast_mul, neg_mul_neg] theorem cast_mul [ring α] (m n) : ((m * n : znum) : α) = m * n := by rw [← cast_to_int, mul_to_int, int.cast_mul, cast_to_int, cast_to_int] @[simp] theorem of_to_int : Π (n : znum), ((n : ℤ) : znum) = n | 0 := rfl | (pos a) := by rw [cast_pos, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum, pos_num.of_to_nat]; refl | (neg a) := by rw [cast_neg, neg_of_int, ← pos_num.cast_to_nat, int.cast_coe_nat', ← num.of_nat_to_znum_neg, pos_num.of_to_nat]; refl @[simp] theorem to_of_int : Π (n : ℤ), ((n : znum) : ℤ) = n | (n : ℕ) := by rw [int.cast_coe_nat, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] | -[1+ n] := by rw [int.cast_neg_succ_of_nat, cast_zneg, add_one, cast_succ, int.neg_succ_of_nat_eq, ← num.of_nat_to_znum, num.cast_to_znum, ← num.cast_to_nat, int.nat_cast_eq_coe_nat, num.to_of_nat] theorem to_int_inj {m n : znum} : (m : ℤ) = n ↔ m = n := ⟨λ h, function.injective_of_left_inverse of_to_int h, congr_arg _⟩ theorem cmp_to_int : ∀ (m n), (ordering.cases_on (cmp m n) ((m:ℤ) < n) (m = n) ((m:ℤ) > n) : Prop) | 0 0 := rfl | (pos a) (pos b) := begin have := pos_num.cmp_to_nat a b; revert this; dsimp [cmp]; cases pos_num.cmp a b; dsimp; [simp, exact congr_arg pos, simp [gt]] end | (neg a) (neg b) := begin have := pos_num.cmp_to_nat b a; revert this; dsimp [cmp]; cases pos_num.cmp b a; dsimp; [simp, simp {contextual := tt}, simp [gt]] end | (pos a) 0 := pos_num.cast_pos _ | (pos a) (neg b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (neg b) := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) 0 := neg_lt_zero.2 $ pos_num.cast_pos _ | (neg a) (pos b) := lt_trans (neg_lt_zero.2 $ pos_num.cast_pos _) (pos_num.cast_pos _) | 0 (pos b) := pos_num.cast_pos _ @[simp] theorem lt_to_int {m n : znum} : (m:ℤ) < n ↔ m < n := show (m:ℤ) < n ↔ cmp m n = ordering.lt, from match cmp m n, cmp_to_int m n with | ordering.lt, h := by simp at h; simp [h] | ordering.eq, h := by simp at h; simp [h, lt_irrefl]; exact dec_trivial | ordering.gt, h := by simp [not_lt_of_gt h]; exact dec_trivial end @[simp] theorem le_to_int {m n : znum} : (m:ℤ) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr lt_to_int @[simp] theorem cast_lt [linear_ordered_ring α] {m n : znum} : (m:α) < n ↔ m < n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_lt, lt_to_int] @[simp] theorem cast_le [linear_ordered_ring α] {m n : znum} : (m:α) ≤ n ↔ m ≤ n := by rw ← not_lt; exact not_congr cast_lt @[simp] theorem cast_inj [linear_ordered_ring α] {m n : znum} : (m:α) = n ↔ m = n := by rw [← cast_to_int m, ← cast_to_int n, int.cast_inj, to_int_inj] meta def transfer_rw : tactic unit := `[repeat {rw ← to_int_inj <|> rw ← lt_to_int <|> rw ← le_to_int}, repeat {rw cast_add <|> rw mul_to_int <|> rw cast_one <|> rw cast_zero}] meta def transfer : tactic unit := `[intros, transfer_rw, try {simp [mul_comm, mul_left_comm]}] instance : decidable_linear_order znum := { lt := (<), lt_iff_le_not_le := by {intros a b, transfer_rw, apply lt_iff_le_not_le}, le := (≤), le_refl := by transfer, le_trans := by {intros a b c, transfer_rw, apply le_trans}, le_antisymm := by {intros a b, transfer_rw, apply le_antisymm}, le_total := by {intros a b, transfer_rw, apply le_total}, decidable_eq := znum.decidable_eq, decidable_le := znum.decidable_le, decidable_lt := znum.decidable_lt } instance : add_comm_group znum := { add := (+), add_assoc := by transfer, zero := 0, zero_add := zero_add, add_zero := add_zero, add_comm := by transfer, neg := has_neg.neg, add_left_neg := by transfer } instance : decidable_linear_ordered_comm_ring znum := { mul := (*), mul_assoc := by transfer, one := 1, one_mul := by transfer, mul_one := by transfer, left_distrib := by {transfer, simp [mul_add]}, right_distrib := by {transfer, simp [mul_add, mul_comm]}, mul_comm := by transfer, zero_ne_one := dec_trivial, add_le_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_le_add_left h c}, add_lt_add_left := by {intros a b h c, revert h, transfer_rw, exact λ h, add_lt_add_left h c}, mul_pos := by {intros a b, transfer_rw, apply mul_pos}, mul_nonneg := by {intros x y, change 0 ≤ x → 0 ≤ y → 0 ≤ x * y, transfer_rw, apply mul_nonneg}, zero_lt_one := dec_trivial, ..znum.decidable_linear_order, ..znum.add_comm_group } end znum
3a79ddc5952e0902c456ce53bebc51a7cb6f538c
94e33a31faa76775069b071adea97e86e218a8ee
/src/order/filter/bases.lean
0d7288657433ca455546f9f4082d80503e171bd2
[ "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
44,172
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import data.prod.pprod import data.set.countable import order.filter.basic /-! # Filter bases A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. Compared to filters, filter bases do not require that any set containing an element of `B` belongs to `B`. A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs to `B.filter` if and only if it contains an element of `B`. Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`, the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p` (ie. `s '' set_of p`) defines a filter basis `h.filter_basis`. If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop` and `s : ι → set α` as above) means that a set belongs to `l` if and only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and `l = h.filter_basis.filter`. The point of this definition is that checking statements involving elements of `l` often reduces to checking them on the basis elements. We define a function `has_basis.index (h : filter.has_basis l p s) (t) (ht : t ∈ l)` that returns some index `i` such that `p i` and `s i ⊆ t`. This function can be useful to avoid manual destruction of `h.mem_iff.mpr ht` using `cases` or `let`. This file also introduces more restricted classes of bases, involving monotonicity or countability. In particular, for `l : filter α`, `l.is_countably_generated` means there is a countable set of sets which generates `s`. This is reformulated in term of bases, and consequences are derived. ## 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 ⊓ 𝓟 t`, `l ×ᶠ l'`, `l ×ᶠ 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. * `is_countably_generated_iff_exists_antitone_basis` : proves a filter is countably generated if and only if it admits a basis parametrized by a decreasing sequence of sets indexed by `ℕ`. * `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous". ## 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`. -/ open set filter open_locale filter classical section sort variables {α β γ : Type*} {ι ι' : Sort*} /-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure filter_basis (α : Type*) := (sets : set (set α)) (nonempty : sets.nonempty) (inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y) instance filter_basis.nonempty_sets (B : filter_basis α) : nonempty B.sets := B.nonempty.to_subtype /-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter_basis α) := ⟨λ U B, U ∈ B.sets⟩ -- For illustration purposes, the filter basis defining (at_top : filter ℕ) instance : inhabited (filter_basis ℕ) := ⟨{ sets := range Ici, nonempty := ⟨Ici 0, mem_range_self 0⟩, inter_sets := begin rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, refine ⟨Ici (max n m), mem_range_self _, _⟩, rintros p p_in, split ; rw mem_Ici at *, exact le_of_max_le_left p_in, exact le_of_max_le_right p_in, end }⟩ /-- View a filter as a filter basis. -/ def filter.as_basis (f : filter α) : filter_basis α := ⟨f.sets, ⟨univ, univ_mem⟩, λ x y hx hy, ⟨x ∩ y, inter_mem hx hy, subset_rfl⟩⟩ /-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/ protected structure filter.is_basis (p : ι → Prop) (s : ι → set α) : Prop := (nonempty : ∃ i, p i) (inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j) namespace filter namespace is_basis /-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/ protected def filter_basis {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α := { sets := {t | ∃ i, p i ∧ s i = t}, nonempty := let ⟨i, hi⟩ := h.nonempty in ⟨s i, ⟨i, hi, rfl⟩⟩, inter_sets := by { rintros _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩, rcases h.inter hi hj with ⟨k, hk, hk'⟩, exact ⟨_, ⟨k, hk, rfl⟩, hk'⟩ } } variables {p : ι → Prop} {s : ι → set α} (h : is_basis p s) lemma mem_filter_basis_iff {U : set α} : U ∈ h.filter_basis ↔ ∃ i, p i ∧ s i = U := iff.rfl end is_basis end filter namespace filter_basis /-- The filter associated to a filter basis. -/ protected def filter (B : filter_basis α) : filter α := { sets := {s | ∃ t ∈ B, t ⊆ s}, univ_sets := let ⟨s, s_in⟩ := B.nonempty in ⟨s, s_in, s.subset_univ⟩, sets_of_superset := λ x y ⟨s, s_in, h⟩ hxy, ⟨s, s_in, set.subset.trans h hxy⟩, inter_sets := λ x y ⟨s, s_in, hs⟩ ⟨t, t_in, ht⟩, let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in in ⟨u, u_in, set.subset.trans u_sub $ set.inter_subset_inter hs ht⟩ } lemma mem_filter_iff (B : filter_basis α) {U : set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U := iff.rfl lemma mem_filter_of_mem (B : filter_basis α) {U : set α} : U ∈ B → U ∈ B.filter:= λ U_in, ⟨U, U_in, subset.refl _⟩ lemma eq_infi_principal (B : filter_basis α) : B.filter = ⨅ s : B.sets, 𝓟 s := begin have : directed (≥) (λ (s : B.sets), 𝓟 (s : set α)), { rintros ⟨U, U_in⟩ ⟨V, V_in⟩, rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩, use [W, W_in], simp only [ge_iff_le, le_principal_iff, mem_principal, subtype.coe_mk], exact subset_inter_iff.mp W_sub }, ext U, simp [mem_filter_iff, mem_infi_of_directed this] end protected lemma generate (B : filter_basis α) : generate B.sets = B.filter := begin apply le_antisymm, { intros U U_in, rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩, exact generate_sets.superset (generate_sets.basic V_in) h }, { rw sets_iff_generate, apply mem_filter_of_mem } end end filter_basis namespace filter namespace is_basis variables {p : ι → Prop} {s : ι → set α} /-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/ protected def filter (h : is_basis p s) : filter α := h.filter_basis.filter protected lemma mem_filter_iff (h : is_basis p s) {U : set α} : U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U := begin erw [h.filter_basis.mem_filter_iff], simp only [mem_filter_basis_iff h, exists_prop], split, { rintros ⟨_, ⟨i, pi, rfl⟩, h⟩, tauto }, { tauto } end lemma filter_eq_generate (h : is_basis p s) : h.filter = generate {U | ∃ i, p i ∧ s i = U} := by erw h.filter_basis.generate ; refl end is_basis /-- 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 structure has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop := (mem_iff' : ∀ (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' : ι'} lemma has_basis_generate (s : set (set α)) : (generate s).has_basis (λ t, set.finite t ∧ t ⊆ s) (λ t, ⋂₀ t) := ⟨begin intro U, rw mem_generate_iff, apply exists_congr, tauto end⟩ /-- The smallest filter basis containing a given collection of sets. -/ def filter_basis.of_sets (s : set (set α)) : filter_basis α := { sets := sInter '' { t | set.finite t ∧ t ⊆ s}, nonempty := ⟨univ, ∅, ⟨⟨finite_empty, empty_subset s⟩, sInter_empty⟩⟩, inter_sets := begin rintros _ _ ⟨a, ⟨fina, suba⟩, rfl⟩ ⟨b, ⟨finb, subb⟩, rfl⟩, exact ⟨⋂₀ (a ∪ b), mem_image_of_mem _ ⟨fina.union finb, union_subset suba subb⟩, by rw sInter_union⟩, end } /-- Definition of `has_basis` unfolded with implicit set argument. -/ lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := hl.mem_iff' t lemma has_basis.eq_of_same_basis (hl : l.has_basis p s) (hl' : l'.has_basis p s) : l = l' := begin ext t, rw [hl.mem_iff, hl'.mem_iff] end lemma has_basis_iff : l.has_basis p s ↔ ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t := ⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩ lemma has_basis.ex_mem (h : l.has_basis p s) : ∃ i, p i := let ⟨i, pi, h⟩ := h.mem_iff.mp univ_mem in ⟨i, pi⟩ protected lemma has_basis.nonempty (h : l.has_basis p s) : nonempty ι := nonempty_of_exists h.ex_mem protected lemma is_basis.has_basis (h : is_basis p s) : has_basis h.filter p s := ⟨λ t, by simp only [h.mem_filter_iff, exists_prop]⟩ lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l := (hl.mem_iff).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 _ /-- Index of a basis set such that `s i ⊆ t` as an element of `subtype p`. -/ noncomputable def has_basis.index (h : l.has_basis p s) (t : set α) (ht : t ∈ l) : {i : ι // p i} := ⟨(h.mem_iff.1 ht).some, (h.mem_iff.1 ht).some_spec.fst⟩ lemma has_basis.property_index (h : l.has_basis p s) (ht : t ∈ l) : p (h.index t ht) := (h.index t ht).2 lemma has_basis.set_index_mem (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ∈ l := h.mem_of_mem $ h.property_index _ lemma has_basis.set_index_subset (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ⊆ t := (h.mem_iff.1 ht).some_spec.snd lemma has_basis.is_basis (h : l.has_basis p s) : is_basis p s := { nonempty := let ⟨i, hi, H⟩ := h.mem_iff.mp univ_mem in ⟨i, hi⟩, inter := λ i j hi hj, by simpa [h.mem_iff] using l.inter_sets (h.mem_of_mem hi) (h.mem_of_mem hj) } lemma has_basis.filter_eq (h : l.has_basis p s) : h.is_basis.filter = l := by { ext U, simp [h.mem_iff, is_basis.mem_filter_iff] } lemma has_basis.eq_generate (h : l.has_basis p s) : l = generate { U | ∃ i, p i ∧ s i = U } := by rw [← h.is_basis.filter_eq_generate, h.filter_eq] lemma generate_eq_generate_inter (s : set (set α)) : generate s = generate (sInter '' { t | set.finite t ∧ t ⊆ s}) := by erw [(filter_basis.of_sets s).generate, ← (has_basis_generate s).filter_eq] ; refl lemma of_sets_filter_eq_generate (s : set (set α)) : (filter_basis.of_sets s).filter = generate s := by rw [← (filter_basis.of_sets s).generate, generate_eq_generate_inter s] ; refl protected lemma _root_.filter_basis.has_basis {α : Type*} (B : filter_basis α) : has_basis (B.filter) (λ s : set α, s ∈ B) id := ⟨λ t, B.mem_filter_iff⟩ lemma has_basis.to_has_basis' (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → s' i' ∈ l) : l.has_basis p' s' := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i', hi', ht⟩, mem_of_superset (h' i' hi') ht⟩⟩, rcases hl.mem_iff.1 ht with ⟨i, hi, ht⟩, rcases h i hi with ⟨i', hi', hs's⟩, exact ⟨i', hi', subset.trans hs's ht⟩ end lemma has_basis.to_has_basis (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l.has_basis p' s' := hl.to_has_basis' h $ λ i' hi', let ⟨i, hi, hss'⟩ := h' i' hi' in hl.mem_iff.2 ⟨i, hi, hss'⟩ lemma has_basis.to_subset (hl : l.has_basis p s) {t : ι → set α} (h : ∀ i, p i → t i ⊆ s i) (ht : ∀ i, p i → t i ∈ l) : l.has_basis p t := hl.to_has_basis' (λ i hi, ⟨i, hi, h i hi⟩) ht lemma has_basis.eventually_iff (hl : l.has_basis p s) {q : α → Prop} : (∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x := by simpa using hl.mem_iff lemma has_basis.frequently_iff (hl : l.has_basis p s) {q : α → Prop} : (∃ᶠ x in l, q x) ↔ ∀ i, p i → ∃ x ∈ s i, q x := by simp [filter.frequently, hl.eventually_iff] lemma has_basis.exists_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) : (∃ s ∈ l, P s) ↔ ∃ (i) (hi : p i), P (s i) := ⟨λ ⟨s, hs, hP⟩, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in ⟨i, hi, mono his hP⟩, λ ⟨i, hi, hP⟩, ⟨s i, hl.mem_of_mem hi, hP⟩⟩ lemma has_basis.forall_iff (hl : l.has_basis p s) {P : set α → Prop} (mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) : (∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) := ⟨λ H i hi, H (s i) $ hl.mem_of_mem hi, λ H s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in mono his (H i hi)⟩ lemma has_basis.ne_bot_iff (hl : l.has_basis p s) : ne_bot l ↔ (∀ {i}, p i → (s i).nonempty) := forall_mem_nonempty_iff_ne_bot.symm.trans $ hl.forall_iff $ λ _ _, nonempty.mono lemma has_basis.eq_bot_iff (hl : l.has_basis p s) : l = ⊥ ↔ ∃ i, p i ∧ s i = ∅ := not_iff_not.1 $ ne_bot_iff.symm.trans $ hl.ne_bot_iff.trans $ by simp only [not_exists, not_and, ← ne_empty_iff_nonempty] lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id := ⟨λ t, exists_mem_subset_iff.symm⟩ lemma as_basis_filter (f : filter α) : f.as_basis.filter = f := by ext t; exact exists_mem_subset_iff lemma has_basis_self {l : filter α} {P : set α → Prop} : has_basis l (λ s, s ∈ l ∧ P s) id ↔ ∀ t ∈ l, ∃ r ∈ l, P r ∧ r ⊆ t := begin simp only [has_basis_iff, exists_prop, id, and_assoc], exact forall_congr (λ s, ⟨λ h, h.1, λ h, ⟨h, λ ⟨t, hl, hP, hts⟩, mem_of_superset hl hts⟩⟩) end lemma has_basis.comp_of_surjective (h : l.has_basis p s) {g : ι' → ι} (hg : function.surjective g) : l.has_basis (p ∘ g) (s ∘ g) := ⟨λ t, h.mem_iff.trans hg.exists⟩ lemma has_basis.comp_equiv (h : l.has_basis p s) (e : ι' ≃ ι) : l.has_basis (p ∘ e) (s ∘ e) := h.comp_of_surjective e.surjective /-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that `p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/ lemma has_basis.restrict (h : l.has_basis p s) {q : ι → Prop} (hq : ∀ i, p i → ∃ j, p j ∧ q j ∧ s j ⊆ s i) : l.has_basis (λ i, p i ∧ q i) s := begin refine ⟨λ t, ⟨λ ht, _, λ ⟨i, hpi, hti⟩, h.mem_iff.2 ⟨i, hpi.1, hti⟩⟩⟩, rcases h.mem_iff.1 ht with ⟨i, hpi, hti⟩, rcases hq i hpi with ⟨j, hpj, hqj, hji⟩, exact ⟨j, ⟨hpj, hqj⟩, subset.trans hji hti⟩ end /-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}` is a basis of `l`. -/ lemma has_basis.restrict_subset (h : l.has_basis p s) {V : set α} (hV : V ∈ l) : l.has_basis (λ i, p i ∧ s i ⊆ V) s := h.restrict $ λ i hi, (h.mem_iff.1 (inter_mem hV (h.mem_of_mem hi))).imp $ λ j hj, ⟨hj.fst, subset_inter_iff.1 hj.snd⟩ lemma has_basis.has_basis_self_subset {p : set α → Prop} (h : l.has_basis (λ s, s ∈ l ∧ p s) id) {V : set α} (hV : V ∈ l) : l.has_basis (λ s, s ∈ l ∧ p s ∧ s ⊆ V) id := by simpa only [and_assoc] using h.restrict_subset hV 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'.mem_iff.1 hs in mem_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.ext (hl : l.has_basis p s) (hl' : l'.has_basis p' s') (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i) (h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l = l' := begin apply le_antisymm, { rw hl.le_basis_iff hl', simpa using h' }, { rw hl'.le_basis_iff hl, simpa using h }, end lemma has_basis.inf' (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊓ l').has_basis (λ i : pprod ι ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) := ⟨begin intro t, split, { simp only [mem_inf_iff, exists_prop, hl.mem_iff, hl'.mem_iff], rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, rfl⟩, use [⟨i, i'⟩, ⟨hi, hi'⟩, inter_subset_inter ht ht'] }, { rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩, exact mem_inf_of_inter (hl.mem_of_mem hi) (hl'.mem_of_mem hi') H } end⟩ lemma has_basis.inf {ι ι' : Type*} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (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) := (hl.inf' hl').to_has_basis (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) lemma has_basis_infi {ι : Type*} {ι' : ι → Type*} {l : ι → filter α} {p : Π i, ι' i → Prop} {s : Π i, ι' i → set α} (hl : ∀ i, (l i).has_basis (p i) (s i)) : (⨅ i, l i).has_basis (λ If : set ι × Π i, ι' i, If.1.finite ∧ ∀ i ∈ If.1, p i (If.2 i)) (λ If : set ι × Π i, ι' i, ⋂ i ∈ If.1, s i (If.2 i)) := ⟨begin intro t, split, { simp only [mem_infi', (hl _).mem_iff], rintros ⟨I, hI, V, hV, -, hVt, -⟩, choose u hu using hV, refine ⟨⟨I, u⟩, ⟨hI, λ i _, (hu i).1⟩, _⟩, rw hVt, exact Inter_mono (λ i, Inter_mono $ λ hi, (hu i).2) }, { rintros ⟨⟨I, f⟩, ⟨hI₁, hI₂⟩, hsub⟩, refine mem_of_superset _ hsub, exact (bInter_mem hI₁).mpr (λ i hi, mem_infi_of_mem i $ (hl i).mem_of_mem $ hI₂ _ hi) } end⟩ lemma has_basis_infi_of_directed' {ι : Type*} {ι' : ι → Sort*} [nonempty ι] {l : ι → filter α} (s : Π i, (ι' i) → set α) (p : Π i, (ι' i) → Prop) (hl : ∀ i, (l i).has_basis (p i) (s i)) (h : directed (≥) l) : (⨅ i, l i).has_basis (λ (ii' : Σ i, ι' i), p ii'.1 ii'.2) (λ ii', s ii'.1 ii'.2) := begin refine ⟨λ t, _⟩, rw [mem_infi_of_directed h, sigma.exists], exact exists_congr (λ i, (hl i).mem_iff) end lemma has_basis_infi_of_directed {ι : Type*} {ι' : Sort*} [nonempty ι] {l : ι → filter α} (s : ι → ι' → set α) (p : ι → ι' → Prop) (hl : ∀ i, (l i).has_basis (p i) (s i)) (h : directed (≥) l) : (⨅ i, l i).has_basis (λ (ii' : ι × ι'), p ii'.1 ii'.2) (λ ii', s ii'.1 ii'.2) := begin refine ⟨λ t, _⟩, rw [mem_infi_of_directed h, prod.exists], exact exists_congr (λ i, (hl i).mem_iff) end lemma has_basis_binfi_of_directed' {ι : Type*} {ι' : ι → Sort*} {dom : set ι} (hdom : dom.nonempty) {l : ι → filter α} (s : Π i, (ι' i) → set α) (p : Π i, (ι' i) → Prop) (hl : ∀ i ∈ dom, (l i).has_basis (p i) (s i)) (h : directed_on (l ⁻¹'o ge) dom) : (⨅ i ∈ dom, l i).has_basis (λ (ii' : Σ i, ι' i), ii'.1 ∈ dom ∧ p ii'.1 ii'.2) (λ ii', s ii'.1 ii'.2) := begin refine ⟨λ t, _⟩, rw [mem_binfi_of_directed h hdom, sigma.exists], refine exists_congr (λ i, ⟨_, _⟩), { rintros ⟨hi, hti⟩, rcases (hl i hi).mem_iff.mp hti with ⟨b, hb, hbt⟩, exact ⟨b, ⟨hi, hb⟩, hbt⟩ }, { rintros ⟨b, ⟨hi, hb⟩, hibt⟩, exact ⟨hi, (hl i hi).mem_iff.mpr ⟨b, hb, hibt⟩⟩ } end lemma has_basis_binfi_of_directed {ι : Type*} {ι' : Sort*} {dom : set ι} (hdom : dom.nonempty) {l : ι → filter α} (s : ι → ι' → set α) (p : ι → ι' → Prop) (hl : ∀ i ∈ dom, (l i).has_basis (p i) (s i)) (h : directed_on (l ⁻¹'o ge) dom) : (⨅ i ∈ dom, l i).has_basis (λ (ii' : ι × ι'), ii'.1 ∈ dom ∧ p ii'.1 ii'.2) (λ ii', s ii'.1 ii'.2) := begin refine ⟨λ t, _⟩, rw [mem_binfi_of_directed h hdom, prod.exists], refine exists_congr (λ i, ⟨_, _⟩), { rintros ⟨hi, hti⟩, rcases (hl i hi).mem_iff.mp hti with ⟨b, hb, hbt⟩, exact ⟨b, ⟨hi, hb⟩, hbt⟩ }, { rintros ⟨b, ⟨hi, hb⟩, hibt⟩, exact ⟨hi, (hl i hi).mem_iff.mpr ⟨b, hb, hibt⟩⟩ } end lemma has_basis_principal (t : set α) : (𝓟 t).has_basis (λ i : unit, true) (λ i, t) := ⟨λ U, by simp⟩ lemma has_basis_pure (x : α) : (pure x : filter α).has_basis (λ i : unit, true) (λ i, {x}) := by simp only [← principal_singleton, has_basis_principal] lemma has_basis.sup' (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : (l ⊔ l').has_basis (λ i : pprod ι ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) := ⟨begin intros t, simp only [mem_sup, hl.mem_iff, hl'.mem_iff, pprod.exists, union_subset_iff, exists_prop, and_assoc, exists_and_distrib_left], simp only [← and_assoc, exists_and_distrib_right, and_comm] end⟩ lemma has_basis.sup {ι ι' : Type*} {p : ι → Prop} {s : ι → set α} {p' : ι' → Prop} {s' : ι' → set α} (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) := (hl.sup' hl').to_has_basis (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) (λ i hi, ⟨⟨i.1, i.2⟩, hi, subset.rfl⟩) lemma has_basis_supr {ι : Sort*} {ι' : ι → Type*} {l : ι → filter α} {p : Π i, ι' i → Prop} {s : Π i, ι' i → set α} (hl : ∀ i, (l i).has_basis (p i) (s i)) : (⨆ i, l i).has_basis (λ f : Π i, ι' i, ∀ i, p i (f i)) (λ f : Π i, ι' i, ⋃ i, s i (f i)) := has_basis_iff.mpr $ λ t, by simp only [has_basis_iff, (hl _).mem_iff, classical.skolem, forall_and_distrib, Union_subset_iff, mem_supr] lemma has_basis.sup_principal (hl : l.has_basis p s) (t : set α) : (l ⊔ 𝓟 t).has_basis p (λ i, s i ∪ t) := ⟨λ u, by simp only [(hl.sup' (has_basis_principal t)).mem_iff, pprod.exists, exists_prop, and_true, unique.exists_iff]⟩ lemma has_basis.sup_pure (hl : l.has_basis p s) (x : α) : (l ⊔ pure x).has_basis p (λ i, s i ∪ {x}) := by simp only [← principal_singleton, hl.sup_principal] lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) : (l ⊓ 𝓟 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.inf_basis_ne_bot_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃i'⦄ (hi' : p' i'), (s i ∩ s' i').nonempty := (hl.inf' hl').ne_bot_iff.trans $ by simp [@forall_swap _ ι'] lemma has_basis.inf_ne_bot_iff (hl : l.has_basis p s) : ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃s'⦄ (hs' : s' ∈ l'), (s i ∩ s').nonempty := hl.inf_basis_ne_bot_iff l'.basis_sets lemma has_basis.inf_principal_ne_bot_iff (hl : l.has_basis p s) {t : set α} : ne_bot (l ⊓ 𝓟 t) ↔ ∀ ⦃i⦄ (hi : p i), (s i ∩ t).nonempty := (hl.inf_principal t).ne_bot_iff lemma has_basis.disjoint_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') : disjoint l l' ↔ ∃ i (hi : p i) i' (hi' : p' i'), disjoint (s i) (s' i') := not_iff_not.mp $ by simp only [disjoint_iff, ← ne.def, ← ne_bot_iff, hl.inf_basis_ne_bot_iff hl', not_exists, bot_eq_empty, ne_empty_iff_nonempty, inf_eq_inter] lemma inf_ne_bot_iff : ne_bot (l ⊓ l') ↔ ∀ ⦃s : set α⦄ (hs : s ∈ l) ⦃s'⦄ (hs' : s' ∈ l'), (s ∩ s').nonempty := l.basis_sets.inf_ne_bot_iff lemma inf_principal_ne_bot_iff {s : set α} : ne_bot (l ⊓ 𝓟 s) ↔ ∀ U ∈ l, (U ∩ s).nonempty := l.basis_sets.inf_principal_ne_bot_iff lemma mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∈ f ↔ f ⊓ 𝓟 sᶜ = ⊥ := begin refine not_iff_not.1 ((inf_principal_ne_bot_iff.trans _).symm.trans ne_bot_iff), exact ⟨λ h hs, by simpa [empty_not_nonempty] using h s hs, λ hs t ht, inter_compl_nonempty_iff.2 $ λ hts, hs $ mem_of_superset ht hts⟩, end lemma not_mem_iff_inf_principal_compl {f : filter α} {s : set α} : s ∉ f ↔ ne_bot (f ⊓ 𝓟 sᶜ) := (not_congr mem_iff_inf_principal_compl).trans ne_bot_iff.symm @[simp] lemma disjoint_principal_right {f : filter α} {s : set α} : disjoint f (𝓟 s) ↔ sᶜ ∈ f := by rw [mem_iff_inf_principal_compl, compl_compl, disjoint_iff] @[simp] lemma disjoint_principal_left {f : filter α} {s : set α} : disjoint (𝓟 s) f ↔ sᶜ ∈ f := by rw [disjoint.comm, disjoint_principal_right] @[simp] lemma disjoint_principal_principal {s t : set α} : disjoint (𝓟 s) (𝓟 t) ↔ disjoint s t := by simp [←subset_compl_iff_disjoint_left] alias disjoint_principal_principal ↔ _ _root_.disjoint.filter_principal @[simp] lemma disjoint_pure_pure {x y : α} : disjoint (pure x : filter α) (pure y) ↔ x ≠ y := by simp only [← principal_singleton, disjoint_principal_principal, disjoint_singleton] @[simp] lemma compl_diagonal_mem_prod {l₁ l₂ : filter α} : (diagonal α)ᶜ ∈ l₁ ×ᶠ l₂ ↔ disjoint l₁ l₂ := by simp only [mem_prod_iff, filter.disjoint_iff, prod_subset_compl_diagonal_iff_disjoint] lemma le_iff_forall_inf_principal_compl {f g : filter α} : f ≤ g ↔ ∀ V ∈ g, f ⊓ 𝓟 Vᶜ = ⊥ := forall₂_congr $ λ _ _, mem_iff_inf_principal_compl lemma inf_ne_bot_iff_frequently_left {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in f, p x) → ∃ᶠ x in g, p x := by simpa only [inf_ne_bot_iff, frequently_iff, exists_prop, and_comm] lemma inf_ne_bot_iff_frequently_right {f g : filter α} : ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in g, p x) → ∃ᶠ x in f, p x := by { rw inf_comm, exact inf_ne_bot_iff_frequently_left } lemma has_basis.eq_binfi (h : l.has_basis p s) : l = ⨅ i (_ : p i), 𝓟 (s i) := eq_binfi_of_mem_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal] lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) : l = ⨅ i, 𝓟 (s i) := by simpa only [infi_true] using h.eq_binfi lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) [nonempty ι] : (⨅ i, 𝓟 (s i)).has_basis (λ _, true) s := ⟨begin refine λ t, (mem_infi_of_directed (h.mono_comp _ _) t).trans $ by simp only [exists_prop, true_and, mem_principal], exact λ _ _, principal_mono.2 end⟩ /-- If `s : ι → set α` is an indexed family of sets, then finite intersections of `s i` form a basis of `⨅ i, 𝓟 (s i)`. -/ lemma has_basis_infi_principal_finite {ι : Type*} (s : ι → set α) : (⨅ i, 𝓟 (s i)).has_basis (λ t : set ι, t.finite) (λ t, ⋂ i ∈ t, s i) := begin refine ⟨λ U, (mem_infi_finite _).trans _⟩, simp only [infi_principal_finset, mem_Union, mem_principal, exists_prop, exists_finite_iff_finset, finset.set_bInter_coe] end lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S) (ne : S.nonempty) : (⨅ i ∈ S, 𝓟 (s i)).has_basis (λ i, i ∈ S) s := ⟨begin refine λ t, (mem_binfi_of_directed _ ne).trans $ by simp only [mem_principal], rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢, apply h.mono_comp _ _, exact λ _ _, principal_mono.2 end⟩ lemma has_basis_binfi_principal' {ι : Type*} {p : ι → Prop} {s : ι → set α} (h : ∀ i, p i → ∀ j, p j → ∃ k (h : p k), s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ i, p i) : (⨅ i (h : p i), 𝓟 (s i)).has_basis p s := filter.has_basis_binfi_principal h ne 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, 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 comap_has_basis (f : α → β) (l : filter β) : has_basis (comap f l) (λ s : set β, s ∈ l) (λ s, f ⁻¹' s) := ⟨λ t, mem_comap⟩ lemma has_basis.prod_self (hl : l.has_basis p s) : (l ×ᶠ l).has_basis p (λ i, s i ×ˢ s i) := ⟨begin intro t, apply mem_prod_iff.trans, split, { rintros ⟨t₁, ht₁, t₂, ht₂, H⟩, rcases hl.mem_iff.1 (inter_mem 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⟩ lemma mem_prod_self_iff {s} : s ∈ l ×ᶠ l ↔ ∃ t ∈ l, t ×ˢ t ⊆ s := l.basis_sets.prod_self.mem_iff lemma has_basis.forall_mem_mem (h : has_basis l p s) {x : α} : (∀ t ∈ l, x ∈ t) ↔ ∀ i, p i → x ∈ s i := begin simp only [h.mem_iff, exists_imp_distrib], exact ⟨λ h i hi, h (s i) i hi subset.rfl, λ h t i hi ht, ht (h i hi)⟩ end lemma has_basis.sInter_sets (h : has_basis l p s) : ⋂₀ l.sets = ⋂ i (hi : p i), s i := begin ext x, simp only [mem_Inter, mem_sInter, filter.mem_sets, h.forall_mem_mem], end variables {ι'' : Type*} [preorder ι''] (l) (s'' : ι'' → set α) /-- `is_antitone_basis s` means the image of `s` is a filter basis such that `s` is decreasing. -/ @[protect_proj] structure is_antitone_basis extends is_basis (λ _, true) s'' : Prop := (antitone : antitone s'') /-- We say that a filter `l` has an antitone basis `s : ι → set α`, if `t ∈ l` if and only if `t` includes `s i` for some `i`, and `s` is decreasing. -/ @[protect_proj] structure has_antitone_basis (l : filter α) (s : ι'' → set α) extends has_basis l (λ _, true) s : Prop := (antitone : antitone s) 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), maps_to f (sa i) 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 in la, f x ∈ sb i := by simpa only [tendsto, hlb.ge_iff, mem_map, filter.eventually] 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 [hlb.tendsto_right_iff, hla.eventually_iff] lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) : ∀ t ∈ lb, ∃ i (hi : pa i), maps_to f (sa i) 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 in la, f x ∈ sb i := 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 ×ᶠ lb).has_basis (λ i : pprod ι ι', pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) := (hla.comap prod.fst).inf' (hlb.comap prod.snd) lemma has_basis.prod {ι ι' : Type*} {pa : ι → Prop} {sa : ι → set α} {pb : ι' → Prop} {sb : ι' → set β} (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la ×ᶠ lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, sa i.1 ×ˢ sb i.2) := (hla.comap prod.fst).inf (hlb.comap prod.snd) lemma has_basis.prod' {la : filter α} {lb : filter β} {ι : Type*} {p : ι → Prop} {sa : ι → set α} {sb : ι → set β} (hla : la.has_basis p sa) (hlb : lb.has_basis p sb) (h_dir : ∀ {i j}, p i → p j → ∃ k, p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) : (la ×ᶠ lb).has_basis p (λ i, sa i ×ˢ sb i) := begin simp only [has_basis_iff, (hla.prod hlb).mem_iff], refine λ t, ⟨_, _⟩, { rintros ⟨⟨i, j⟩, ⟨hi, hj⟩, hsub : sa i ×ˢ sb j ⊆ t⟩, rcases h_dir hi hj with ⟨k, hk, ki, kj⟩, exact ⟨k, hk, (set.prod_mono ki kj).trans hsub⟩ }, { rintro ⟨i, hi, h⟩, exact ⟨⟨i, i⟩, ⟨hi, hi⟩, h⟩ }, end lemma has_antitone_basis.prod {f : filter α} {g : filter β} {s : ℕ → set α} {t : ℕ → set β} (hf : has_antitone_basis f s) (hg : has_antitone_basis g t) : has_antitone_basis (f ×ᶠ g) (λ n, s n ×ˢ t n) := begin have h : has_basis (f ×ᶠ g) _ _ := has_basis.prod' hf.to_has_basis hg.to_has_basis _, swap, { intros i j, simp only [true_and, forall_true_left], exact ⟨max i j, hf.antitone (le_max_left _ _), hg.antitone (le_max_right _ _)⟩, }, refine ⟨h, λ n m hn_le_m, set.prod_mono _ _⟩, exacts [hf.antitone hn_le_m, hg.antitone hn_le_m] end lemma has_basis.coprod {ι ι' : Type*} {pa : ι → Prop} {sa : ι → set α} {pb : ι' → Prop} {sb : ι' → set β} (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) : (la.coprod lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, prod.fst ⁻¹' sa i.1 ∪ prod.snd ⁻¹' sb i.2) := (hla.comap prod.fst).sup (hlb.comap prod.snd) end two_types lemma map_sigma_mk_comap {π : α → Type*} {π' : β → Type*} {f : α → β} (hf : function.injective f) (g : Π a, π a → π' (f a)) (a : α) (l : filter (π' (f a))) : map (sigma.mk a) (comap (g a) l) = comap (sigma.map f g) (map (sigma.mk (f a)) l) := begin refine (((basis_sets _).comap _).map _).eq_of_same_basis _, convert ((basis_sets _).map _).comap _, ext1 s, apply image_sigma_mk_preimage_sigma_map hf end end filter end sort namespace filter variables {α β γ ι : Type*} {ι' : Sort*} /-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/ class is_countably_generated (f : filter α) : Prop := (out [] : ∃ s : set (set α), s.countable ∧ f = generate s) /-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/ structure is_countable_basis (p : ι → Prop) (s : ι → set α) extends is_basis p s : Prop := (countable : (set_of p).countable) /-- We say that a filter `l` has a countable 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`, and the set defined by `p` is countable. -/ structure has_countable_basis (l : filter α) (p : ι → Prop) (s : ι → set α) extends has_basis l p s : Prop := (countable : (set_of p).countable) /-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α` such that the intersection of two elements of this collection contains some element of the collection. -/ structure countable_filter_basis (α : Type*) extends filter_basis α := (countable : sets.countable) -- For illustration purposes, the countable filter basis defining (at_top : filter ℕ) instance nat.inhabited_countable_filter_basis : inhabited (countable_filter_basis ℕ) := ⟨{ countable := countable_range (λ n, Ici n), ..(default : filter_basis ℕ) }⟩ lemma has_countable_basis.is_countably_generated {f : filter α} {p : ι → Prop} {s : ι → set α} (h : f.has_countable_basis p s) : f.is_countably_generated := ⟨⟨{t | ∃ i, p i ∧ s i = t}, h.countable.image s, h.to_has_basis.eq_generate⟩⟩ lemma antitone_seq_of_seq (s : ℕ → set α) : ∃ t : ℕ → set α, antitone t ∧ (⨅ i, 𝓟 $ s i) = ⨅ i, 𝓟 (t i) := begin use λ n, ⋂ m ≤ n, s m, split, { exact λ i j hij, bInter_mono (Iic_subset_Iic.2 hij) (λ n hn, subset.refl _) }, apply le_antisymm; rw le_infi_iff; intro i, { rw le_principal_iff, refine (bInter_mem (finite_le_nat _)).2 (λ j hji, _), rw ← le_principal_iff, apply infi_le_of_le j _, exact le_rfl }, { apply infi_le_of_le i _, rw principal_mono, intro a, simp, intro h, apply h, refl }, end lemma countable_binfi_eq_infi_seq [complete_lattice α] {B : set ι} (Bcbl : B.countable) (Bne : B.nonempty) (f : ι → α) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin rw countable_iff_exists_surjective_to_subtype Bne at Bcbl, rcases Bcbl with ⟨g, gsurj⟩, rw infi_subtype', use (λ n, g n), apply le_antisymm; rw le_infi_iff, { intro i, apply infi_le_of_le (g i) _, apply le_rfl }, { intros a, rcases gsurj a with ⟨i, rfl⟩, apply infi_le } end lemma countable_binfi_eq_infi_seq' [complete_lattice α] {B : set ι} (Bcbl : B.countable) (f : ι → α) {i₀ : ι} (h : f i₀ = ⊤) : ∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) := begin cases B.eq_empty_or_nonempty with hB Bnonempty, { rw [hB, infi_emptyset], use λ n, i₀, simp [h] }, { exact countable_binfi_eq_infi_seq Bcbl Bnonempty f } end lemma countable_binfi_principal_eq_seq_infi {B : set (set α)} (Bcbl : B.countable) : ∃ (x : ℕ → set α), (⨅ t ∈ B, 𝓟 t) = ⨅ i, 𝓟 (x i) := countable_binfi_eq_infi_seq' Bcbl 𝓟 principal_univ section is_countably_generated protected lemma has_antitone_basis.mem [preorder ι] {l : filter α} {s : ι → set α} (hs : l.has_antitone_basis s) (i : ι) : s i ∈ l := hs.to_has_basis.mem_of_mem trivial /-- If `f` is countably generated and `f.has_basis p s`, then `f` admits a decreasing basis enumerated by natural numbers such that all sets have the form `s i`. More precisely, there is a sequence `i n` such that `p (i n)` for all `n` and `s (i n)` is a decreasing sequence of sets which forms a basis of `f`-/ lemma has_basis.exists_antitone_subbasis {f : filter α} [h : f.is_countably_generated] {p : ι' → Prop} {s : ι' → set α} (hs : f.has_basis p s) : ∃ x : ℕ → ι', (∀ i, p (x i)) ∧ f.has_antitone_basis (λ i, s (x i)) := begin obtain ⟨x', hx'⟩ : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 (x i), { unfreezingI { rcases h with ⟨s, hsc, rfl⟩ }, rw generate_eq_binfi, exact countable_binfi_principal_eq_seq_infi hsc }, have : ∀ i, x' i ∈ f := λ i, hx'.symm ▸ (infi_le (λ i, 𝓟 (x' i)) i) (mem_principal_self _), let x : ℕ → {i : ι' // p i} := λ n, nat.rec_on n (hs.index _ $ this 0) (λ n xn, (hs.index _ $ inter_mem (this $ n + 1) (hs.mem_of_mem xn.2))), have x_mono : antitone (λ i, s (x i)), { refine antitone_nat_of_succ_le (λ i, _), exact (hs.set_index_subset _).trans (inter_subset_right _ _) }, have x_subset : ∀ i, s (x i) ⊆ x' i, { rintro (_|i), exacts [hs.set_index_subset _, subset.trans (hs.set_index_subset _) (inter_subset_left _ _)] }, refine ⟨λ i, x i, λ i, (x i).2, _⟩, have : (⨅ i, 𝓟 (s (x i))).has_antitone_basis (λ i, s (x i)) := ⟨has_basis_infi_principal (directed_of_sup x_mono), x_mono⟩, convert this, exact le_antisymm (le_infi $ λ i, le_principal_iff.2 $ by cases i; apply hs.set_index_mem) (hx'.symm ▸ le_infi (λ i, le_principal_iff.2 $ this.to_has_basis.mem_iff.2 ⟨i, trivial, x_subset i⟩)) end /-- A countably generated filter admits a basis formed by an antitone sequence of sets. -/ lemma exists_antitone_basis (f : filter α) [f.is_countably_generated] : ∃ x : ℕ → set α, f.has_antitone_basis x := let ⟨x, hxf, hx⟩ := f.basis_sets.exists_antitone_subbasis in ⟨x, hx⟩ lemma exists_antitone_seq (f : filter α) [f.is_countably_generated] : ∃ x : ℕ → set α, antitone x ∧ ∀ {s}, (s ∈ f ↔ ∃ i, x i ⊆ s) := let ⟨x, hx⟩ := f.exists_antitone_basis in ⟨x, hx.antitone, λ s, by simp [hx.to_has_basis.mem_iff]⟩ instance inf.is_countably_generated (f g : filter α) [is_countably_generated f] [is_countably_generated g] : is_countably_generated (f ⊓ g) := begin rcases f.exists_antitone_basis with ⟨s, hs⟩, rcases g.exists_antitone_basis with ⟨t, ht⟩, exact has_countable_basis.is_countably_generated ⟨hs.to_has_basis.inf ht.to_has_basis, set.countable_encodable _⟩ end instance comap.is_countably_generated (l : filter β) [l.is_countably_generated] (f : α → β) : (comap f l).is_countably_generated := let ⟨x, hxl⟩ := l.exists_antitone_basis in has_countable_basis.is_countably_generated ⟨hxl.to_has_basis.comap _, countable_encodable _⟩ instance sup.is_countably_generated (f g : filter α) [is_countably_generated f] [is_countably_generated g] : is_countably_generated (f ⊔ g) := begin rcases f.exists_antitone_basis with ⟨s, hs⟩, rcases g.exists_antitone_basis with ⟨t, ht⟩, exact has_countable_basis.is_countably_generated ⟨hs.to_has_basis.sup ht.to_has_basis, set.countable_encodable _⟩ end end is_countably_generated @[instance] lemma is_countably_generated_seq [encodable β] (x : β → set α) : is_countably_generated (⨅ i, 𝓟 $ x i) := begin use [range x, countable_range x], rw [generate_eq_binfi, infi_range] end lemma is_countably_generated_of_seq {f : filter α} (h : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 $ x i) : f.is_countably_generated := let ⟨x, h⟩ := h in by rw h ; apply is_countably_generated_seq lemma is_countably_generated_binfi_principal {B : set $ set α} (h : B.countable) : is_countably_generated (⨅ (s ∈ B), 𝓟 s) := is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h) lemma is_countably_generated_iff_exists_antitone_basis {f : filter α} : is_countably_generated f ↔ ∃ x : ℕ → set α, f.has_antitone_basis x := begin split, { introI h, exact f.exists_antitone_basis }, { rintros ⟨x, h⟩, rw h.to_has_basis.eq_infi, exact is_countably_generated_seq x }, end @[instance] lemma is_countably_generated_principal (s : set α) : is_countably_generated (𝓟 s) := is_countably_generated_of_seq ⟨λ _, s, infi_const.symm⟩ @[instance] lemma is_countably_generated_pure (a : α) : is_countably_generated (pure a) := by { rw ← principal_singleton, exact is_countably_generated_principal _, } @[instance] lemma is_countably_generated_bot : is_countably_generated (⊥ : filter α) := @principal_empty α ▸ is_countably_generated_principal _ @[instance] lemma is_countably_generated_top : is_countably_generated (⊤ : filter α) := @principal_univ α ▸ is_countably_generated_principal _ instance is_countably_generated.prod {f : filter α} {g : filter β} [hf : f.is_countably_generated] [hg : g.is_countably_generated] : is_countably_generated (f ×ᶠ g) := begin simp_rw is_countably_generated_iff_exists_antitone_basis at hf hg ⊢, rcases hf with ⟨s, hs⟩, rcases hg with ⟨t, ht⟩, refine ⟨_, hs.prod ht⟩, end end filter
6667bf430c3d5bbafbc82fa4c1f9ad01c4fcc7bb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monoidal/tor.lean
9ea38314c8550689ff8af32a0a4e7f4c651b8138
[ "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
2,924
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 category_theory.functor.left_derived import category_theory.monoidal.preadditive /-! # Tor, the left-derived functor of tensor product > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define `Tor C n : C ⥤ C ⥤ C`, by left-deriving in the second factor of `(X, Y) ↦ X ⊗ Y`. For now we have almost nothing to say about it! It would be good to show that this is naturally isomorphic to the functor obtained by left-deriving in the first factor, instead. For now we define `Tor'` by left-deriving in the first factor, but showing `Tor C n ≅ Tor' C n` will require a bit more theory! Possibly it's best to axiomatize delta functors, and obtain a unique characterisation? -/ noncomputable theory open category_theory.limits open category_theory.monoidal_category namespace category_theory variables {C : Type*} [category C] [monoidal_category C] [preadditive C] [monoidal_preadditive C] [has_zero_object C] [has_equalizers C] [has_cokernels C] [has_images C] [has_image_maps C] [has_projective_resolutions C] variables (C) /-- We define `Tor C n : C ⥤ C ⥤ C` by left-deriving in the second factor of `(X, Y) ↦ X ⊗ Y`. -/ @[simps] def Tor (n : ℕ) : C ⥤ C ⥤ C := { obj := λ X, functor.left_derived ((tensoring_left C).obj X) n, map := λ X Y f, nat_trans.left_derived ((tensoring_left C).map f) n, map_id' := λ X, by rw [(tensoring_left C).map_id, nat_trans.left_derived_id], map_comp' := λ X Y Z f g, by rw [(tensoring_left C).map_comp, nat_trans.left_derived_comp], } /-- An alternative definition of `Tor`, where we left-derive in the first factor instead. -/ @[simps] def Tor' (n : ℕ) : C ⥤ C ⥤ C := functor.flip { obj := λ X, functor.left_derived ((tensoring_right C).obj X) n, map := λ X Y f, nat_trans.left_derived ((tensoring_right C).map f) n, map_id' := λ X, by rw [(tensoring_right C).map_id, nat_trans.left_derived_id], map_comp' := λ X Y Z f g, by rw [(tensoring_right C).map_comp, nat_trans.left_derived_comp], } open_locale zero_object /-- The higher `Tor` groups for `X` and `Y` are zero if `Y` is projective. -/ def Tor_succ_of_projective (X Y : C) [projective Y] (n : ℕ) : ((Tor C (n + 1)).obj X).obj Y ≅ 0 := ((tensoring_left C).obj X).left_derived_obj_projective_succ n Y /-- The higher `Tor'` groups for `X` and `Y` are zero if `X` is projective. -/ def Tor'_succ_of_projective (X Y : C) [projective X] (n : ℕ) : ((Tor' C (n + 1)).obj X).obj Y ≅ 0 := -- This unfortunately needs a manual `dsimp`, to avoid a slow unification problem. begin dsimp only [Tor', functor.flip], exact ((tensoring_right C).obj Y).left_derived_obj_projective_succ n X end end category_theory assert_not_exists Module.abelian
e0cee1c8664fdeb90014f1ec8d5a9085ddd1f748
a8a8012e62ebc4c8550b92736c0b20faab882ba0
/yoneda_bug.hlean
3cae14bc0ec481e3f521f09e83af2dc53f664513
[]
no_license
fpvandoorn/Bergen-Lean
d02d173f79492498b0ee042ae6699a984108c6ef
40638f1e04b6c681858127e85546c9012b62ab63
refs/heads/master
1,610,398,839,774
1,484,840,344,000
1,484,840,344,000
79,229,751
0
2
null
null
null
null
UTF-8
Lean
false
false
3,610
hlean
--The following special case of the Yoneda lemma: --If A -> X ~= B -> X for all X, then A ~= B import types.equiv import types.pointed open pointed eq equiv is_equiv set_option pp.all true structure typeclass := (data : Type → Type) namespace typeclass structure obj.{u v} (C : typeclass.{u v}) : Type.{max (u+1) v} := (U : Type.{u}) (struct : data C U) attribute obj.U [coercion] end typeclass open typeclass -- A "concrete infinity-category", a subcategory of the inf-category of types -- An object consists of a type plus some data -- The arrows are the 'good' maps structure cCat.{u v w} extends CC:typeclass.{u v} : Type.{(max u v w)+1} := (good : Π (A B : obj CC) , (A → B) → Type.{w}) (idwd : Π (A : obj CC), good A A (λ x , x)) namespace cCat variables {C : cCat} structure arr (A B : obj C) := (to_fun : A → B) (wd : good C A B to_fun) infix ` →* `:30 := pmap attribute to_fun [coercion] definition id (A : obj C) : arr A A := arr.mk (λ x , x) (idwd C A) structure cequiv.{u v w} {C : cCat.{u v w}} (A B : obj C) extends e:equiv.{u u} A B, arr A B : Type.{(max u v w)+1} := (wd_inv : good C B A e⁻¹ᵉ) infix ` ≃* `:25 := cequiv definition inv_inv {A B : Type} (e : A ≃ B) : e⁻¹⁻¹ = e := begin apply eq_of_homotopy, intro a, exact equiv.to_inv_eq_of_eq _ (symm (to_left_inv e a)) end protected definition cequiv.symm [symm] [constructor] {A B : obj C} (f : A ≃* B) : B ≃* A := begin apply cequiv.mk, { exact cequiv.wd_inv f }, { esimp, apply transport (good C A B), rotate 1, { exact cequiv.wd f }, { symmetry, apply inv_inv } } end end cCat open cCat --Closed concrete infinity-category structure ccCat.{u v} extends CC:cCat.{u v u} : Type.{(max u v)+1} := (closed : Π {A B : obj CC} , data (arr A B)) namespace ccCat variables {C : ccCat} definition hom (A B : obj C) : obj C := obj.mk (arr A B) (closed C) definition deYonedify.{u v w} {C : ccCat.{u v}} {A B : obj C} (f : Π X, cequiv.{u v u} (hom A X) (hom B X)) : B → A := begin refine @arr.to_fun C _ _ _, apply equiv.to_fun (f A), apply id end definition yoneda {A B : obj C} (e : Π X , hom A X ≃* hom B X) : A ≃* B := begin fapply cequiv.mk, { apply deYonedify, intro X, apply cequiv.symm, exact (e X) }, { }, { } end definition pTypeC.{u} : ccCat.{u u u} := begin fapply mk, { fapply cCat.mk, { exact λ A , A }, { intro A B f, exact f (obj.struct A) = obj.struct B }, { intro A, exact refl _ } }, { intro A B, apply arr.mk, exact refl _ } end namespace pointed definition yoneda.{u} {A B : pType.{u}} (e : Π (X : pType.{u}) , (ppmap A X) ≃* (ppmap B X)) : A ≃* B := begin fapply pequiv_of_equiv, { fapply equiv.mk, { apply ccCat.deYonedify pTypeC, intro X, apply to_equiv, apply pequiv.symm, exact (e X) }, { fapply is_equiv.mk, { apply Yonedable.deYonedify pTypeY, intro X, apply to_equiv, exact (e X) }, { }, { }, { } } }, { } end end pointed
2a6611a62135f8973e1796768db41011c837d61b
c055f4b7c29cf1aac2223bd8c1ac8d181a7c6447
/src/categories/universal/default.lean
73c03b223d2c669112ddd690f2667ec0c341dca0
[ "Apache-2.0" ]
permissive
rwbarton/lean-category-theory-pr
77207b6674eeec1e258ec85dea58f3bff8d27065
591847d70c6a11c4d5561cd0eaf69b1fe85a70ab
refs/heads/master
1,584,595,111,303
1,528,029,041,000
1,528,029,041,000
135,919,126
0
0
null
1,528,041,805,000
1,528,041,805,000
null
UTF-8
Lean
false
false
5,723
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import .cones open categories open categories.functor open categories.isomorphism open categories.initial open categories.types namespace categories.universal universes u v w variables {C : Type u} variables [𝒞 : category.{u v} C] include 𝒞 variables {X Y : C} structure Equalizer (f g : X ⟶ Y) := (equalizer : C) (inclusion : equalizer ⟶ X) (map : ∀ {Z : C} (k : Z ⟶ X) (w : k ≫ f = k ≫ g), Z ⟶ equalizer) (witness : inclusion ≫ f = inclusion ≫ g . obviously) (factorisation : ∀ {Z : C} (k : Z ⟶ X) (w : k ≫ f = k ≫ g), (map k w) ≫ inclusion = k . obviously) (uniqueness : ∀ {Z : C} (a b : Z ⟶ equalizer) (witness : a ≫ inclusion = b ≫ inclusion), a = b . obviously) make_lemma Equalizer.witness make_lemma Equalizer.factorisation make_lemma Equalizer.uniqueness attribute [simp,ematch] Equalizer.factorisation_lemma attribute [applicable] Equalizer.inclusion Equalizer.map attribute [applicable] Equalizer.uniqueness_lemma -- Or should we write out yet another structure, and prove it agrees with the equalizer? definition Kernel [Z : ZeroObject C] (f : X ⟶ Y) := Equalizer f (Z.zero_morphism X Y) structure BinaryProduct (X Y : C) := (product : C) (left_projection : product ⟶ X) (right_projection : product ⟶ Y) (map : ∀ {Z : C} (f : Z ⟶ X) (g : Z ⟶ Y), Z ⟶ product) (left_factorisation : ∀ {Z : C} (f : Z ⟶ X) (g : Z ⟶ Y), (map f g) ≫ left_projection = f . obviously) (right_factorisation : ∀ {Z : C} (f : Z ⟶ X) (g : Z ⟶ Y), (map f g) ≫ right_projection = g . obviously) (uniqueness : ∀ {Z : C} (f g : Z ⟶ product) (left_witness : f ≫ left_projection = g ≫ left_projection ) (right_witness : f ≫ right_projection = g ≫ right_projection), f = g . obviously) make_lemma BinaryProduct.left_factorisation make_lemma BinaryProduct.right_factorisation make_lemma BinaryProduct.uniqueness attribute [simp,ematch] BinaryProduct.left_factorisation_lemma BinaryProduct.right_factorisation_lemma attribute [applicable] BinaryProduct.left_projection BinaryProduct.right_projection BinaryProduct.map attribute [applicable] BinaryProduct.uniqueness_lemma structure Product {I : Type w} (F : I → C) := (product : C) (projection : Π i : I, product ⟶ (F i)) (map : ∀ {Z : C} (f : Π i : I, Z ⟶ (F i)), Z ⟶ product) (factorisation : ∀ {Z : C} (f : Π i : I, Z ⟶ (F i)) (i : I), (map f) ≫ (projection i) = f i . obviously) (uniqueness : ∀ {Z : C} (f g : Z ⟶ product) (witness : ∀ i : I, f ≫ (projection i) = g ≫ (projection i)), f = g . obviously) make_lemma Product.factorisation make_lemma Product.uniqueness attribute [simp,ematch] Product.factorisation_lemma attribute [applicable] Product.projection Product.map attribute [applicable] Product.uniqueness_lemma structure Coequalizer (f g : X ⟶ Y) := (coequalizer : C) (projection : Y ⟶ coequalizer) (map : ∀ {Z : C} (k : Y ⟶ Z) (w : f ≫ k = g ≫ k), coequalizer ⟶ Z) (witness : f ≫ projection = g ≫ projection . obviously) (factorisation : ∀ {Z : C} (k : Y ⟶ Z) (w : f ≫ k = g ≫ k), projection ≫ (map k w) = k . obviously) (uniqueness : ∀ {Z : C} (a b : coequalizer ⟶ Z) (witness : projection ≫ a = projection ≫ b), a = b . obviously) make_lemma Coequalizer.witness make_lemma Coequalizer.factorisation make_lemma Coequalizer.uniqueness attribute [simp,ematch] Coequalizer.factorisation_lemma attribute [applicable] Coequalizer.projection Coequalizer.map attribute [applicable] Coequalizer.uniqueness_lemma definition Cokernel [Z : ZeroObject C] (f : X ⟶ Y) := Coequalizer f (Z.zero_morphism X Y) structure BinaryCoproduct (X Y : C) := (coproduct : C) (left_inclusion : X ⟶ coproduct) (right_inclusion : Y ⟶ coproduct) (map : ∀ {Z : C} (f : X ⟶ Z) (g : Y ⟶ Z), coproduct ⟶ Z) (left_factorisation : ∀ {Z : C} (f : X ⟶ Z) (g : Y ⟶ Z), left_inclusion ≫ (map f g) = f . obviously) (right_factorisation : ∀ {Z : C} (f : X ⟶ Z) (g : Y ⟶ Z), right_inclusion ≫ (map f g) = g . obviously) (uniqueness : ∀ {Z : C} (f g : coproduct ⟶ Z) (left_witness : left_inclusion ≫ f = left_inclusion ≫ g) (right_witness : right_inclusion ≫ f = right_inclusion ≫ g), f = g . obviously) make_lemma BinaryCoproduct.left_factorisation make_lemma BinaryCoproduct.right_factorisation make_lemma BinaryCoproduct.uniqueness attribute [simp,ematch] BinaryCoproduct.left_factorisation_lemma BinaryCoproduct.right_factorisation_lemma attribute [applicable] BinaryCoproduct.left_inclusion BinaryCoproduct.right_inclusion BinaryCoproduct.map attribute [applicable] BinaryCoproduct.uniqueness_lemma structure Coproduct {I : Type w} (X : I → C) := (coproduct : C) (inclusion : Π i : I, (X i) ⟶ coproduct) (map : ∀ {Z : C} (f : Π i : I, (X i) ⟶ Z), coproduct ⟶ Z) (factorisation : ∀ {Z : C} (f : Π i : I, (X i) ⟶ Z) (i : I), (inclusion i) ≫ (map f) = f i . obviously) (uniqueness : ∀ {Z : C} (f g : coproduct ⟶ Z) (witness : ∀ i : I, (inclusion i) ≫ f = (inclusion i) ≫ g), f = g . obviously) -- Coming in later PRs: all these things are unique up to unique isomorphism, and are special cases of (co)limits. end categories.universal
c441db91f9252ffd2524570af661a3e358a11015
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/bounded.lean
b7e2634a12a816f54ad978a93f6aeef5aa22c32c
[ "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
14,049
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import order.rel_classes import data.set.intervals.basic /-! # Bounded and unbounded sets We prove miscellaneous lemmas about bounded and unbounded sets. Many of these are just variations on the same ideas, or similar results with a few minor differences. The file is divided into these different general ideas. -/ namespace set variables {α : Type*} {r : α → α → Prop} {s t : set α} /-! ### Subsets of bounded and unbounded sets -/ theorem bounded.mono (hst : s ⊆ t) (hs : bounded r t) : bounded r s := hs.imp $ λ a ha b hb, ha b (hst hb) theorem unbounded.mono (hst : s ⊆ t) (hs : unbounded r s) : unbounded r t := λ a, let ⟨b, hb, hb'⟩ := hs a in ⟨b, hst hb, hb'⟩ /-! ### Alternate characterizations of unboundedness on orders -/ lemma unbounded_le_of_forall_exists_lt [preorder α] (h : ∀ a, ∃ b ∈ s, a < b) : unbounded (≤) s := λ a, let ⟨b, hb, hb'⟩ := h a in ⟨b, hb, λ hba, hba.not_lt hb'⟩ lemma unbounded_le_iff [linear_order α] : unbounded (≤) s ↔ ∀ a, ∃ b ∈ s, a < b := by simp only [unbounded, not_le] lemma unbounded_lt_of_forall_exists_le [preorder α] (h : ∀ a, ∃ b ∈ s, a ≤ b) : unbounded (<) s := λ a, let ⟨b, hb, hb'⟩ := h a in ⟨b, hb, λ hba, hba.not_le hb'⟩ lemma unbounded_lt_iff [linear_order α] : unbounded (<) s ↔ ∀ a, ∃ b ∈ s, a ≤ b := by simp only [unbounded, not_lt] lemma unbounded_ge_of_forall_exists_gt [preorder α] (h : ∀ a, ∃ b ∈ s, b < a) : unbounded (≥) s := @unbounded_le_of_forall_exists_lt αᵒᵈ _ _ h lemma unbounded_ge_iff [linear_order α] : unbounded (≥) s ↔ ∀ a, ∃ b ∈ s, b < a := ⟨λ h a, let ⟨b, hb, hba⟩ := h a in ⟨b, hb, lt_of_not_ge hba⟩, unbounded_ge_of_forall_exists_gt⟩ lemma unbounded_gt_of_forall_exists_ge [preorder α] (h : ∀ a, ∃ b ∈ s, b ≤ a) : unbounded (>) s := λ a, let ⟨b, hb, hb'⟩ := h a in ⟨b, hb, λ hba, not_le_of_gt hba hb'⟩ lemma unbounded_gt_iff [linear_order α] : unbounded (>) s ↔ ∀ a, ∃ b ∈ s, b ≤ a := ⟨λ h a, let ⟨b, hb, hba⟩ := h a in ⟨b, hb, le_of_not_gt hba⟩, unbounded_gt_of_forall_exists_ge⟩ /-! ### Relation between boundedness by strict and nonstrict orders. -/ /-! #### Less and less or equal -/ lemma bounded.rel_mono {r' : α → α → Prop} (h : bounded r s) (hrr' : r ≤ r') : bounded r' s := let ⟨a, ha⟩ := h in ⟨a, λ b hb, hrr' b a (ha b hb)⟩ lemma bounded_le_of_bounded_lt [preorder α] (h : bounded (<) s) : bounded (≤) s := h.rel_mono $ λ _ _, le_of_lt lemma unbounded.rel_mono {r' : α → α → Prop} (hr : r' ≤ r) (h : unbounded r s) : unbounded r' s := λ a, let ⟨b, hb, hba⟩ := h a in ⟨b, hb, λ hba', hba (hr b a hba')⟩ lemma unbounded_lt_of_unbounded_le [preorder α] (h : unbounded (≤) s) : unbounded (<) s := h.rel_mono $ λ _ _, le_of_lt lemma bounded_le_iff_bounded_lt [preorder α] [no_max_order α] : bounded (≤) s ↔ bounded (<) s := begin refine ⟨λ h, _, bounded_le_of_bounded_lt⟩, cases h with a ha, cases exists_gt a with b hb, exact ⟨b, λ c hc, lt_of_le_of_lt (ha c hc) hb⟩ end lemma unbounded_lt_iff_unbounded_le [preorder α] [no_max_order α] : unbounded (<) s ↔ unbounded (≤) s := by simp_rw [← not_bounded_iff, bounded_le_iff_bounded_lt] /-! #### Greater and greater or equal -/ lemma bounded_ge_of_bounded_gt [preorder α] (h : bounded (>) s) : bounded (≥) s := let ⟨a, ha⟩ := h in ⟨a, λ b hb, le_of_lt (ha b hb)⟩ lemma unbounded_gt_of_unbounded_ge [preorder α] (h : unbounded (≥) s) : unbounded (>) s := λ a, let ⟨b, hb, hba⟩ := h a in ⟨b, hb, λ hba', hba (le_of_lt hba')⟩ lemma bounded_ge_iff_bounded_gt [preorder α] [no_min_order α] : bounded (≥) s ↔ bounded (>) s := @bounded_le_iff_bounded_lt αᵒᵈ _ _ _ lemma unbounded_gt_iff_unbounded_ge [preorder α] [no_min_order α] : unbounded (>) s ↔ unbounded (≥) s := @unbounded_lt_iff_unbounded_le αᵒᵈ _ _ _ /-! ### The universal set -/ theorem unbounded_le_univ [has_le α] [no_top_order α] : unbounded (≤) (@set.univ α) := λ a, let ⟨b, hb⟩ := exists_not_le a in ⟨b, ⟨⟩, hb⟩ theorem unbounded_lt_univ [preorder α] [no_top_order α] : unbounded (<) (@set.univ α) := unbounded_lt_of_unbounded_le unbounded_le_univ theorem unbounded_ge_univ [has_le α] [no_bot_order α] : unbounded (≥) (@set.univ α) := λ a, let ⟨b, hb⟩ := exists_not_ge a in ⟨b, ⟨⟩, hb⟩ theorem unbounded_gt_univ [preorder α] [no_bot_order α] : unbounded (>) (@set.univ α) := unbounded_gt_of_unbounded_ge unbounded_ge_univ /-! ### Bounded and unbounded intervals -/ theorem bounded_self (a : α) : bounded r {b | r b a} := ⟨a, λ x, id⟩ /-! #### Half-open bounded intervals -/ theorem bounded_lt_Iio [preorder α] (a : α) : bounded (<) (set.Iio a) := bounded_self a theorem bounded_le_Iio [preorder α] (a : α) : bounded (≤) (set.Iio a) := bounded_le_of_bounded_lt (bounded_lt_Iio a) theorem bounded_le_Iic [preorder α] (a : α) : bounded (≤) (set.Iic a) := bounded_self a theorem bounded_lt_Iic [preorder α] [no_max_order α] (a : α) : bounded (<) (set.Iic a) := by simp only [← bounded_le_iff_bounded_lt, bounded_le_Iic] theorem bounded_gt_Ioi [preorder α] (a : α) : bounded (>) (set.Ioi a) := bounded_self a theorem bounded_ge_Ioi [preorder α] (a : α) : bounded (≥) (set.Ioi a) := bounded_ge_of_bounded_gt (bounded_gt_Ioi a) theorem bounded_ge_Ici [preorder α] (a : α) : bounded (≥) (set.Ici a) := bounded_self a theorem bounded_gt_Ici [preorder α] [no_min_order α] (a : α) : bounded (>) (set.Ici a) := by simp only [← bounded_ge_iff_bounded_gt, bounded_ge_Ici] /-! #### Other bounded intervals -/ theorem bounded_lt_Ioo [preorder α] (a b : α) : bounded (<) (set.Ioo a b) := (bounded_lt_Iio b).mono set.Ioo_subset_Iio_self theorem bounded_lt_Ico [preorder α] (a b : α) : bounded (<) (set.Ico a b) := (bounded_lt_Iio b).mono set.Ico_subset_Iio_self theorem bounded_lt_Ioc [preorder α] [no_max_order α] (a b : α) : bounded (<) (set.Ioc a b) := (bounded_lt_Iic b).mono set.Ioc_subset_Iic_self theorem bounded_lt_Icc [preorder α] [no_max_order α] (a b : α) : bounded (<) (set.Icc a b) := (bounded_lt_Iic b).mono set.Icc_subset_Iic_self theorem bounded_le_Ioo [preorder α] (a b : α) : bounded (≤) (set.Ioo a b) := (bounded_le_Iio b).mono set.Ioo_subset_Iio_self theorem bounded_le_Ico [preorder α] (a b : α) : bounded (≤) (set.Ico a b) := (bounded_le_Iio b).mono set.Ico_subset_Iio_self theorem bounded_le_Ioc [preorder α] (a b : α) : bounded (≤) (set.Ioc a b) := (bounded_le_Iic b).mono set.Ioc_subset_Iic_self theorem bounded_le_Icc [preorder α] (a b : α) : bounded (≤) (set.Icc a b) := (bounded_le_Iic b).mono set.Icc_subset_Iic_self theorem bounded_gt_Ioo [preorder α] (a b : α) : bounded (>) (set.Ioo a b) := (bounded_gt_Ioi a).mono set.Ioo_subset_Ioi_self theorem bounded_gt_Ioc [preorder α] (a b : α) : bounded (>) (set.Ioc a b) := (bounded_gt_Ioi a).mono set.Ioc_subset_Ioi_self theorem bounded_gt_Ico [preorder α] [no_min_order α] (a b : α) : bounded (>) (set.Ico a b) := (bounded_gt_Ici a).mono set.Ico_subset_Ici_self theorem bounded_gt_Icc [preorder α] [no_min_order α] (a b : α) : bounded (>) (set.Icc a b) := (bounded_gt_Ici a).mono set.Icc_subset_Ici_self theorem bounded_ge_Ioo [preorder α] (a b : α) : bounded (≥) (set.Ioo a b) := (bounded_ge_Ioi a).mono set.Ioo_subset_Ioi_self theorem bounded_ge_Ioc [preorder α] (a b : α) : bounded (≥) (set.Ioc a b) := (bounded_ge_Ioi a).mono set.Ioc_subset_Ioi_self theorem bounded_ge_Ico [preorder α] (a b : α) : bounded (≥) (set.Ico a b) := (bounded_ge_Ici a).mono set.Ico_subset_Ici_self theorem bounded_ge_Icc [preorder α] (a b : α) : bounded (≥) (set.Icc a b) := (bounded_ge_Ici a).mono set.Icc_subset_Ici_self /-! #### Unbounded intervals -/ theorem unbounded_le_Ioi [semilattice_sup α] [no_max_order α] (a : α) : unbounded (≤) (set.Ioi a) := λ b, let ⟨c, hc⟩ := exists_gt (a ⊔ b) in ⟨c, le_sup_left.trans_lt hc, (le_sup_right.trans_lt hc).not_le⟩ theorem unbounded_le_Ici [semilattice_sup α] [no_max_order α] (a : α) : unbounded (≤) (set.Ici a) := (unbounded_le_Ioi a).mono set.Ioi_subset_Ici_self theorem unbounded_lt_Ioi [semilattice_sup α] [no_max_order α] (a : α) : unbounded (<) (set.Ioi a) := unbounded_lt_of_unbounded_le (unbounded_le_Ioi a) theorem unbounded_lt_Ici [semilattice_sup α] (a : α) : unbounded (<) (set.Ici a) := λ b, ⟨a ⊔ b, le_sup_left, le_sup_right.not_lt⟩ /-! ### Bounded initial segments -/ theorem bounded_inter_not (H : ∀ a b, ∃ m, ∀ c, r c a ∨ r c b → r c m) (a : α) : bounded r (s ∩ {b | ¬ r b a}) ↔ bounded r s := begin refine ⟨_, bounded.mono (set.inter_subset_left s _)⟩, rintro ⟨b, hb⟩, cases H a b with m hm, exact ⟨m, λ c hc, hm c (or_iff_not_imp_left.2 (λ hca, (hb c ⟨hc, hca⟩)))⟩ end theorem unbounded_inter_not (H : ∀ a b, ∃ m, ∀ c, r c a ∨ r c b → r c m) (a : α) : unbounded r (s ∩ {b | ¬ r b a}) ↔ unbounded r s := by simp_rw [← not_bounded_iff, bounded_inter_not H] /-! #### Less or equal -/ theorem bounded_le_inter_not_le [semilattice_sup α] (a : α) : bounded (≤) (s ∩ {b | ¬ b ≤ a}) ↔ bounded (≤) s := bounded_inter_not (λ x y, ⟨x ⊔ y, λ z h, h.elim le_sup_of_le_left le_sup_of_le_right⟩) a theorem unbounded_le_inter_not_le [semilattice_sup α] (a : α) : unbounded (≤) (s ∩ {b | ¬ b ≤ a}) ↔ unbounded (≤) s := begin rw [←not_bounded_iff, ←not_bounded_iff, not_iff_not], exact bounded_le_inter_not_le a end theorem bounded_le_inter_lt [linear_order α] (a : α) : bounded (≤) (s ∩ {b | a < b}) ↔ bounded (≤) s := by simp_rw [← not_le, bounded_le_inter_not_le] theorem unbounded_le_inter_lt [linear_order α] (a : α) : unbounded (≤) (s ∩ {b | a < b}) ↔ unbounded (≤) s := by { convert unbounded_le_inter_not_le a, ext, exact lt_iff_not_le } theorem bounded_le_inter_le [linear_order α] (a : α) : bounded (≤) (s ∩ {b | a ≤ b}) ↔ bounded (≤) s := begin refine ⟨_, bounded.mono (set.inter_subset_left s _)⟩, rw ←@bounded_le_inter_lt _ s _ a, exact bounded.mono (λ x ⟨hx, hx'⟩, ⟨hx, le_of_lt hx'⟩) end theorem unbounded_le_inter_le [linear_order α] (a : α) : unbounded (≤) (s ∩ {b | a ≤ b}) ↔ unbounded (≤) s := begin rw [←not_bounded_iff, ←not_bounded_iff, not_iff_not], exact bounded_le_inter_le a end /-! #### Less than -/ theorem bounded_lt_inter_not_lt [semilattice_sup α] (a : α) : bounded (<) (s ∩ {b | ¬ b < a}) ↔ bounded (<) s := bounded_inter_not (λ x y, ⟨x ⊔ y, λ z h, h.elim lt_sup_of_lt_left lt_sup_of_lt_right⟩) a theorem unbounded_lt_inter_not_lt [semilattice_sup α] (a : α) : unbounded (<) (s ∩ {b | ¬ b < a}) ↔ unbounded (<) s := begin rw [←not_bounded_iff, ←not_bounded_iff, not_iff_not], exact bounded_lt_inter_not_lt a end theorem bounded_lt_inter_le [linear_order α] (a : α) : bounded (<) (s ∩ {b | a ≤ b}) ↔ bounded (<) s := by { convert bounded_lt_inter_not_lt a, ext, exact not_lt.symm } theorem unbounded_lt_inter_le [linear_order α] (a : α) : unbounded (<) (s ∩ {b | a ≤ b}) ↔ unbounded (<) s := by { convert unbounded_lt_inter_not_lt a, ext, exact not_lt.symm } theorem bounded_lt_inter_lt [linear_order α] [no_max_order α] (a : α) : bounded (<) (s ∩ {b | a < b}) ↔ bounded (<) s := begin rw [←bounded_le_iff_bounded_lt, ←bounded_le_iff_bounded_lt], exact bounded_le_inter_lt a end theorem unbounded_lt_inter_lt [linear_order α] [no_max_order α] (a : α) : unbounded (<) (s ∩ {b | a < b}) ↔ unbounded (<) s := begin rw [←not_bounded_iff, ←not_bounded_iff, not_iff_not], exact bounded_lt_inter_lt a end /-! #### Greater or equal -/ theorem bounded_ge_inter_not_ge [semilattice_inf α] (a : α) : bounded (≥) (s ∩ {b | ¬ a ≤ b}) ↔ bounded (≥) s := @bounded_le_inter_not_le αᵒᵈ s _ a theorem unbounded_ge_inter_not_ge [semilattice_inf α] (a : α) : unbounded (≥) (s ∩ {b | ¬ a ≤ b}) ↔ unbounded (≥) s := @unbounded_le_inter_not_le αᵒᵈ s _ a theorem bounded_ge_inter_gt [linear_order α] (a : α) : bounded (≥) (s ∩ {b | b < a}) ↔ bounded (≥) s := @bounded_le_inter_lt αᵒᵈ s _ a theorem unbounded_ge_inter_gt [linear_order α] (a : α) : unbounded (≥) (s ∩ {b | b < a}) ↔ unbounded (≥) s := @unbounded_le_inter_lt αᵒᵈ s _ a theorem bounded_ge_inter_ge [linear_order α] (a : α) : bounded (≥) (s ∩ {b | b ≤ a}) ↔ bounded (≥) s := @bounded_le_inter_le αᵒᵈ s _ a theorem unbounded_ge_iff_unbounded_inter_ge [linear_order α] (a : α) : unbounded (≥) (s ∩ {b | b ≤ a}) ↔ unbounded (≥) s := @unbounded_le_inter_le αᵒᵈ s _ a /-! #### Greater than -/ theorem bounded_gt_inter_not_gt [semilattice_inf α] (a : α) : bounded (>) (s ∩ {b | ¬ a < b}) ↔ bounded (>) s := @bounded_lt_inter_not_lt αᵒᵈ s _ a theorem unbounded_gt_inter_not_gt [semilattice_inf α] (a : α) : unbounded (>) (s ∩ {b | ¬ a < b}) ↔ unbounded (>) s := @unbounded_lt_inter_not_lt αᵒᵈ s _ a theorem bounded_gt_inter_ge [linear_order α] (a : α) : bounded (>) (s ∩ {b | b ≤ a}) ↔ bounded (>) s := @bounded_lt_inter_le αᵒᵈ s _ a theorem unbounded_inter_ge [linear_order α] (a : α) : unbounded (>) (s ∩ {b | b ≤ a}) ↔ unbounded (>) s := @unbounded_lt_inter_le αᵒᵈ s _ a theorem bounded_gt_inter_gt [linear_order α] [no_min_order α] (a : α) : bounded (>) (s ∩ {b | b < a}) ↔ bounded (>) s := @bounded_lt_inter_lt αᵒᵈ s _ _ a theorem unbounded_gt_inter_gt [linear_order α] [no_min_order α] (a : α) : unbounded (>) (s ∩ {b | b < a}) ↔ unbounded (>) s := @unbounded_lt_inter_lt αᵒᵈ s _ _ a end set
1f026041777145a8bf08cc1279a819381cadd448
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/heapSort.lean
a92bcca95af20d3558024e987706ab971b1b6324
[ "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
7,800
lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ /-- A max-heap data structure. -/ structure BinaryHeap (α) (lt : α → α → Bool) where arr : Array α namespace BinaryHeap /-- Core operation for binary heaps, expressed directly on arrays. Given an array which is a max-heap, push item `i` down to restore the max-heap property. -/ def heapifyDown (lt : α → α → Bool) (a : Array α) (i : Fin a.size) : {a' : Array α // a'.size = a.size} := let left := 2 * i.1 + 1 let right := left + 1 have left_le : i ≤ left := Nat.le_trans (by rw [Nat.succ_mul, Nat.one_mul]; exact Nat.le_add_left i i) (Nat.le_add_right ..) have right_le : i ≤ right := Nat.le_trans left_le (Nat.le_add_right ..) have i_le : i ≤ i := Nat.le_refl _ have j : {j : Fin a.size // i ≤ j} := if h : left < a.size then if lt (a.get i) (a.get ⟨left, h⟩) then ⟨⟨left, h⟩, left_le⟩ else ⟨i, i_le⟩ else ⟨i, i_le⟩ have j := if h : right < a.size then if lt (a.get j) (a.get ⟨right, h⟩) then ⟨⟨right, h⟩, right_le⟩ else j else j if h : i.1 = j then ⟨a, rfl⟩ else let a' := a.swap i j let j' := ⟨j, by rw [a.size_swap i j]; exact j.1.2⟩ have : a'.size - j < a.size - i := by rw [a.size_swap i j]; sorry let ⟨a₂, h₂⟩ := heapifyDown lt a' j' ⟨a₂, h₂.trans (a.size_swap i j)⟩ termination_by _ => a.size - i decreasing_by assumption @[simp] theorem size_heapifyDown (lt : α → α → Bool) (a : Array α) (i : Fin a.size) : (heapifyDown lt a i).1.size = a.size := (heapifyDown lt a i).2 /-- Core operation for binary heaps, expressed directly on arrays. Construct a heap from an unsorted array, by heapifying all the elements. -/ def mkHeap (lt : α → α → Bool) (a : Array α) : {a' : Array α // a'.size = a.size} := let rec loop : (i : Nat) → (a : Array α) → i ≤ a.size → {a' : Array α // a'.size = a.size} | 0, a, _ => ⟨a, rfl⟩ | i+1, a, h => let h := Nat.lt_of_succ_le h let a' := heapifyDown lt a ⟨i, h⟩ let ⟨a₂, h₂⟩ := loop i a' ((heapifyDown ..).2.symm ▸ Nat.le_of_lt h) ⟨a₂, h₂.trans a'.2⟩ loop (a.size / 2) a sorry @[simp] theorem size_mkHeap (lt : α → α → Bool) (a : Array α) (i : Fin a.size) : (mkHeap lt a).1.size = a.size := (mkHeap lt a).2 /-- Core operation for binary heaps, expressed directly on arrays. Given an array which is a max-heap, push item `i` up to restore the max-heap property. -/ def heapifyUp (lt : α → α → Bool) (a : Array α) (i : Fin a.size) : {a' : Array α // a'.size = a.size} := if i0 : i.1 = 0 then ⟨a, rfl⟩ else have : (i.1 - 1) / 2 < i := sorry let j := ⟨(i.1 - 1) / 2, Nat.lt_trans this i.2⟩ if lt (a.get j) (a.get i) then let a' := a.swap i j let ⟨a₂, h₂⟩ := heapifyUp lt a' ⟨j.1, by rw [a.size_swap i j]; exact j.2⟩ ⟨a₂, h₂.trans (a.size_swap i j)⟩ else ⟨a, rfl⟩ termination_by _ => i.1 decreasing_by assumption @[simp] theorem size_heapifyUp (lt : α → α → Bool) (a : Array α) (i : Fin a.size) : (heapifyUp lt a i).1.size = a.size := (heapifyUp lt a i).2 /-- `O(1)`. Build a new empty heap. -/ def empty (lt) : BinaryHeap α lt := ⟨#[]⟩ instance (lt) : Inhabited (BinaryHeap α lt) := ⟨empty _⟩ instance (lt) : EmptyCollection (BinaryHeap α lt) := ⟨empty _⟩ /-- `O(1)`. Build a one-element heap. -/ def singleton (lt) (x : α) : BinaryHeap α lt := ⟨#[x]⟩ /-- `O(1)`. Get the number of elements in a `BinaryHeap`. -/ def size {lt} (self : BinaryHeap α lt) : Nat := self.1.size /-- `O(1)`. Get an element in the heap by index. -/ def get {lt} (self : BinaryHeap α lt) (i : Fin self.size) : α := self.1.get i /-- `O(log n)`. Insert an element into a `BinaryHeap`, preserving the max-heap property. -/ def insert {lt} (self : BinaryHeap α lt) (x : α) : BinaryHeap α lt where arr := let n := self.size; heapifyUp lt (self.1.push x) ⟨n, by rw [Array.size_push]; apply Nat.lt_succ_self⟩ @[simp] theorem size_insert {lt} (self : BinaryHeap α lt) (x : α) : (self.insert x).size = self.size + 1 := by simp [insert, size, size_heapifyUp] /-- `O(1)`. Get the maximum element in a `BinaryHeap`. -/ def max {lt} (self : BinaryHeap α lt) : Option α := self.1.get? 0 /-- Auxiliary for `popMax`. -/ def popMaxAux {lt} (self : BinaryHeap α lt) : {a' : BinaryHeap α lt // a'.size = self.size - 1} := match e: self.1.size with | 0 => ⟨self, by simp [size, e]⟩ | n+1 => have h0 := by rw [e]; apply Nat.succ_pos have hn := by rw [e]; apply Nat.lt_succ_self if hn0 : 0 < n then let a := self.1.swap ⟨0, h0⟩ ⟨n, hn⟩ |>.pop ⟨⟨heapifyDown lt a ⟨0, sorry⟩⟩, by simp [size]⟩ else ⟨⟨self.1.pop⟩, by simp [size]⟩ /-- `O(log n)`. Remove the maximum element from a `BinaryHeap`. Call `max` first to actually retrieve the maximum element. -/ def popMax {lt} (self : BinaryHeap α lt) : BinaryHeap α lt := self.popMaxAux @[simp] theorem size_popMax {lt} (self : BinaryHeap α lt) : self.popMax.size = self.size - 1 := self.popMaxAux.2 /-- `O(log n)`. Return and remove the maximum element from a `BinaryHeap`. -/ def extractMax {lt} (self : BinaryHeap α lt) : Option α × BinaryHeap α lt := (self.max, self.popMax) theorem size_pos_of_max {lt} {self : BinaryHeap α lt} (e : self.max = some x) : 0 < self.size := Decidable.of_not_not fun h: ¬ 0 < self.1.size => by simp [BinaryHeap.max, Array.get?, h] at e /-- `O(log n)`. Equivalent to `extractMax (self.insert x)`, except that extraction cannot fail. -/ def insertExtractMax {lt} (self : BinaryHeap α lt) (x : α) : α × BinaryHeap α lt := match e: self.max with | none => (x, self) | some m => if lt x m then let a := self.1.set ⟨0, size_pos_of_max e⟩ x (m, ⟨heapifyDown lt a ⟨0, by simp; exact size_pos_of_max e⟩⟩) else (x, self) /-- `O(log n)`. Equivalent to `(self.max, self.popMax.insert x)`. -/ def replaceMax {lt} (self : BinaryHeap α lt) (x : α) : Option α × BinaryHeap α lt := match e: self.max with | none => (none, ⟨self.1.push x⟩) | some m => let a := self.1.set ⟨0, size_pos_of_max e⟩ x (some m, ⟨heapifyDown lt a ⟨0, by simp; exact size_pos_of_max e⟩⟩) /-- `O(log n)`. Replace the value at index `i` by `x`. Assumes that `x ≤ self.get i`. -/ def decreaseKey {lt} (self : BinaryHeap α lt) (i : Fin self.size) (x : α) : BinaryHeap α lt where arr := heapifyDown lt (self.1.set i x) ⟨i, by rw [self.1.size_set]; exact i.2⟩ /-- `O(log n)`. Replace the value at index `i` by `x`. Assumes that `self.get i ≤ x`. -/ def increaseKey {lt} (self : BinaryHeap α lt) (i : Fin self.size) (x : α) : BinaryHeap α lt where arr := heapifyUp lt (self.1.set i x) ⟨i, by rw [self.1.size_set]; exact i.2⟩ end BinaryHeap /-- `O(n)`. Convert an unsorted array to a `BinaryHeap`. -/ def Array.toBinaryHeap (lt : α → α → Bool) (a : Array α) : BinaryHeap α lt where arr := BinaryHeap.mkHeap lt a /-- `O(n log n)`. Sort an array using a `BinaryHeap`. -/ @[specialize] def Array.heapSort (a : Array α) (lt : α → α → Bool) : Array α := let gt y x := lt x y let rec loop (a : BinaryHeap α gt) (out : Array α) : Array α := match e:a.max with | none => out | some x => have : a.popMax.size < a.size := by simp; exact Nat.sub_lt (BinaryHeap.size_pos_of_max e) Nat.zero_lt_one loop a.popMax (out.push x) loop (a.toBinaryHeap gt) #[] termination_by _ => a.size decreasing_by assumption attribute [simp] Array.heapSort.loop #check Array.heapSort.loop._eq_1 attribute [simp] BinaryHeap.heapifyDown
22587435d56b43d5012fdeaae42057867c1939c6
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/shapes/biproducts.lean
91e712e77d37831caaa89c2dc974f46bc769f4aa
[ "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
69,327
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Jakob von Raumer -/ import algebra.group.ext import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.binary_products import category_theory.preadditive import category_theory.limits.shapes.kernels /-! # Biproducts and binary biproducts We introduce the notion of (finite) biproducts and binary biproducts. These are slightly unusual relative to the other shapes in the library, as they are simultaneously limits and colimits. (Zero objects are similar; they are "biterminal".) We treat first the case of a general category with zero morphisms, and subsequently the case of a preadditive category. In a category with zero morphisms, we model the (binary) biproduct of `P Q : C` using a `binary_bicone`, which has a cone point `X`, and morphisms `fst : X ⟶ P`, `snd : X ⟶ Q`, `inl : P ⟶ X` and `inr : X ⟶ Q`, such that `inl ≫ fst = 𝟙 P`, `inl ≫ snd = 0`, `inr ≫ fst = 0`, and `inr ≫ snd = 𝟙 Q`. Such a `binary_bicone` is a biproduct if the cone is a limit cone, and the cocone is a colimit cocone. In a preadditive category, * any `binary_biproduct` satisfies `total : fst ≫ inl + snd ≫ inr = 𝟙 X` * any `binary_product` is a `binary_biproduct` * any `binary_coproduct` is a `binary_biproduct` For biproducts indexed by a `fintype J`, a `bicone` again consists of a cone point `X` and morphisms `π j : X ⟶ F j` and `ι j : F j ⟶ X` for each `j`, such that `ι j ≫ π j'` is the identity when `j = j'` and zero otherwise. In a preadditive category, * any `biproduct` satisfies `total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)` * any `product` is a `biproduct` * any `coproduct` is a `biproduct` ## Notation As `⊕` is already taken for the sum of types, we introduce the notation `X ⊞ Y` for a binary biproduct. We introduce `⨁ f` for the indexed biproduct. -/ noncomputable theory universes v u open category_theory open category_theory.functor namespace category_theory namespace limits variables {J : Type v} [decidable_eq J] variables {C : Type u} [category.{v} C] [has_zero_morphisms C] /-- A `c : bicone F` is: * an object `c.X` and * morphisms `π j : X ⟶ F j` and `ι j : F j ⟶ X` for each `j`, * such that `ι j ≫ π j'` is the identity when `j = j'` and zero otherwise. -/ @[nolint has_inhabited_instance] structure bicone (F : J → C) := (X : C) (π : Π j, X ⟶ F j) (ι : Π j, F j ⟶ X) (ι_π : ∀ j j', ι j ≫ π j' = if h : j = j' then eq_to_hom (congr_arg F h) else 0) @[simp, reassoc] lemma bicone_ι_π_self {F : J → C} (B : bicone F) (j : J) : B.ι j ≫ B.π j = 𝟙 (F j) := by simpa using B.ι_π j j @[simp, reassoc] lemma bicone_ι_π_ne {F : J → C} (B : bicone F) {j j' : J} (h : j ≠ j') : B.ι j ≫ B.π j' = 0 := by simpa [h] using B.ι_π j j' variables {F : J → C} namespace bicone /-- Extract the cone from a bicone. -/ @[simps] def to_cone (B : bicone F) : cone (discrete.functor F) := { X := B.X, π := { app := λ j, B.π j }, } /-- Extract the cocone from a bicone. -/ @[simps] def to_cocone (B : bicone F) : cocone (discrete.functor F) := { X := B.X, ι := { app := λ j, B.ι j }, } /-- We can turn any limit cone over a discrete collection of objects into a bicone. -/ @[simps] def of_limit_cone {f : J → C} {t : cone (discrete.functor f)} (ht : is_limit t) : bicone f := { X := t.X, π := t.π.app, ι := λ j, ht.lift (fan.mk _ (λ j', if h : j = j' then eq_to_hom (congr_arg f h) else 0)), ι_π := λ j j', by simp } lemma ι_of_is_limit {f : J → C} {t : bicone f} (ht : is_limit t.to_cone) (j : J) : t.ι j = ht.lift (fan.mk _ (λ j', if h : j = j' then eq_to_hom (congr_arg f h) else 0)) := ht.hom_ext (λ j', by { rw ht.fac, simp [t.ι_π] }) /-- We can turn any colimit cocone over a discrete collection of objects into a bicone. -/ @[simps] def of_colimit_cocone {f : J → C} {t : cocone (discrete.functor f)} (ht : is_colimit t) : bicone f := { X := t.X, π := λ j, ht.desc (cofan.mk _ (λ j', if h : j' = j then eq_to_hom (congr_arg f h) else 0)), ι := t.ι.app, ι_π := λ j j', by simp } lemma π_of_is_colimit {f : J → C} {t : bicone f} (ht : is_colimit t.to_cocone) (j : J) : t.π j = ht.desc (cofan.mk _ (λ j', if h : j' = j then eq_to_hom (congr_arg f h) else 0)) := ht.hom_ext (λ j', by { rw ht.fac, simp [t.ι_π] }) /-- Structure witnessing that a bicone is both a limit cone and a colimit cocone. -/ @[nolint has_inhabited_instance] structure is_bilimit {F : J → C} (B : bicone F) := (is_limit : is_limit B.to_cone) (is_colimit : is_colimit B.to_cocone) end bicone /-- A bicone over `F : J → C`, which is both a limit cone and a colimit cocone. -/ @[nolint has_inhabited_instance] structure limit_bicone (F : J → C) := (bicone : bicone F) (is_bilimit : bicone.is_bilimit) /-- `has_biproduct F` expresses the mere existence of a bicone which is simultaneously a limit and a colimit of the diagram `F`. -/ class has_biproduct (F : J → C) : Prop := mk' :: (exists_biproduct : nonempty (limit_bicone F)) lemma has_biproduct.mk {F : J → C} (d : limit_bicone F) : has_biproduct F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `biproduct_data F` from `has_biproduct F`. -/ def get_biproduct_data (F : J → C) [has_biproduct F] : limit_bicone F := classical.choice has_biproduct.exists_biproduct /-- A bicone for `F` which is both a limit cone and a colimit cocone. -/ def biproduct.bicone (F : J → C) [has_biproduct F] : bicone F := (get_biproduct_data F).bicone /-- `biproduct.bicone F` is a bilimit bicone. -/ def biproduct.is_bilimit (F : J → C) [has_biproduct F] : (biproduct.bicone F).is_bilimit := (get_biproduct_data F).is_bilimit /-- `biproduct.bicone F` is a limit cone. -/ def biproduct.is_limit (F : J → C) [has_biproduct F] : is_limit (biproduct.bicone F).to_cone := (get_biproduct_data F).is_bilimit.is_limit /-- `biproduct.bicone F` is a colimit cocone. -/ def biproduct.is_colimit (F : J → C) [has_biproduct F] : is_colimit (biproduct.bicone F).to_cocone := (get_biproduct_data F).is_bilimit.is_colimit @[priority 100] instance has_product_of_has_biproduct [has_biproduct F] : has_limit (discrete.functor F) := has_limit.mk { cone := (biproduct.bicone F).to_cone, is_limit := biproduct.is_limit F, } @[priority 100] instance has_coproduct_of_has_biproduct [has_biproduct F] : has_colimit (discrete.functor F) := has_colimit.mk { cocone := (biproduct.bicone F).to_cocone, is_colimit := biproduct.is_colimit F, } variables (J C) /-- `C` has biproducts of shape `J` if we have a limit and a colimit, with the same cone points, of every function `F : J → C`. -/ class has_biproducts_of_shape : Prop := (has_biproduct : Π F : J → C, has_biproduct F) attribute [instance, priority 100] has_biproducts_of_shape.has_biproduct /-- `has_finite_biproducts C` represents a choice of biproduct for every family of objects in `C` indexed by a finite type with decidable equality. -/ class has_finite_biproducts : Prop := (has_biproducts_of_shape : Π (J : Type v) [decidable_eq J] [fintype J], has_biproducts_of_shape J C) attribute [instance, priority 100] has_finite_biproducts.has_biproducts_of_shape @[priority 100] instance has_finite_products_of_has_finite_biproducts [has_finite_biproducts C] : has_finite_products C := { out := λ J _ _, ⟨λ F, by exactI has_limit_of_iso discrete.nat_iso_functor.symm⟩ } @[priority 100] instance has_finite_coproducts_of_has_finite_biproducts [has_finite_biproducts C] : has_finite_coproducts C := { out := λ J _ _, ⟨λ F, by exactI has_colimit_of_iso discrete.nat_iso_functor⟩ } variables {J C} /-- The isomorphism between the specified limit and the specified colimit for a functor with a bilimit. -/ def biproduct_iso (F : J → C) [has_biproduct F] : limits.pi_obj F ≅ limits.sigma_obj F := (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (biproduct.is_limit F)).trans $ is_colimit.cocone_point_unique_up_to_iso (biproduct.is_colimit F) (colimit.is_colimit _) end limits namespace limits variables {J : Type v} [decidable_eq J] variables {C : Type u} [category.{v} C] [has_zero_morphisms C] /-- `biproduct f` computes the biproduct of a family of elements `f`. (It is defined as an abbreviation for `limit (discrete.functor f)`, so for most facts about `biproduct f`, you will just use general facts about limits and colimits.) -/ abbreviation biproduct (f : J → C) [has_biproduct f] : C := (biproduct.bicone f).X notation `⨁ ` f:20 := biproduct f /-- The projection onto a summand of a biproduct. -/ abbreviation biproduct.π (f : J → C) [has_biproduct f] (b : J) : ⨁ f ⟶ f b := (biproduct.bicone f).π b @[simp] lemma biproduct.bicone_π (f : J → C) [has_biproduct f] (b : J) : (biproduct.bicone f).π b = biproduct.π f b := rfl /-- The inclusion into a summand of a biproduct. -/ abbreviation biproduct.ι (f : J → C) [has_biproduct f] (b : J) : f b ⟶ ⨁ f := (biproduct.bicone f).ι b @[simp] lemma biproduct.bicone_ι (f : J → C) [has_biproduct f] (b : J) : (biproduct.bicone f).ι b = biproduct.ι f b := rfl @[reassoc] lemma biproduct.ι_π (f : J → C) [has_biproduct f] (j j' : J) : biproduct.ι f j ≫ biproduct.π f j' = if h : j = j' then eq_to_hom (congr_arg f h) else 0 := (biproduct.bicone f).ι_π j j' @[simp,reassoc] lemma biproduct.ι_π_self (f : J → C) [has_biproduct f] (j : J) : biproduct.ι f j ≫ biproduct.π f j = 𝟙 _ := by simp [biproduct.ι_π] @[simp,reassoc] lemma biproduct.ι_π_ne (f : J → C) [has_biproduct f] {j j' : J} (h : j ≠ j') : biproduct.ι f j ≫ biproduct.π f j' = 0 := by simp [biproduct.ι_π, h] /-- Given a collection of maps into the summands, we obtain a map into the biproduct. -/ abbreviation biproduct.lift {f : J → C} [has_biproduct f] {P : C} (p : Π b, P ⟶ f b) : P ⟶ ⨁ f := (biproduct.is_limit f).lift (fan.mk P p) /-- Given a collection of maps out of the summands, we obtain a map out of the biproduct. -/ abbreviation biproduct.desc {f : J → C} [has_biproduct f] {P : C} (p : Π b, f b ⟶ P) : ⨁ f ⟶ P := (biproduct.is_colimit f).desc (cofan.mk P p) @[simp, reassoc] lemma biproduct.lift_π {f : J → C} [has_biproduct f] {P : C} (p : Π b, P ⟶ f b) (j : J) : biproduct.lift p ≫ biproduct.π f j = p j := (biproduct.is_limit f).fac _ _ @[simp, reassoc] lemma biproduct.ι_desc {f : J → C} [has_biproduct f] {P : C} (p : Π b, f b ⟶ P) (j : J) : biproduct.ι f j ≫ biproduct.desc p = p j := (biproduct.is_colimit f).fac _ _ /-- Given a collection of maps between corresponding summands of a pair of biproducts indexed by the same type, we obtain a map between the biproducts. -/ abbreviation biproduct.map {f g : J → C} [has_biproduct f] [has_biproduct g] (p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g := is_limit.map (biproduct.bicone f).to_cone (biproduct.is_limit g) (discrete.nat_trans p) /-- An alternative to `biproduct.map` constructed via colimits. This construction only exists in order to show it is equal to `biproduct.map`. -/ abbreviation biproduct.map' {f g : J → C} [has_biproduct f] [has_biproduct g] (p : Π b, f b ⟶ g b) : ⨁ f ⟶ ⨁ g := is_colimit.map (biproduct.is_colimit f) (biproduct.bicone g).to_cocone (discrete.nat_trans p) @[ext] lemma biproduct.hom_ext {f : J → C} [has_biproduct f] {Z : C} (g h : Z ⟶ ⨁ f) (w : ∀ j, g ≫ biproduct.π f j = h ≫ biproduct.π f j) : g = h := (biproduct.is_limit f).hom_ext w @[ext] lemma biproduct.hom_ext' {f : J → C} [has_biproduct f] {Z : C} (g h : ⨁ f ⟶ Z) (w : ∀ j, biproduct.ι f j ≫ g = biproduct.ι f j ≫ h) : g = h := (biproduct.is_colimit f).hom_ext w lemma biproduct.map_eq_map' {f g : J → C} [has_biproduct f] [has_biproduct g] (p : Π b, f b ⟶ g b) : biproduct.map p = biproduct.map' p := begin ext j j', simp only [discrete.nat_trans_app, limits.is_colimit.ι_map, limits.is_limit.map_π, category.assoc, ←bicone.to_cone_π_app, ←biproduct.bicone_π, ←bicone.to_cocone_ι_app, ←biproduct.bicone_ι], simp only [biproduct.bicone_ι, biproduct.bicone_π, bicone.to_cocone_ι_app, bicone.to_cone_π_app], rw [biproduct.ι_π_assoc, biproduct.ι_π], split_ifs, { subst h, rw [eq_to_hom_refl, category.id_comp], erw category.comp_id, }, { simp, }, end @[simp, reassoc] lemma biproduct.map_π {f g : J → C} [has_biproduct f] [has_biproduct g] (p : Π j, f j ⟶ g j) (j : J) : biproduct.map p ≫ biproduct.π g j = biproduct.π f j ≫ p j := limits.is_limit.map_π _ _ _ _ @[simp, reassoc] lemma biproduct.ι_map {f g : J → C} [has_biproduct f] [has_biproduct g] (p : Π j, f j ⟶ g j) (j : J) : biproduct.ι f j ≫ biproduct.map p = p j ≫ biproduct.ι g j := begin rw biproduct.map_eq_map', convert limits.is_colimit.ι_map _ _ _ _; refl end @[simp, reassoc] lemma biproduct.map_desc {f g : J → C} [has_biproduct f] [has_biproduct g] (p : Π j, f j ⟶ g j) {P : C} (k : Π j, g j ⟶ P) : biproduct.map p ≫ biproduct.desc k = biproduct.desc (λ j, p j ≫ k j) := by { ext, simp, } @[simp, reassoc] lemma biproduct.lift_map {f g : J → C} [has_biproduct f] [has_biproduct g] {P : C} (k : Π j, P ⟶ f j) (p : Π j, f j ⟶ g j) : biproduct.lift k ≫ biproduct.map p = biproduct.lift (λ j, k j ≫ p j) := by { ext, simp, } /-- Given a collection of isomorphisms between corresponding summands of a pair of biproducts indexed by the same type, we obtain an isomorphism between the biproducts. -/ @[simps] def biproduct.map_iso {f g : J → C} [has_biproduct f] [has_biproduct g] (p : Π b, f b ≅ g b) : ⨁ f ≅ ⨁ g := { hom := biproduct.map (λ b, (p b).hom), inv := biproduct.map (λ b, (p b).inv), } section π_kernel section variables (f : J → C) [has_biproduct f] variables (p : J → Prop) [has_biproduct (subtype.restrict p f)] /-- The canonical morphism from the biproduct over a restricted index type to the biproduct of the full index type. -/ def biproduct.from_subtype : ⨁ subtype.restrict p f ⟶ ⨁ f := biproduct.desc $ λ j, biproduct.ι _ _ /-- The canonical morophism from a biproduct to the biproduct over a restriction of its index type. -/ def biproduct.to_subtype : ⨁ f ⟶ ⨁ subtype.restrict p f := biproduct.lift $ λ j, biproduct.π _ _ @[simp, reassoc] lemma biproduct.from_subtype_π (j : J) [decidable (p j)] : biproduct.from_subtype f p ≫ biproduct.π f j = if h : p j then biproduct.π (subtype.restrict p f) ⟨j, h⟩ else 0 := begin ext i, rw [biproduct.from_subtype, biproduct.ι_desc_assoc, biproduct.ι_π], by_cases h : p j, { rw [dif_pos h, biproduct.ι_π], split_ifs with h₁ h₂ h₂, exacts [rfl, false.elim (h₂ (subtype.ext h₁)), false.elim (h₁ (congr_arg subtype.val h₂)), rfl] }, { rw [dif_neg h, dif_neg (show (i : J) ≠ j, from λ h₂, h (h₂ ▸ i.2)), comp_zero] } end lemma biproduct.from_subtype_eq_lift [decidable_pred p] : biproduct.from_subtype f p = biproduct.lift (λ j, if h : p j then biproduct.π (subtype.restrict p f) ⟨j, h⟩ else 0) := biproduct.hom_ext _ _ (by simp) @[simp, reassoc] lemma biproduct.from_subtype_π_subtype (j : subtype p) : biproduct.from_subtype f p ≫ biproduct.π f j = biproduct.π (subtype.restrict p f) j := begin ext i, rw [biproduct.from_subtype, biproduct.ι_desc_assoc, biproduct.ι_π, biproduct.ι_π], split_ifs with h₁ h₂ h₂, exacts [rfl, false.elim (h₂ (subtype.ext h₁)), false.elim (h₁ (congr_arg subtype.val h₂)), rfl] end @[simp, reassoc] lemma biproduct.to_subtype_π (j : subtype p) : biproduct.to_subtype f p ≫ biproduct.π (subtype.restrict p f) j = biproduct.π f j := biproduct.lift_π _ _ @[simp, reassoc] lemma biproduct.ι_to_subtype (j : J) [decidable (p j)] : biproduct.ι f j ≫ biproduct.to_subtype f p = if h : p j then biproduct.ι (subtype.restrict p f) ⟨j, h⟩ else 0 := begin ext i, rw [biproduct.to_subtype, category.assoc, biproduct.lift_π, biproduct.ι_π], by_cases h : p j, { rw [dif_pos h, biproduct.ι_π], split_ifs with h₁ h₂ h₂, exacts [rfl, false.elim (h₂ (subtype.ext h₁)), false.elim (h₁ (congr_arg subtype.val h₂)), rfl] }, { rw [dif_neg h, dif_neg (show j ≠ i, from λ h₂, h (h₂.symm ▸ i.2)), zero_comp] } end lemma biproduct.to_subtype_eq_desc [decidable_pred p] : biproduct.to_subtype f p = biproduct.desc (λ j, if h : p j then biproduct.ι (subtype.restrict p f) ⟨j, h⟩ else 0) := biproduct.hom_ext' _ _ (by simp) @[simp, reassoc] lemma biproduct.ι_to_subtype_subtype (j : subtype p) : biproduct.ι f j ≫ biproduct.to_subtype f p = biproduct.ι (subtype.restrict p f) j := begin ext i, rw [biproduct.to_subtype, category.assoc, biproduct.lift_π, biproduct.ι_π, biproduct.ι_π], split_ifs with h₁ h₂ h₂, exacts [rfl, false.elim (h₂ (subtype.ext h₁)), false.elim (h₁ (congr_arg subtype.val h₂)), rfl] end @[simp, reassoc] lemma biproduct.ι_from_subtype (j : subtype p) : biproduct.ι (subtype.restrict p f) j ≫ biproduct.from_subtype f p = biproduct.ι f j := biproduct.ι_desc _ _ @[simp, reassoc] lemma biproduct.from_subtype_to_subtype : biproduct.from_subtype f p ≫ biproduct.to_subtype f p = 𝟙 (⨁ subtype.restrict p f) := begin refine biproduct.hom_ext _ _ (λ j, _), rw [category.assoc, biproduct.to_subtype_π, biproduct.from_subtype_π_subtype, category.id_comp] end @[simp, reassoc] lemma biproduct.to_subtype_from_subtype [decidable_pred p] : biproduct.to_subtype f p ≫ biproduct.from_subtype f p = biproduct.map (λ j, if p j then 𝟙 (f j) else 0) := begin ext1 i, by_cases h : p i, { simp [h], congr }, { simp [h] } end end variables (f : J → C) (i : J) [has_biproduct f] [has_biproduct (subtype.restrict (λ j, i ≠ j) f)] /-- The kernel of `biproduct.π f i` is the inclusion from the biproduct which omits `i` from the index set `J` into the biproduct over `J`. -/ def biproduct.is_limit_from_subtype : is_limit (kernel_fork.of_ι (biproduct.from_subtype f (λ j, i ≠ j)) (by simp) : kernel_fork (biproduct.π f i)) := fork.is_limit.mk' _ $ λ s, ⟨s.ι ≫ biproduct.to_subtype _ _, begin ext j, rw [kernel_fork.ι_of_ι, category.assoc, category.assoc, biproduct.to_subtype_from_subtype_assoc, biproduct.map_π], rcases em (i = j) with (rfl|h), { rw [if_neg (not_not.2 rfl), comp_zero, comp_zero, kernel_fork.condition] }, { rw [if_pos h, category.comp_id] } end, begin intros m hm, rw [← hm, kernel_fork.ι_of_ι, category.assoc, biproduct.from_subtype_to_subtype], exact (category.comp_id _).symm end⟩ /-- The cokernel of `biproduct.ι f i` is the projection from the biproduct over the index set `J` onto the biproduct omitting `i`. -/ def biproduct.is_colimit_to_subtype : is_colimit (cokernel_cofork.of_π (biproduct.to_subtype f (λ j, i ≠ j)) (by simp) : cokernel_cofork (biproduct.ι f i)) := cofork.is_colimit.mk' _ $ λ s, ⟨biproduct.from_subtype _ _ ≫ s.π, begin ext j, rw [cokernel_cofork.π_of_π, biproduct.to_subtype_from_subtype_assoc, biproduct.ι_map_assoc], rcases em (i = j) with (rfl|h), { rw [if_neg (not_not.2 rfl), zero_comp, cokernel_cofork.condition] }, { rw [if_pos h, category.id_comp] } end, begin intros m hm, rw [← hm, cokernel_cofork.π_of_π, ← category.assoc, biproduct.from_subtype_to_subtype], exact (category.id_comp _).symm end⟩ end π_kernel section variables [fintype J] {K : Type v} [fintype K] [decidable_eq K] {f : J → C} {g : K → C} [has_finite_biproducts C] /-- Convert a (dependently typed) matrix to a morphism of biproducts. -/ def biproduct.matrix (m : Π j k, f j ⟶ g k) : ⨁ f ⟶ ⨁ g := biproduct.desc (λ j, biproduct.lift (λ k, m j k)) @[simp, reassoc] lemma biproduct.matrix_π (m : Π j k, f j ⟶ g k) (k : K) : biproduct.matrix m ≫ biproduct.π g k = biproduct.desc (λ j, m j k) := by { ext, simp [biproduct.matrix], } @[simp, reassoc] lemma biproduct.ι_matrix (m : Π j k, f j ⟶ g k) (j : J) : biproduct.ι f j ≫ biproduct.matrix m = biproduct.lift (λ k, m j k) := by { ext, simp [biproduct.matrix], } /-- Extract the matrix components from a morphism of biproducts. -/ def biproduct.components (m : ⨁ f ⟶ ⨁ g) (j : J) (k : K) : f j ⟶ g k := biproduct.ι f j ≫ m ≫ biproduct.π g k @[simp] lemma biproduct.matrix_components (m : Π j k, f j ⟶ g k) (j : J) (k : K) : biproduct.components (biproduct.matrix m) j k = m j k := by simp [biproduct.components] @[simp] lemma biproduct.components_matrix (m : ⨁ f ⟶ ⨁ g) : biproduct.matrix (λ j k, biproduct.components m j k) = m := by { ext, simp [biproduct.components], } /-- Morphisms between direct sums are matrices. -/ @[simps] def biproduct.matrix_equiv : (⨁ f ⟶ ⨁ g) ≃ (Π j k, f j ⟶ g k) := { to_fun := biproduct.components, inv_fun := biproduct.matrix, left_inv := biproduct.components_matrix, right_inv := λ m, by { ext, apply biproduct.matrix_components } } end instance biproduct.ι_mono (f : J → C) [has_biproduct f] (b : J) : split_mono (biproduct.ι f b) := { retraction := biproduct.desc $ λ b', if h : b' = b then eq_to_hom (congr_arg f h) else biproduct.ι f b' ≫ biproduct.π f b } instance biproduct.π_epi (f : J → C) [has_biproduct f] (b : J) : split_epi (biproduct.π f b) := { section_ := biproduct.lift $ λ b', if h : b = b' then eq_to_hom (congr_arg f h) else biproduct.ι f b ≫ biproduct.π f b' } /-- Auxiliary lemma for `biproduct.unique_up_to_iso`. -/ lemma biproduct.cone_point_unique_up_to_iso_hom (f : J → C) [has_biproduct f] {b : bicone f} (hb : b.is_bilimit) : (hb.is_limit.cone_point_unique_up_to_iso (biproduct.is_limit _)).hom = biproduct.lift b.π := rfl /-- Auxiliary lemma for `biproduct.unique_up_to_iso`. -/ lemma biproduct.cone_point_unique_up_to_iso_inv (f : J → C) [has_biproduct f] {b : bicone f} (hb : b.is_bilimit) : (hb.is_limit.cone_point_unique_up_to_iso (biproduct.is_limit _)).inv = biproduct.desc b.ι := begin refine biproduct.hom_ext' _ _ (λ j, hb.is_limit.hom_ext (λ j', _)), rw [category.assoc, is_limit.cone_point_unique_up_to_iso_inv_comp, bicone.to_cone_π_app, biproduct.bicone_π, biproduct.ι_desc, biproduct.ι_π, b.to_cone_π_app, b.ι_π] end /-- Biproducts are unique up to isomorphism. This already follows because bilimits are limits, but in the case of biproducts we can give an isomorphism with particularly nice definitional properties, namely that `biproduct.lift b.π` and `biproduct.desc b.ι` are inverses of each other. -/ @[simps] def biproduct.unique_up_to_iso (f : J → C) [has_biproduct f] {b : bicone f} (hb : b.is_bilimit) : b.X ≅ ⨁ f := { hom := biproduct.lift b.π, inv := biproduct.desc b.ι, hom_inv_id' := by rw [← biproduct.cone_point_unique_up_to_iso_hom f hb, ← biproduct.cone_point_unique_up_to_iso_inv f hb, iso.hom_inv_id], inv_hom_id' := by rw [← biproduct.cone_point_unique_up_to_iso_hom f hb, ← biproduct.cone_point_unique_up_to_iso_inv f hb, iso.inv_hom_id] } section variables (C) /-- A category with finite biproducts has a zero object. -/ @[priority 100] -- see Note [lower instance priority] instance has_zero_object_of_has_finite_biproducts [has_finite_biproducts C] : has_zero_object C := by { refine ⟨⟨biproduct pempty.elim, λ X, ⟨⟨⟨0⟩, _⟩⟩, λ X, ⟨⟨⟨0⟩, _⟩⟩⟩⟩, tidy, } end /-- A binary bicone for a pair of objects `P Q : C` consists of the cone point `X`, maps from `X` to both `P` and `Q`, and maps from both `P` and `Q` to `X`, so that `inl ≫ fst = 𝟙 P`, `inl ≫ snd = 0`, `inr ≫ fst = 0`, and `inr ≫ snd = 𝟙 Q` -/ @[nolint has_inhabited_instance] structure binary_bicone (P Q : C) := (X : C) (fst : X ⟶ P) (snd : X ⟶ Q) (inl : P ⟶ X) (inr : Q ⟶ X) (inl_fst' : inl ≫ fst = 𝟙 P . obviously) (inl_snd' : inl ≫ snd = 0 . obviously) (inr_fst' : inr ≫ fst = 0 . obviously) (inr_snd' : inr ≫ snd = 𝟙 Q . obviously) restate_axiom binary_bicone.inl_fst' restate_axiom binary_bicone.inl_snd' restate_axiom binary_bicone.inr_fst' restate_axiom binary_bicone.inr_snd' attribute [simp, reassoc] binary_bicone.inl_fst binary_bicone.inl_snd binary_bicone.inr_fst binary_bicone.inr_snd namespace binary_bicone variables {P Q : C} /-- Extract the cone from a binary bicone. -/ def to_cone (c : binary_bicone P Q) : cone (pair P Q) := binary_fan.mk c.fst c.snd @[simp] lemma to_cone_X (c : binary_bicone P Q) : c.to_cone.X = c.X := rfl @[simp] lemma to_cone_π_app_left (c : binary_bicone P Q) : c.to_cone.π.app (walking_pair.left) = c.fst := rfl @[simp] lemma to_cone_π_app_right (c : binary_bicone P Q) : c.to_cone.π.app (walking_pair.right) = c.snd := rfl @[simp] lemma binary_fan_fst_to_cone (c : binary_bicone P Q) : binary_fan.fst c.to_cone = c.fst := rfl @[simp] lemma binary_fan_snd_to_cone (c : binary_bicone P Q) : binary_fan.snd c.to_cone = c.snd := rfl /-- Extract the cocone from a binary bicone. -/ def to_cocone (c : binary_bicone P Q) : cocone (pair P Q) := binary_cofan.mk c.inl c.inr @[simp] lemma to_cocone_X (c : binary_bicone P Q) : c.to_cocone.X = c.X := rfl @[simp] lemma to_cocone_ι_app_left (c : binary_bicone P Q) : c.to_cocone.ι.app (walking_pair.left) = c.inl := rfl @[simp] lemma to_cocone_ι_app_right (c : binary_bicone P Q) : c.to_cocone.ι.app (walking_pair.right) = c.inr := rfl @[simp] lemma binary_cofan_inl_to_cocone (c : binary_bicone P Q) : binary_cofan.inl c.to_cocone = c.inl := rfl @[simp] lemma binary_cofan_inr_to_cocone (c : binary_bicone P Q) : binary_cofan.inr c.to_cocone = c.inr := rfl /-- Convert a `binary_bicone` into a `bicone` over a pair. -/ @[simps] def to_bicone {X Y : C} (b : binary_bicone X Y) : bicone (pair X Y).obj := { X := b.X, π := λ j, walking_pair.cases_on j b.fst b.snd, ι := λ j, walking_pair.cases_on j b.inl b.inr, ι_π := λ j j', by { cases j; cases j', tidy } } /-- A binary bicone is a limit cone if and only if the corresponding bicone is a limit cone. -/ def to_bicone_is_limit {X Y : C} (b : binary_bicone X Y) : is_limit (b.to_bicone.to_cone) ≃ is_limit (b.to_cone) := is_limit.equiv_iso_limit $ cones.ext (iso.refl _) (λ j, by { cases j, tidy }) /-- A binary bicone is a colimit cocone if and only if the corresponding bicone is a colimit cocone. -/ def to_bicone_is_colimit {X Y : C} (b : binary_bicone X Y) : is_colimit (b.to_bicone.to_cocone) ≃ is_colimit (b.to_cocone) := is_colimit.equiv_iso_colimit $ cocones.ext (iso.refl _) (λ j, by { cases j, tidy }) end binary_bicone namespace bicone /-- Convert a `bicone` over a function on `walking_pair` to a binary_bicone. -/ @[simps] def to_binary_bicone {X Y : C} (b : bicone (pair X Y).obj) : binary_bicone X Y := { X := b.X, fst := b.π walking_pair.left, snd := b.π walking_pair.right, inl := b.ι walking_pair.left, inr := b.ι walking_pair.right, inl_fst' := by { simp [bicone.ι_π], refl, }, inr_fst' := by simp [bicone.ι_π], inl_snd' := by simp [bicone.ι_π], inr_snd' := by { simp [bicone.ι_π], refl, }, } /-- A bicone over a pair is a limit cone if and only if the corresponding binary bicone is a limit cone. -/ def to_binary_bicone_is_limit {X Y : C} (b : bicone (pair X Y).obj) : is_limit (b.to_binary_bicone.to_cone) ≃ is_limit (b.to_cone) := is_limit.equiv_iso_limit $ cones.ext (iso.refl _) (λ j, by { cases j, tidy }) /-- A bicone over a pair is a colimit cocone if and only if the corresponding binary bicone is a colimit cocone. -/ def to_binary_bicone_is_colimit {X Y : C} (b : bicone (pair X Y).obj) : is_colimit (b.to_binary_bicone.to_cocone) ≃ is_colimit (b.to_cocone) := is_colimit.equiv_iso_colimit $ cocones.ext (iso.refl _) (λ j, by { cases j, tidy }) end bicone /-- Structure witnessing that a binary bicone is a limit cone and a limit cocone. -/ @[nolint has_inhabited_instance] structure binary_bicone.is_bilimit {P Q : C} (b : binary_bicone P Q) := (is_limit : is_limit b.to_cone) (is_colimit : is_colimit b.to_cocone) /-- A binary bicone is a bilimit bicone if and only if the corresponding bicone is a bilimit. -/ def binary_bicone.to_bicone_is_bilimit {X Y : C} (b : binary_bicone X Y) : b.to_bicone.is_bilimit ≃ b.is_bilimit := { to_fun := λ h, ⟨b.to_bicone_is_limit h.is_limit, b.to_bicone_is_colimit h.is_colimit⟩, inv_fun := λ h, ⟨b.to_bicone_is_limit.symm h.is_limit, b.to_bicone_is_colimit.symm h.is_colimit⟩, left_inv := λ ⟨h, h'⟩, by { dsimp only, simp }, right_inv := λ ⟨h, h'⟩, by { dsimp only, simp } } /-- A bicone over a pair is a bilimit bicone if and only if the corresponding binary bicone is a bilimit. -/ def bicone.to_binary_bicone_is_bilimit {X Y : C} (b : bicone (pair X Y).obj) : b.to_binary_bicone.is_bilimit ≃ b.is_bilimit := { to_fun := λ h, ⟨b.to_binary_bicone_is_limit h.is_limit, b.to_binary_bicone_is_colimit h.is_colimit⟩, inv_fun := λ h, ⟨b.to_binary_bicone_is_limit.symm h.is_limit, b.to_binary_bicone_is_colimit.symm h.is_colimit⟩, left_inv := λ ⟨h, h'⟩, by { dsimp only, simp }, right_inv := λ ⟨h, h'⟩, by { dsimp only, simp } } /-- A bicone over `P Q : C`, which is both a limit cone and a colimit cocone. -/ @[nolint has_inhabited_instance] structure binary_biproduct_data (P Q : C) := (bicone : binary_bicone P Q) (is_bilimit : bicone.is_bilimit) /-- `has_binary_biproduct P Q` expresses the mere existence of a bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`. -/ class has_binary_biproduct (P Q : C) : Prop := mk' :: (exists_binary_biproduct : nonempty (binary_biproduct_data P Q)) lemma has_binary_biproduct.mk {P Q : C} (d : binary_biproduct_data P Q) : has_binary_biproduct P Q := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `binary_biproduct_data F` from `has_binary_biproduct F`. -/ def get_binary_biproduct_data (P Q : C) [has_binary_biproduct P Q] : binary_biproduct_data P Q := classical.choice has_binary_biproduct.exists_binary_biproduct /-- A bicone for `P Q ` which is both a limit cone and a colimit cocone. -/ def binary_biproduct.bicone (P Q : C) [has_binary_biproduct P Q] : binary_bicone P Q := (get_binary_biproduct_data P Q).bicone /-- `binary_biproduct.bicone P Q` is a limit bicone. -/ def binary_biproduct.is_bilimit (P Q : C) [has_binary_biproduct P Q] : (binary_biproduct.bicone P Q).is_bilimit := (get_binary_biproduct_data P Q).is_bilimit /-- `binary_biproduct.bicone P Q` is a limit cone. -/ def binary_biproduct.is_limit (P Q : C) [has_binary_biproduct P Q] : is_limit (binary_biproduct.bicone P Q).to_cone := (get_binary_biproduct_data P Q).is_bilimit.is_limit /-- `binary_biproduct.bicone P Q` is a colimit cocone. -/ def binary_biproduct.is_colimit (P Q : C) [has_binary_biproduct P Q] : is_colimit (binary_biproduct.bicone P Q).to_cocone := (get_binary_biproduct_data P Q).is_bilimit.is_colimit section variable (C) /-- `has_binary_biproducts C` represents the existence of a bicone which is simultaneously a limit and a colimit of the diagram `pair P Q`, for every `P Q : C`. -/ class has_binary_biproducts : Prop := (has_binary_biproduct : Π (P Q : C), has_binary_biproduct P Q) attribute [instance, priority 100] has_binary_biproducts.has_binary_biproduct /-- A category with finite biproducts has binary biproducts. This is not an instance as typically in concrete categories there will be an alternative construction with nicer definitional properties. -/ lemma has_binary_biproducts_of_finite_biproducts [has_finite_biproducts C] : has_binary_biproducts C := { has_binary_biproduct := λ P Q, has_binary_biproduct.mk { bicone := (biproduct.bicone (pair P Q).obj).to_binary_bicone, is_bilimit := (bicone.to_binary_bicone_is_bilimit _).symm (biproduct.is_bilimit _) } } end variables {P Q : C} instance has_binary_biproduct.has_limit_pair [has_binary_biproduct P Q] : has_limit (pair P Q) := has_limit.mk ⟨_, binary_biproduct.is_limit P Q⟩ instance has_binary_biproduct.has_colimit_pair [has_binary_biproduct P Q] : has_colimit (pair P Q) := has_colimit.mk ⟨_, binary_biproduct.is_colimit P Q⟩ @[priority 100] instance has_binary_products_of_has_binary_biproducts [has_binary_biproducts C] : has_binary_products C := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } @[priority 100] instance has_binary_coproducts_of_has_binary_biproducts [has_binary_biproducts C] : has_binary_coproducts C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } /-- The isomorphism between the specified binary product and the specified binary coproduct for a pair for a binary biproduct. -/ def biprod_iso (X Y : C) [has_binary_biproduct X Y] : limits.prod X Y ≅ limits.coprod X Y := (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (binary_biproduct.is_limit X Y)).trans $ is_colimit.cocone_point_unique_up_to_iso (binary_biproduct.is_colimit X Y) (colimit.is_colimit _) /-- An arbitrary choice of biproduct of a pair of objects. -/ abbreviation biprod (X Y : C) [has_binary_biproduct X Y] := (binary_biproduct.bicone X Y).X notation X ` ⊞ `:20 Y:20 := biprod X Y /-- The projection onto the first summand of a binary biproduct. -/ abbreviation biprod.fst {X Y : C} [has_binary_biproduct X Y] : X ⊞ Y ⟶ X := (binary_biproduct.bicone X Y).fst /-- The projection onto the second summand of a binary biproduct. -/ abbreviation biprod.snd {X Y : C} [has_binary_biproduct X Y] : X ⊞ Y ⟶ Y := (binary_biproduct.bicone X Y).snd /-- The inclusion into the first summand of a binary biproduct. -/ abbreviation biprod.inl {X Y : C} [has_binary_biproduct X Y] : X ⟶ X ⊞ Y := (binary_biproduct.bicone X Y).inl /-- The inclusion into the second summand of a binary biproduct. -/ abbreviation biprod.inr {X Y : C} [has_binary_biproduct X Y] : Y ⟶ X ⊞ Y := (binary_biproduct.bicone X Y).inr section variables {X Y : C} [has_binary_biproduct X Y] @[simp] lemma binary_biproduct.bicone_fst : (binary_biproduct.bicone X Y).fst = biprod.fst := rfl @[simp] lemma binary_biproduct.bicone_snd : (binary_biproduct.bicone X Y).snd = biprod.snd := rfl @[simp] lemma binary_biproduct.bicone_inl : (binary_biproduct.bicone X Y).inl = biprod.inl := rfl @[simp] lemma binary_biproduct.bicone_inr : (binary_biproduct.bicone X Y).inr = biprod.inr := rfl end @[simp,reassoc] lemma biprod.inl_fst {X Y : C} [has_binary_biproduct X Y] : (biprod.inl : X ⟶ X ⊞ Y) ≫ (biprod.fst : X ⊞ Y ⟶ X) = 𝟙 X := (binary_biproduct.bicone X Y).inl_fst @[simp,reassoc] lemma biprod.inl_snd {X Y : C} [has_binary_biproduct X Y] : (biprod.inl : X ⟶ X ⊞ Y) ≫ (biprod.snd : X ⊞ Y ⟶ Y) = 0 := (binary_biproduct.bicone X Y).inl_snd @[simp,reassoc] lemma biprod.inr_fst {X Y : C} [has_binary_biproduct X Y] : (biprod.inr : Y ⟶ X ⊞ Y) ≫ (biprod.fst : X ⊞ Y ⟶ X) = 0 := (binary_biproduct.bicone X Y).inr_fst @[simp,reassoc] lemma biprod.inr_snd {X Y : C} [has_binary_biproduct X Y] : (biprod.inr : Y ⟶ X ⊞ Y) ≫ (biprod.snd : X ⊞ Y ⟶ Y) = 𝟙 Y := (binary_biproduct.bicone X Y).inr_snd /-- Given a pair of maps into the summands of a binary biproduct, we obtain a map into the binary biproduct. -/ abbreviation biprod.lift {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⊞ Y := (binary_biproduct.is_limit X Y).lift (binary_fan.mk f g) /-- Given a pair of maps out of the summands of a binary biproduct, we obtain a map out of the binary biproduct. -/ abbreviation biprod.desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : X ⊞ Y ⟶ W := (binary_biproduct.is_colimit X Y).desc (binary_cofan.mk f g) @[simp, reassoc] lemma biprod.lift_fst {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) : biprod.lift f g ≫ biprod.fst = f := (binary_biproduct.is_limit X Y).fac _ walking_pair.left @[simp, reassoc] lemma biprod.lift_snd {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) : biprod.lift f g ≫ biprod.snd = g := (binary_biproduct.is_limit X Y).fac _ walking_pair.right @[simp, reassoc] lemma biprod.inl_desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : biprod.inl ≫ biprod.desc f g = f := (binary_biproduct.is_colimit X Y).fac _ walking_pair.left @[simp, reassoc] lemma biprod.inr_desc {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) : biprod.inr ≫ biprod.desc f g = g := (binary_biproduct.is_colimit X Y).fac _ walking_pair.right instance biprod.mono_lift_of_mono_left {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (biprod.lift f g) := mono_of_mono_fac $ biprod.lift_fst _ _ instance biprod.mono_lift_of_mono_right {W X Y : C} [has_binary_biproduct X Y] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (biprod.lift f g) := mono_of_mono_fac $ biprod.lift_snd _ _ instance biprod.epi_desc_of_epi_left {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (biprod.desc f g) := epi_of_epi_fac $ biprod.inl_desc _ _ instance biprod.epi_desc_of_epi_right {W X Y : C} [has_binary_biproduct X Y] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (biprod.desc f g) := epi_of_epi_fac $ biprod.inr_desc _ _ /-- Given a pair of maps between the summands of a pair of binary biproducts, we obtain a map between the binary biproducts. -/ abbreviation biprod.map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z := is_limit.map (binary_biproduct.bicone W X).to_cone (binary_biproduct.is_limit Y Z) (@map_pair _ _ (pair W X) (pair Y Z) f g) /-- An alternative to `biprod.map` constructed via colimits. This construction only exists in order to show it is equal to `biprod.map`. -/ abbreviation biprod.map' {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : W ⊞ X ⟶ Y ⊞ Z := is_colimit.map (binary_biproduct.is_colimit W X) (binary_biproduct.bicone Y Z).to_cocone (@map_pair _ _ (pair W X) (pair Y Z) f g) @[ext] lemma biprod.hom_ext {X Y Z : C} [has_binary_biproduct X Y] (f g : Z ⟶ X ⊞ Y) (h₀ : f ≫ biprod.fst = g ≫ biprod.fst) (h₁ : f ≫ biprod.snd = g ≫ biprod.snd) : f = g := binary_fan.is_limit.hom_ext (binary_biproduct.is_limit X Y) h₀ h₁ @[ext] lemma biprod.hom_ext' {X Y Z : C} [has_binary_biproduct X Y] (f g : X ⊞ Y ⟶ Z) (h₀ : biprod.inl ≫ f = biprod.inl ≫ g) (h₁ : biprod.inr ≫ f = biprod.inr ≫ g) : f = g := binary_cofan.is_colimit.hom_ext (binary_biproduct.is_colimit X Y) h₀ h₁ lemma biprod.map_eq_map' {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g = biprod.map' f g := begin ext, { simp only [map_pair_left, is_colimit.ι_map, is_limit.map_π, biprod.inl_fst_assoc, category.assoc, ←binary_bicone.to_cone_π_app_left, ←binary_biproduct.bicone_fst, ←binary_bicone.to_cocone_ι_app_left, ←binary_biproduct.bicone_inl], simp }, { simp only [map_pair_left, is_colimit.ι_map, is_limit.map_π, zero_comp, biprod.inl_snd_assoc, category.assoc, ←binary_bicone.to_cone_π_app_right, ←binary_biproduct.bicone_snd, ←binary_bicone.to_cocone_ι_app_left, ←binary_biproduct.bicone_inl], simp }, { simp only [map_pair_right, biprod.inr_fst_assoc, is_colimit.ι_map, is_limit.map_π, zero_comp, category.assoc, ←binary_bicone.to_cone_π_app_left, ←binary_biproduct.bicone_fst, ←binary_bicone.to_cocone_ι_app_right, ←binary_biproduct.bicone_inr], simp }, { simp only [map_pair_right, is_colimit.ι_map, is_limit.map_π, biprod.inr_snd_assoc, category.assoc, ←binary_bicone.to_cone_π_app_right, ←binary_biproduct.bicone_snd, ←binary_bicone.to_cocone_ι_app_right, ←binary_biproduct.bicone_inr], simp } end instance biprod.inl_mono {X Y : C} [has_binary_biproduct X Y] : split_mono (biprod.inl : X ⟶ X ⊞ Y) := { retraction := biprod.desc (𝟙 X) (biprod.inr ≫ biprod.fst) } instance biprod.inr_mono {X Y : C} [has_binary_biproduct X Y] : split_mono (biprod.inr : Y ⟶ X ⊞ Y) := { retraction := biprod.desc (biprod.inl ≫ biprod.snd) (𝟙 Y)} instance biprod.fst_epi {X Y : C} [has_binary_biproduct X Y] : split_epi (biprod.fst : X ⊞ Y ⟶ X) := { section_ := biprod.lift (𝟙 X) (biprod.inl ≫ biprod.snd) } instance biprod.snd_epi {X Y : C} [has_binary_biproduct X Y] : split_epi (biprod.snd : X ⊞ Y ⟶ Y) := { section_ := biprod.lift (biprod.inr ≫ biprod.fst) (𝟙 Y) } @[simp,reassoc] lemma biprod.map_fst {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g ≫ biprod.fst = biprod.fst ≫ f := is_limit.map_π _ _ _ walking_pair.left @[simp,reassoc] lemma biprod.map_snd {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.map f g ≫ biprod.snd = biprod.snd ≫ g := is_limit.map_π _ _ _ walking_pair.right -- Because `biprod.map` is defined in terms of `lim` rather than `colim`, -- we need to provide additional `simp` lemmas. @[simp,reassoc] lemma biprod.inl_map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.inl ≫ biprod.map f g = f ≫ biprod.inl := begin rw biprod.map_eq_map', exact is_colimit.ι_map (binary_biproduct.is_colimit W X) _ _ walking_pair.left end @[simp,reassoc] lemma biprod.inr_map {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ⟶ Y) (g : X ⟶ Z) : biprod.inr ≫ biprod.map f g = g ≫ biprod.inr := begin rw biprod.map_eq_map', exact is_colimit.ι_map (binary_biproduct.is_colimit W X) _ _ walking_pair.right end /-- Given a pair of isomorphisms between the summands of a pair of binary biproducts, we obtain an isomorphism between the binary biproducts. -/ @[simps] def biprod.map_iso {W X Y Z : C} [has_binary_biproduct W X] [has_binary_biproduct Y Z] (f : W ≅ Y) (g : X ≅ Z) : W ⊞ X ≅ Y ⊞ Z := { hom := biprod.map f.hom g.hom, inv := biprod.map f.inv g.inv } /-- Auxiliary lemma for `biprod.unique_up_to_iso`. -/ lemma biprod.cone_point_unique_up_to_iso_hom (X Y : C) [has_binary_biproduct X Y] {b : binary_bicone X Y} (hb : b.is_bilimit) : (hb.is_limit.cone_point_unique_up_to_iso (binary_biproduct.is_limit _ _)).hom = biprod.lift b.fst b.snd := rfl /-- Auxiliary lemma for `biprod.unique_up_to_iso`. -/ lemma biprod.cone_point_unique_up_to_iso_inv (X Y : C) [has_binary_biproduct X Y] {b : binary_bicone X Y} (hb : b.is_bilimit) : (hb.is_limit.cone_point_unique_up_to_iso (binary_biproduct.is_limit _ _)).inv = biprod.desc b.inl b.inr := begin refine biprod.hom_ext' _ _ (hb.is_limit.hom_ext (λ j, _)) (hb.is_limit.hom_ext (λ j, _)), all_goals { simp only [category.assoc, is_limit.cone_point_unique_up_to_iso_inv_comp], cases j }, all_goals { simp } end /-- Binary biproducts are unique up to isomorphism. This already follows because bilimits are limits, but in the case of biproducts we can give an isomorphism with particularly nice definitional properties, namely that `biprod.lift b.fst b.snd` and `biprod.desc b.inl b.inr` are inverses of each other. -/ @[simps] def biprod.unique_up_to_iso (X Y : C) [has_binary_biproduct X Y] {b : binary_bicone X Y} (hb : b.is_bilimit) : b.X ≅ X ⊞ Y := { hom := biprod.lift b.fst b.snd, inv := biprod.desc b.inl b.inr, hom_inv_id' := by rw [← biprod.cone_point_unique_up_to_iso_hom X Y hb, ← biprod.cone_point_unique_up_to_iso_inv X Y hb, iso.hom_inv_id], inv_hom_id' := by rw [← biprod.cone_point_unique_up_to_iso_hom X Y hb, ← biprod.cone_point_unique_up_to_iso_inv X Y hb, iso.inv_hom_id] } section variables (X Y : C) [has_binary_biproduct X Y] -- There are three further variations, -- about `is_iso biprod.inr`, `is_iso biprod.fst` and `is_iso biprod.snd`, -- but any one suffices to prove `indecomposable_of_simple` -- and they are likely not separately useful. lemma biprod.is_iso_inl_iff_id_eq_fst_comp_inl : is_iso (biprod.inl : X ⟶ X ⊞ Y) ↔ 𝟙 (X ⊞ Y) = biprod.fst ≫ biprod.inl := begin split, { introI h, have := (cancel_epi (inv biprod.inl : X ⊞ Y ⟶ X)).2 biprod.inl_fst, rw [is_iso.inv_hom_id_assoc, category.comp_id] at this, rw [this, is_iso.inv_hom_id], }, { intro h, exact ⟨⟨biprod.fst, biprod.inl_fst, h.symm⟩⟩, }, end end section biprod_kernel variables (X Y : C) [has_binary_biproduct X Y] /-- A kernel fork for the kernel of `biprod.fst`. It consists of the morphism `biprod.inr`. -/ def biprod.fst_kernel_fork : kernel_fork (biprod.fst : X ⊞ Y ⟶ X) := kernel_fork.of_ι biprod.inr biprod.inr_fst @[simp] lemma biprod.fst_kernel_fork_ι : fork.ι (biprod.fst_kernel_fork X Y) = biprod.inr := rfl /-- The fork `biprod.fst_kernel_fork` is indeed a limit. -/ def biprod.is_kernel_fst_kernel_fork : is_limit (biprod.fst_kernel_fork X Y) := fork.is_limit.mk' _ $ λ s, ⟨s.ι ≫ biprod.snd, by ext; simp, λ m hm, by simp [← hm]⟩ /-- A kernel fork for the kernel of `biprod.snd`. It consists of the morphism `biprod.inl`. -/ def biprod.snd_kernel_fork : kernel_fork (biprod.snd : X ⊞ Y ⟶ Y) := kernel_fork.of_ι biprod.inl biprod.inl_snd @[simp] lemma biprod.snd_kernel_fork_ι : fork.ι (biprod.snd_kernel_fork X Y) = biprod.inl := rfl /-- The fork `biprod.snd_kernel_fork` is indeed a limit. -/ def biprod.is_kernel_snd_kernel_fork : is_limit (biprod.snd_kernel_fork X Y) := fork.is_limit.mk' _ $ λ s, ⟨s.ι ≫ biprod.fst, by ext; simp, λ m hm, by simp [← hm]⟩ /-- A cokernel cofork for the cokernel of `biprod.inl`. It consists of the morphism `biprod.snd`. -/ def biprod.inl_cokernel_fork : cokernel_cofork (biprod.inl : X ⟶ X ⊞ Y) := cokernel_cofork.of_π biprod.snd biprod.inl_snd @[simp] lemma biprod.inl_cokernel_fork_π : cofork.π (biprod.inl_cokernel_fork X Y) = biprod.snd := rfl /-- The cofork `biprod.inl_cokernel_fork` is indeed a colimit. -/ def biprod.is_cokernel_inl_cokernel_fork : is_colimit (biprod.inl_cokernel_fork X Y) := cofork.is_colimit.mk' _ $ λ s, ⟨biprod.inr ≫ s.π, by ext; simp, λ m hm, by simp [← hm]⟩ /-- A cokernel cofork for the cokernel of `biprod.inr`. It consists of the morphism `biprod.fst`. -/ def biprod.inr_cokernel_fork : cokernel_cofork (biprod.inr : Y ⟶ X ⊞ Y) := cokernel_cofork.of_π biprod.fst biprod.inr_fst @[simp] lemma biprod.inr_cokernel_fork_π : cofork.π (biprod.inr_cokernel_fork X Y) = biprod.fst := rfl /-- The cofork `biprod.inr_cokernel_fork` is indeed a colimit. -/ def biprod.is_cokernel_inr_cokernel_fork : is_colimit (biprod.inr_cokernel_fork X Y) := cofork.is_colimit.mk' _ $ λ s, ⟨biprod.inl ≫ s.π, by ext; simp, λ m hm, by simp [← hm]⟩ end biprod_kernel section variables [has_binary_biproducts C] /-- The braiding isomorphism which swaps a binary biproduct. -/ @[simps] def biprod.braiding (P Q : C) : P ⊞ Q ≅ Q ⊞ P := { hom := biprod.lift biprod.snd biprod.fst, inv := biprod.lift biprod.snd biprod.fst } /-- An alternative formula for the braiding isomorphism which swaps a binary biproduct, using the fact that the biproduct is a coproduct. -/ @[simps] def biprod.braiding' (P Q : C) : P ⊞ Q ≅ Q ⊞ P := { hom := biprod.desc biprod.inr biprod.inl, inv := biprod.desc biprod.inr biprod.inl } lemma biprod.braiding'_eq_braiding {P Q : C} : biprod.braiding' P Q = biprod.braiding P Q := by tidy /-- The braiding isomorphism can be passed through a map by swapping the order. -/ @[reassoc] lemma biprod.braid_natural {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) : biprod.map f g ≫ (biprod.braiding _ _).hom = (biprod.braiding _ _).hom ≫ biprod.map g f := by tidy @[reassoc] lemma biprod.braiding_map_braiding {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : (biprod.braiding X W).hom ≫ biprod.map f g ≫ (biprod.braiding Y Z).hom = biprod.map g f := by tidy @[simp, reassoc] lemma biprod.symmetry' (P Q : C) : biprod.lift biprod.snd biprod.fst ≫ biprod.lift biprod.snd biprod.fst = 𝟙 (P ⊞ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ @[reassoc] lemma biprod.symmetry (P Q : C) : (biprod.braiding P Q).hom ≫ (biprod.braiding Q P).hom = 𝟙 _ := by simp end -- TODO: -- If someone is interested, they could provide the constructions: -- has_binary_biproducts ↔ has_finite_biproducts end limits namespace limits section preadditive variables {C : Type u} [category.{v} C] [preadditive C] variables {J : Type v} [decidable_eq J] [fintype J] open category_theory.preadditive open_locale big_operators /-- In a preadditive category, we can construct a biproduct for `f : J → C` from any bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ def is_bilimit_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) : b.is_bilimit := { is_limit := { lift := λ s, ∑ j, s.π.app j ≫ b.ι j, uniq' := λ s m h, begin erw [←category.comp_id m, ←total, comp_sum], apply finset.sum_congr rfl, intros j m, erw [reassoc_of (h j)], end, fac' := λ s j, begin simp only [sum_comp, category.assoc, bicone.to_cone_π_app, b.ι_π, comp_dite], -- See note [dsimp, simp]. dsimp, simp, end }, is_colimit := { desc := λ s, ∑ j, b.π j ≫ s.ι.app j, uniq' := λ s m h, begin erw [←category.id_comp m, ←total, sum_comp], apply finset.sum_congr rfl, intros j m, erw [category.assoc, h], end, fac' := λ s j, begin simp only [comp_sum, ←category.assoc, bicone.to_cocone_ι_app, b.ι_π, dite_comp], dsimp, simp, end } } lemma is_bilimit.total {f : J → C} {b : bicone f} (i : b.is_bilimit) : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X := i.is_limit.hom_ext (λ j, by simp [sum_comp, b.ι_π, comp_dite]) /-- In a preadditive category, we can construct a biproduct for `f : J → C` from any bicone `b` for `f` satisfying `total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ lemma has_biproduct_of_total {f : J → C} (b : bicone f) (total : ∑ j : J, b.π j ≫ b.ι j = 𝟙 b.X) : has_biproduct f := has_biproduct.mk { bicone := b, is_bilimit := is_bilimit_of_total b total } /-- In a preadditive category, any finite bicone which is a limit cone is in fact a bilimit bicone. -/ def is_bilimit_of_is_limit {f : J → C} (t : bicone f) (ht : is_limit t.to_cone) : t.is_bilimit := is_bilimit_of_total _ $ ht.hom_ext $ λ j, by simp [sum_comp, t.ι_π, dite_comp, comp_dite] /-- We can turn any limit cone over a pair into a bilimit bicone. -/ def bicone_is_bilimit_of_limit_cone_of_is_limit {f : J → C} {t : cone (discrete.functor f)} (ht : is_limit t) : (bicone.of_limit_cone ht).is_bilimit := is_bilimit_of_is_limit _ $ is_limit.of_iso_limit ht $ cones.ext (iso.refl _) (by tidy) /-- In a preadditive category, if the product over `f : J → C` exists, then the biproduct over `f` exists. -/ lemma has_biproduct.of_has_product (f : J → C) [has_product f] : has_biproduct f := has_biproduct.mk { bicone := _, is_bilimit := bicone_is_bilimit_of_limit_cone_of_is_limit (limit.is_limit _) } /-- In a preadditive category, any finite bicone which is a colimit cocone is in fact a bilimit bicone. -/ def is_bilimit_of_is_colimit {f : J → C} (t : bicone f) (ht : is_colimit t.to_cocone) : t.is_bilimit := is_bilimit_of_total _ $ ht.hom_ext $ λ j, by { simp_rw [bicone.to_cocone_ι_app, comp_sum, ← category.assoc, t.ι_π, dite_comp], tidy } /-- We can turn any limit cone over a pair into a bilimit bicone. -/ def bicone_is_bilimit_of_colimit_cocone_of_is_colimit {f : J → C} {t : cocone (discrete.functor f)} (ht : is_colimit t) : (bicone.of_colimit_cocone ht).is_bilimit := is_bilimit_of_is_colimit _ $ is_colimit.of_iso_colimit ht $ cocones.ext (iso.refl _) (by tidy) /-- In a preadditive category, if the coproduct over `f : J → C` exists, then the biproduct over `f` exists. -/ lemma has_biproduct.of_has_coproduct (f : J → C) [has_coproduct f] : has_biproduct f := has_biproduct.mk { bicone := _, is_bilimit := bicone_is_bilimit_of_colimit_cocone_of_is_colimit (colimit.is_colimit _) } /-- A preadditive category with finite products has finite biproducts. -/ lemma has_finite_biproducts.of_has_finite_products [has_finite_products C] : has_finite_biproducts C := ⟨λ J _ _, { has_biproduct := λ F, by exactI has_biproduct.of_has_product _ }⟩ /-- A preadditive category with finite coproducts has finite biproducts. -/ lemma has_finite_biproducts.of_has_finite_coproducts [has_finite_coproducts C] : has_finite_biproducts C := ⟨λ J _ _, { has_biproduct := λ F, by exactI has_biproduct.of_has_coproduct _ }⟩ section variables {f : J → C} [has_biproduct f] /-- In any preadditive category, any biproduct satsifies `∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f)` -/ @[simp] lemma biproduct.total : ∑ j : J, biproduct.π f j ≫ biproduct.ι f j = 𝟙 (⨁ f) := is_bilimit.total (biproduct.is_bilimit _) lemma biproduct.lift_eq {T : C} {g : Π j, T ⟶ f j} : biproduct.lift g = ∑ j, g j ≫ biproduct.ι f j := begin ext j, simp [sum_comp, biproduct.ι_π, comp_dite], end lemma biproduct.desc_eq {T : C} {g : Π j, f j ⟶ T} : biproduct.desc g = ∑ j, biproduct.π f j ≫ g j := begin ext j, simp [comp_sum, biproduct.ι_π_assoc, dite_comp], end @[simp, reassoc] lemma biproduct.lift_desc {T U : C} {g : Π j, T ⟶ f j} {h : Π j, f j ⟶ U} : biproduct.lift g ≫ biproduct.desc h = ∑ j : J, g j ≫ h j := by simp [biproduct.lift_eq, biproduct.desc_eq, comp_sum, sum_comp, biproduct.ι_π_assoc, comp_dite, dite_comp] lemma biproduct.map_eq [has_finite_biproducts C] {f g : J → C} {h : Π j, f j ⟶ g j} : biproduct.map h = ∑ j : J, biproduct.π f j ≫ h j ≫ biproduct.ι g j := begin ext, simp [biproduct.ι_π, biproduct.ι_π_assoc, comp_sum, sum_comp, comp_dite, dite_comp], end @[simp, reassoc] lemma biproduct.matrix_desc {K : Type v} [fintype K] [decidable_eq K] [has_finite_biproducts C] {f : J → C} {g : K → C} (m : Π j k, f j ⟶ g k) {P} (x : Π k, g k ⟶ P) : biproduct.matrix m ≫ biproduct.desc x = biproduct.desc (λ j, ∑ k, m j k ≫ x k) := by { ext, simp, } @[simp, reassoc] lemma biproduct.lift_matrix {K : Type v} [fintype K] [decidable_eq K] [has_finite_biproducts C] {f : J → C} {g : K → C} {P} (x : Π j, P ⟶ f j) (m : Π j k, f j ⟶ g k) : biproduct.lift x ≫ biproduct.matrix m = biproduct.lift (λ k, ∑ j, x j ≫ m j k) := by { ext, simp, } @[reassoc] lemma biproduct.matrix_map {K : Type v} [fintype K] [decidable_eq K] [has_finite_biproducts C] {f : J → C} {g : K → C} {h : K → C} (m : Π j k, f j ⟶ g k) (n : Π k, g k ⟶ h k) : biproduct.matrix m ≫ biproduct.map n = biproduct.matrix (λ j k, m j k ≫ n k) := by { ext, simp, } @[reassoc] lemma biproduct.map_matrix {K : Type v} [fintype K] [decidable_eq K] [has_finite_biproducts C] {f : J → C} {g : J → C} {h : K → C} (m : Π k, f k ⟶ g k) (n : Π j k, g j ⟶ h k) : biproduct.map m ≫ biproduct.matrix n = biproduct.matrix (λ j k, m j ≫ n j k) := by { ext, simp, } end /-- In a preadditive category, we can construct a binary biproduct for `X Y : C` from any binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ def is_binary_bilimit_of_total {X Y : C} (b : binary_bicone X Y) (total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : b.is_bilimit := { is_limit := { lift := λ s, binary_fan.fst s ≫ b.inl + binary_fan.snd s ≫ b.inr, uniq' := λ s m h, by erw [←category.comp_id m, ←total, comp_add, reassoc_of (h walking_pair.left), reassoc_of (h walking_pair.right)], fac' := λ s j, by cases j; simp, }, is_colimit := { desc := λ s, b.fst ≫ binary_cofan.inl s + b.snd ≫ binary_cofan.inr s, uniq' := λ s m h, by erw [←category.id_comp m, ←total, add_comp, category.assoc, category.assoc, h walking_pair.left, h walking_pair.right], fac' := λ s j, by cases j; simp, } } lemma is_bilimit.binary_total {X Y : C} {b : binary_bicone X Y} (i : b.is_bilimit) : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X := i.is_limit.hom_ext (λ j, by { cases j; simp, }) /-- In a preadditive category, we can construct a binary biproduct for `X Y : C` from any binary bicone `b` satisfying `total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X`. (That is, such a bicone is a limit cone and a colimit cocone.) -/ lemma has_binary_biproduct_of_total {X Y : C} (b : binary_bicone X Y) (total : b.fst ≫ b.inl + b.snd ≫ b.inr = 𝟙 b.X) : has_binary_biproduct X Y := has_binary_biproduct.mk { bicone := b, is_bilimit := is_binary_bilimit_of_total b total } /-- We can turn any limit cone over a pair into a bicone. -/ @[simps] def binary_bicone.of_limit_cone {X Y : C} {t : cone (pair X Y)} (ht : is_limit t) : binary_bicone X Y := { X := t.X, fst := t.π.app walking_pair.left, snd := t.π.app walking_pair.right, inl := ht.lift (binary_fan.mk (𝟙 X) 0), inr := ht.lift (binary_fan.mk 0 (𝟙 Y)) } lemma inl_of_is_limit {X Y : C} {t : binary_bicone X Y} (ht : is_limit t.to_cone) : t.inl = ht.lift (binary_fan.mk (𝟙 X) 0) := ht.hom_ext $ λ j, by { rw ht.fac, cases j; simp } lemma inr_of_is_limit {X Y : C} {t : binary_bicone X Y} (ht : is_limit t.to_cone) : t.inr = ht.lift (binary_fan.mk 0 (𝟙 Y)) := ht.hom_ext $ λ j, by { rw ht.fac, cases j; simp } /-- In a preadditive category, any binary bicone which is a limit cone is in fact a bilimit bicone. -/ def is_binary_bilimit_of_is_limit {X Y : C} (t : binary_bicone X Y) (ht : is_limit t.to_cone) : t.is_bilimit := is_binary_bilimit_of_total _ (by refine binary_fan.is_limit.hom_ext ht _ _; simp) /-- We can turn any limit cone over a pair into a bilimit bicone. -/ def binary_bicone_is_bilimit_of_limit_cone_of_is_limit {X Y : C} {t : cone (pair X Y)} (ht : is_limit t) : (binary_bicone.of_limit_cone ht).is_bilimit := is_binary_bilimit_of_total _ $ binary_fan.is_limit.hom_ext ht (by simp) (by simp) /-- In a preadditive category, if the product of `X` and `Y` exists, then the binary biproduct of `X` and `Y` exists. -/ lemma has_binary_biproduct.of_has_binary_product (X Y : C) [has_binary_product X Y] : has_binary_biproduct X Y := has_binary_biproduct.mk { bicone := _, is_bilimit := binary_bicone_is_bilimit_of_limit_cone_of_is_limit (limit.is_limit _) } /-- In a preadditive category, if all binary products exist, then all binary biproducts exist. -/ lemma has_binary_biproducts.of_has_binary_products [has_binary_products C] : has_binary_biproducts C := { has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_product X Y, } /-- We can turn any colimit cocone over a pair into a bicone. -/ @[simps] def binary_bicone.of_colimit_cocone {X Y : C} {t : cocone (pair X Y)} (ht : is_colimit t) : binary_bicone X Y := { X := t.X, fst := ht.desc (binary_cofan.mk (𝟙 X) 0), snd := ht.desc (binary_cofan.mk 0 (𝟙 Y)), inl := t.ι.app walking_pair.left, inr := t.ι.app walking_pair.right } lemma fst_of_is_colimit {X Y : C} {t : binary_bicone X Y} (ht : is_colimit t.to_cocone) : t.fst = ht.desc (binary_cofan.mk (𝟙 X) 0) := begin refine ht.hom_ext (λ j, _), rw ht.fac, cases j, all_goals { simp only [binary_bicone.to_cocone_ι_app_left, binary_bicone.inl_fst, binary_cofan.mk_ι_app_left, binary_bicone.to_cocone_ι_app_right, binary_bicone.inr_fst, binary_cofan.mk_ι_app_right] }, refl end lemma snd_of_is_colimit {X Y : C} {t : binary_bicone X Y} (ht : is_colimit t.to_cocone) : t.snd = ht.desc (binary_cofan.mk 0 (𝟙 Y)) := begin refine ht.hom_ext (λ j, _), rw ht.fac, cases j, all_goals { simp only [binary_bicone.to_cocone_ι_app_left, binary_bicone.inl_snd, binary_cofan.mk_ι_app_left, binary_bicone.to_cocone_ι_app_right, binary_bicone.inr_snd, binary_cofan.mk_ι_app_right] }, refl end /-- In a preadditive category, any binary bicone which is a colimit cocone is in fact a bilimit bicone. -/ def is_binary_bilimit_of_is_colimit {X Y : C} (t : binary_bicone X Y) (ht : is_colimit t.to_cocone) : t.is_bilimit := is_binary_bilimit_of_total _ begin refine binary_cofan.is_colimit.hom_ext ht _ _; simp, { rw [category.comp_id t.inl] }, { rw [category.comp_id t.inr] } end /-- We can turn any colimit cocone over a pair into a bilimit bicone. -/ def binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit {X Y : C} {t : cocone (pair X Y)} (ht : is_colimit t) : (binary_bicone.of_colimit_cocone ht).is_bilimit := is_binary_bilimit_of_is_colimit (binary_bicone.of_colimit_cocone ht) $ is_colimit.of_iso_colimit ht $ cocones.ext (iso.refl _) $ λ j, by { cases j, tidy } /-- In a preadditive category, if the coproduct of `X` and `Y` exists, then the binary biproduct of `X` and `Y` exists. -/ lemma has_binary_biproduct.of_has_binary_coproduct (X Y : C) [has_binary_coproduct X Y] : has_binary_biproduct X Y := has_binary_biproduct.mk { bicone := _, is_bilimit := binary_bicone_is_bilimit_of_colimit_cocone_of_is_colimit (colimit.is_colimit _) } /-- In a preadditive category, if all binary coproducts exist, then all binary biproducts exist. -/ lemma has_binary_biproducts.of_has_binary_coproducts [has_binary_coproducts C] : has_binary_biproducts C := { has_binary_biproduct := λ X Y, has_binary_biproduct.of_has_binary_coproduct X Y, } section variables {X Y : C} [has_binary_biproduct X Y] /-- In any preadditive category, any binary biproduct satsifies `biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y)`. -/ @[simp] lemma biprod.total : biprod.fst ≫ biprod.inl + biprod.snd ≫ biprod.inr = 𝟙 (X ⊞ Y) := begin ext; simp [add_comp], end lemma biprod.lift_eq {T : C} {f : T ⟶ X} {g : T ⟶ Y} : biprod.lift f g = f ≫ biprod.inl + g ≫ biprod.inr := begin ext; simp [add_comp], end lemma biprod.desc_eq {T : C} {f : X ⟶ T} {g : Y ⟶ T} : biprod.desc f g = biprod.fst ≫ f + biprod.snd ≫ g := begin ext; simp [add_comp], end @[simp, reassoc] lemma biprod.lift_desc {T U : C} {f : T ⟶ X} {g : T ⟶ Y} {h : X ⟶ U} {i : Y ⟶ U} : biprod.lift f g ≫ biprod.desc h i = f ≫ h + g ≫ i := by simp [biprod.lift_eq, biprod.desc_eq] lemma biprod.map_eq [has_binary_biproducts C] {W X Y Z : C} {f : W ⟶ Y} {g : X ⟶ Z} : biprod.map f g = biprod.fst ≫ f ≫ biprod.inl + biprod.snd ≫ g ≫ biprod.inr := by apply biprod.hom_ext; apply biprod.hom_ext'; simp /-- Every split mono `f` with a cokernel induces a binary bicone with `f` as its `inl` and the cokernel map as its `snd`. We will show in `is_bilimit_binary_bicone_of_split_mono_of_cokernel` that this binary bicone is in fact already a biproduct. -/ @[simps] def binary_bicone_of_split_mono_of_cokernel {X Y : C} {f : X ⟶ Y} [split_mono f] {c : cokernel_cofork f} (i : is_colimit c) : binary_bicone X c.X := { X := Y, fst := retraction f, snd := c.π, inl := f, inr := let c' : cokernel_cofork (𝟙 Y - (𝟙 Y - retraction f ≫ f)) := cokernel_cofork.of_π (cofork.π c) (by simp) in let i' : is_colimit c' := is_cokernel_epi_comp i (retraction f) (by simp) in let i'' := is_colimit_cofork_of_cokernel_cofork i' in (split_epi_of_idempotent_of_is_colimit_cofork C (by simp) i'').section_, inl_fst' := by simp, inl_snd' := by simp, inr_fst' := begin dsimp only, rw [split_epi_of_idempotent_of_is_colimit_cofork_section_, is_colimit_cofork_of_cokernel_cofork_desc, is_cokernel_epi_comp_desc], dsimp only [cokernel_cofork_of_cofork_of_π], letI := epi_of_is_colimit_cofork i, apply zero_of_epi_comp c.π, simp only [sub_comp, comp_sub, category.comp_id, category.assoc, split_mono.id, sub_self, cofork.is_colimit.π_comp_desc_assoc, cokernel_cofork.π_of_π, split_mono.id_assoc], apply sub_eq_zero_of_eq, apply category.id_comp end, inr_snd' := by apply split_epi.id } /-- The bicone constructed in `binary_bicone_of_split_mono_of_cokernel` is a bilimit. This is a version of the splitting lemma that holds in all preadditive categories. -/ def is_bilimit_binary_bicone_of_split_mono_of_cokernel {X Y : C} {f : X ⟶ Y} [split_mono f] {c : cokernel_cofork f} (i : is_colimit c) : (binary_bicone_of_split_mono_of_cokernel i).is_bilimit := is_binary_bilimit_of_total _ begin simp only [binary_bicone_of_split_mono_of_cokernel_fst, binary_bicone_of_split_mono_of_cokernel_inr, binary_bicone_of_split_mono_of_cokernel_snd, split_epi_of_idempotent_of_is_colimit_cofork_section_], dsimp only [binary_bicone_of_split_mono_of_cokernel_X], rw [is_colimit_cofork_of_cokernel_cofork_desc, is_cokernel_epi_comp_desc], simp only [binary_bicone_of_split_mono_of_cokernel_inl, cofork.is_colimit.π_comp_desc, cokernel_cofork_of_cofork_π, cofork.π_of_π, add_sub_cancel'_right] end /-- Every split epi `f` with a kernel induces a binary bicone with `f` as its `snd` and the kernel map as its `inl`. We will show in `binary_bicone_of_split_mono_of_cokernel` that this binary bicone is in fact already a biproduct. -/ @[simps] def binary_bicone_of_split_epi_of_kernel {X Y : C} {f : X ⟶ Y} [split_epi f] {c : kernel_fork f} (i : is_limit c) : binary_bicone c.X Y := { X := X, fst := let c' : kernel_fork (𝟙 X - (𝟙 X - f ≫ section_ f)) := kernel_fork.of_ι (fork.ι c) (by simp) in let i' : is_limit c' := is_kernel_comp_mono i (section_ f) (by simp) in let i'' := is_limit_fork_of_kernel_fork i' in (split_mono_of_idempotent_of_is_limit_fork C (by simp) i'').retraction, snd := f, inl := c.ι, inr := section_ f, inl_fst' := by apply split_mono.id, inl_snd' := by simp, inr_fst' := begin dsimp only, rw [split_mono_of_idempotent_of_is_limit_fork_retraction, is_limit_fork_of_kernel_fork_lift, is_kernel_comp_mono_lift], dsimp only [kernel_fork_of_fork_ι], letI := mono_of_is_limit_fork i, apply zero_of_comp_mono c.ι, simp only [comp_sub, category.comp_id, category.assoc, sub_self, fork.is_limit.lift_comp_ι, fork.ι_of_ι, split_epi.id_assoc] end, inr_snd' := by simp } /-- The bicone constructed in `binary_bicone_of_split_epi_of_kernel` is a bilimit. This is a version of the splitting lemma that holds in all preadditive categories. -/ def is_bilimit_binary_bicone_of_split_epi_of_kernel {X Y : C} {f : X ⟶ Y} [split_epi f] {c : kernel_fork f} (i : is_limit c) : (binary_bicone_of_split_epi_of_kernel i).is_bilimit := is_binary_bilimit_of_total _ begin simp only [binary_bicone_of_split_epi_of_kernel_fst, binary_bicone_of_split_epi_of_kernel_inl, binary_bicone_of_split_epi_of_kernel_inr, binary_bicone_of_split_epi_of_kernel_snd, split_mono_of_idempotent_of_is_limit_fork_retraction], dsimp only [binary_bicone_of_split_epi_of_kernel_X], rw [is_limit_fork_of_kernel_fork_lift, is_kernel_comp_mono_lift], simp only [fork.is_limit.lift_comp_ι, fork.ι_of_ι, kernel_fork_of_fork_ι, sub_add_cancel] end end section variables {X Y : C} (f g : X ⟶ Y) /-- The existence of binary biproducts implies that there is at most one preadditive structure. -/ lemma biprod.add_eq_lift_id_desc [has_binary_biproduct X X] : f + g = biprod.lift (𝟙 X) (𝟙 X) ≫ biprod.desc f g := by simp /-- The existence of binary biproducts implies that there is at most one preadditive structure. -/ lemma biprod.add_eq_lift_desc_id [has_binary_biproduct Y Y] : f + g = biprod.lift f g ≫ biprod.desc (𝟙 Y) (𝟙 Y) := by simp end end preadditive end limits open category_theory.limits section local attribute [ext] preadditive /-- The existence of binary biproducts implies that there is at most one preadditive structure. -/ instance subsingleton_preadditive_of_has_binary_biproducts {C : Type u} [category.{v} C] [has_zero_morphisms C] [has_binary_biproducts C] : subsingleton (preadditive C) := subsingleton.intro $ λ a b, begin ext X Y f g, have h₁ := @biprod.add_eq_lift_id_desc _ _ a _ _ f g (by convert (infer_instance : has_binary_biproduct X X)), have h₂ := @biprod.add_eq_lift_id_desc _ _ b _ _ f g (by convert (infer_instance : has_binary_biproduct X X)), refine h₁.trans (eq.trans _ h₂.symm), congr' 2; exact subsingleton.elim _ _ end end variables {C : Type u} [category.{v} C] [has_zero_morphisms C] [has_binary_biproducts C] /-- An object is indecomposable if it cannot be written as the biproduct of two nonzero objects. -/ def indecomposable (X : C) : Prop := ¬ is_zero X ∧ ∀ Y Z, (X ≅ Y ⊞ Z) → is_zero Y ∨ is_zero Z end category_theory
e3f77b56145bb8c6b8a5b0be54d2b625ce04f150
cbcb0199842f03e7606d4e43666573fc15dd07a5
/src/algebra/roption_instances.lean
902452e844c7d2e8f474cad50a2d0fc90542abc1
[ "Apache-2.0" ]
permissive
truonghoangle/mathlib
a6a7c14b3767ec71156239d8ea97f6921fe79627
673bae584febcd830c2c9256eb7e7a81e27ed303
refs/heads/master
1,590,347,998,944
1,559,728,860,000
1,559,728,860,000
187,431,971
0
0
null
1,558,238,525,000
1,558,238,525,000
null
UTF-8
Lean
false
false
4,525
lean
/- Copyright (c) 2019 Hoang Le Truong. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Hoang Le Truong. If α is a semigroup, a comm_semigroup, a comm_monoid,a add_semigroup, a add_comm_semigroup, a add_comm_monoid, a mul_action, a distrib_mul_action, so is roption α. -/ import algebra.module data.pfun namespace roption universes u v w variables {α : Type u} {β : Type v} {γ : Type w} noncomputable theory instance [has_zero α] : has_zero (roption α) := ⟨some (0 : α)⟩ lemma zero_def [has_zero α] : (0 : roption α) = ⟨true, λ _, (0 : α)⟩ := rfl instance [has_one α] : has_one (roption α) := ⟨some (1 : α)⟩ lemma one_def [has_one α] : (1 : roption α) = ⟨true, λ _, (1 : α)⟩ := rfl attribute [to_additive roption.has_zero] roption.has_one attribute [to_additive roption.zero_def] roption.one_def instance [has_add α] : has_add (roption α) := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get (h.1)+ y.get (h.2)⟩⟩ lemma add_def [has_add α] (x y : roption α) : x+y = ⟨x.dom ∧ y.dom, λ h, x.get (h.1)+ y.get (h.2)⟩ := rfl instance [has_mul α] : has_mul (roption α) := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get (h.1) * y.get (h.2)⟩⟩ lemma mul_def [has_mul α] (x y : roption α) : x * y = ⟨x.dom ∧ y.dom , λ h, x.get (h.1) * y.get (h.2)⟩ := rfl attribute [to_additive roption.has_add] roption.has_mul attribute [to_additive roption.add_def] roption.mul_def instance [has_scalar α β] : has_scalar α (roption β) := ⟨λ a f, ⟨f.dom, λ h, a • (f.get h)⟩⟩ lemma smul_def [has_scalar α β] (a : α) (x : roption β) : a • x = ⟨x.dom , λ h, a • x.get h⟩ := rfl instance semigroup [semigroup α] : semigroup (roption α) := { mul_assoc := λ x y z, roption.ext' and.assoc (λ _ _, mul_assoc _ _ _), ..roption.has_mul} instance comm_semigroup [comm_semigroup α] : comm_semigroup (roption α) := { mul_comm := λ x y, roption.ext' and.comm (λ _ _, mul_comm _ _) ..roption.semigroup} instance monoid [monoid α] : monoid (roption α) := { monoid. mul := roption.has_mul.mul, mul_assoc := λ x y z, roption.ext' and.assoc (λ _ _, mul_assoc _ _ _), one := roption.has_one.one, one_mul := λ x, roption.ext' (true_and _) (λ _ _, one_mul _), mul_one := λ x, roption.ext' (and_true _) (λ _ _, mul_one _)} instance comm_monoid [comm_monoid α] : comm_monoid (roption α) := { mul_comm := λ x y, roption.ext' and.comm (λ _ _, mul_comm _ _), ..roption.monoid} attribute [to_additive roption.add_semigroup._proof_1] roption.semigroup._proof_1 attribute [to_additive roption.add_semigroup] roption.semigroup attribute [to_additive roption.add_monoid._proof_1] roption.monoid._proof_1 attribute [to_additive roption.add_monoid._proof_2] roption.monoid._proof_2 attribute [to_additive roption.add_monoid._proof_3] roption.monoid._proof_3 attribute [to_additive roption.add_monoid'] roption.monoid attribute [to_additive roption.add_comm_semigroup._proof_1] roption.comm_semigroup._proof_1 attribute [to_additive roption.add_comm_semigroup._proof_2] roption.comm_semigroup._proof_2 attribute [to_additive roption.add_comm_semigroup] roption.comm_semigroup attribute [to_additive roption.add_comm_monoid._proof_1] roption.comm_monoid._proof_1 attribute [to_additive roption.add_comm_monoid._proof_2] roption.comm_monoid._proof_2 attribute [to_additive roption.add_comm_monoid._proof_3] roption.comm_monoid._proof_3 attribute [to_additive roption.add_comm_monoid._proof_4] roption.comm_monoid._proof_4 attribute [to_additive roption.add_comm_monoid] roption.comm_monoid instance [monoid β] [mul_action β α] : mul_action β (roption α) := { one_smul := λ x, roption.ext' (by simp[one_def,smul_def]) (by { intros, simp[smul_def,one_def,one_smul]}), mul_smul := λ a b x, roption.ext' (by simp[smul_def]) (by { intros, simp[smul_def,mul_smul]}), ..roption.has_scalar} instance [monoid β] [add_monoid α] [distrib_mul_action β α] : distrib_mul_action β (roption α) := { smul_add := λ a x y, roption.ext' (by simp[add_def,smul_def]) (by{ intros, simp[smul_def,add_def,smul_add]}), smul_zero := λ x, roption.ext' (by simp[zero_def,smul_def]) (by{ intros, simp[smul_def,zero_def,smul_zero]}), ..roption.mul_action} end roption
6b6b133ca840e3973dfd2e15df8e318cd961bbae
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/bench/rbmap2.lean
58fff6a1124e531447277c8c6bbcd1e2832f1969
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
2,898
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 -/ prelude import init.coe init.data.option.basic init.system.io universes u v w w' inductive color | Red | Black inductive Tree | Leaf {} : Tree | Node (color : color) (lchild : Tree) (key : Nat) (val : Bool) (rchild : Tree) : Tree variable {σ : Type w} open color Nat Tree def fold (f : Nat → Bool → σ → σ) : Tree → σ → σ | Leaf, b => b | Node _ l k v r, b => fold r (f k v (fold l b)) def balance1 : Tree → Tree → Tree | Node _ _ kv vv t, Node _ (Node Red l kx vx r₁) ky vy r₂ => Node Red (Node Black l kx vx r₁) ky vy (Node Black r₂ kv vv t) | Node _ _ kv vv t, Node _ l₁ ky vy (Node Red l₂ kx vx r) => Node Red (Node Black l₁ ky vy l₂) kx vx (Node Black r kv vv t) | Node _ _ kv vv t, Node _ l ky vy r => Node Black (Node Red l ky vy r) kv vv t | _, _ => Leaf def balance2 : Tree → Tree → Tree | Node _ t kv vv _, Node _ (Node Red l kx₁ vx₁ r₁) ky vy r₂ => Node Red (Node Black t kv vv l) kx₁ vx₁ (Node Black r₁ ky vy r₂) | Node _ t kv vv _, Node _ l₁ ky vy (Node Red l₂ kx₂ vx₂ r₂) => Node Red (Node Black t kv vv l₁) ky vy (Node Black l₂ kx₂ vx₂ r₂) | Node _ t kv vv _, Node _ l ky vy r => Node Black t kv vv (Node Red l ky vy r) | _, _ => Leaf def isRed : Tree → Bool | Node Red _ _ _ _ => true | _ => false def ins : Tree → Nat → Bool → Tree | Leaf, kx, vx => Node Red Leaf kx vx Leaf | Node Red a ky vy b, kx, vx => (if kx < ky then Node Red (ins a kx vx) ky vy b else if kx = ky then Node Red a kx vx b else Node Red a ky vy (ins b kx vx)) | Node Black a ky vy b, kx, vx => if kx < ky then (if isRed a then balance1 (Node Black Leaf ky vy b) (ins a kx vx) else Node Black (ins a kx vx) ky vy b) else if kx = ky then Node Black a kx vx b else if isRed b then balance2 (Node Black a ky vy Leaf) (ins b kx vx) else Node Black a ky vy (ins b kx vx) def setBlack : Tree → Tree | Node _ l k v r => Node Black l k v r | e => e def insert (t : Tree) (k : Nat) (v : Bool) : Tree := if isRed t then setBlack (ins t k v) else ins t k v def mkMapAux : Nat → Tree → Tree | 0, m => m | n+1, m => mkMapAux n (insert m n (n % 10 = 0)) def mkMap (n : Nat) := mkMapAux n Leaf def main (xs : List String) : IO UInt32 := let m := mkMap xs.head.toNat; let v := fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0; IO.println (toString v) *> pure 0
c3ed255485e18de468ec3bde0bbca24f9006a73b
d0c6b2ba2af981e9ab0a98f6e169262caad4b9b9
/tests/lean/run/whileRepeat.lean
3f1f157383837604e7920e94ddb88b7e86f7499c
[ "Apache-2.0" ]
permissive
fizruk/lean4
953b7dcd76e78c17a0743a2c1a918394ab64bbc0
545ed50f83c570f772ade4edbe7d38a078cbd761
refs/heads/master
1,677,655,987,815
1,612,393,885,000
1,612,393,885,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,208
lean
structure Loop where @[inline] partial def Loop.forIn {β : Type u} {m : Type u → Type v} [Monad m] (loop : Loop) (init : β) (f : Unit → β → m (ForInStep β)) : m β := let rec @[specialize] loop (b : β) : m β := do match ← f () b with | ForInStep.done b => pure b | ForInStep.yield b => loop b loop init syntax "repeat " doSeq : doElem macro_rules | `(doElem| repeat $seq) => `(doElem| for _ in Loop.mk do $seq) syntax "while " termBeforeDo " do " doSeq : doElem macro_rules | `(doElem| while $cond do $seq) => `(doElem| repeat if $cond then $seq else break) def test1 : IO Unit := do let mut i := 0 while i < 10 do println! "{i}" i := i + 1 println! "test1 done {i}" #eval test1 syntax "repeat " doSeq " until " term : doElem macro_rules | `(doElem| repeat $seq until $cond) => `(doElem| repeat do $seq; if $cond then break) def test2 : IO Unit := do let mut i := 0 repeat println! "{i}" i := i + 1 until i >= 10 println! "test2 done {i}" #eval test2 def test3 : IO Unit := do let mut i := 0 repeat println! "{i}" if i > 10 && i % 3 == 0 then break i := i + 1 println! "test3 done {i}" #eval test3
6462db50135cab993b187065e60c1eb500afb6a3
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/nat/choose/dvd.lean
78200b71d7dff5100fb5ca70a90115bc4670d4b3
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,228
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 data.nat.prime /-! # Divisibility properties of binomial coefficients -/ namespace nat open_locale nat namespace prime lemma dvd_choose_add {p a b : ℕ} (hap : a < p) (hbp : b < p) (h : p ≤ a + b) (hp : prime p) : p ∣ choose (a + b) a := have h₁ : p ∣ (a + b)!, from hp.dvd_factorial.2 h, have h₂ : ¬p ∣ a!, from mt hp.dvd_factorial.1 (not_le_of_gt hap), have h₃ : ¬p ∣ b!, from mt hp.dvd_factorial.1 (not_le_of_gt hbp), by rw [← choose_mul_factorial_mul_factorial (le.intro rfl), mul_assoc, hp.dvd_mul, hp.dvd_mul, nat.add_sub_cancel_left a b] at h₁; exact h₁.resolve_right (not_or_distrib.2 ⟨h₂, h₃⟩) lemma dvd_choose_self {p k : ℕ} (hk : 0 < k) (hkp : k < p) (hp : prime p) : p ∣ choose p k := begin have r : k + (p - k) = p, by rw [← nat.add_sub_assoc (nat.le_of_lt hkp) k, nat.add_sub_cancel_left], have e : p ∣ choose (k + (p - k)) k, by exact dvd_choose_add hkp (nat.sub_lt (hk.trans hkp) hk) (by rw r) hp, rwa r at e, end end prime end nat
5bdbfa5afbea017bb9e4800f771e824bf0571bd0
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/NonassociativeNondistributiveRing.lean
16af8e2eb03352bfb7cb4ce85a1c9eb02fbc01bd
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
14,959
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section NonassociativeNondistributiveRing structure NonassociativeNondistributiveRing (A : Type) : Type := (times : (A → (A → A))) (one : A) (lunit_one : (∀ {x : A} , (times one x) = x)) (runit_one : (∀ {x : A} , (times x one) = x)) (associative_times : (∀ {x y z : A} , (times (times x y) z) = (times x (times y z)))) (inv : (A → A)) (leftInverse_inv_op_one : (∀ {x : A} , (times x (inv x)) = one)) (rightInverse_inv_op_one : (∀ {x : A} , (times (inv x) x) = one)) (commutative_times : (∀ {x y : A} , (times x y) = (times y x))) (plus : (A → (A → A))) open NonassociativeNondistributiveRing structure Sig (AS : Type) : Type := (timesS : (AS → (AS → AS))) (oneS : AS) (invS : (AS → AS)) (plusS : (AS → (AS → AS))) structure Product (A : Type) : Type := (timesP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (oneP : (Prod A A)) (invP : ((Prod A A) → (Prod A A))) (plusP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (lunit_1P : (∀ {xP : (Prod A A)} , (timesP oneP xP) = xP)) (runit_1P : (∀ {xP : (Prod A A)} , (timesP xP oneP) = xP)) (associative_timesP : (∀ {xP yP zP : (Prod A A)} , (timesP (timesP xP yP) zP) = (timesP xP (timesP yP zP)))) (leftInverse_inv_op_1P : (∀ {xP : (Prod A A)} , (timesP xP (invP xP)) = oneP)) (rightInverse_inv_op_1P : (∀ {xP : (Prod A A)} , (timesP (invP xP) xP) = oneP)) (commutative_timesP : (∀ {xP yP : (Prod A A)} , (timesP xP yP) = (timesP yP xP))) structure Hom {A1 : Type} {A2 : Type} (No1 : (NonassociativeNondistributiveRing A1)) (No2 : (NonassociativeNondistributiveRing A2)) : Type := (hom : (A1 → A2)) (pres_times : (∀ {x1 x2 : A1} , (hom ((times No1) x1 x2)) = ((times No2) (hom x1) (hom x2)))) (pres_one : (hom (one No1)) = (one No2)) (pres_inv : (∀ {x1 : A1} , (hom ((inv No1) x1)) = ((inv No2) (hom x1)))) (pres_plus : (∀ {x1 x2 : A1} , (hom ((plus No1) x1 x2)) = ((plus No2) (hom x1) (hom x2)))) structure RelInterp {A1 : Type} {A2 : Type} (No1 : (NonassociativeNondistributiveRing A1)) (No2 : (NonassociativeNondistributiveRing A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_times : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((times No1) x1 x2) ((times No2) y1 y2)))))) (interp_one : (interp (one No1) (one No2))) (interp_inv : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((inv No1) x1) ((inv No2) y1))))) (interp_plus : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((plus No1) x1 x2) ((plus No2) y1 y2)))))) inductive NonassociativeNondistributiveRingTerm : Type | timesL : (NonassociativeNondistributiveRingTerm → (NonassociativeNondistributiveRingTerm → NonassociativeNondistributiveRingTerm)) | oneL : NonassociativeNondistributiveRingTerm | invL : (NonassociativeNondistributiveRingTerm → NonassociativeNondistributiveRingTerm) | plusL : (NonassociativeNondistributiveRingTerm → (NonassociativeNondistributiveRingTerm → NonassociativeNondistributiveRingTerm)) open NonassociativeNondistributiveRingTerm inductive ClNonassociativeNondistributiveRingTerm (A : Type) : Type | sing : (A → ClNonassociativeNondistributiveRingTerm) | timesCl : (ClNonassociativeNondistributiveRingTerm → (ClNonassociativeNondistributiveRingTerm → ClNonassociativeNondistributiveRingTerm)) | oneCl : ClNonassociativeNondistributiveRingTerm | invCl : (ClNonassociativeNondistributiveRingTerm → ClNonassociativeNondistributiveRingTerm) | plusCl : (ClNonassociativeNondistributiveRingTerm → (ClNonassociativeNondistributiveRingTerm → ClNonassociativeNondistributiveRingTerm)) open ClNonassociativeNondistributiveRingTerm inductive OpNonassociativeNondistributiveRingTerm (n : ℕ) : Type | v : ((fin n) → OpNonassociativeNondistributiveRingTerm) | timesOL : (OpNonassociativeNondistributiveRingTerm → (OpNonassociativeNondistributiveRingTerm → OpNonassociativeNondistributiveRingTerm)) | oneOL : OpNonassociativeNondistributiveRingTerm | invOL : (OpNonassociativeNondistributiveRingTerm → OpNonassociativeNondistributiveRingTerm) | plusOL : (OpNonassociativeNondistributiveRingTerm → (OpNonassociativeNondistributiveRingTerm → OpNonassociativeNondistributiveRingTerm)) open OpNonassociativeNondistributiveRingTerm inductive OpNonassociativeNondistributiveRingTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpNonassociativeNondistributiveRingTerm2) | sing2 : (A → OpNonassociativeNondistributiveRingTerm2) | timesOL2 : (OpNonassociativeNondistributiveRingTerm2 → (OpNonassociativeNondistributiveRingTerm2 → OpNonassociativeNondistributiveRingTerm2)) | oneOL2 : OpNonassociativeNondistributiveRingTerm2 | invOL2 : (OpNonassociativeNondistributiveRingTerm2 → OpNonassociativeNondistributiveRingTerm2) | plusOL2 : (OpNonassociativeNondistributiveRingTerm2 → (OpNonassociativeNondistributiveRingTerm2 → OpNonassociativeNondistributiveRingTerm2)) open OpNonassociativeNondistributiveRingTerm2 def simplifyCl {A : Type} : ((ClNonassociativeNondistributiveRingTerm A) → (ClNonassociativeNondistributiveRingTerm A)) | (timesCl oneCl x) := x | (timesCl x oneCl) := x | (timesCl x1 x2) := (timesCl (simplifyCl x1) (simplifyCl x2)) | oneCl := oneCl | (invCl x1) := (invCl (simplifyCl x1)) | (plusCl x1 x2) := (plusCl (simplifyCl x1) (simplifyCl x2)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpNonassociativeNondistributiveRingTerm n) → (OpNonassociativeNondistributiveRingTerm n)) | (timesOL oneOL x) := x | (timesOL x oneOL) := x | (timesOL x1 x2) := (timesOL (simplifyOpB x1) (simplifyOpB x2)) | oneOL := oneOL | (invOL x1) := (invOL (simplifyOpB x1)) | (plusOL x1 x2) := (plusOL (simplifyOpB x1) (simplifyOpB x2)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpNonassociativeNondistributiveRingTerm2 n A) → (OpNonassociativeNondistributiveRingTerm2 n A)) | (timesOL2 oneOL2 x) := x | (timesOL2 x oneOL2) := x | (timesOL2 x1 x2) := (timesOL2 (simplifyOp x1) (simplifyOp x2)) | oneOL2 := oneOL2 | (invOL2 x1) := (invOL2 (simplifyOp x1)) | (plusOL2 x1 x2) := (plusOL2 (simplifyOp x1) (simplifyOp x2)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((NonassociativeNondistributiveRing A) → (NonassociativeNondistributiveRingTerm → A)) | No (timesL x1 x2) := ((times No) (evalB No x1) (evalB No x2)) | No oneL := (one No) | No (invL x1) := ((inv No) (evalB No x1)) | No (plusL x1 x2) := ((plus No) (evalB No x1) (evalB No x2)) def evalCl {A : Type} : ((NonassociativeNondistributiveRing A) → ((ClNonassociativeNondistributiveRingTerm A) → A)) | No (sing x1) := x1 | No (timesCl x1 x2) := ((times No) (evalCl No x1) (evalCl No x2)) | No oneCl := (one No) | No (invCl x1) := ((inv No) (evalCl No x1)) | No (plusCl x1 x2) := ((plus No) (evalCl No x1) (evalCl No x2)) def evalOpB {A : Type} {n : ℕ} : ((NonassociativeNondistributiveRing A) → ((vector A n) → ((OpNonassociativeNondistributiveRingTerm n) → A))) | No vars (v x1) := (nth vars x1) | No vars (timesOL x1 x2) := ((times No) (evalOpB No vars x1) (evalOpB No vars x2)) | No vars oneOL := (one No) | No vars (invOL x1) := ((inv No) (evalOpB No vars x1)) | No vars (plusOL x1 x2) := ((plus No) (evalOpB No vars x1) (evalOpB No vars x2)) def evalOp {A : Type} {n : ℕ} : ((NonassociativeNondistributiveRing A) → ((vector A n) → ((OpNonassociativeNondistributiveRingTerm2 n A) → A))) | No vars (v2 x1) := (nth vars x1) | No vars (sing2 x1) := x1 | No vars (timesOL2 x1 x2) := ((times No) (evalOp No vars x1) (evalOp No vars x2)) | No vars oneOL2 := (one No) | No vars (invOL2 x1) := ((inv No) (evalOp No vars x1)) | No vars (plusOL2 x1 x2) := ((plus No) (evalOp No vars x1) (evalOp No vars x2)) def inductionB {P : (NonassociativeNondistributiveRingTerm → Type)} : ((∀ (x1 x2 : NonassociativeNondistributiveRingTerm) , ((P x1) → ((P x2) → (P (timesL x1 x2))))) → ((P oneL) → ((∀ (x1 : NonassociativeNondistributiveRingTerm) , ((P x1) → (P (invL x1)))) → ((∀ (x1 x2 : NonassociativeNondistributiveRingTerm) , ((P x1) → ((P x2) → (P (plusL x1 x2))))) → (∀ (x : NonassociativeNondistributiveRingTerm) , (P x)))))) | ptimesl p1l pinvl pplusl (timesL x1 x2) := (ptimesl _ _ (inductionB ptimesl p1l pinvl pplusl x1) (inductionB ptimesl p1l pinvl pplusl x2)) | ptimesl p1l pinvl pplusl oneL := p1l | ptimesl p1l pinvl pplusl (invL x1) := (pinvl _ (inductionB ptimesl p1l pinvl pplusl x1)) | ptimesl p1l pinvl pplusl (plusL x1 x2) := (pplusl _ _ (inductionB ptimesl p1l pinvl pplusl x1) (inductionB ptimesl p1l pinvl pplusl x2)) def inductionCl {A : Type} {P : ((ClNonassociativeNondistributiveRingTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((∀ (x1 x2 : (ClNonassociativeNondistributiveRingTerm A)) , ((P x1) → ((P x2) → (P (timesCl x1 x2))))) → ((P oneCl) → ((∀ (x1 : (ClNonassociativeNondistributiveRingTerm A)) , ((P x1) → (P (invCl x1)))) → ((∀ (x1 x2 : (ClNonassociativeNondistributiveRingTerm A)) , ((P x1) → ((P x2) → (P (plusCl x1 x2))))) → (∀ (x : (ClNonassociativeNondistributiveRingTerm A)) , (P x))))))) | psing ptimescl p1cl pinvcl ppluscl (sing x1) := (psing x1) | psing ptimescl p1cl pinvcl ppluscl (timesCl x1 x2) := (ptimescl _ _ (inductionCl psing ptimescl p1cl pinvcl ppluscl x1) (inductionCl psing ptimescl p1cl pinvcl ppluscl x2)) | psing ptimescl p1cl pinvcl ppluscl oneCl := p1cl | psing ptimescl p1cl pinvcl ppluscl (invCl x1) := (pinvcl _ (inductionCl psing ptimescl p1cl pinvcl ppluscl x1)) | psing ptimescl p1cl pinvcl ppluscl (plusCl x1 x2) := (ppluscl _ _ (inductionCl psing ptimescl p1cl pinvcl ppluscl x1) (inductionCl psing ptimescl p1cl pinvcl ppluscl x2)) def inductionOpB {n : ℕ} {P : ((OpNonassociativeNondistributiveRingTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((∀ (x1 x2 : (OpNonassociativeNondistributiveRingTerm n)) , ((P x1) → ((P x2) → (P (timesOL x1 x2))))) → ((P oneOL) → ((∀ (x1 : (OpNonassociativeNondistributiveRingTerm n)) , ((P x1) → (P (invOL x1)))) → ((∀ (x1 x2 : (OpNonassociativeNondistributiveRingTerm n)) , ((P x1) → ((P x2) → (P (plusOL x1 x2))))) → (∀ (x : (OpNonassociativeNondistributiveRingTerm n)) , (P x))))))) | pv ptimesol p1ol pinvol pplusol (v x1) := (pv x1) | pv ptimesol p1ol pinvol pplusol (timesOL x1 x2) := (ptimesol _ _ (inductionOpB pv ptimesol p1ol pinvol pplusol x1) (inductionOpB pv ptimesol p1ol pinvol pplusol x2)) | pv ptimesol p1ol pinvol pplusol oneOL := p1ol | pv ptimesol p1ol pinvol pplusol (invOL x1) := (pinvol _ (inductionOpB pv ptimesol p1ol pinvol pplusol x1)) | pv ptimesol p1ol pinvol pplusol (plusOL x1 x2) := (pplusol _ _ (inductionOpB pv ptimesol p1ol pinvol pplusol x1) (inductionOpB pv ptimesol p1ol pinvol pplusol x2)) def inductionOp {n : ℕ} {A : Type} {P : ((OpNonassociativeNondistributiveRingTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((∀ (x1 x2 : (OpNonassociativeNondistributiveRingTerm2 n A)) , ((P x1) → ((P x2) → (P (timesOL2 x1 x2))))) → ((P oneOL2) → ((∀ (x1 : (OpNonassociativeNondistributiveRingTerm2 n A)) , ((P x1) → (P (invOL2 x1)))) → ((∀ (x1 x2 : (OpNonassociativeNondistributiveRingTerm2 n A)) , ((P x1) → ((P x2) → (P (plusOL2 x1 x2))))) → (∀ (x : (OpNonassociativeNondistributiveRingTerm2 n A)) , (P x)))))))) | pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 (v2 x1) := (pv2 x1) | pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 (sing2 x1) := (psing2 x1) | pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 (timesOL2 x1 x2) := (ptimesol2 _ _ (inductionOp pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 x1) (inductionOp pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 x2)) | pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 oneOL2 := p1ol2 | pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 (invOL2 x1) := (pinvol2 _ (inductionOp pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 x1)) | pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 (plusOL2 x1 x2) := (pplusol2 _ _ (inductionOp pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 x1) (inductionOp pv2 psing2 ptimesol2 p1ol2 pinvol2 pplusol2 x2)) def stageB : (NonassociativeNondistributiveRingTerm → (Staged NonassociativeNondistributiveRingTerm)) | (timesL x1 x2) := (stage2 timesL (codeLift2 timesL) (stageB x1) (stageB x2)) | oneL := (Now oneL) | (invL x1) := (stage1 invL (codeLift1 invL) (stageB x1)) | (plusL x1 x2) := (stage2 plusL (codeLift2 plusL) (stageB x1) (stageB x2)) def stageCl {A : Type} : ((ClNonassociativeNondistributiveRingTerm A) → (Staged (ClNonassociativeNondistributiveRingTerm A))) | (sing x1) := (Now (sing x1)) | (timesCl x1 x2) := (stage2 timesCl (codeLift2 timesCl) (stageCl x1) (stageCl x2)) | oneCl := (Now oneCl) | (invCl x1) := (stage1 invCl (codeLift1 invCl) (stageCl x1)) | (plusCl x1 x2) := (stage2 plusCl (codeLift2 plusCl) (stageCl x1) (stageCl x2)) def stageOpB {n : ℕ} : ((OpNonassociativeNondistributiveRingTerm n) → (Staged (OpNonassociativeNondistributiveRingTerm n))) | (v x1) := (const (code (v x1))) | (timesOL x1 x2) := (stage2 timesOL (codeLift2 timesOL) (stageOpB x1) (stageOpB x2)) | oneOL := (Now oneOL) | (invOL x1) := (stage1 invOL (codeLift1 invOL) (stageOpB x1)) | (plusOL x1 x2) := (stage2 plusOL (codeLift2 plusOL) (stageOpB x1) (stageOpB x2)) def stageOp {n : ℕ} {A : Type} : ((OpNonassociativeNondistributiveRingTerm2 n A) → (Staged (OpNonassociativeNondistributiveRingTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | (timesOL2 x1 x2) := (stage2 timesOL2 (codeLift2 timesOL2) (stageOp x1) (stageOp x2)) | oneOL2 := (Now oneOL2) | (invOL2 x1) := (stage1 invOL2 (codeLift1 invOL2) (stageOp x1)) | (plusOL2 x1 x2) := (stage2 plusOL2 (codeLift2 plusOL2) (stageOp x1) (stageOp x2)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (timesT : ((Repr A) → ((Repr A) → (Repr A)))) (oneT : (Repr A)) (invT : ((Repr A) → (Repr A))) (plusT : ((Repr A) → ((Repr A) → (Repr A)))) end NonassociativeNondistributiveRing
4c1f3daa02765899f40643e4d48835643b888757
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/dynamics/ergodic/measure_preserving.lean
fd40d553097f79933a74ad0e1c28ecec94d2acb4
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,581
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import measure_theory.constructions.prod /-! # Measure preserving maps We say that `f : α → β` is a measure preserving map w.r.t. measures `μ : measure α` and `ν : measure β` if `f` is measurable and `map f μ = ν`. In this file we define the predicate `measure_theory.measure_preserving` and prove its basic properties. We use the term "measure preserving" because in many applications `α = β` and `μ = ν`. ## References Partially based on [this](https://www.isa-afp.org/browser_info/current/AFP/Ergodic_Theory/Measure_Preserving_Transformations.html) Isabelle formalization. ## Tags measure preserving map, measure -/ variables {α β γ δ : Type*} [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] namespace measure_theory open measure function set variables {μa : measure α} {μb : measure β} {μc : measure γ} {μd : measure δ} /-- `f` is a measure preserving map w.r.t. measures `μa` and `μb` if `f` is measurable and `map f μa = μb`. -/ @[protect_proj] structure measure_preserving (f : α → β) (μa : measure α . volume_tac) (μb : measure β . volume_tac) : Prop := (measurable : measurable f) (map_eq : map f μa = μb) namespace measure_preserving protected lemma id (μ : measure α) : measure_preserving id μ μ := ⟨measurable_id, map_id⟩ protected lemma quasi_measure_preserving {f : α → β} (hf : measure_preserving f μa μb) : quasi_measure_preserving f μa μb := ⟨hf.1, hf.2.absolutely_continuous⟩ lemma comp {g : β → γ} {f : α → β} (hg : measure_preserving g μb μc) (hf : measure_preserving f μa μb) : measure_preserving (g ∘ f) μa μc := ⟨hg.1.comp hf.1, by rw [← map_map hg.1 hf.1, hf.2, hg.2]⟩ protected lemma sigma_finite {f : α → β} (hf : measure_preserving f μa μb) [sigma_finite μb] : sigma_finite μa := sigma_finite.of_map μa hf.1 (by rwa hf.map_eq) lemma measure_preimage {f : α → β} (hf : measure_preserving f μa μb) {s : set β} (hs : measurable_set s) : μa (f ⁻¹' s) = μb s := by rw [← hf.map_eq, map_apply hf.1 hs] protected lemma iterate {f : α → α} (hf : measure_preserving f μa μa) : ∀ n, measure_preserving (f^[n]) μa μa | 0 := measure_preserving.id μa | (n + 1) := (iterate n).comp hf 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`. -/ by_cases ha : μa = 0, { rw [← hf.map_eq, ha, zero_prod, (map f).map_zero, zero_prod], exact ⟨this, (map _).map_zero⟩ }, haveI : μa.ae.ne_bot := ae_ne_bot.2 ha, rcases hg.exists with ⟨x, hx⟩, haveI : sigma_finite μc := sigma_finite.of_map _ hgm.of_uncurry_left (by rwa hx), clear hx x, 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.prod t) = indicator (f ⁻¹' s) (λ y, μd t) x, { refine hg.mono (λ x hx, _), simp only [mk_preimage_prod_right_fn_eq_if, indicator_apply, mem_preimage], split_ifs, { rw [← map_apply hgm.of_uncurry_left ht, hx] }, { exact 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`. -/ 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 variables {μ : measure α} {f : α → α} {s : set α} /-- If `μ univ < n * μ s` and `f` is a map preserving measure `μ`, then for some `x ∈ s` and `0 < m < n`, `f^[m] x ∈ s`. -/ lemma exists_mem_image_mem_of_volume_lt_mul_volume (hf : measure_preserving f μ μ) (hs : measurable_set s) {n : ℕ} (hvol : μ (univ : set α) < n * μ s) : ∃ (x ∈ s) (m ∈ Ioo 0 n), f^[m] x ∈ s := begin have A : ∀ m, measurable_set (f^[m] ⁻¹' s) := λ m, (hf.iterate m).measurable hs, have B : ∀ m, μ (f^[m] ⁻¹' s) = μ s, from λ m, (hf.iterate m).measure_preimage hs, have : μ (univ : set α) < (finset.range n).sum (λ m, μ (f^[m] ⁻¹' s)), by simpa only [B, nsmul_eq_mul, finset.sum_const, finset.card_range], rcases exists_nonempty_inter_of_measure_univ_lt_sum_measure μ (λ m hm, A m) this with ⟨i, hi, j, hj, hij, x, hxi, hxj⟩, -- without `tactic.skip` Lean closes the extra goal but it takes a long time; not sure why wlog hlt : i < j := hij.lt_or_lt using [i j, j i] tactic.skip, { simp only [set.mem_preimage, finset.mem_range] at hi hj hxi hxj, refine ⟨f^[i] x, hxi, j - i, ⟨nat.sub_pos_of_lt hlt, lt_of_le_of_lt (j.sub_le i) hj⟩, _⟩, rwa [← iterate_add_apply, nat.sub_add_cancel hlt.le] }, { exact λ hi hj hij hxi hxj, this hj hi hij.symm hxj hxi } end /-- A self-map preserving a finite measure is conservative: if `μ s ≠ 0`, then at least one point `x ∈ s` comes back to `s` under iterations of `f`. Actually, a.e. point of `s` comes back to `s` infinitely many times, see `measure_theory.measure_preserving.conservative` and theorems about `measure_theory.conservative`. -/ lemma exists_mem_image_mem [is_finite_measure μ] (hf : measure_preserving f μ μ) (hs : measurable_set s) (hs' : μ s ≠ 0) : ∃ (x ∈ s) (m ≠ 0), f^[m] x ∈ s := begin rcases ennreal.exists_nat_mul_gt hs' (measure_ne_top μ (univ : set α)) with ⟨N, hN⟩, rcases hf.exists_mem_image_mem_of_volume_lt_mul_volume hs hN with ⟨x, hx, m, hm, hmx⟩, exact ⟨x, hx, m, hm.1.ne', hmx⟩ end end measure_preserving end measure_theory
7d0c6179480736985a2a06e2fc4c672d7f506923
618003631150032a5676f229d13a079ac875ff77
/src/tactic/simp_rw.lean
34c058ff931ff5ede1f3899e12a9c1200eb865e4
[ "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
2,341
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen The `simp_rw` tactic, a mix of `simp` and `rewrite`. -/ import tactic.core /-! # The `simp_rw` tactic This module defines a tactic `simp_rw` which functions as a mix of `simp` and `rw`. Like `rw`, it applies each rewrite rule in the given order, but like `simp` it repeatedly applies these rules and also under binders like `∀ x, ...`, `∃ x, ...` and `λ x, ...`. ## Implementation notes The tactic works by taking each rewrite rule in turn and applying `simp only` to it. Arguments to `simp_rw` are of the format used by `rw` and are translated to their equivalents for `simp`. -/ namespace tactic.interactive open interactive interactive.types tactic /-- `simp_rw` functions as a mix of `simp` and `rw`. Like `rw`, it applies each rewrite rule in the given order, but like `simp` it repeatedly applies these rules and also under binders like `∀ x, ...`, `∃ x, ...` and `λ x, ...`. Usage: - `simp_rw [lemma_1, ..., lemma_n]` will rewrite the goal by applying the lemmas in that order. A lemma preceded by `←` is applied in the reverse direction. - `simp_rw [lemma_1, ..., lemma_n] at h₁ ... hₙ` will rewrite the given hypotheses. - `simp_rw [...] at ⊢ h₁ ... hₙ` rewrites the goal as well as the given hypotheses. - `simp_rw [...] at *` rewrites in the whole context: all hypotheses and the goal. Lemmas passed to `simp_rw` must be expressions that are valid arguments to `simp`. For example, neither `simp` nor `rw` can solve the following, but `simp_rw` can: ```lean example {α β : Type} {f : α → β} {t : set β} : (∀ s, f '' s ⊆ t) = ∀ s : set α, ∀ x ∈ s, x ∈ f ⁻¹' t := by simp_rw [set.image_subset_iff, set.subset_def] ``` -/ meta def simp_rw (q : parse rw_rules) (l : parse location) : tactic unit := q.rules.mmap' (λ rule, do let simp_arg := if rule.symm then simp_arg_type.symm_expr rule.rule else simp_arg_type.expr rule.rule, save_info rule.pos, simp none tt [simp_arg] [] l) -- equivalent to `simp only [rule] at l` add_tactic_doc { name := "simp_rw", category := doc_category.tactic, decl_names := [`tactic.interactive.simp_rw], tags := ["simplification"] } end tactic.interactive
1aefa86c7f8fd9c9340a1133774a4ab90e12c831
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/limits/lattice.lean
b40b444fc6e2630614332af0daff34497a75b518
[ "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
7,308
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import category_theory.category.preorder import category_theory.limits.shapes.finite_limits import order.complete_lattice /-! # Limits in lattice categories are given by infimums and supremums. -/ universes u open category_theory open category_theory.limits namespace category_theory.limits.complete_lattice section semilattice variables {α : Type u} variables {J : Type u} [small_category J] [fin_category J] /-- The limit cone over any functor from a finite diagram into a `semilattice_inf_top`. -/ def finite_limit_cone [semilattice_inf_top α] (F : J ⥤ α) : limit_cone F := { cone := { X := finset.univ.inf F.obj, π := { app := λ j, hom_of_le (finset.inf_le (fintype.complete _)) } }, is_limit := { lift := λ s, hom_of_le (finset.le_inf (λ j _, (s.π.app j).down.down)) } } /-- The colimit cocone over any functor from a finite diagram into a `semilattice_sup_bot`. -/ def finite_colimit_cocone [semilattice_sup_bot α] (F : J ⥤ α) : colimit_cocone F := { cocone := { X := finset.univ.sup F.obj, ι := { app := λ i, hom_of_le (finset.le_sup (fintype.complete _)) } }, is_colimit := { desc := λ s, hom_of_le (finset.sup_le (λ j _, (s.ι.app j).down.down)) } } @[priority 100] -- see Note [lower instance priority] instance has_finite_limits_of_semilattice_inf_top [semilattice_inf_top α] : has_finite_limits α := ⟨λ J 𝒥₁ 𝒥₂, by exactI { has_limit := λ F, has_limit.mk (finite_limit_cone F) }⟩ @[priority 100] -- see Note [lower instance priority] instance has_finite_colimits_of_semilattice_sup_bot [semilattice_sup_bot α] : has_finite_colimits α := ⟨λ J 𝒥₁ 𝒥₂, by exactI { has_colimit := λ F, has_colimit.mk (finite_colimit_cocone F) }⟩ /-- The limit of a functor from a finite diagram into a `semilattice_inf_top` is the infimum of the objects in the image. -/ lemma finite_limit_eq_finset_univ_inf [semilattice_inf_top α] (F : J ⥤ α) : limit F = finset.univ.inf F.obj := (is_limit.cone_point_unique_up_to_iso (limit.is_limit F) (finite_limit_cone F).is_limit).to_eq /-- The colimit of a functor from a finite diagram into a `semilattice_sup_bot` is the supremum of the objects in the image. -/ lemma finite_colimit_eq_finset_univ_sup [semilattice_sup_bot α] (F : J ⥤ α) : colimit F = finset.univ.sup F.obj := (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (finite_colimit_cocone F).is_colimit).to_eq /-- A finite product in the category of a `semilattice_inf_top` is the same as the infimum. -/ lemma finite_product_eq_finset_inf [semilattice_inf_top α] {ι : Type u} [decidable_eq ι] [fintype ι] (f : ι → α) : (∏ f) = (fintype.elems ι).inf f := (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) (finite_limit_cone (discrete.functor f)).is_limit).to_eq /-- A finite coproduct in the category of a `semilattice_sup_bot` is the same as the supremum. -/ lemma finite_coproduct_eq_finset_sup [semilattice_sup_bot α] {ι : Type u} [decidable_eq ι] [fintype ι] (f : ι → α) : (∐ f) = (fintype.elems ι).sup f := (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (finite_colimit_cocone (discrete.functor f)).is_colimit).to_eq /-- The binary product in the category of a `semilattice_inf_top` is the same as the infimum. -/ @[simp] lemma prod_eq_inf [semilattice_inf_top α] (x y : α) : limits.prod x y = x ⊓ y := calc limits.prod x y = limit (pair x y) : rfl ... = finset.univ.inf (pair x y).obj : by rw finite_limit_eq_finset_univ_inf (pair x y) ... = x ⊓ (y ⊓ ⊤) : rfl -- Note: finset.inf is realized as a fold, hence the definitional equality ... = x ⊓ y : by rw inf_top_eq /-- The binary coproduct in the category of a `semilattice_sup_bot` is the same as the supremum. -/ @[simp] lemma coprod_eq_sup [semilattice_sup_bot α] (x y : α) : limits.coprod x y = x ⊔ y := calc limits.coprod x y = colimit (pair x y) : rfl ... = finset.univ.sup (pair x y).obj : by rw finite_colimit_eq_finset_univ_sup (pair x y) ... = x ⊔ (y ⊔ ⊥) : rfl -- Note: finset.sup is realized as a fold, hence the definitional equality ... = x ⊔ y : by rw sup_bot_eq /-- The pullback in the category of a `semilattice_inf_top` is the same as the infimum over the objects. -/ @[simp] lemma pullback_eq_inf [semilattice_inf_top α] {x y z : α} (f : x ⟶ z) (g : y ⟶ z) : pullback f g = x ⊓ y := calc pullback f g = limit (cospan f g) : rfl ... = finset.univ.inf (cospan f g).obj : by rw finite_limit_eq_finset_univ_inf ... = z ⊓ (x ⊓ (y ⊓ ⊤)) : rfl ... = z ⊓ (x ⊓ y) : by rw inf_top_eq ... = x ⊓ y : inf_eq_right.mpr (inf_le_of_left_le f.le) /-- The pushout in the category of a `semilattice_sup_bot` is the same as the supremum over the objects. -/ @[simp] lemma pushout_eq_sup [semilattice_sup_bot α] (x y z : α) (f : z ⟶ x) (g : z ⟶ y) : pushout f g = x ⊔ y := calc pushout f g = colimit (span f g) : rfl ... = finset.univ.sup (span f g).obj : by rw finite_colimit_eq_finset_univ_sup ... = z ⊔ (x ⊔ (y ⊔ ⊥)) : rfl ... = z ⊔ (x ⊔ y) : by rw sup_bot_eq ... = x ⊔ y : sup_eq_right.mpr (le_sup_of_le_left f.le) end semilattice variables {α : Type u} [complete_lattice α] variables {J : Type u} [small_category J] /-- The limit cone over any functor into a complete lattice. -/ def limit_cone (F : J ⥤ α) : limit_cone F := { cone := { X := infi F.obj, π := { app := λ j, hom_of_le (complete_lattice.Inf_le _ _ (set.mem_range_self _)) } }, is_limit := { lift := λ s, hom_of_le (complete_lattice.le_Inf _ _ begin rintros _ ⟨j, rfl⟩, exact (s.π.app j).le, end) } } /-- The colimit cocone over any functor into a complete lattice. -/ def colimit_cocone (F : J ⥤ α) : colimit_cocone F := { cocone := { X := supr F.obj, ι := { app := λ j, hom_of_le (complete_lattice.le_Sup _ _ (set.mem_range_self _)) } }, is_colimit := { desc := λ s, hom_of_le (complete_lattice.Sup_le _ _ begin rintros _ ⟨j, rfl⟩, exact (s.ι.app j).le, end) } } -- It would be nice to only use the `Inf` half of the complete lattice, but -- this seems not to have been described separately. @[priority 100] -- see Note [lower instance priority] instance has_limits_of_complete_lattice : has_limits α := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, has_limit.mk (limit_cone F) } } @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_complete_lattice : has_colimits α := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk (colimit_cocone F) } } /-- The limit of a functor into a complete lattice is the infimum of the objects in the image. -/ lemma limit_eq_infi (F : J ⥤ α) : limit F = infi F.obj := (is_limit.cone_point_unique_up_to_iso (limit.is_limit F) (limit_cone F).is_limit).to_eq /-- The colimit of a functor into a complete lattice is the supremum of the objects in the image. -/ lemma colimit_eq_supr (F : J ⥤ α) : colimit F = supr F.obj := (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_cocone F).is_colimit).to_eq end category_theory.limits.complete_lattice
8faec8f560e4e99707cfc558bc33362472b0dace
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/matrix/notation.lean
2915fd7f8d4482f1573a8a023799eba99379c062
[ "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
14,453
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Eric Wieser -/ import data.matrix.basic import data.fin.vec_notation import tactic.fin_cases import algebra.big_operators.fin /-! # Matrix and vector notation This file includes `simp` lemmas for applying operations in `data.matrix.basic` to values built out of the matrix notation `![a, b] = vec_cons a (vec_cons b vec_empty)` defined in `data.fin.vec_notation`. This also provides the new notation `!![a, b; c, d] = ![![a, b], ![c, d]]`. This notation also works for empty matrices; `!![,,,] : matrix (fin 0) (fin 3)` and `!![;;;] : matrix (fin 3) (fin 0)`. ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vec_cons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations This file provide notation `!![a, b; c, d]` for matrices, which corresponds to `matrix.of ![![a, b], ![c, d]]`. A parser for `a, b; c, d`-style strings is provided as `matrix.entry_parser`, while `matrix.notation` provides the hook for the `!!` notation. Note that in lean 3 the pretty-printer will not show `!!` notation, instead showing the version with `of ![![...]]`. ## Examples Examples of usage can be found in the `test/matrix.lean` file. -/ namespace matrix universe u variables {α : Type u} {o n m : ℕ} {m' n' o' : Type*} open_locale matrix /-- Matrices can be reflected whenever their entries can. We insert an `@id (matrix m' n' α)` to prevent immediate decay to a function. -/ meta instance matrix.reflect [reflected_univ.{u}] [reflected_univ.{u_1}] [reflected_univ.{u_2}] [reflected _ α] [reflected _ m'] [reflected _ n'] [h : has_reflect (m' → n' → α)] : has_reflect (matrix m' n' α) := λ m, (by reflect_name : reflected _ @id.{(max u_1 u_2 u) + 1}).subst₂ ((by reflect_name : reflected _ @matrix.{u_1 u_2 u}).subst₃ `(_) `(_) `(_)) $ by { dunfold matrix, exact h m } section parser open lean open lean.parser open interactive open interactive.types /-- Parse the entries of a matrix -/ meta def entry_parser {α : Type} (p : parser α) : parser (Σ m n, fin m → fin n → α) := do -- a list of lists if the matrix has at least one row, or the number of columns if the matrix has -- zero rows. let p : parser (list (list α) ⊕ ℕ) := (sum.inl <$> ( (pure [] <* tk ";").repeat_at_least 1 <|> -- empty rows (sep_by_trailing (tk ";") $ sep_by_trailing (tk ",") p)) <|> (sum.inr <$> list.length <$> many (tk ","))), -- empty columns which ← p, match which with | (sum.inl l) := do h :: tl ← pure l, let n := h.length, l : list (vector α n) ← l.mmap (λ row, if h : row.length = n then pure (⟨row, h⟩ : vector α n) else interaction_monad.fail "Rows must be of equal length"), pure ⟨l.length, n, λ i j, (l.nth_le _ i.prop).nth j⟩ | (sum.inr n) := pure ⟨0, n, fin_zero_elim⟩ end -- Lean can't find this instance without some help. We only need it available in `Type 0`, and it is -- a massive amount of effort to make it universe-polymorphic. @[instance] meta def sigma_sigma_fin_matrix_has_reflect {α : Type} [has_reflect α] [reflected _ α] : has_reflect (Σ (m n : ℕ), fin m → fin n → α) := @sigma.reflect.{0 0} _ _ ℕ (λ m, Σ n, fin m → fin n → α) _ _ _ $ λ i, @sigma.reflect.{0 0} _ _ ℕ _ _ _ _ (λ j, infer_instance) /-- `!![a, b; c, d]` notation for matrices indexed by `fin m` and `fin n`. See the module docstring for details. -/ @[user_notation] meta def «notation» (_ : parse $ tk "!![") (val : parse (entry_parser (parser.pexpr 1) <* tk "]")) : parser pexpr := do let ⟨m, n, entries⟩ := val, let entry_vals := pi_fin.to_pexpr (pi_fin.to_pexpr ∘ entries), pure (``(@matrix.of (fin %%`(m)) (fin %%`(n)) _).app entry_vals) end parser variables (a b : ℕ) /-- Use `![...]` notation for displaying a `fin`-indexed matrix, for example: ``` #eval !![1, 2; 3, 4] + !![3, 4; 5, 6] -- !![4, 6; 8, 10] ``` -/ instance [has_repr α] : has_repr (matrix (fin m) (fin n) α) := { repr := λ f, "!![" ++ (string.intercalate "; " $ (list.fin_range m).map $ λ i, string.intercalate ", " $ (list.fin_range n).map (λ j, repr (f i j))) ++ "]" } @[simp] lemma cons_val' (v : n' → α) (B : fin m → n' → α) (i j) : vec_cons v B i j = vec_cons (v j) (λ i, B i j) i := by { refine fin.cases _ _ i; simp } @[simp] lemma head_val' (B : fin m.succ → n' → α) (j : n') : vec_head (λ i, B i j) = vec_head B j := rfl @[simp] lemma tail_val' (B : fin m.succ → n' → α) (j : n') : vec_tail (λ i, B i j) = λ i, vec_tail B i j := by { ext, simp [vec_tail] } section dot_product variables [add_comm_monoid α] [has_mul α] @[simp] lemma dot_product_empty (v w : fin 0 → α) : dot_product v w = 0 := finset.sum_empty @[simp] lemma cons_dot_product (x : α) (v : fin n → α) (w : fin n.succ → α) : dot_product (vec_cons x v) w = x * vec_head w + dot_product v (vec_tail w) := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] @[simp] lemma dot_product_cons (v : fin n.succ → α) (x : α) (w : fin n → α) : dot_product v (vec_cons x w) = vec_head v * x + dot_product (vec_tail v) w := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] @[simp] lemma cons_dot_product_cons (x : α) (v : fin n → α) (y : α) (w : fin n → α) : dot_product (vec_cons x v) (vec_cons y w) = x * y + dot_product v w := by simp end dot_product section col_row @[simp] lemma col_empty (v : fin 0 → α) : col v = vec_empty := empty_eq _ @[simp] lemma col_cons (x : α) (u : fin m → α) : col (vec_cons x u) = vec_cons (λ _, x) (col u) := by { ext i j, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma row_empty : row (vec_empty : fin 0 → α) = λ _, vec_empty := by { ext, refl } @[simp] lemma row_cons (x : α) (u : fin m → α) : row (vec_cons x u) = λ _, vec_cons x u := by { ext, refl } end col_row section transpose @[simp] lemma transpose_empty_rows (A : matrix m' (fin 0) α) : Aᵀ = of ![] := empty_eq _ @[simp] lemma transpose_empty_cols (A : matrix (fin 0) m' α) : Aᵀ = of (λ i, ![]) := funext (λ i, empty_eq _) @[simp] lemma cons_transpose (v : n' → α) (A : matrix (fin m) n' α) : (of (vec_cons v A))ᵀ = of (λ i, vec_cons (v i) (Aᵀ i)) := by { ext i j, refine fin.cases _ _ j; simp } @[simp] lemma head_transpose (A : matrix m' (fin n.succ) α) : vec_head (of.symm Aᵀ) = vec_head ∘ (of.symm A) := rfl @[simp] lemma tail_transpose (A : matrix m' (fin n.succ) α) : vec_tail (of.symm Aᵀ) = (vec_tail ∘ A)ᵀ := by { ext i j, refl } end transpose section mul variables [semiring α] @[simp] lemma empty_mul [fintype n'] (A : matrix (fin 0) n' α) (B : matrix n' o' α) : A ⬝ B = of ![] := empty_eq _ @[simp] lemma empty_mul_empty (A : matrix m' (fin 0) α) (B : matrix (fin 0) o' α) : A ⬝ B = 0 := rfl @[simp] lemma mul_empty [fintype n'] (A : matrix m' n' α) (B : matrix n' (fin 0) α) : A ⬝ B = of (λ _, ![]) := funext (λ _, empty_eq _) lemma mul_val_succ [fintype n'] (A : matrix (fin m.succ) n' α) (B : matrix n' o' α) (i : fin m) (j : o') : (A ⬝ B) i.succ j = (of (vec_tail (of.symm A)) ⬝ B) i j := rfl @[simp] lemma cons_mul [fintype n'] (v : n' → α) (A : fin m → n' → α) (B : matrix n' o' α) : of (vec_cons v A) ⬝ B = of (vec_cons (vec_mul v B) (of.symm (of A ⬝ B))) := by { ext i j, refine fin.cases _ _ i, { refl }, simp [mul_val_succ], } end mul section vec_mul variables [semiring α] @[simp] lemma empty_vec_mul (v : fin 0 → α) (B : matrix (fin 0) o' α) : vec_mul v B = 0 := rfl @[simp] lemma vec_mul_empty [fintype n'] (v : n' → α) (B : matrix n' (fin 0) α) : vec_mul v B = ![] := empty_eq _ @[simp] lemma cons_vec_mul (x : α) (v : fin n → α) (B : fin n.succ → o' → α) : vec_mul (vec_cons x v) (of B) = x • (vec_head B) + vec_mul v (of $ vec_tail B) := by { ext i, simp [vec_mul] } @[simp] lemma vec_mul_cons (v : fin n.succ → α) (w : o' → α) (B : fin n → o' → α) : vec_mul v (of $ vec_cons w B) = vec_head v • w + vec_mul (vec_tail v) (of B) := by { ext i, simp [vec_mul] } end vec_mul section mul_vec variables [semiring α] @[simp] lemma empty_mul_vec [fintype n'] (A : matrix (fin 0) n' α) (v : n' → α) : mul_vec A v = ![] := empty_eq _ @[simp] lemma mul_vec_empty (A : matrix m' (fin 0) α) (v : fin 0 → α) : mul_vec A v = 0 := rfl @[simp] lemma cons_mul_vec [fintype n'] (v : n' → α) (A : fin m → n' → α) (w : n' → α) : mul_vec (of $ vec_cons v A) w = vec_cons (dot_product v w) (mul_vec (of A) w) := by { ext i, refine fin.cases _ _ i; simp [mul_vec] } @[simp] lemma mul_vec_cons {α} [comm_semiring α] (A : m' → (fin n.succ) → α) (x : α) (v : fin n → α) : mul_vec (of A) (vec_cons x v) = (x • vec_head ∘ A) + mul_vec (of (vec_tail ∘ A)) v := by { ext i, simp [mul_vec, mul_comm] } end mul_vec section vec_mul_vec variables [semiring α] @[simp] lemma empty_vec_mul_vec (v : fin 0 → α) (w : n' → α) : vec_mul_vec v w = ![] := empty_eq _ @[simp] lemma vec_mul_vec_empty (v : m' → α) (w : fin 0 → α) : vec_mul_vec v w = λ _, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_vec_mul_vec (x : α) (v : fin m → α) (w : n' → α) : vec_mul_vec (vec_cons x v) w = vec_cons (x • w) (vec_mul_vec v w) := by { ext i, refine fin.cases _ _ i; simp [vec_mul_vec] } @[simp] lemma vec_mul_vec_cons (v : m' → α) (x : α) (w : fin n → α) : vec_mul_vec v (vec_cons x w) = λ i, v i • vec_cons x w := by { ext i j, rw [vec_mul_vec, pi.smul_apply, smul_eq_mul] } end vec_mul_vec section smul variables [semiring α] @[simp] lemma smul_mat_empty {m' : Type*} (x : α) (A : fin 0 → m' → α) : x • A = ![] := empty_eq _ @[simp] lemma smul_mat_cons (x : α) (v : n' → α) (A : fin m → n' → α) : x • vec_cons v A = vec_cons (x • v) (x • A) := by { ext i, refine fin.cases _ _ i; simp } end smul section minor @[simp] lemma minor_empty (A : matrix m' n' α) (row : fin 0 → m') (col : o' → n') : minor A row col = ![] := empty_eq _ @[simp] lemma minor_cons_row (A : matrix m' n' α) (i : m') (row : fin m → m') (col : o' → n') : minor A (vec_cons i row) col = vec_cons (λ j, A i (col j)) (minor A row col) := by { ext i j, refine fin.cases _ _ i; simp [minor] } end minor section vec2_and_vec3 section one variables [has_zero α] [has_one α] lemma one_fin_two : (1 : matrix (fin 2) (fin 2) α) = !![1, 0; 0, 1] := by { ext i j, fin_cases i; fin_cases j; refl } lemma one_fin_three : (1 : matrix (fin 3) (fin 3) α) = !![1, 0, 0; 0, 1, 0; 0, 0, 1] := by { ext i j, fin_cases i; fin_cases j; refl } end one lemma mul_fin_two [add_comm_monoid α] [has_mul α] (a₁₁ a₁₂ a₂₁ a₂₂ b₁₁ b₁₂ b₂₁ b₂₂ : α) : !![a₁₁, a₁₂; a₂₁, a₂₂] ⬝ !![b₁₁, b₁₂; b₂₁, b₂₂] = !![a₁₁ * b₁₁ + a₁₂ * b₂₁, a₁₁ * b₁₂ + a₁₂ * b₂₂; a₂₁ * b₁₁ + a₂₂ * b₂₁, a₂₁ * b₁₂ + a₂₂ * b₂₂] := begin ext i j, fin_cases i; fin_cases j; simp [matrix.mul, dot_product, fin.sum_univ_succ] end lemma mul_fin_three [add_comm_monoid α] [has_mul α] (a₁₁ a₁₂ a₁₃ a₂₁ a₂₂ a₂₃ a₃₁ a₃₂ a₃₃ b₁₁ b₁₂ b₁₃ b₂₁ b₂₂ b₂₃ b₃₁ b₃₂ b₃₃ : α) : !![a₁₁, a₁₂, a₁₃; a₂₁, a₂₂, a₂₃; a₃₁, a₃₂, a₃₃] ⬝ !![b₁₁, b₁₂, b₁₃; b₂₁, b₂₂, b₂₃; b₃₁, b₃₂, b₃₃] = !![a₁₁*b₁₁ + a₁₂*b₂₁ + a₁₃*b₃₁, a₁₁*b₁₂ + a₁₂*b₂₂ + a₁₃*b₃₂, a₁₁*b₁₃ + a₁₂*b₂₃ + a₁₃*b₃₃; a₂₁*b₁₁ + a₂₂*b₂₁ + a₂₃*b₃₁, a₂₁*b₁₂ + a₂₂*b₂₂ + a₂₃*b₃₂, a₂₁*b₁₃ + a₂₂*b₂₃ + a₂₃*b₃₃; a₃₁*b₁₁ + a₃₂*b₂₁ + a₃₃*b₃₁, a₃₁*b₁₂ + a₃₂*b₂₂ + a₃₃*b₃₂, a₃₁*b₁₃ + a₃₂*b₂₃ + a₃₃*b₃₃] := begin ext i j, fin_cases i; fin_cases j; simp [matrix.mul, dot_product, fin.sum_univ_succ, ←add_assoc], end lemma vec2_eq {a₀ a₁ b₀ b₁ : α} (h₀ : a₀ = b₀) (h₁ : a₁ = b₁) : ![a₀, a₁] = ![b₀, b₁] := by subst_vars lemma vec3_eq {a₀ a₁ a₂ b₀ b₁ b₂ : α} (h₀ : a₀ = b₀) (h₁ : a₁ = b₁) (h₂ : a₂ = b₂) : ![a₀, a₁, a₂] = ![b₀, b₁, b₂] := by subst_vars lemma vec2_add [has_add α] (a₀ a₁ b₀ b₁ : α) : ![a₀, a₁] + ![b₀, b₁] = ![a₀ + b₀, a₁ + b₁] := by rw [cons_add_cons, cons_add_cons, empty_add_empty] lemma vec3_add [has_add α] (a₀ a₁ a₂ b₀ b₁ b₂ : α) : ![a₀, a₁, a₂] + ![b₀, b₁, b₂] = ![a₀ + b₀, a₁ + b₁, a₂ + b₂] := by rw [cons_add_cons, cons_add_cons, cons_add_cons, empty_add_empty] lemma smul_vec2 {R : Type*} [has_smul R α] (x : R) (a₀ a₁ : α) : x • ![a₀, a₁] = ![x • a₀, x • a₁] := by rw [smul_cons, smul_cons, smul_empty] lemma smul_vec3 {R : Type*} [has_smul R α] (x : R) (a₀ a₁ a₂ : α) : x • ![a₀, a₁, a₂] = ![x • a₀, x • a₁, x • a₂] := by rw [smul_cons, smul_cons, smul_cons, smul_empty] variables [add_comm_monoid α] [has_mul α] lemma vec2_dot_product' {a₀ a₁ b₀ b₁ : α} : ![a₀, a₁] ⬝ᵥ ![b₀, b₁] = a₀ * b₀ + a₁ * b₁ := by rw [cons_dot_product_cons, cons_dot_product_cons, dot_product_empty, add_zero] @[simp] lemma vec2_dot_product (v w : fin 2 → α) : v ⬝ᵥ w = v 0 * w 0 + v 1 * w 1 := vec2_dot_product' lemma vec3_dot_product' {a₀ a₁ a₂ b₀ b₁ b₂ : α} : ![a₀, a₁, a₂] ⬝ᵥ ![b₀, b₁, b₂] = a₀ * b₀ + a₁ * b₁ + a₂ * b₂ := by rw [cons_dot_product_cons, cons_dot_product_cons, cons_dot_product_cons, dot_product_empty, add_zero, add_assoc] @[simp] lemma vec3_dot_product (v w : fin 3 → α) : v ⬝ᵥ w = v 0 * w 0 + v 1 * w 1 + v 2 * w 2 := vec3_dot_product' end vec2_and_vec3 end matrix
3f14aa5428f0dce1788e06530e538129e8d932a2
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/univIssue.lean
0b00401e85a4832fe7fc5d5107602ae312cd4f53
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
308
lean
universes u v @[inline] def ex1 {σ : Type u} {m : Type u → Type v} [Functor m] {α : Type u} (x : StateT σ m α) (s : σ) : m α := Functor.map Prod.fst (x s) @[inline] def ex2 {σ : Type u} {m : Type u → Type v} [Functor m] {α : Type u} (x : StateT σ m α) (s : σ) : m α := Prod.fst <$> x s
0b303fe00a398cf5eba671326e1c4b5125aa3605
dfbb669f3f58ceb57cb207dcfab5726a07425b03
/vscode-lean4/test/test-fixtures/simple/Main.lean
5e66ab0fffd0eb0b23eb2d515fd585359f8cffe3
[ "Apache-2.0" ]
permissive
leanprover/vscode-lean4
8bcf7f06867b3c1d42007fe6da863a7a17444dbb
6ef0bfa668bdeaad0979e6df10551d42fcc01094
refs/heads/master
1,692,247,771,767
1,691,608,804,000
1,691,608,804,000
325,845,305
64
24
Apache-2.0
1,694,176,429,000
1,609,435,614,000
TypeScript
UTF-8
Lean
false
false
113
lean
import Test.Version def main : IO Unit := IO.println s!"Hello: {getLeanVersion}" #eval main #eval IO.appPath
46eee1d8db6ddc6b19719272c3823e9701c003be
87a08a8e9b222ec02f3327dca4ae24590c1b3de9
/src/topology/uniform_space/basic.lean
3689b3ad799e53c09c41fe676ae8428ce5c01c42
[ "Apache-2.0" ]
permissive
naussicaa/mathlib
86d05223517a39e80920549a8052f9cf0e0b77b8
1ef2c2df20cf45c21675d855436228c7ae02d47a
refs/heads/master
1,592,104,950,080
1,562,073,069,000
1,562,073,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
42,148
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, Patrick Massot Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact The central concept of uniform spaces is its uniformity: a filter relating two elements of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter.basic order.filter.lift topology.constructions open set lattice filter classical local attribute [instance, priority 0] prop_decidable set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) := by ext p; cases p; simp only [mem_comp_rel]; tauto /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, {p | prod.swap p ∈ r} ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, comp_rel t t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.refl _ } def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.refl _ } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[extensionality] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity local notation `𝓤` := uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), comp_rel s s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := assume s hs, show {x | (a, a) ∈ s} ∈ f, from univ_mem_sets' $ assume b, refl_mem_uniformity hs lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, comp_rel t t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), comp_rel t t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f): (𝓤 α).lift (λs, f (comp_rel s s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (comp_rel s s)) = ((𝓤 α).lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal ... = (𝓤 α).lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity lemma mem_nhds_uniformity_iff {x : α} {s : set α} : s ∈ nhds x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_sets_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_comap_uniformity {x : α} : nhds x = (𝓤 α).comap (prod.mk x) := by ext s; rw [mem_nhds_uniformity_iff, mem_comap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, (𝓤 α).sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_uniformity {x : α} : nhds x = (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ s}) := begin ext s, rw [mem_lift'_sets], tactic.swap, apply monotone_preimage, simp [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, (𝓤 α).sets_of_superset h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ nhds x := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ nhds y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (nhds a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (nhds a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_comp monotone_preimage $ monotone_comp monotone_preimage monotone_principal) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ monotone_comp monotone_preimage hg ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (nhds a).lift (λs:set α, (nhds b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ nhds (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed [uniform_space α] {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := have s ∈ (𝓤 α).lift' closure, by rwa [uniformity_eq_uniformity_closure] at h, have ∃ t ∈ 𝓤 α, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, (𝓤 α).sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /- uniform continuity -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, {x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := @tendsto_const_uniformity _ _ _ b (𝓤 α) lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf lemma uniform_continuous.continuous [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_continuous_at.mpr $ assume a, calc map f (nhds a) ≤ (map (λp:α×α, (f p.1, f p.2)) (𝓤 α)).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) : begin rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2], exact (lift'_mono' $ assume s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩, ⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩), exact monotone_preimage, exact monotone_preimage end ... ≤ nhds (f a) : by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _) end uniform_space end local notation `𝓤` := uniformity section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₂, exact (mem_singleton_iff.1 h).symm ▸ h₁ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced_eq_comap, mem_nhds_uniformity_iff, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff.1 $ mem_nhds_left _ ht⟩ } end } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap_comp {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap_comp lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] (f : α → β) : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := eq_of_nhds_eq_nhds $ assume a, begin simp [nhds_induced_eq_comap, nhds_eq_uniformity, nhds_eq_uniformity], change (u.uniformity.comap (λp:α×α, (f p.1, f p.2))).lift' (preimage (λa', (a, a'))) = comap f ((𝓤 β).lift' (preimage (λb, (f a, b)))), rw [comap_lift'_eq monotone_preimage, comap_lift'_eq2 monotone_preimage], exact rfl end lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, begin rw [infi_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, (@nhds_eq_uniformity α (u i) a).symm), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (le_infi $ assume i, to_topological_space_mono $ infi_le _ _) (have infi u = ⊤, from top_unique $ le_infi $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (infi u) = ⊤, from this.symm ▸ to_topological_space_top, this.symm ▸ le_top)) lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi, to_topological_space_infi], apply congr rfl, funext x, exact to_topological_space_infi end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space unit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ nhds a) : tendsto f (nhds a) (nhds (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod (𝓤 α) (𝓤 β)) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp] lemma mem_map_sets_iff' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_sets_iff lemma mem_uniformity_of_uniform_continuous_invarant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_sets_iff'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma to_topological_space_prod [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_sets_iff.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ comp_rel tα tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ comp_rel tβ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_sets_iff.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_sets_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff.1 (mem_nhds_sets hs.1 xs)) univ_mem_sets) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_sets_of_superset (union_mem_uniformity_sum univ_mem_sets (mem_nhds_uniformity_iff.1 (mem_nhds_sets hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff.2 _), rcases mem_map_sets_iff.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff.2 _), rcases mem_map_sets_iff.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity [uniform_space α] [uniform_space β] : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ comp_rel m n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases compact_elim_finite_subcover_image hs hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂
b7a0a5d58789534482d4b296e9f6c4339d9506cc
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/data/rat/basic.lean
29ad7db2cf8513c07aff73fb3c124e3c8c07a3f7
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
24,803
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.nat.gcd data.pnat.basic data.int.sqrt data.equiv.encodable algebra.group algebra.ordered_group algebra.group_power algebra.euclidean_domain algebra.ordered_field tactic.norm_cast tactic.lift /-! # Basics for the Rational Numbers ## Summary We define a rational number `q` as a structure `{ num, denom, pos, cop }`, where - `num` is the numerator of `q`, - `denom` is the denominator of `q`, - `pos` is a proof that `denom > 0`, and - `cop` is a proof `num` and `denom` are coprime. We then define the expected (discrete) field structure on `ℚ` and prove basic lemmas about it. Moreoever, we provide the expected casts from `ℕ` and `ℤ` into `ℚ`, i.e. `(↑n : ℚ) = n / 1`. ## Main Definitions - `rat` is the structure encoding `ℚ`. - `rat.mk n d` constructs a rational number `q = n / d` from `n d : ℤ`. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom -/ /-- `rat`, or `ℚ`, is the type of rational numbers. It is defined as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and `d` are coprime. This representation is preferred to the quotient because without periodic reduction, the numerator and denominator can grow exponentially (for example, adding 1/2 to itself repeatedly). -/ structure rat := mk' :: (num : ℤ) (denom : ℕ) (pos : 0 < denom) (cop : num.nat_abs.coprime denom) notation `ℚ` := rat namespace rat protected def repr : ℚ → string | ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else _root_.repr n ++ "/" ++ _root_.repr d instance : has_repr ℚ := ⟨rat.repr⟩ instance : has_to_string ℚ := ⟨rat.repr⟩ meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩ instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // 0 < d ∧ n.nat_abs.coprime d}) ⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩ /-- Embed an integer as a rational number -/ def of_int (n : ℤ) : ℚ := ⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩ instance : has_zero ℚ := ⟨of_int 0⟩ instance : has_one ℚ := ⟨of_int 1⟩ instance : inhabited ℚ := ⟨0⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/ def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ := let n' := n.nat_abs, g := n'.gcd d in ⟨n / g, d / g, begin apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2, simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _) end, begin have : int.nat_abs (n / ↑g) = n' / g, { cases int.nat_abs_eq n with e e; rw e, { refl }, rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl }, exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) }, rw this, exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos) end⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we define `n / 0 = 0` by convention. -/ def mk_nat (n : ℤ) (d : ℕ) : ℚ := if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩ /-- Form the quotient `n / d` where `n d : ℤ`. -/ def mk : ℤ → ℤ → ℚ | n (d : ℕ) := mk_nat n d | n -[1+ d] := mk_pnat (-n) d.succ_pnat localized "infix ` /. `:70 := rat.mk" in rat theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d := by change n /. d with dite _ _ _; simp [ne_of_gt h] theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl @[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl @[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 := by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl @[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 := by by_cases n = 0; simp [*, mk_nat] @[simp] theorem zero_mk (n) : 0 /. n = 0 := by cases n; simp [mk] private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a := int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b @[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 := begin constructor; intro h; [skip, {subst a, simp}], have : ∀ {a b}, mk_pnat a b = 0 → a = 0, { intros a b e, cases b with b h, injection e with e, apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e }, cases b with b; simp [mk, mk_nat] at h, { simp [mt (congr_arg int.of_nat) b0] at h, exact this h }, { apply neg_inj, simp [this h] } end theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0), a /. b = c /. d ↔ a * d = c * b := suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b, begin intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hb], all_goals { cases d with d d; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hd], all_goals { rw this, try {refl} } }, { change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b, constructor; intro h; apply neg_inj; simpa [left_distrib, neg_add_eq_iff_eq_add, eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h }, { change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ, constructor; intro h; apply neg_inj; simpa [left_distrib, eq_comm] using h }, { change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ, simp [left_distrib, sub_eq_add_neg], cc } end, begin intros, simp [mk_pnat], constructor; intro h, { cases h with ha hb, have ha, { have dv := @gcd_abs_dvd_left, have := int.eq_mul_of_div_eq_right dv ha, rw ← int.mul_div_assoc _ dv at this, exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have hb, { have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b, have := nat.eq_mul_of_div_eq_right dv hb, rw ← nat.mul_div_assoc _ dv at this, exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, { refine int.coe_nat_ne_zero.2 (ne_of_gt _), apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption }, apply eq_of_mul_eq_mul_right m0, simpa [mul_comm, mul_left_comm] using congr (congr_arg (*) ha.symm) (congr_arg coe hb) }, { suffices : ∀ a c, a * d = c * b → a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d, { cases this a.nat_abs c.nat_abs (by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂, have hs := congr_arg int.sign h, simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb), int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs, conv in a { rw ← int.sign_mul_nat_abs a }, conv in c { rw ← int.sign_mul_nat_abs c }, rw [int.mul_div_assoc, int.mul_div_assoc], exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩, all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } }, intros a c h, suffices bd : b / a.gcd b = d / c.gcd d, { refine ⟨_, bd⟩, apply nat.eq_of_mul_eq_mul_left hb, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd, ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] }, suffices : ∀ {a c : ℕ} (b>0) (d>0), a * d = c * b → b / a.gcd b ≤ d / c.gcd d, { exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) }, intros a c b hb d hd h, have gb0 := nat.gcd_pos_of_pos_right a hb, have gd0 := nat.gcd_pos_of_pos_right c hd, apply nat.le_of_dvd, apply (nat.le_div_iff_mul_le _ _ gd0).2, simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _), apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left, refine ⟨c / c.gcd d, _⟩, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)], apply congr_arg (/ c.gcd d), rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] } end @[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) : (a * c) /. (b * c) = a /. b := begin by_cases b0 : b = 0, { subst b0, simp }, apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc] end @[simp] theorem num_denom : ∀ {a : ℚ}, a.num /. a.denom = a | ⟨n, d, h, (c:_=1)⟩ := show mk_nat n d = _, by simp [mk_nat, ne_of_gt h, mk_pnat, c] theorem num_denom' {n d h c} : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom.symm theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' @[elab_as_eliminator] def {u} num_denom_cases_on {C : ℚ → Sort u} : ∀ (a : ℚ) (H : ∀ n d, 0 < d → (int.nat_abs n).coprime d → C (n /. d)), C a | ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c @[elab_as_eliminator] def {u} num_denom_cases_on' {C : ℚ → Sort u} (a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a := num_denom_cases_on a $ λ n d h c, H n d $ ne_of_gt h theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := begin cases e : a /. b with n d h c, rw [rat.num_denom', rat.mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.dvd_of_dvd_mul_right _), have := congr_arg int.nat_abs e, simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this] end theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b := begin by_cases b0 : b = 0, {simp [b0]}, cases e : a /. b with n d h c, rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _), rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp end protected def add : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_add ℚ := ⟨rat.add⟩ theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ) (fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂}, f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂) (f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0) (a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0) (H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d), f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) : f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc, rw fv, have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁), have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂), exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc)) end @[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b + c /. d = (a * d + c * b) /. (b * d) := begin apply lift_binop_eq rat.add; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, calc (n₁ * d₂ + n₂ * d₁) * (b * d) = (n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm] ... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂] ... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm] end protected def neg : ℚ → ℚ | ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩ instance : has_neg ℚ := ⟨rat.neg⟩ @[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b := begin by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, show rat.mk' _ _ _ _ = _, rw num_denom', have d0 := ne_of_gt (int.coe_nat_lt.2 h₁), apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha, simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁] end protected def mul : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_mul ℚ := ⟨rat.mul⟩ @[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : (a /. b) * (c /. d) = (a * c) /. (b * d) := begin apply lift_binop_eq rat.mul; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, cc end protected def inv : ℚ → ℚ | ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩ | ⟨0, d, h, c⟩ := 0 | ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩ instance : has_inv ℚ := ⟨rat.inv⟩ @[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a := begin by_cases a0 : a = 0, { subst a0, simp, refl }, by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha, refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _, { cases n with n; [cases n with n, skip], { refl }, { change int.of_nat n.succ with (n+1:ℕ), unfold rat.inv, rw num_denom' }, { unfold rat.inv, rw num_denom', refl } }, have n0 : n ≠ 0, { refine mt (λ (n0 : n = 0), _) a0, subst n0, simp at ha, exact (mk_eq_zero b0).1 ha }, have d0 := ne_of_gt (int.coe_nat_lt.2 h), have ha := (mk_eq b0 d0).1 ha, apply (mk_eq n0 a0).2, cc end variables (a b c : ℚ) protected theorem add_zero : a + 0 = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem zero_add : 0 + a = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem add_comm : a + b = b + a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂]; cc protected theorem add_assoc : a + b + c = a + (b + c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm] protected theorem add_left_neg : -a + a = 0 := num_denom_cases_on' a $ λ n d h, by simp [h] protected theorem mul_one : a * 1 = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem one_mul : 1 * a = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem mul_comm : a * b = b * a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂, mul_comm] protected theorem mul_assoc : a * b * c = a * (b * c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm] protected theorem add_mul : (a + b) * c = a * c + b * c := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero]; refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _; simp [mul_add, mul_comm, mul_assoc, mul_left_comm] protected theorem mul_add : a * (b + c) = a * b + a * c := by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a] protected theorem zero_ne_one : 0 ≠ (1:ℚ) := mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 := num_denom_cases_on' a $ λ n d h a0, have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0, by simp [h, n0, mul_comm]; exact eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0) protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h) instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance instance : field ℚ := { zero := 0, add := rat.add, neg := rat.neg, one := 1, mul := rat.mul, inv := rat.inv, zero_add := rat.zero_add, add_zero := rat.add_zero, add_comm := rat.add_comm, add_assoc := rat.add_assoc, add_left_neg := rat.add_left_neg, mul_one := rat.mul_one, one_mul := rat.one_mul, mul_comm := rat.mul_comm, mul_assoc := rat.mul_assoc, left_distrib := rat.mul_add, right_distrib := rat.add_mul, zero_ne_one := rat.zero_ne_one, mul_inv_cancel := rat.mul_inv_cancel, inv_zero := rfl } /- Extra instances to short-circuit type class resolution -/ instance : division_ring ℚ := by apply_instance instance : integral_domain ℚ := by apply_instance -- TODO(Mario): this instance slows down data.real.basic --instance : domain ℚ := by apply_instance instance : nonzero_comm_ring ℚ := by apply_instance instance : comm_ring ℚ := by apply_instance --instance : ring ℚ := by apply_instance instance : comm_semiring ℚ := by apply_instance instance : semiring ℚ := by apply_instance instance : add_comm_group ℚ := by apply_instance instance : add_group ℚ := by apply_instance instance : add_comm_monoid ℚ := by apply_instance instance : add_monoid ℚ := by apply_instance instance : add_left_cancel_semigroup ℚ := by apply_instance instance : add_right_cancel_semigroup ℚ := by apply_instance instance : add_comm_semigroup ℚ := by apply_instance instance : add_semigroup ℚ := by apply_instance instance : comm_monoid ℚ := by apply_instance instance : monoid ℚ := by apply_instance instance : comm_semigroup ℚ := by apply_instance instance : semigroup ℚ := by apply_instance theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b - c /. d = (a * d - c * b) /. (b * d) := by simp [b0, d0, sub_eq_add_neg] @[simp] lemma denom_neg_eq_denom : ∀ q : ℚ, (-q).denom = q.denom | ⟨_, d, _, _⟩ := rfl @[simp] lemma num_neg_eq_neg_num : ∀ q : ℚ, (-q).num = -(q.num) | ⟨n, _, _, _⟩ := rfl @[simp] lemma num_zero : rat.num 0 = 0 := rfl lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 := have q = q.num /. q.denom, from num_denom.symm, by simpa [hq] lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 := ⟨λ _, by simp *, zero_of_num_zero⟩ lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 := assume : q.num = 0, h $ zero_of_num_zero this @[simp] lemma num_one : (1 : ℚ).num = 1 := rfl @[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 := ne_of_gt q.pos lemma eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.denom = q.num * p.denom := begin conv_lhs { rw [←(@num_denom p), ←(@num_denom q)] }, apply rat.mk_eq, { exact_mod_cast p.denom_ne_zero }, { exact_mod_cast q.denom_ne_zero } end lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 := assume : n = 0, hq $ by simpa [this] using hqnd lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 := assume : d = 0, hq $ by simpa [this] using hqnd lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 := assume : n /. d = 0, h $ (mk_eq_zero hd).1 this lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) := have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa, have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa, suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom), by simpa using this, by simp [mul_def hq' hr', -num_denom] lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) := if hr : r.num = 0 then have hr' : r = 0, from zero_of_num_zero hr, by simp * else calc q / r = q * r⁻¹ : div_eq_mul_inv ... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by simp ... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def ... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.denom := have hq : q ≠ 0, from assume : q = 0, hn $ (rat.mk_eq_zero hd).1 (by cc), have q.num /. q.denom = n /. d, by rwa [num_denom], have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this, begin existsi n / q.num, have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end, split, { rw int.div_mul_cancel hqdn }, { apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left, { apply rat.num_ne_zero_of_ne_zero hq }, repeat { assumption } } end theorem mk_pnat_num (n : ℤ) (d : ℕ+) : (mk_pnat n d).num = n / nat.gcd n.nat_abs d := by cases d; refl theorem mk_pnat_denom (n : ℤ) (d : ℕ+) : (mk_pnat n d).denom = d / nat.gcd n.nat_abs d := by cases d; refl theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num = (q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom = (q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num := by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom := by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) lemma add_num_denom (q r : ℚ) : q + r = ((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) := have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3, have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3, by conv_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] }; simp [mul_comm] section casts theorem coe_int_eq_mk : ∀ (z : ℤ), ↑z = z /. 1 | (n : ℕ) := show (n:ℚ) = n /. 1, by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl] | -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin induction n with n IH, {refl}, show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1, rw [neg_add, IH], simpa [show -1 = (-1) /. 1, from rfl] end theorem mk_eq_div (n d : ℤ) : n /. d = ((n : ℚ) / d) := begin by_cases d0 : d = 0, {simp [d0, div_zero]}, simp [division_def, coe_int_eq_mk, mul_def one_ne_zero d0] end theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z := (coe_int_eq_mk z).trans (of_int_eq_mk z).symm @[simp, norm_cast] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n := by rw coe_int_eq_of_int; refl @[simp, norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 := by rw coe_int_eq_of_int; refl lemma coe_int_num_of_denom_eq_one {q : ℚ} (hq : q.denom = 1) : ↑(q.num) = q := by { conv_rhs { rw [←(@num_denom q), hq] }, rw [coe_int_eq_mk], refl } instance : can_lift ℚ ℤ := ⟨coe, λ q, q.denom = 1, λ q hq, ⟨q.num, coe_int_num_of_denom_eq_one hq⟩⟩ theorem coe_nat_eq_mk (n : ℕ) : ↑n = n /. 1 := by rw [← int.cast_coe_nat, coe_int_eq_mk] @[simp, norm_cast] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n := by rw [← int.cast_coe_nat, coe_int_num] @[simp, norm_cast] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 := by rw [← int.cast_coe_nat, coe_int_denom] end casts lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num := by { conv_lhs { rw ←(@num_denom q) }, cases q, simp [div_num_denom] } @[simp] lemma mul_own_denom_eq_num {q : ℚ} : q * q.denom = q.num := begin suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by { conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] }, have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos), rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)] end end rat
15858b6b77408296cecd891d8424820975153e8a
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/e1.lean
a3496d42b2ef33a8522965b6475516c478910117
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
329
lean
definition Prop [inline] : Type.{1} := Type.{0} variable eq : forall {A : Type}, A → A → Prop variable N : Type.{1} variables a b c : N infix `=`:50 := eq check a = b variable f : Prop → N → N variable g : N → N → N precedence `+`:50 infixl + := f infixl + := g check a + b + c variable p : Prop check p + a + b + c
2cc44338acbcf134cb009d2d5eaadb659584ec16
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/linear_algebra/affine_space/affine_subspace.lean
9f7268b4262b269a1f0ed1cc2f851e8d10598f13
[ "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
45,070
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.affine_space.basic import linear_algebra.tensor_product import data.set.intervals.unordered_interval /-! # Affine spaces This file defines affine subspaces (over modules) and the affine span of a set of points. ## Main definitions * `affine_subspace k P` is the type of affine subspaces. Unlike affine spaces, affine subspaces are allowed to be empty, and lemmas that do not apply to empty affine subspaces have `nonempty` hypotheses. There is a `complete_lattice` structure on affine subspaces. * `affine_subspace.direction` gives the `submodule` spanned by the pairwise differences of points in an `affine_subspace`. There are various lemmas relating to the set of vectors in the `direction`, and relating the lattice structure on affine subspaces to that on their directions. * `affine_span` gives the affine subspace spanned by a set of points, with `vector_span` giving its direction. `affine_span` is defined in terms of `span_points`, which gives an explicit description of the points contained in the affine span; `span_points` itself should generally only be used when that description is required, with `affine_span` being the main definition for other purposes. Two other descriptions of the affine span are proved equivalent: it is the `Inf` of affine subspaces containing the points, and (if `[nontrivial k]`) it contains exactly those points that are affine combinations of points in the given set. ## Implementation notes `out_param` is used in the definiton of `add_torsor V P` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ noncomputable theory open_locale big_operators classical affine open set section variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space V P] include V /-- The submodule spanning the differences of a (possibly empty) set of points. -/ def vector_span (s : set P) : submodule k V := submodule.span k (s -ᵥ s) /-- The definition of `vector_span`, for rewriting. -/ lemma vector_span_def (s : set P) : vector_span k s = submodule.span k (s -ᵥ s) := rfl /-- `vector_span` is monotone. -/ lemma vector_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : vector_span k s₁ ≤ vector_span k s₂ := submodule.span_mono (vsub_self_mono h) variables (P) /-- The `vector_span` of the empty set is `⊥`. -/ @[simp] lemma vector_span_empty : vector_span k (∅ : set P) = (⊥ : submodule k V) := by rw [vector_span_def, vsub_empty, submodule.span_empty] variables {P} /-- The `vector_span` of a single point is `⊥`. -/ @[simp] lemma vector_span_singleton (p : P) : vector_span k ({p} : set P) = ⊥ := by simp [vector_span_def] /-- The `s -ᵥ s` lies within the `vector_span k s`. -/ lemma vsub_set_subset_vector_span (s : set P) : s -ᵥ s ⊆ ↑(vector_span k s) := submodule.subset_span /-- Each pairwise difference is in the `vector_span`. -/ lemma vsub_mem_vector_span {s : set P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : p1 -ᵥ p2 ∈ vector_span k s := vsub_set_subset_vector_span k s (vsub_mem_vsub hp1 hp2) /-- The points in the affine span of a (possibly empty) set of points. Use `affine_span` instead to get an `affine_subspace k P`. -/ def span_points (s : set P) : set P := {p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k s), p = v +ᵥ p1} /-- A point in a set is in its affine span. -/ lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k s | hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩ /-- A set is contained in its `span_points`. -/ lemma subset_span_points (s : set P) : s ⊆ span_points k s := λ p, mem_span_points k p s /-- The `span_points` of a set is nonempty if and only if that set is. -/ @[simp] lemma span_points_nonempty (s : set P) : (span_points k s).nonempty ↔ s.nonempty := begin split, { contrapose, rw [set.not_nonempty_iff_eq_empty, set.not_nonempty_iff_eq_empty], intro h, simp [h, span_points] }, { exact λ h, h.mono (subset_span_points _ _) } end /-- Adding a point in the affine span and a vector in the spanning submodule produces a point in the affine span. -/ lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V} (hp : p ∈ span_points k s) (hv : v ∈ vector_span k s) : v +ᵥ p ∈ span_points k s := begin rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv2p, vadd_vadd], use [p2, hp2, v + v2, (vector_span k s).add_mem hv hv2, rfl] end /-- Subtracting two points in the affine span produces a vector in the spanning submodule. -/ lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P} (hp1 : p1 ∈ span_points k s) (hp2 : p2 ∈ span_points k s) : p1 -ᵥ p2 ∈ vector_span k s := begin rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩, rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc], have hv1v2 : v1 - v2 ∈ vector_span k s, { rw sub_eq_add_neg, apply (vector_span k s).add_mem hv1, rw ←neg_one_smul k v2, exact (vector_span k s).smul_mem (-1 : k) hv2 }, refine (vector_span k s).add_mem _ hv1v2, exact vsub_mem_vector_span k hp1a hp2a end end /-- An `affine_subspace k P` is a subset of an `affine_space V P` that, if not empty, has an affine space structure induced by a corresponding subspace of the `module k V`. -/ structure affine_subspace (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] := (carrier : set P) (smul_vsub_vadd_mem : ∀ (c : k) {p1 p2 p3 : P}, p1 ∈ carrier → p2 ∈ carrier → p3 ∈ carrier → c • (p1 -ᵥ p2 : V) +ᵥ p3 ∈ carrier) namespace submodule variables {k V : Type*} [ring k] [add_comm_group V] [module k V] /-- Reinterpret `p : submodule k V` as an `affine_subspace k V`. -/ def to_affine_subspace (p : submodule k V) : affine_subspace k V := { carrier := p, smul_vsub_vadd_mem := λ c p₁ p₂ p₃ h₁ h₂ h₃, p.add_mem (p.smul_mem _ (p.sub_mem h₁ h₂)) h₃ } end submodule namespace affine_subspace variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] include V instance : has_coe (affine_subspace k P) (set P) := ⟨carrier⟩ instance : has_mem P (affine_subspace k P) := ⟨λ p s, p ∈ (s : set P)⟩ /-- A point is in an affine subspace coerced to a set if and only if it is in that affine subspace. -/ @[simp] lemma mem_coe (p : P) (s : affine_subspace k P) : p ∈ (s : set P) ↔ p ∈ s := iff.rfl variables {k P} /-- The direction of an affine subspace is the submodule spanned by the pairwise differences of points. (Except in the case of an empty affine subspace, where the direction is the zero submodule, every vector in the direction is the difference of two points in the affine subspace.) -/ def direction (s : affine_subspace k P) : submodule k V := vector_span k (s : set P) /-- The direction equals the `vector_span`. -/ lemma direction_eq_vector_span (s : affine_subspace k P) : s.direction = vector_span k (s : set P) := rfl /-- Alternative definition of the direction when the affine subspace is nonempty. This is defined so that the order on submodules (as used in the definition of `submodule.span`) can be used in the proof of `coe_direction_eq_vsub_set`, and is not intended to be used beyond that proof. -/ def direction_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : submodule k V := { carrier := (s : set P) -ᵥ s, zero_mem' := begin cases h with p hp, exact (vsub_self p) ▸ vsub_mem_vsub hp hp end, add_mem' := begin intros a b ha hb, rcases ha with ⟨p1, p2, hp1, hp2, rfl⟩, rcases hb with ⟨p3, p4, hp3, hp4, rfl⟩, rw [←vadd_vsub_assoc], refine vsub_mem_vsub _ hp4, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp3, rw one_smul end, smul_mem' := begin intros c v hv, rcases hv with ⟨p1, p2, hp1, hp2, rfl⟩, rw [←vadd_vsub (c • (p1 -ᵥ p2)) p2], refine vsub_mem_vsub _ hp2, exact s.smul_vsub_vadd_mem c hp1 hp2 hp2 end } /-- `direction_of_nonempty` gives the same submodule as `direction`. -/ lemma direction_of_nonempty_eq_direction {s : affine_subspace k P} (h : (s : set P).nonempty) : direction_of_nonempty h = s.direction := le_antisymm (vsub_set_subset_vector_span k s) (submodule.span_le.2 set.subset.rfl) /-- The set of vectors in the direction of a nonempty affine subspace is given by `vsub_set`. -/ lemma coe_direction_eq_vsub_set {s : affine_subspace k P} (h : (s : set P).nonempty) : (s.direction : set V) = (s : set P) -ᵥ s := direction_of_nonempty_eq_direction h ▸ rfl /-- A vector is in the direction of a nonempty affine subspace if and only if it is the subtraction of two vectors in the subspace. -/ lemma mem_direction_iff_eq_vsub {s : affine_subspace k P} (h : (s : set P).nonempty) (v : V) : v ∈ s.direction ↔ ∃ p1 ∈ s, ∃ p2 ∈ s, v = p1 -ᵥ p2 := begin rw [←set_like.mem_coe, coe_direction_eq_vsub_set h], exact ⟨λ ⟨p1, p2, hp1, hp2, hv⟩, ⟨p1, hp1, p2, hp2, hv.symm⟩, λ ⟨p1, hp1, p2, hp2, hv⟩, ⟨p1, p2, hp1, hp2, hv.symm⟩⟩ end /-- Adding a vector in the direction to a point in the subspace produces a point in the subspace. -/ lemma vadd_mem_of_mem_direction {s : affine_subspace k P} {v : V} (hv : v ∈ s.direction) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s := begin rw mem_direction_iff_eq_vsub ⟨p, hp⟩ at hv, rcases hv with ⟨p1, hp1, p2, hp2, hv⟩, rw hv, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp, rw one_smul end /-- Subtracting two points in the subspace produces a vector in the direction. -/ lemma vsub_mem_direction {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : (p1 -ᵥ p2) ∈ s.direction := vsub_mem_vector_span k hp1 hp2 /-- Adding a vector to a point in a subspace produces a point in the subspace if and only if the vector is in the direction. -/ lemma vadd_mem_iff_mem_direction {s : affine_subspace k P} (v : V) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s ↔ v ∈ s.direction := ⟨λ h, by simpa using vsub_mem_direction h hp, λ h, vadd_mem_of_mem_direction h hp⟩ /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the right. -/ lemma coe_direction_eq_vsub_set_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ p) '' s := begin rw coe_direction_eq_vsub_set ⟨p, hp⟩, refine le_antisymm _ _, { rintros v ⟨p1, p2, hp1, hp2, rfl⟩, exact ⟨p1 -ᵥ p2 +ᵥ p, vadd_mem_of_mem_direction (vsub_mem_direction hp1 hp2) hp, (vadd_vsub _ _)⟩ }, { rintros v ⟨p2, hp2, rfl⟩, exact ⟨p2, p, hp2, hp, rfl⟩ } end /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the left. -/ lemma coe_direction_eq_vsub_set_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ) p '' s := begin ext v, rw [set_like.mem_coe, ←submodule.neg_mem_iff, ←set_like.mem_coe, coe_direction_eq_vsub_set_right hp, set.mem_image_iff_bex, set.mem_image_iff_bex], conv_lhs { congr, funext, rw [←neg_vsub_eq_vsub_rev, neg_inj] } end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the right. -/ lemma mem_direction_iff_eq_vsub_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p2 -ᵥ p := begin rw [←set_like.mem_coe, coe_direction_eq_vsub_set_right hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the left. -/ lemma mem_direction_iff_eq_vsub_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p -ᵥ p2 := begin rw [←set_like.mem_coe, coe_direction_eq_vsub_set_left hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a result of subtracting that point on the right is in the direction if and only if the other point is in the subspace. -/ lemma vsub_right_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p2 -ᵥ p ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_right hp, simp end /-- Given a point in an affine subspace, a result of subtracting that point on the left is in the direction if and only if the other point is in the subspace. -/ lemma vsub_left_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p -ᵥ p2 ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_left hp, simp end /-- Two affine subspaces are equal if they have the same points. -/ @[ext] lemma ext {s1 s2 : affine_subspace k P} (h : (s1 : set P) = s2) : s1 = s2 := begin cases s1, cases s2, congr, exact h end /-- Two affine subspaces with the same direction and nonempty intersection are equal. -/ lemma ext_of_direction_eq {s1 s2 : affine_subspace k P} (hd : s1.direction = s2.direction) (hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 := begin ext p, have hq1 := set.mem_of_mem_inter_left hn.some_mem, have hq2 := set.mem_of_mem_inter_right hn.some_mem, split, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq2, rw ←hd, exact vsub_mem_direction hp hq1 }, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq1, rw hd, exact vsub_mem_direction hp hq2 } end instance to_add_torsor (s : affine_subspace k P) [nonempty s] : add_torsor s.direction s := { vadd := λ a b, ⟨(a:V) +ᵥ (b:P), vadd_mem_of_mem_direction a.2 b.2⟩, zero_vadd := by simp, add_vadd := λ a b c, by { ext, apply add_vadd }, vsub := λ a b, ⟨(a:P) -ᵥ (b:P), (vsub_left_mem_direction_iff_mem a.2 _).mpr b.2 ⟩, nonempty := by apply_instance, vsub_vadd' := λ a b, by { ext, apply add_torsor.vsub_vadd' }, vadd_vsub' := λ a b, by { ext, apply add_torsor.vadd_vsub' } } @[simp, norm_cast] lemma coe_vsub (s : affine_subspace k P) [nonempty s] (a b : s) : ↑(a -ᵥ b) = (a:P) -ᵥ (b:P) := rfl @[simp, norm_cast] lemma coe_vadd (s : affine_subspace k P) [nonempty s] (a : s.direction) (b : s) : ↑(a +ᵥ b) = (a:V) +ᵥ (b:P) := rfl /-- Two affine subspaces with nonempty intersection are equal if and only if their directions are equal. -/ lemma eq_iff_direction_eq_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : s₁ = s₂ ↔ s₁.direction = s₂.direction := ⟨λ h, h ▸ rfl, λ h, ext_of_direction_eq h ⟨p, h₁, h₂⟩⟩ /-- Construct an affine subspace from a point and a direction. -/ def mk' (p : P) (direction : submodule k V) : affine_subspace k P := { carrier := {q | ∃ v ∈ direction, q = v +ᵥ p}, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, begin rcases hp1 with ⟨v1, hv1, hp1⟩, rcases hp2 with ⟨v2, hv2, hp2⟩, rcases hp3 with ⟨v3, hv3, hp3⟩, use [c • (v1 - v2) + v3, direction.add_mem (direction.smul_mem c (direction.sub_mem hv1 hv2)) hv3], simp [hp1, hp2, hp3, vadd_vadd] end } /-- An affine subspace constructed from a point and a direction contains that point. -/ lemma self_mem_mk' (p : P) (direction : submodule k V) : p ∈ mk' p direction := ⟨0, ⟨direction.zero_mem, (zero_vadd _ _).symm⟩⟩ /-- An affine subspace constructed from a point and a direction contains the result of adding a vector in that direction to that point. -/ lemma vadd_mem_mk' {v : V} (p : P) {direction : submodule k V} (hv : v ∈ direction) : v +ᵥ p ∈ mk' p direction := ⟨v, hv, rfl⟩ /-- An affine subspace constructed from a point and a direction is nonempty. -/ lemma mk'_nonempty (p : P) (direction : submodule k V) : (mk' p direction : set P).nonempty := ⟨p, self_mem_mk' p direction⟩ /-- The direction of an affine subspace constructed from a point and a direction. -/ @[simp] lemma direction_mk' (p : P) (direction : submodule k V) : (mk' p direction).direction = direction := begin ext v, rw mem_direction_iff_eq_vsub (mk'_nonempty _ _), split, { rintros ⟨p1, ⟨v1, hv1, hp1⟩, p2, ⟨v2, hv2, hp2⟩, hv⟩, rw [hv, hp1, hp2, vadd_vsub_vadd_cancel_right], exact direction.sub_mem hv1 hv2 }, { exact λ hv, ⟨v +ᵥ p, vadd_mem_mk' _ hv, p, self_mem_mk' _ _, (vadd_vsub _ _).symm⟩ } end /-- Constructing an affine subspace from a point in a subspace and that subspace's direction yields the original subspace. -/ @[simp] lemma mk'_eq {s : affine_subspace k P} {p : P} (hp : p ∈ s) : mk' p s.direction = s := ext_of_direction_eq (direction_mk' p s.direction) ⟨p, set.mem_inter (self_mem_mk' _ _) hp⟩ /-- If an affine subspace contains a set of points, it contains the `span_points` of that set. -/ lemma span_points_subset_coe_of_subset_coe {s : set P} {s1 : affine_subspace k P} (h : s ⊆ s1) : span_points k s ⊆ s1 := begin rintros p ⟨p1, hp1, v, hv, hp⟩, rw hp, have hp1s1 : p1 ∈ (s1 : set P) := set.mem_of_mem_of_subset hp1 h, refine vadd_mem_of_mem_direction _ hp1s1, have hs : vector_span k s ≤ s1.direction := vector_span_mono k h, rw set_like.le_def at hs, rw ←set_like.mem_coe, exact set.mem_of_mem_of_subset hv hs end end affine_subspace section affine_span variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The affine span of a set of points is the smallest affine subspace containing those points. (Actually defined here in terms of spans in modules.) -/ def affine_span (s : set P) : affine_subspace k P := { carrier := span_points k s, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k hp3 ((vector_span k s).smul_mem c (vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k hp1 hp2)) } /-- The affine span, converted to a set, is `span_points`. -/ @[simp] lemma coe_affine_span (s : set P) : (affine_span k s : set P) = span_points k s := rfl /-- A set is contained in its affine span. -/ lemma subset_affine_span (s : set P) : s ⊆ affine_span k s := subset_span_points k s /-- The direction of the affine span is the `vector_span`. -/ lemma direction_affine_span (s : set P) : (affine_span k s).direction = vector_span k s := begin apply le_antisymm, { refine submodule.span_le.2 _, rintros v ⟨p1, p3, ⟨p2, hp2, v1, hv1, hp1⟩, ⟨p4, hp4, v2, hv2, hp3⟩, rfl⟩, rw [hp1, hp3, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, set_like.mem_coe], exact (vector_span k s).sub_mem ((vector_span k s).add_mem hv1 (vsub_mem_vector_span k hp2 hp4)) hv2 }, { exact vector_span_mono k (subset_span_points k s) } end /-- A point in a set is in its affine span. -/ lemma mem_affine_span {p : P} {s : set P} (hp : p ∈ s) : p ∈ affine_span k s := mem_span_points k p s hp end affine_span namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [S : affine_space V P] include S instance : complete_lattice (affine_subspace k P) := { sup := λ s1 s2, affine_span k (s1 ∪ s2), le_sup_left := λ s1 s2, set.subset.trans (set.subset_union_left s1 s2) (subset_span_points k _), le_sup_right := λ s1 s2, set.subset.trans (set.subset_union_right s1 s2) (subset_span_points k _), sup_le := λ s1 s2 s3 hs1 hs2, span_points_subset_coe_of_subset_coe (set.union_subset hs1 hs2), inf := λ s1 s2, mk (s1 ∩ s2) (λ c p1 p2 p3 hp1 hp2 hp3, ⟨s1.smul_vsub_vadd_mem c hp1.1 hp2.1 hp3.1, s2.smul_vsub_vadd_mem c hp1.2 hp2.2 hp3.2⟩), inf_le_left := λ _ _, set.inter_subset_left _ _, inf_le_right := λ _ _, set.inter_subset_right _ _, le_inf := λ _ _ _, set.subset_inter, top := { carrier := set.univ, smul_vsub_vadd_mem := λ _ _ _ _ _ _ _, set.mem_univ _ }, le_top := λ _ _ _, set.mem_univ _, bot := { carrier := ∅, smul_vsub_vadd_mem := λ _ _ _ _, false.elim }, bot_le := λ _ _, false.elim, Sup := λ s, affine_span k (⋃ s' ∈ s, (s' : set P)), Inf := λ s, mk (⋂ s' ∈ s, (s' : set P)) (λ c p1 p2 p3 hp1 hp2 hp3, set.mem_bInter_iff.2 $ λ s2 hs2, s2.smul_vsub_vadd_mem c (set.mem_bInter_iff.1 hp1 s2 hs2) (set.mem_bInter_iff.1 hp2 s2 hs2) (set.mem_bInter_iff.1 hp3 s2 hs2)), le_Sup := λ _ _ h, set.subset.trans (set.subset_bUnion_of_mem h) (subset_span_points k _), Sup_le := λ _ _ h, span_points_subset_coe_of_subset_coe (set.bUnion_subset h), Inf_le := λ _ _, set.bInter_subset_of_mem, le_Inf := λ _ _, set.subset_bInter, .. partial_order.lift (coe : affine_subspace k P → set P) (λ _ _, ext) } instance : inhabited (affine_subspace k P) := ⟨⊤⟩ /-- The `≤` order on subspaces is the same as that on the corresponding sets. -/ lemma le_def (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ (s1 : set P) ⊆ s2 := iff.rfl /-- One subspace is less than or equal to another if and only if all its points are in the second subspace. -/ lemma le_def' (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ ∀ p ∈ s1, p ∈ s2 := iff.rfl /-- The `<` order on subspaces is the same as that on the corresponding sets. -/ lemma lt_def (s1 s2 : affine_subspace k P) : s1 < s2 ↔ (s1 : set P) ⊂ s2 := iff.rfl /-- One subspace is not less than or equal to another if and only if it has a point not in the second subspace. -/ lemma not_le_iff_exists (s1 s2 : affine_subspace k P) : ¬ s1 ≤ s2 ↔ ∃ p ∈ s1, p ∉ s2 := set.not_subset /-- If a subspace is less than another, there is a point only in the second. -/ lemma exists_of_lt {s1 s2 : affine_subspace k P} (h : s1 < s2) : ∃ p ∈ s2, p ∉ s1 := set.exists_of_ssubset h /-- A subspace is less than another if and only if it is less than or equal to the second subspace and there is a point only in the second. -/ lemma lt_iff_le_and_exists (s1 s2 : affine_subspace k P) : s1 < s2 ↔ s1 ≤ s2 ∧ ∃ p ∈ s2, p ∉ s1 := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If an affine subspace is nonempty and contained in another with the same direction, they are equal. -/ lemma eq_of_direction_eq_of_nonempty_of_le {s₁ s₂ : affine_subspace k P} (hd : s₁.direction = s₂.direction) (hn : (s₁ : set P).nonempty) (hle : s₁ ≤ s₂) : s₁ = s₂ := let ⟨p, hp⟩ := hn in ext_of_direction_eq hd ⟨p, hp, hle hp⟩ variables (k V) /-- The affine span is the `Inf` of subspaces containing the given points. -/ lemma affine_span_eq_Inf (s : set P) : affine_span k s = Inf {s' | s ⊆ s'} := le_antisymm (span_points_subset_coe_of_subset_coe (set.subset_bInter (λ _ h, h))) (Inf_le (subset_span_points k _)) variables (P) /-- The Galois insertion formed by `affine_span` and coercion back to a set. -/ protected def gi : galois_insertion (affine_span k) (coe : affine_subspace k P → set P) := { choice := λ s _, affine_span k s, gc := λ s1 s2, ⟨λ h, set.subset.trans (subset_span_points k s1) h, span_points_subset_coe_of_subset_coe⟩, le_l_u := λ _, subset_span_points k _, choice_eq := λ _ _, rfl } /-- The span of the empty set is `⊥`. -/ @[simp] lemma span_empty : affine_span k (∅ : set P) = ⊥ := (affine_subspace.gi k V P).gc.l_bot /-- The span of `univ` is `⊤`. -/ @[simp] lemma span_univ : affine_span k (set.univ : set P) = ⊤ := eq_top_iff.2 $ subset_span_points k _ variables {P} /-- The affine span of a single point, coerced to a set, contains just that point. -/ @[simp] lemma coe_affine_span_singleton (p : P) : (affine_span k ({p} : set P) : set P) = {p} := begin ext x, rw [mem_coe, ←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_singleton p)) _, direction_affine_span], simp end /-- A point is in the affine span of a single point if and only if they are equal. -/ @[simp] lemma mem_affine_span_singleton (p1 p2 : P) : p1 ∈ affine_span k ({p2} : set P) ↔ p1 = p2 := by simp [←mem_coe] /-- The span of a union of sets is the sup of their spans. -/ lemma span_union (s t : set P) : affine_span k (s ∪ t) = affine_span k s ⊔ affine_span k t := (affine_subspace.gi k V P).gc.l_sup /-- The span of a union of an indexed family of sets is the sup of their spans. -/ lemma span_Union {ι : Type*} (s : ι → set P) : affine_span k (⋃ i, s i) = ⨆ i, affine_span k (s i) := (affine_subspace.gi k V P).gc.l_supr variables (P) /-- `⊤`, coerced to a set, is the whole set of points. -/ @[simp] lemma top_coe : ((⊤ : affine_subspace k P) : set P) = set.univ := rfl variables {P} /-- All points are in `⊤`. -/ lemma mem_top (p : P) : p ∈ (⊤ : affine_subspace k P) := set.mem_univ p variables (P) /-- The direction of `⊤` is the whole module as a submodule. -/ @[simp] lemma direction_top : (⊤ : affine_subspace k P).direction = ⊤ := begin cases S.nonempty with p, ext v, refine ⟨imp_intro submodule.mem_top, λ hv, _⟩, have hpv : (v +ᵥ p -ᵥ p : V) ∈ (⊤ : affine_subspace k P).direction := vsub_mem_direction (mem_top k V _) (mem_top k V _), rwa vadd_vsub at hpv end /-- `⊥`, coerced to a set, is the empty set. -/ @[simp] lemma bot_coe : ((⊥ : affine_subspace k P) : set P) = ∅ := rfl variables {P} /-- No points are in `⊥`. -/ lemma not_mem_bot (p : P) : p ∉ (⊥ : affine_subspace k P) := set.not_mem_empty p variables (P) /-- The direction of `⊥` is the submodule `⊥`. -/ @[simp] lemma direction_bot : (⊥ : affine_subspace k P).direction = ⊥ := by rw [direction_eq_vector_span, bot_coe, vector_span_def, vsub_empty, submodule.span_empty] variables {k V P} /-- A nonempty affine subspace is `⊤` if and only if its direction is `⊤`. -/ @[simp] lemma direction_eq_top_iff_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : s.direction = ⊤ ↔ s = ⊤ := begin split, { intro hd, rw ←direction_top k V P at hd, refine ext_of_direction_eq hd _, simp [h] }, { rintro rfl, simp } end /-- The inf of two affine subspaces, coerced to a set, is the intersection of the two sets of points. -/ @[simp] lemma inf_coe (s1 s2 : affine_subspace k P) : ((s1 ⊓ s2) : set P) = s1 ∩ s2 := rfl /-- A point is in the inf of two affine subspaces if and only if it is in both of them. -/ lemma mem_inf_iff (p : P) (s1 s2 : affine_subspace k P) : p ∈ s1 ⊓ s2 ↔ p ∈ s1 ∧ p ∈ s2 := iff.rfl /-- The direction of the inf of two affine subspaces is less than or equal to the inf of their directions. -/ lemma direction_inf (s1 s2 : affine_subspace k P) : (s1 ⊓ s2).direction ≤ s1.direction ⊓ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact le_inf (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_left _ _)) hp)) (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_right _ _)) hp)) end /-- If two affine subspaces have a point in common, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := begin ext v, rw [submodule.mem_inf, ←vadd_mem_iff_mem_direction v h₁, ←vadd_mem_iff_mem_direction v h₂, ←vadd_mem_iff_mem_direction v ((mem_inf_iff p s₁ s₂).2 ⟨h₁, h₂⟩), mem_inf_iff] end /-- If two affine subspaces have a point in their inf, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem_inf {s₁ s₂ : affine_subspace k P} {p : P} (h : p ∈ s₁ ⊓ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := direction_inf_of_mem ((mem_inf_iff p s₁ s₂).1 h).1 ((mem_inf_iff p s₁ s₂).1 h).2 /-- If one affine subspace is less than or equal to another, the same applies to their directions. -/ lemma direction_le {s1 s2 : affine_subspace k P} (h : s1 ≤ s2) : s1.direction ≤ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact vector_span_mono k h end /-- If one nonempty affine subspace is less than another, the same applies to their directions -/ lemma direction_lt_of_nonempty {s1 s2 : affine_subspace k P} (h : s1 < s2) (hn : (s1 : set P).nonempty) : s1.direction < s2.direction := begin cases hn with p hp, rw lt_iff_le_and_exists at h, rcases h with ⟨hle, p2, hp2, hp2s1⟩, rw set_like.lt_iff_le_and_exists, use [direction_le hle, p2 -ᵥ p, vsub_mem_direction hp2 (hle hp)], intro hm, rw vsub_right_mem_direction_iff_mem hp p2 at hm, exact hp2s1 hm end /-- The sup of the directions of two affine subspaces is less than or equal to the direction of their sup. -/ lemma sup_direction_le (s1 s2 : affine_subspace k P) : s1.direction ⊔ s2.direction ≤ (s1 ⊔ s2).direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact sup_le (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_left : s1 ≤ s1 ⊔ s2)) hp)) (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_right : s2 ≤ s1 ⊔ s2)) hp)) end /-- The sup of the directions of two nonempty affine subspaces with empty intersection is less than the direction of their sup. -/ lemma sup_direction_lt_of_nonempty_of_inter_empty {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (he : (s1 ∩ s2 : set P) = ∅) : s1.direction ⊔ s2.direction < (s1 ⊔ s2).direction := begin cases h1 with p1 hp1, cases h2 with p2 hp2, rw set_like.lt_iff_le_and_exists, use [sup_direction_le s1 s2, p2 -ᵥ p1, vsub_mem_direction ((le_sup_right : s2 ≤ s1 ⊔ s2) hp2) ((le_sup_left : s1 ≤ s1 ⊔ s2) hp1)], intro h, rw submodule.mem_sup at h, rcases h with ⟨v1, hv1, v2, hv2, hv1v2⟩, rw [←sub_eq_zero, sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm v1, add_assoc, ←vadd_vsub_assoc, ←neg_neg v2, add_comm, ←sub_eq_add_neg, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hv1v2, refine set.nonempty.ne_empty _ he, use [v1 +ᵥ p1, vadd_mem_of_mem_direction hv1 hp1], rw hv1v2, exact vadd_mem_of_mem_direction (submodule.neg_mem _ hv2) hp2 end /-- If the directions of two nonempty affine subspaces span the whole module, they have nonempty intersection. -/ lemma inter_nonempty_of_nonempty_of_sup_direction_eq_top {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : s1.direction ⊔ s2.direction = ⊤) : ((s1 : set P) ∩ s2).nonempty := begin by_contradiction h, rw set.not_nonempty_iff_eq_empty at h, have hlt := sup_direction_lt_of_nonempty_of_inter_empty h1 h2 h, rw hd at hlt, exact not_top_lt hlt end /-- If the directions of two nonempty affine subspaces are complements of each other, they intersect in exactly one point. -/ lemma inter_eq_singleton_of_nonempty_of_is_compl {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : is_compl s1.direction s2.direction) : ∃ p, (s1 : set P) ∩ s2 = {p} := begin cases inter_nonempty_of_nonempty_of_sup_direction_eq_top h1 h2 hd.sup_eq_top with p hp, use p, ext q, rw set.mem_singleton_iff, split, { rintros ⟨hq1, hq2⟩, have hqp : q -ᵥ p ∈ s1.direction ⊓ s2.direction := ⟨vsub_mem_direction hq1 hp.1, vsub_mem_direction hq2 hp.2⟩, rwa [hd.inf_eq_bot, submodule.mem_bot, vsub_eq_zero_iff_eq] at hqp }, { exact λ h, h.symm ▸ hp } end /-- Coercing a subspace to a set then taking the affine span produces the original subspace. -/ @[simp] lemma affine_span_coe (s : affine_subspace k P) : affine_span k (s : set P) = s := begin refine le_antisymm _ (subset_span_points _ _), rintros p ⟨p1, hp1, v, hv, rfl⟩, exact vadd_mem_of_mem_direction hv hp1 end end affine_subspace section affine_space' variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V open affine_subspace set /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_eq_span_vsub_set_left {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_left p1 p2 p at hv, rw [←hv, set_like.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p2, hp2, rfl⟩) (hm ⟨p1, hp1, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p, p2, hp, hp2, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_eq_span_vsub_set_right {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_right p1 p2 p at hv, rw [←hv, set_like.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p1, hp1, rfl⟩) (hm ⟨p2, hp2, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p2, p, hp2, hp, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_left_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_right_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_left_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ) (p i) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_right_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ (p i)) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_range_eq_span_range_vsub_left (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i0 -ᵥ p i)) := by rw [vector_span_eq_span_vsub_set_left k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_range_eq_span_range_vsub_right (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i -ᵥ p i0)) := by rw [vector_span_eq_span_vsub_set_right k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_left_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i₀ -ᵥ p i)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_left_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_right_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i -ᵥ p i₀)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_right_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The affine span of a set is nonempty if and only if that set is. -/ lemma affine_span_nonempty (s : set P) : (affine_span k s : set P).nonempty ↔ s.nonempty := span_points_nonempty k s /-- The affine span of a nonempty set is nonempty. -/ instance {s : set P} [nonempty s] : nonempty (affine_span k s) := ((affine_span_nonempty k s).mpr (nonempty_subtype.mp ‹_›)).to_subtype variables {k} /-- Suppose a set of vectors spans `V`. Then a point `p`, together with those vectors added to `p`, spans `P`. -/ lemma affine_span_singleton_union_vadd_eq_top_of_span_eq_top {s : set V} (p : P) (h : submodule.span k (set.range (coe : s → V)) = ⊤) : affine_span k ({p} ∪ (λ v, v +ᵥ p) '' s) = ⊤ := begin convert ext_of_direction_eq _ ⟨p, mem_affine_span k (set.mem_union_left _ (set.mem_singleton _)), mem_top k V p⟩, rw [direction_affine_span, direction_top, vector_span_eq_span_vsub_set_right k ((set.mem_union_left _ (set.mem_singleton _)) : p ∈ _), eq_top_iff, ←h], apply submodule.span_mono, rintros v ⟨v', rfl⟩, use (v' : V) +ᵥ p, simp end variables (k) /-- `affine_span` is monotone. -/ lemma affine_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : affine_span k s₁ ≤ affine_span k s₂ := span_points_subset_coe_of_subset_coe (set.subset.trans h (subset_affine_span k _)) /-- Taking the affine span of a set, adding a point and taking the span again produces the same results as adding the point to the set and taking the span. -/ lemma affine_span_insert_affine_span (p : P) (ps : set P) : affine_span k (insert p (affine_span k ps : set P)) = affine_span k (insert p ps) := by rw [set.insert_eq, set.insert_eq, span_union, span_union, affine_span_coe] /-- If a point is in the affine span of a set, adding it to that set does not change the affine span. -/ lemma affine_span_insert_eq_affine_span {p : P} {ps : set P} (h : p ∈ affine_span k ps) : affine_span k (insert p ps) = affine_span k ps := begin rw ←mem_coe at h, rw [←affine_span_insert_affine_span, set.insert_eq_of_mem h, affine_span_coe] end end affine_space' namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The direction of the sup of two nonempty affine subspaces is the sup of the two directions and of any one difference between points in the two subspaces. -/ lemma direction_sup {s1 s2 : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s1) (hp2 : p2 ∈ s2) : (s1 ⊔ s2).direction = s1.direction ⊔ s2.direction ⊔ k ∙ (p2 -ᵥ p1) := begin refine le_antisymm _ _, { change (affine_span k ((s1 : set P) ∪ s2)).direction ≤ _, rw ←mem_coe at hp1, rw [direction_affine_span, vector_span_eq_span_vsub_set_right k (set.mem_union_left _ hp1), submodule.span_le], rintros v ⟨p3, hp3, rfl⟩, cases hp3, { rw [sup_assoc, sup_comm, set_like.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw zero_add }, { rw [sup_assoc, set_like.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1], rw [and_comm, zero_add], use rfl, rw [←vsub_add_vsub_cancel p3 p2 p1, submodule.mem_sup], use [p3 -ᵥ p2, vsub_mem_direction hp3 hp2, p2 -ᵥ p1, submodule.mem_span_singleton_self _] } }, { refine sup_le (sup_direction_le _ _) _, rw [direction_eq_vector_span, vector_span_def], exact Inf_le_Inf (λ p hp, set.subset.trans (set.singleton_subset_iff.2 (vsub_mem_vsub (mem_span_points k p2 _ (set.mem_union_right _ hp2)) (mem_span_points k p1 _ (set.mem_union_left _ hp1)))) hp) } end /-- The direction of the span of the result of adding a point to a nonempty affine subspace is the sup of the direction of that subspace and of any one difference between that point and a point in the subspace. -/ lemma direction_affine_span_insert {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) : (affine_span k (insert p2 (s : set P))).direction = submodule.span k {p2 -ᵥ p1} ⊔ s.direction := begin rw [sup_comm, ←set.union_singleton, ←coe_affine_span_singleton k V p2], change (s ⊔ affine_span k {p2}).direction = _, rw [direction_sup hp1 (mem_affine_span k (set.mem_singleton _)), direction_affine_span], simp end /-- Given a point `p1` in an affine subspace `s`, and a point `p2`, a point `p` is in the span of `s` with `p2` added if and only if it is a multiple of `p2 -ᵥ p1` added to a point in `s`. -/ lemma mem_affine_span_insert_iff {s : affine_subspace k P} {p1 : P} (hp1 : p1 ∈ s) (p2 p : P) : p ∈ affine_span k (insert p2 (s : set P)) ↔ ∃ (r : k) (p0 : P) (hp0 : p0 ∈ s), p = r • (p2 -ᵥ p1 : V) +ᵥ p0 := begin rw ←mem_coe at hp1, rw [←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_insert_of_mem _ hp1)), direction_affine_span_insert hp1, submodule.mem_sup], split, { rintros ⟨v1, hv1, v2, hv2, hp⟩, rw submodule.mem_span_singleton at hv1, rcases hv1 with ⟨r, rfl⟩, use [r, v2 +ᵥ p1, vadd_mem_of_mem_direction hv2 hp1], symmetry' at hp, rw [←sub_eq_zero, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hp, rw [hp, vadd_vadd] }, { rintros ⟨r, p3, hp3, rfl⟩, use [r • (p2 -ᵥ p1), submodule.mem_span_singleton.2 ⟨r, rfl⟩, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw [vadd_vsub_assoc, add_comm] } end end affine_subspace