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
691120f8729d7815101c1576bd2157b01e41f822
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/fin/tuple/sort.lean
e9bd615cca290c09ad9843963ef232c24bb54551
[ "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,213
lean
/- Copyright (c) 2021 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.fin.basic import data.finset.sort import data.prod.lex import group_theory.perm.basic /-! # Sorting tuples by their values Given an `n`-tuple `f : fin n → α` where `α` is ordered, we may want to turn it into a sorted `n`-tuple. This file provides an API for doing so, with the sorted `n`-tuple given by `f ∘ tuple.sort f`. ## Main declarations * `tuple.sort`: given `f : fin n → α`, produces a permutation on `fin n` * `tuple.monotone_sort`: `f ∘ tuple.sort f` is `monotone` -/ namespace tuple variables {n : ℕ} variables {α : Type*} [linear_order α] /-- `graph f` produces the finset of pairs `(f i, i)` equipped with the lexicographic order. -/ def graph (f : fin n → α) : finset (α ×ₗ (fin n)) := finset.univ.image (λ i, (f i, i)) /-- Given `p : α ×ₗ (fin n) := (f i, i)` with `p ∈ graph f`, `graph.proj p` is defined to be `f i`. -/ def graph.proj {f : fin n → α} : graph f → α := λ p, p.1.1 @[simp] lemma graph.card (f : fin n → α) : (graph f).card = n := begin rw [graph, finset.card_image_of_injective], { exact finset.card_fin _ }, { intros _ _, simp } end /-- `graph_equiv₁ f` is the natural equivalence between `fin n` and `graph f`, mapping `i` to `(f i, i)`. -/ def graph_equiv₁ (f : fin n → α) : fin n ≃ graph f := { to_fun := λ i, ⟨(f i, i), by simp [graph]⟩, inv_fun := λ p, p.1.2, left_inv := λ i, by simp, right_inv := λ ⟨⟨x, i⟩, h⟩, by simpa [graph] using h } @[simp] lemma proj_equiv₁' (f : fin n → α) : graph.proj ∘ graph_equiv₁ f = f := rfl /-- `graph_equiv₂ f` is an equivalence between `fin n` and `graph f` that respects the order. -/ def graph_equiv₂ (f : fin n → α) : fin n ≃o graph f := finset.order_iso_of_fin _ (by simp) /-- `sort f` is the permutation that orders `fin n` according to the order of the outputs of `f`. -/ def sort (f : fin n → α) : equiv.perm (fin n) := (graph_equiv₂ f).to_equiv.trans (graph_equiv₁ f).symm lemma graph_equiv₂_apply (f : fin n → α) (i : fin n) : graph_equiv₂ f i = graph_equiv₁ f (sort f i) := ((graph_equiv₁ f).apply_symm_apply _).symm lemma self_comp_sort (f : fin n → α) : f ∘ sort f = graph.proj ∘ graph_equiv₂ f := show graph.proj ∘ ((graph_equiv₁ f) ∘ (graph_equiv₁ f).symm) ∘ (graph_equiv₂ f).to_equiv = _, by simp lemma monotone_proj (f : fin n → α) : monotone (graph.proj : graph f → α) := begin rintro ⟨⟨x, i⟩, hx⟩ ⟨⟨y, j⟩, hy⟩ (_|h), { exact le_of_lt ‹_› }, { simp [graph.proj] }, end lemma monotone_sort (f : fin n → α) : monotone (f ∘ sort f) := begin rw [self_comp_sort], exact (monotone_proj f).comp (graph_equiv₂ f).monotone, end end tuple namespace tuple open list variables {n : ℕ} {α : Type*} /-- If two permutations of a tuple `f` are both monotone, then they are equal. -/ lemma unique_monotone [partial_order α] {f : fin n → α} {σ τ : equiv.perm (fin n)} (hfσ : monotone (f ∘ σ)) (hfτ : monotone (f ∘ τ)) : f ∘ σ = f ∘ τ := of_fn_injective $ eq_of_perm_of_sorted ((σ.of_fn_comp_perm f).trans (τ.of_fn_comp_perm f).symm) hfσ.of_fn_sorted hfτ.of_fn_sorted variables [linear_order α] {f : fin n → α} {σ : equiv.perm (fin n)} /-- A permutation `σ` equals `sort f` if and only if the map `i ↦ (f (σ i), σ i)` is strictly monotone (w.r.t. the lexicographic ordering on the target). -/ lemma eq_sort_iff' : σ = sort f ↔ strict_mono (σ.trans $ graph_equiv₁ f) := begin split; intro h, { rw [h, sort, equiv.trans_assoc, equiv.symm_trans_self], exact (graph_equiv₂ f).strict_mono }, { have := subsingleton.elim (graph_equiv₂ f) (h.order_iso_of_surjective _ $ equiv.surjective _), ext1, exact (graph_equiv₁ f).apply_eq_iff_eq_symm_apply.1 (fun_like.congr_fun this x).symm }, end /-- A permutation `σ` equals `sort f` if and only if `f ∘ σ` is monotone and whenever `i < j` and `f (σ i) = f (σ j)`, then `σ i < σ j`. This means that `sort f` is the lexicographically smallest permutation `σ` such that `f ∘ σ` is monotone. -/ lemma eq_sort_iff : σ = sort f ↔ monotone (f ∘ σ) ∧ ∀ i j, i < j → f (σ i) = f (σ j) → σ i < σ j := begin rw eq_sort_iff', refine ⟨λ h, ⟨(monotone_proj f).comp h.monotone, λ i j hij hfij, _⟩, λ h i j hij, _⟩, { exact (((prod.lex.lt_iff _ _).1 $ h hij).resolve_left hfij.not_lt).2 }, { obtain he|hl := (h.1 hij.le).eq_or_lt; apply (prod.lex.lt_iff _ _).2, exacts [or.inr ⟨he, h.2 i j hij he⟩, or.inl hl] }, end /-- The permutation that sorts `f` is the identity if and only if `f` is monotone. -/ lemma sort_eq_refl_iff_monotone : sort f = equiv.refl _ ↔ monotone f := begin rw [eq_comm, eq_sort_iff, equiv.coe_refl, function.comp.right_id], simp only [id.def, and_iff_left_iff_imp], exact λ _ _ _ hij _, hij, end /-- A permutation of a tuple `f` is `f` sorted if and only if it is monotone. -/ lemma comp_sort_eq_comp_iff_monotone : f ∘ σ = f ∘ sort f ↔ monotone (f ∘ σ) := ⟨λ h, h.symm ▸ monotone_sort f, λ h, unique_monotone h (monotone_sort f)⟩ /-- The sorted versions of a tuple `f` and of any permutation of `f` agree. -/ lemma comp_perm_comp_sort_eq_comp_sort : (f ∘ σ) ∘ (sort (f ∘ σ)) = f ∘ sort f := begin rw [function.comp.assoc, ← equiv.perm.coe_mul], exact unique_monotone (monotone_sort (f ∘ σ)) (monotone_sort f), end /-- If a permutation `f ∘ σ` of the tuple `f` is not the same as `f ∘ sort f`, then `f ∘ σ` has a pair of strictly decreasing entries. -/ lemma antitone_pair_of_not_sorted' (h : f ∘ σ ≠ f ∘ sort f) : ∃ i j, i < j ∧ (f ∘ σ) j < (f ∘ σ) i := by { contrapose! h, exact comp_sort_eq_comp_iff_monotone.mpr (monotone_iff_forall_lt.mpr h) } /-- If the tuple `f` is not the same as `f ∘ sort f`, then `f` has a pair of strictly decreasing entries. -/ lemma antitone_pair_of_not_sorted (h : f ≠ f ∘ sort f) : ∃ i j, i < j ∧ f j < f i := antitone_pair_of_not_sorted' (id h : f ∘ equiv.refl _ ≠ _) end tuple
ab2a6794869548e701632fccfa9f18a6e9ee0cd5
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/test/local_cache.lean
19888e29644eb6ed197923fa7c629bdb916edaf6
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
9,903
lean
import tactic.local_cache open tactic namespace block_local section example_tactic def TEST_NS_1 : name := `my_tactic def TEST_NS_2 : name := `my_other_tactic -- Example "expensive" function meta def generate_some_data : tactic (list ℕ) := do trace "cache regenerating", return [1, 2, 3, 4] meta def my_tactic : tactic unit := do my_cached_data ← run_once TEST_NS_1 generate_some_data, -- Do some stuff with `my_cached_data` skip meta def my_other_tactic : tactic unit := run_once TEST_NS_2 (return [10, 20, 30, 40]) >> skip end example_tactic section example_usage -- Note only a single cache regeneration (only a single trace message), -- even upon descent to a sub-tactic-block. lemma my_lemma : true := begin my_tactic, my_tactic, my_tactic, have h : true, { my_tactic, trivial }, trivial end end example_usage section test meta def fail_if_cache_miss (ns : name) : tactic unit := do p ← local_cache.present ns, if p then skip else fail "cache miss" meta def fail_if_cache_miss_1 : tactic unit := fail_if_cache_miss TEST_NS_1 meta def fail_if_cache_miss_2 : tactic unit := fail_if_cache_miss TEST_NS_2 end test -- Test: the cache persists only within a single tactic block section test_scope structure dummy := (a b : ℕ) def my_definition : dummy := ⟨ begin my_tactic, fail_if_cache_miss_1, exact 1 end, begin success_if_fail { fail_if_cache_miss_1 }, exact 1 end, ⟩ def my_definition' : dummy := ⟨ begin success_if_fail { fail_if_cache_miss_1 }, exact 1 end, begin success_if_fail { fail_if_cache_miss_1 }, exact 1 end, ⟩ lemma my_lemma' : dummy := ⟨ begin my_tactic, fail_if_cache_miss_1, exact 1 end, begin success_if_fail { fail_if_cache_miss_1 }, exact 1 end, ⟩ end test_scope -- Test: the cache is reliably persistent, decends to sub-blocks, -- the api to inspect whether a cache entry is present works, and -- the cache can be manually cleared. section test_persistence lemma my_test_ps : true := begin success_if_fail { fail_if_cache_miss_1 }, my_tactic, fail_if_cache_miss_1, fail_if_cache_miss_1, success_if_fail { fail_if_cache_miss_2 }, have h : true, { fail_if_cache_miss_1, trivial }, -- Manually clear cache local_cache.clear TEST_NS_1, success_if_fail { fail_if_cache_miss_1 }, trivial end end test_persistence -- Test: caching under different namespaces doesn't share the -- cached state. section test_ns_collison lemma my_test_ns : true := begin my_tactic, fail_if_cache_miss_1, success_if_fail { fail_if_cache_miss_2 }, my_other_tactic, fail_if_cache_miss_1, fail_if_cache_miss_2, local_cache.clear TEST_NS_1, success_if_fail { fail_if_cache_miss_1 }, fail_if_cache_miss_2, my_other_tactic, success_if_fail { fail_if_cache_miss_1 }, fail_if_cache_miss_2, trivial end end test_ns_collison -- Test: cached results don't leak between `def`s or `lemma`s. section test_locality def my_def_1 : true := begin success_if_fail { fail_if_cache_miss_1 }, my_tactic, fail_if_cache_miss_1, trivial end def my_def_2 : true := begin success_if_fail { fail_if_cache_miss_1 }, my_tactic, fail_if_cache_miss_1, trivial end lemma my_lemma_1 : true := begin success_if_fail { fail_if_cache_miss_1 }, my_tactic, fail_if_cache_miss_1, trivial end lemma my_lemma_2 : true := begin success_if_fail { fail_if_cache_miss_1 }, my_tactic, fail_if_cache_miss_1, trivial end end test_locality -- Test: the `local_cache.get` function. section test_get meta def assert_equal {α : Type} [decidable_eq α] (a : α) (ta : tactic α) : tactic unit := do a' ← ta, if a = a' then skip else fail "not equal!" lemma my_lemma_3 : true := begin assert_equal none (local_cache.get TEST_NS_1 (list ℕ)), my_tactic, my_other_tactic, assert_equal (some [1,2,3,4]) (local_cache.get TEST_NS_1 (list ℕ)), assert_equal (some [10, 20, 30, 40]) (local_cache.get TEST_NS_2 (list ℕ)), trivial end end test_get end block_local --------------------------- -- Now test again with the `def_local` scope. --------------------------- namespace def_local open tactic.local_cache.cache_scope section example_tactic def TEST_NS_1 : name := `my_tactic def TEST_NS_2 : name := `my_other_tactic -- Example "expensive" function meta def generate_some_data : tactic (list ℕ) := do trace "cache regenerating", return [1, 2, 3, 4] meta def my_tactic : tactic unit := do my_cached_data ← run_once TEST_NS_1 generate_some_data def_local, -- Do some stuff with `my_cached_data` skip meta def my_other_tactic : tactic unit := run_once TEST_NS_2 (return [10, 20, 30, 40]) def_local >> skip end example_tactic section example_usage -- Note only a single cache regeneration (only a single trace message), -- even upon descent to a sub-tactic-block. lemma my_lemma : true := begin my_tactic, my_tactic, my_tactic, have h : true, { my_tactic, trivial }, trivial end end example_usage section test meta def fail_if_cache_miss (ns : name) : tactic unit := do p ← local_cache.present ns def_local, if p then skip else fail "cache miss" meta def fail_if_cache_miss_1 : tactic unit := fail_if_cache_miss TEST_NS_1 meta def fail_if_cache_miss_2 : tactic unit := fail_if_cache_miss TEST_NS_2 end test -- Test: the cache really does persist over a whole definition section test_scope structure dummy := (a b : ℕ) def my_definition : dummy := ⟨ begin my_tactic, fail_if_cache_miss_1, exact 1 end, begin fail_if_cache_miss_1, exact 1 end, ⟩ def my_definition' : dummy := ⟨ begin success_if_fail { fail_if_cache_miss_1 }, exact 1 end, begin success_if_fail { fail_if_cache_miss_1 }, exact 1 end, ⟩ lemma my_lemma' : dummy := ⟨ begin my_tactic, fail_if_cache_miss_1, exact 1 end, begin fail_if_cache_miss_1, exact 1 end, ⟩ end test_scope -- Test: the cache is reliably persistent, decends to sub-blocks, -- the api to inspect whether a cache entry is present works, and -- the cache can be manually cleared. section test_persistence lemma my_test_ps : true := begin success_if_fail { fail_if_cache_miss_1 }, my_tactic, my_tactic, fail_if_cache_miss_1, fail_if_cache_miss_1, success_if_fail { fail_if_cache_miss_2 }, have h : true, { fail_if_cache_miss_1, trivial }, -- Manually clear cache local_cache.clear TEST_NS_1 def_local, success_if_fail { fail_if_cache_miss_1 }, trivial end end test_persistence -- Test: caching under different namespaces doesn't share the -- cached state. section test_ns_collison lemma my_test_ns : true := begin my_tactic, fail_if_cache_miss_1, success_if_fail { fail_if_cache_miss_2 }, my_other_tactic, fail_if_cache_miss_1, fail_if_cache_miss_2, local_cache.clear TEST_NS_1 def_local, success_if_fail { fail_if_cache_miss_1 }, fail_if_cache_miss_2, my_other_tactic, success_if_fail { fail_if_cache_miss_1 }, fail_if_cache_miss_2, trivial end end test_ns_collison -- Test: cached results don't leak between `def`s or `lemma`s. section test_locality def my_def_1 : true := begin success_if_fail { fail_if_cache_miss_1 }, my_tactic, fail_if_cache_miss_1, trivial end def my_def_2 : true := begin success_if_fail { fail_if_cache_miss_1 }, my_tactic, fail_if_cache_miss_1, trivial end lemma my_lemma_1 : true := begin success_if_fail { fail_if_cache_miss_1 }, my_tactic, fail_if_cache_miss_1, trivial end lemma my_lemma_2 : true := begin success_if_fail { fail_if_cache_miss_1 }, my_tactic, fail_if_cache_miss_1, trivial end end test_locality -- Test: the `local_cache.get` function. section test_get meta def assert_equal {α : Type} [decidable_eq α] (a : α) (ta : tactic α) : tactic unit := do a' ← ta, if a = a' then skip else fail "not equal!" lemma my_lemma_3 : true := begin assert_equal none (local_cache.get TEST_NS_1 (list ℕ)), my_tactic, my_other_tactic, assert_equal (some [1,2,3,4]) (local_cache.get TEST_NS_1 (list ℕ) def_local), assert_equal (some [10, 20, 30, 40]) (local_cache.get TEST_NS_2 (list ℕ) def_local), trivial end end test_get end def_local -- Test: finally, make sure the `block_local` and `def_local` caches -- don't collide. namespace collision open tactic.local_cache.cache_scope def TEST_NS : name := `my_tactic -- Example "expensive" function meta def generate_some_data : tactic (list ℕ) := do trace "cache regenerating", return [1, 2, 3, 4] meta def tac_block : tactic unit := do my_cached_data ← run_once TEST_NS generate_some_data block_local, skip meta def tac_def : tactic unit := do my_cached_data ← run_once TEST_NS generate_some_data def_local, skip meta def fail_if_cache_miss_def : tactic unit := do p ← local_cache.present TEST_NS def_local, if p then skip else fail "cache miss" meta def fail_if_cache_miss_block : tactic unit := do p ← local_cache.present TEST_NS block_local, if p then skip else fail "cache miss" lemma my_lemma_1 : true := begin tac_block, fail_if_cache_miss_block, success_if_fail { fail_if_cache_miss_def }, trivial end lemma my_lemma_2 : true := begin tac_def, fail_if_cache_miss_def, success_if_fail { fail_if_cache_miss_block }, trivial end lemma my_lemma_3 : true := begin tac_block, tac_def, local_cache.clear TEST_NS block_local, fail_if_cache_miss_def, success_if_fail { fail_if_cache_miss_block }, trivial end lemma my_lemma_4 : true := begin tac_block, tac_def, local_cache.clear TEST_NS def_local, fail_if_cache_miss_block, success_if_fail { fail_if_cache_miss_def }, trivial end end collision
fb60867811a6e5cedb201546d8d05367933d8143
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/yoneda.lean
daebdd43a83bb030ae7a50adc45b6753a2166591
[ "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,282
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.functor.hom import category_theory.functor.currying import category_theory.products.basic /-! # The Yoneda embedding The Yoneda embedding as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`, along with an instance that it is `fully_faithful`. Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`. ## References * [Stacks: Opposite Categories and the Yoneda Lemma](https://stacks.math.columbia.edu/tag/001L) -/ namespace category_theory open opposite universes v₁ u₁ u₂-- morphism levels before object levels. See note [category_theory universes]. variables {C : Type u₁} [category.{v₁} C] /-- The Yoneda embedding, as a functor from `C` into presheaves on `C`. See <https://stacks.math.columbia.edu/tag/001O>. -/ @[simps] def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop Y ⟶ X, map := λ Y Y' f g, f.unop ≫ g, map_comp' := λ _ _ _ f g, begin ext, dsimp, erw [category.assoc] end, map_id' := λ Y, begin ext, dsimp, erw [category.id_comp] end }, map := λ X X' f, { app := λ Y g, g ≫ f } } /-- The co-Yoneda embedding, as a functor from `Cᵒᵖ` into co-presheaves on `C`. -/ @[simps] def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) := { obj := λ X, { obj := λ Y, unop X ⟶ Y, map := λ Y Y' f g, g ≫ f }, map := λ X X' f, { app := λ Y g, f.unop ≫ g } } namespace yoneda lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) : (yoneda.obj X).map f (𝟙 X) = (yoneda.map f.unop).app (op Y) (𝟙 Y) := by { dsimp, simp } @[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y) {Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) := (functor_to_types.naturality _ _ α f.op h).symm /-- The Yoneda embedding is full. See <https://stacks.math.columbia.edu/tag/001P>. -/ instance yoneda_full : full (yoneda : C ⥤ Cᵒᵖ ⥤ Type v₁) := { preimage := λ X Y f, f.app (op X) (𝟙 X) } /-- The Yoneda embedding is faithful. See <https://stacks.math.columbia.edu/tag/001P>. -/ instance yoneda_faithful : faithful (yoneda : C ⥤ Cᵒᵖ ⥤ Type v₁) := { map_injective' := λ X Y f g p, by convert (congr_fun (congr_app p (op X)) (𝟙 X)); dsimp; simp } /-- Extensionality via Yoneda. The typical usage would be ``` -- Goal is `X ≅ Y` apply yoneda.ext, -- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these functions are inverses and natural in `Z`. ``` -/ def ext (X Y : C) (p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X)) (h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f) (n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y := yoneda.preimage_iso (nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy)) /-- If `yoneda.map f` is an isomorphism, so was `f`. -/ lemma is_iso {X Y : C} (f : X ⟶ Y) [is_iso (yoneda.map f)] : is_iso f := is_iso_of_fully_faithful yoneda f end yoneda namespace coyoneda @[simp] lemma naturality {X Y : Cᵒᵖ} (α : coyoneda.obj X ⟶ coyoneda.obj Y) {Z Z' : C} (f : Z' ⟶ Z) (h : unop X ⟶ Z') : (α.app Z' h) ≫ f = α.app Z (h ≫ f) := (functor_to_types.naturality _ _ α f h).symm instance coyoneda_full : full (coyoneda : Cᵒᵖ ⥤ C ⥤ Type v₁) := { preimage := λ X Y f, (f.app _ (𝟙 X.unop)).op } instance coyoneda_faithful : faithful (coyoneda : Cᵒᵖ ⥤ C ⥤ Type v₁) := { map_injective' := λ X Y f g p, begin have t := congr_fun (congr_app p X.unop) (𝟙 _), simpa using congr_arg quiver.hom.op t, end } /-- If `coyoneda.map f` is an isomorphism, so was `f`. -/ lemma is_iso {X Y : Cᵒᵖ} (f : X ⟶ Y) [is_iso (coyoneda.map f)] : is_iso f := is_iso_of_fully_faithful coyoneda f /-- The identity functor on `Type` is isomorphic to the coyoneda functor coming from `punit`. -/ def punit_iso : coyoneda.obj (opposite.op punit) ≅ 𝟭 (Type v₁) := nat_iso.of_components (λ X, { hom := λ f, f ⟨⟩, inv := λ x _, x }) (by tidy) /-- Taking the `unop` of morphisms is a natural isomorphism. -/ @[simps] def obj_op_op (X : C) : coyoneda.obj (op (op X)) ≅ yoneda.obj X := nat_iso.of_components (λ Y, (op_equiv _ _).to_iso) (λ X Y f, rfl) end coyoneda namespace functor /-- A functor `F : Cᵒᵖ ⥤ Type v₁` is representable if there is object `X` so `F ≅ yoneda.obj X`. See <https://stacks.math.columbia.edu/tag/001Q>. -/ class representable (F : Cᵒᵖ ⥤ Type v₁) : Prop := (has_representation : ∃ X (f : yoneda.obj X ⟶ F), is_iso f) instance {X : C} : representable (yoneda.obj X) := { has_representation := ⟨X, 𝟙 _, infer_instance⟩ } /-- A functor `F : C ⥤ Type v₁` is corepresentable if there is object `X` so `F ≅ coyoneda.obj X`. See <https://stacks.math.columbia.edu/tag/001Q>. -/ class corepresentable (F : C ⥤ Type v₁) : Prop := (has_corepresentation : ∃ X (f : coyoneda.obj X ⟶ F), is_iso f) instance {X : Cᵒᵖ} : corepresentable (coyoneda.obj X) := { has_corepresentation := ⟨X, 𝟙 _, infer_instance⟩ } -- instance : corepresentable (𝟭 (Type v₁)) := -- corepresentable_of_nat_iso (op punit) coyoneda.punit_iso section representable variables (F : Cᵒᵖ ⥤ Type v₁) variable [F.representable] /-- The representing object for the representable functor `F`. -/ noncomputable def repr_X : C := (representable.has_representation : ∃ X (f : _ ⟶ F), _).some /-- The (forward direction of the) isomorphism witnessing `F` is representable. -/ noncomputable def repr_f : yoneda.obj F.repr_X ⟶ F := representable.has_representation.some_spec.some /-- The representing element for the representable functor `F`, sometimes called the universal element of the functor. -/ noncomputable def repr_x : F.obj (op F.repr_X) := F.repr_f.app (op F.repr_X) (𝟙 F.repr_X) instance : is_iso F.repr_f := representable.has_representation.some_spec.some_spec /-- An isomorphism between `F` and a functor of the form `C(-, F.repr_X)`. Note the components `F.repr_w.app X` definitionally have type `(X.unop ⟶ F.repr_X) ≅ F.obj X`. -/ noncomputable def repr_w : yoneda.obj F.repr_X ≅ F := as_iso F.repr_f @[simp] lemma repr_w_hom : F.repr_w.hom = F.repr_f := rfl lemma repr_w_app_hom (X : Cᵒᵖ) (f : unop X ⟶ F.repr_X) : (F.repr_w.app X).hom f = F.map f.op F.repr_x := begin change F.repr_f.app X f = (F.repr_f.app (op F.repr_X) ≫ F.map f.op) (𝟙 F.repr_X), rw ←F.repr_f.naturality, dsimp, simp end end representable section corepresentable variables (F : C ⥤ Type v₁) variable [F.corepresentable] /-- The representing object for the corepresentable functor `F`. -/ noncomputable def corepr_X : C := (corepresentable.has_corepresentation : ∃ X (f : _ ⟶ F), _).some.unop /-- The (forward direction of the) isomorphism witnessing `F` is corepresentable. -/ noncomputable def corepr_f : coyoneda.obj (op F.corepr_X) ⟶ F := corepresentable.has_corepresentation.some_spec.some /-- The representing element for the corepresentable functor `F`, sometimes called the universal element of the functor. -/ noncomputable def corepr_x : F.obj F.corepr_X := F.corepr_f.app F.corepr_X (𝟙 F.corepr_X) instance : is_iso F.corepr_f := corepresentable.has_corepresentation.some_spec.some_spec /-- An isomorphism between `F` and a functor of the form `C(F.corepr X, -)`. Note the components `F.corepr_w.app X` definitionally have type `F.corepr_X ⟶ X ≅ F.obj X`. -/ noncomputable def corepr_w : coyoneda.obj (op F.corepr_X) ≅ F := as_iso F.corepr_f lemma corepr_w_app_hom (X : C) (f : F.corepr_X ⟶ X) : (F.corepr_w.app X).hom f = F.map f F.corepr_x := begin change F.corepr_f.app X f = (F.corepr_f.app F.corepr_X ≫ F.map f) (𝟙 F.corepr_X), rw ←F.corepr_f.naturality, dsimp, simp end end corepresentable end functor lemma representable_of_nat_iso (F : Cᵒᵖ ⥤ Type v₁) {G} (i : F ≅ G) [F.representable] : G.representable := { has_representation := ⟨F.repr_X, F.repr_f ≫ i.hom, infer_instance⟩ } lemma corepresentable_of_nat_iso (F : C ⥤ Type v₁) {G} (i : F ≅ G) [F.corepresentable] : G.corepresentable := { has_corepresentation := ⟨op F.corepr_X, F.corepr_f ≫ i.hom, infer_instance⟩ } instance : functor.corepresentable (𝟭 (Type v₁)) := corepresentable_of_nat_iso (coyoneda.obj (op punit)) coyoneda.punit_iso open opposite variables (C) -- We need to help typeclass inference with some awkward universe levels here. instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) := category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) := category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁) open yoneda /-- The "Yoneda evaluation" functor, which sends `X : Cᵒᵖ` and `F : Cᵒᵖ ⥤ Type` to `F.obj X`, functorially in both `X` and `F`. -/ def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁} @[simp] lemma yoneda_evaluation_map_down (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) : ((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl /-- The "Yoneda pairing" functor, which sends `X : Cᵒᵖ` and `F : Cᵒᵖ ⥤ Type` to `yoneda.op.obj X ⟶ F`, functorially in both `X` and `F`. -/ def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) := functor.prod yoneda.op (𝟭 (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁) @[simp] lemma yoneda_pairing_map (P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) : (yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl /-- The Yoneda lemma asserts that that the Yoneda pairing `(X : Cᵒᵖ, F : Cᵒᵖ ⥤ Type) ↦ (yoneda.obj (unop X) ⟶ F)` is naturally isomorphic to the evaluation `(X, F) ↦ F.obj X`. See <https://stacks.math.columbia.edu/tag/001P>. -/ def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C := { hom := { app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))), naturality' := begin intros X Y f, ext, dsimp, erw [category.id_comp, ←functor_to_types.naturality], simp only [category.comp_id, yoneda_obj_map], end }, inv := { app := λ F x, { app := λ X a, (F.2.map a.op) x.down, naturality' := begin intros X Y f, ext, dsimp, rw [functor_to_types.map_comp_apply] end }, naturality' := begin intros X Y f, ext, dsimp, rw [←functor_to_types.naturality, functor_to_types.map_comp_apply] end }, hom_inv_id' := begin ext, dsimp, erw [←functor_to_types.naturality, obj_map_id], simp only [yoneda_map_app, quiver.hom.unop_op], erw [category.id_comp], end, inv_hom_id' := begin ext, dsimp, rw [functor_to_types.map_id_apply] end }. variables {C} /-- The isomorphism between `yoneda.obj X ⟶ F` and `F.obj (op X)` (we need to insert a `ulift` to get the universes right!) given by the Yoneda lemma. -/ @[simps] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) : (yoneda.obj X ⟶ F) ≅ ulift.{u₁} (F.obj (op X)) := (yoneda_lemma C).app (op X, F) /-- We have a type-level equivalence between natural transformations from the yoneda embedding and elements of `F.obj X`, without any universe switching. -/ def yoneda_equiv {X : C} {F : Cᵒᵖ ⥤ Type v₁} : (yoneda.obj X ⟶ F) ≃ F.obj (op X) := (yoneda_sections X F).to_equiv.trans equiv.ulift @[simp] lemma yoneda_equiv_apply {X : C} {F : Cᵒᵖ ⥤ Type v₁} (f : yoneda.obj X ⟶ F) : yoneda_equiv f = f.app (op X) (𝟙 X) := rfl @[simp] lemma yoneda_equiv_symm_app_apply {X : C} {F : Cᵒᵖ ⥤ Type v₁} (x : F.obj (op X)) (Y : Cᵒᵖ) (f : Y.unop ⟶ X) : (yoneda_equiv.symm x).app Y f = F.map f.op x := rfl lemma yoneda_equiv_naturality {X Y : C} {F : Cᵒᵖ ⥤ Type v₁} (f : yoneda.obj X ⟶ F) (g : Y ⟶ X) : F.map g.op (yoneda_equiv f) = yoneda_equiv (yoneda.map g ≫ f) := begin change (f.app (op X) ≫ F.map g.op) (𝟙 X) = f.app (op Y) (𝟙 Y ≫ g), rw ←f.naturality, dsimp, simp, end /-- When `C` is a small category, we can restate the isomorphism from `yoneda_sections` without having to change universes. -/ def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) : (yoneda.obj X ⟶ F) ≅ F.obj (op X) := yoneda_sections X F ≪≫ ulift_trivial _ @[simp] lemma yoneda_sections_small_hom {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) (f : yoneda.obj X ⟶ F) : (yoneda_sections_small X F).hom f = f.app _ (𝟙 _) := rfl @[simp] lemma yoneda_sections_small_inv_app_apply {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) (t : F.obj (op X)) (Y : Cᵒᵖ) (f : Y.unop ⟶ X) : ((yoneda_sections_small X F).inv t).app Y f = F.map f.op t := rfl local attribute [ext] functor.ext /-- The curried version of yoneda lemma when `C` is small. -/ def curried_yoneda_lemma {C : Type u₁} [small_category C] : (yoneda.op ⋙ coyoneda : Cᵒᵖ ⥤ (Cᵒᵖ ⥤ Type u₁) ⥤ Type u₁) ≅ evaluation Cᵒᵖ (Type u₁) := eq_to_iso (by tidy) ≪≫ curry.map_iso (yoneda_lemma C ≪≫ iso_whisker_left (evaluation_uncurried Cᵒᵖ (Type u₁)) ulift_functor_trivial) ≪≫ eq_to_iso (by tidy) /-- The curried version of yoneda lemma when `C` is small. -/ def curried_yoneda_lemma' {C : Type u₁} [small_category C] : yoneda ⋙ (whiskering_left Cᵒᵖ (Cᵒᵖ ⥤ Type u₁)ᵒᵖ (Type u₁)).obj yoneda.op ≅ 𝟭 (Cᵒᵖ ⥤ Type u₁) := eq_to_iso (by tidy) ≪≫ curry.map_iso (iso_whisker_left (prod.swap _ _) (yoneda_lemma C ≪≫ iso_whisker_left (evaluation_uncurried Cᵒᵖ (Type u₁)) ulift_functor_trivial : _)) ≪≫ eq_to_iso (by tidy) end category_theory
8c57aa0b12620dee7c7fe2bd60a07710bbeb00c5
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_1999.lean
27e3dc1688bc70ac688d237f1d38be20c74813c4
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
177
lean
variables {p q : Prop} -- BEGIN example : (p → false) → (p → q) := begin assume h₁ : p → false, assume h₂ : p, exfalso, show false, from h₁ h₂ end -- END
03187c98c4e522ee29af5f9413be85aa697df0ac
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/direct_sum/basic.lean
71ed46656061b76dbb654b67ff5f173bffb2a0e8
[ "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
9,789
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 data.dfinsupp.basic import group_theory.submonoid.operations import group_theory.subgroup.basic /-! # Direct sum This file defines the direct sum of abelian groups, indexed by a discrete type. ## Notation `⨁ i, β i` is the n-ary direct sum `direct_sum`. This notation is in the `direct_sum` locale, accessible after `open_locale direct_sum`. ## References * https://en.wikipedia.org/wiki/Direct_sum -/ open_locale big_operators universes u v w u₁ variables (ι : Type v) [dec_ι : decidable_eq ι] (β : ι → Type w) /-- `direct_sum β` is the direct sum of a family of additive commutative monoids `β i`. Note: `open_locale direct_sum` will enable the notation `⨁ i, β i` for `direct_sum β`. -/ @[derive [add_comm_monoid, inhabited]] def direct_sum [Π i, add_comm_monoid (β i)] : Type* := Π₀ i, β i instance [Π i, add_comm_monoid (β i)] : has_coe_to_fun (direct_sum ι β) (λ _, Π i : ι, β i) := dfinsupp.has_coe_to_fun localized "notation `⨁` binders `, ` r:(scoped f, direct_sum _ f) := r" in direct_sum namespace direct_sum variables {ι} section add_comm_group variables [Π i, add_comm_group (β i)] instance : add_comm_group (direct_sum ι β) := dfinsupp.add_comm_group variables {β} @[simp] lemma sub_apply (g₁ g₂ : ⨁ i, β i) (i : ι) : (g₁ - g₂) i = g₁ i - g₂ i := dfinsupp.sub_apply _ _ _ end add_comm_group variables [Π i, add_comm_monoid (β i)] @[simp] lemma zero_apply (i : ι) : (0 : ⨁ i, β i) i = 0 := rfl variables {β} @[simp] lemma add_apply (g₁ g₂ : ⨁ i, β i) (i : ι) : (g₁ + g₂) i = g₁ i + g₂ i := dfinsupp.add_apply _ _ _ variables (β) include dec_ι /-- `mk β s x` is the element of `⨁ i, β i` that is zero outside `s` and has coefficient `x i` for `i` in `s`. -/ def mk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →+ ⨁ i, β i := { to_fun := dfinsupp.mk s, map_add' := λ _ _, dfinsupp.mk_add, map_zero' := dfinsupp.mk_zero, } /-- `of i` is the natural inclusion map from `β i` to `⨁ i, β i`. -/ def of (i : ι) : β i →+ ⨁ i, β i := dfinsupp.single_add_hom β i @[simp] lemma of_eq_same (i : ι) (x : β i) : (of _ i x) i = x := dfinsupp.single_eq_same lemma of_eq_of_ne (i j : ι) (x : β i) (h : i ≠ j) : (of _ i x) j = 0 := dfinsupp.single_eq_of_ne h @[simp] lemma support_zero [Π (i : ι) (x : β i), decidable (x ≠ 0)] : (0 : ⨁ i, β i).support = ∅ := dfinsupp.support_zero @[simp] lemma support_of [Π (i : ι) (x : β i), decidable (x ≠ 0)] (i : ι) (x : β i) (h : x ≠ 0) : (of _ i x).support = {i} := dfinsupp.support_single_ne_zero h lemma support_of_subset [Π (i : ι) (x : β i), decidable (x ≠ 0)] {i : ι} {b : β i} : (of _ i b).support ⊆ {i} := dfinsupp.support_single_subset lemma sum_support_of [Π (i : ι) (x : β i), decidable (x ≠ 0)] (x : ⨁ i, β i) : ∑ i in x.support, of β i (x i) = x := dfinsupp.sum_single variables {β} theorem mk_injective (s : finset ι) : function.injective (mk β s) := dfinsupp.mk_injective s theorem of_injective (i : ι) : function.injective (of β i) := dfinsupp.single_injective @[elab_as_eliminator] protected theorem induction_on {C : (⨁ i, β i) → Prop} (x : ⨁ i, β i) (H_zero : C 0) (H_basic : ∀ (i : ι) (x : β i), C (of β i x)) (H_plus : ∀ x y, C x → C y → C (x + y)) : C x := begin apply dfinsupp.induction x H_zero, intros i b f h1 h2 ih, solve_by_elim end /-- If two additive homomorphisms from `⨁ i, β i` are equal on each `of β i y`, then they are equal. -/ lemma add_hom_ext {γ : Type*} [add_monoid γ] ⦃f g : (⨁ i, β i) →+ γ⦄ (H : ∀ (i : ι) (y : β i), f (of _ i y) = g (of _ i y)) : f = g := dfinsupp.add_hom_ext H /-- If two additive homomorphisms from `⨁ i, β i` are equal on each `of β i y`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma add_hom_ext' {γ : Type*} [add_monoid γ] ⦃f g : (⨁ i, β i) →+ γ⦄ (H : ∀ (i : ι), f.comp (of _ i) = g.comp (of _ i)) : f = g := add_hom_ext $ λ i, add_monoid_hom.congr_fun $ H i variables {γ : Type u₁} [add_comm_monoid γ] section to_add_monoid variables (φ : Π i, β i →+ γ) (ψ : (⨁ i, β i) →+ γ) /-- `to_add_monoid φ` is the natural homomorphism from `⨁ i, β i` to `γ` induced by a family `φ` of homomorphisms `β i → γ`. -/ def to_add_monoid : (⨁ i, β i) →+ γ := (dfinsupp.lift_add_hom φ) @[simp] lemma to_add_monoid_of (i) (x : β i) : to_add_monoid φ (of β i x) = φ i x := dfinsupp.lift_add_hom_apply_single φ i x theorem to_add_monoid.unique (f : ⨁ i, β i) : ψ f = to_add_monoid (λ i, ψ.comp (of β i)) f := by {congr, ext, simp [to_add_monoid, of]} end to_add_monoid section from_add_monoid /-- `from_add_monoid φ` is the natural homomorphism from `γ` to `⨁ i, β i` induced by a family `φ` of homomorphisms `γ → β i`. Note that this is not an isomorphism. Not every homomorphism `γ →+ ⨁ i, β i` arises in this way. -/ def from_add_monoid : (⨁ i, γ →+ β i) →+ (γ →+ ⨁ i, β i) := to_add_monoid $ λ i, add_monoid_hom.comp_hom (of β i) @[simp] lemma from_add_monoid_of (i : ι) (f : γ →+ β i) : from_add_monoid (of _ i f) = (of _ i).comp f := by { rw [from_add_monoid, to_add_monoid_of], refl } lemma from_add_monoid_of_apply (i : ι) (f : γ →+ β i) (x : γ) : from_add_monoid (of _ i f) x = of _ i (f x) := by rw [from_add_monoid_of, add_monoid_hom.coe_comp] end from_add_monoid variables (β) /-- `set_to_set β S T h` is the natural homomorphism `⨁ (i : S), β i → ⨁ (i : T), β i`, where `h : S ⊆ T`. -/ -- TODO: generalize this to remove the assumption `S ⊆ T`. def set_to_set (S T : set ι) (H : S ⊆ T) : (⨁ (i : S), β i) →+ (⨁ (i : T), β i) := to_add_monoid $ λ i, of (λ (i : subtype T), β i) ⟨↑i, H i.prop⟩ variables {β} omit dec_ι /-- The natural equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/ protected def id (M : Type v) (ι : Type* := punit) [add_comm_monoid M] [unique ι] : (⨁ (_ : ι), M) ≃+ M := { to_fun := direct_sum.to_add_monoid (λ _, add_monoid_hom.id M), inv_fun := of (λ _, M) default, left_inv := λ x, direct_sum.induction_on x (by rw [add_monoid_hom.map_zero, add_monoid_hom.map_zero]) (λ p x, by rw [unique.default_eq p, to_add_monoid_of]; refl) (λ x y ihx ihy, by rw [add_monoid_hom.map_add, add_monoid_hom.map_add, ihx, ihy]), right_inv := λ x, to_add_monoid_of _ _ _, ..direct_sum.to_add_monoid (λ _, add_monoid_hom.id M) } /-- The canonical embedding from `⨁ i, A i` to `M` where `A` is a collection of `add_submonoid M` indexed by `ι`-/ def add_submonoid_coe {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) : (⨁ i, A i) →+ M := to_add_monoid (λ i, (A i).subtype) @[simp] lemma add_submonoid_coe_of {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) (i : ι) (x : A i) : add_submonoid_coe A (of (λ i, A i) i x) = x := to_add_monoid_of _ _ _ lemma coe_of_add_submonoid_apply {M : Type*} [decidable_eq ι] [add_comm_monoid M] {A : ι → add_submonoid M} (i j : ι) (x : A i) : (of _ i x j : M) = if i = j then x else 0 := begin obtain rfl | h := decidable.eq_or_ne i j, { rw [direct_sum.of_eq_same, if_pos rfl], }, { rw [direct_sum.of_eq_of_ne _ _ _ _ h, if_neg h, add_submonoid.coe_zero], }, end /-- The `direct_sum` formed by a collection of `add_submonoid`s of `M` is said to be internal if the canonical map `(⨁ i, A i) →+ M` is bijective. See `direct_sum.add_subgroup_is_internal` for the same statement about `add_subgroup`s. -/ def add_submonoid_is_internal {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) : Prop := function.bijective (add_submonoid_coe A) lemma add_submonoid_is_internal.supr_eq_top {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) (h : add_submonoid_is_internal A) : supr A = ⊤ := begin rw [add_submonoid.supr_eq_mrange_dfinsupp_sum_add_hom, add_monoid_hom.mrange_top_iff_surjective], exact function.bijective.surjective h, end /-- The canonical embedding from `⨁ i, A i` to `M` where `A` is a collection of `add_subgroup M` indexed by `ι`-/ def add_subgroup_coe {M : Type*} [decidable_eq ι] [add_comm_group M] (A : ι → add_subgroup M) : (⨁ i, A i) →+ M := to_add_monoid (λ i, (A i).subtype) @[simp] lemma add_subgroup_coe_of {M : Type*} [decidable_eq ι] [add_comm_group M] (A : ι → add_subgroup M) (i : ι) (x : A i) : add_subgroup_coe A (of (λ i, A i) i x) = x := to_add_monoid_of _ _ _ lemma coe_of_add_subgroup_apply {M : Type*} [decidable_eq ι] [add_comm_group M] {A : ι → add_subgroup M} (i j : ι) (x : A i) : (of _ i x j : M) = if i = j then x else 0 := begin obtain rfl | h := decidable.eq_or_ne i j, { rw [direct_sum.of_eq_same, if_pos rfl], }, { rw [direct_sum.of_eq_of_ne _ _ _ _ h, if_neg h, add_subgroup.coe_zero], }, end /-- The `direct_sum` formed by a collection of `add_subgroup`s of `M` is said to be internal if the canonical map `(⨁ i, A i) →+ M` is bijective. See `direct_sum.submodule_is_internal` for the same statement about `submodules`s. -/ def add_subgroup_is_internal {M : Type*} [decidable_eq ι] [add_comm_group M] (A : ι → add_subgroup M) : Prop := function.bijective (add_subgroup_coe A) lemma add_subgroup_is_internal.to_add_submonoid {M : Type*} [decidable_eq ι] [add_comm_group M] (A : ι → add_subgroup M) : add_subgroup_is_internal A ↔ add_submonoid_is_internal (λ i, (A i).to_add_submonoid) := iff.rfl end direct_sum
d301b2d8971ed55f747bb1d8922a27e206e1e219
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/namePatEqThm.lean
18c118508212223a6ebcf05f090b2cb37e4e1d65
[ "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
304
lean
@[simp] def iota : Nat → List Nat | 0 => [] | m@(n+1) => m :: iota n #check iota._eq_1 #check iota._eq_2 @[simp] def f : List Nat → List Nat × List Nat | xs@(x :: ys@(y :: [])) => (xs, ys) | xs@(x :: ys@(y :: zs)) => f zs | _ => ([], []) #check f._eq_1 #check f._eq_2 #check f._eq_3
5e333624efc019f1316d085eb678b7dd4e7be4c5
46125763b4dbf50619e8846a1371029346f4c3db
/src/data/subtype.lean
a0197afd05e3ddf5d8fb8ed4811ddd02e8365b59
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
4,648
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ import tactic.lint -- Lean complains if this section is turned into a namespace open function section subtype variables {α : Sort*} {p : α → Prop} @[simp] theorem subtype.forall {q : {a // p a} → Prop} : (∀ x, q x) ↔ (∀ a b, q ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ /-- An alternative version of `subtype.forall`. This one is useful if Lean cannot figure out `q` when using `subtype.forall` from right to left. -/ theorem subtype.forall' {q : ∀x, p x → Prop} : (∀ x h, q x h) ↔ (∀ x : {a // p a}, q x.1 x.2) := (@subtype.forall _ _ (λ x, q x.1 x.2)).symm @[simp] theorem subtype.exists {q : {a // p a} → Prop} : (∃ x, q x) ↔ (∃ a b, q ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ end subtype namespace subtype variables {α : Sort*} {β : Sort*} {γ : Sort*} {p : α → Prop} protected lemma eq' : ∀ {a1 a2 : {x // p x}}, a1.val = a2.val → a1 = a2 | ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl lemma ext {a1 a2 : {x // p x}} : a1 = a2 ↔ a1.val = a2.val := ⟨congr_arg _, subtype.eq'⟩ lemma coe_ext {a1 a2 : {x // p x}} : a1 = a2 ↔ (a1 : α) = a2 := ext theorem val_injective : injective (@val _ p) := λ a b, subtype.eq' /-- Restrict a (dependent) function to a subtype -/ def restrict {α} {β : α → Type*} (f : Πx, β x) (p : α → Prop) (x : subtype p) : β x.1 := f x.1 lemma restrict_apply {α} {β : α → Type*} (f : Πx, β x) (p : α → Prop) (x : subtype p) : restrict f p x = f x.1 := by refl lemma restrict_def {α β} (f : α → β) (p : α → Prop) : restrict f p = f ∘ subtype.val := by refl lemma restrict_injective {α β} {f : α → β} (p : α → Prop) (h : injective f) : injective (restrict f p) := injective_comp h subtype.val_injective /-- Defining a map into a subtype, this can be seen as an "coinduction principle" of `subtype`-/ def coind {α β} (f : α → β) {p : β → Prop} (h : ∀a, p (f a)) : α → subtype p := λ a, ⟨f a, h a⟩ theorem coind_injective {α β} {f : α → β} {p : β → Prop} (h : ∀a, p (f a)) (hf : injective f) : injective (coind f h) := λ x y hxy, hf $ by apply congr_arg subtype.val hxy /-- Restriction of a function to a function on subtypes. -/ def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀a, p a → q (f a)) : subtype p → subtype q := λ x, ⟨f x.1, h x.1 x.2⟩ theorem map_comp {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : subtype p} (f : α → β) (h : ∀a, p a → q (f a)) (g : β → γ) (l : ∀a, q a → r (g a)) : map g l (map f h x) = map (g ∘ f) (assume a ha, l (f a) $ h a ha) x := rfl theorem map_id {p : α → Prop} {h : ∀a, p a → p (id a)} : map (@id α) h = id := funext $ assume ⟨v, h⟩, rfl lemma map_injective {p : α → Prop} {q : β → Prop} {f : α → β} (h : ∀a, p a → q (f a)) (hf : injective f) : injective (map f h) := coind_injective _ $ injective_comp hf val_injective instance [has_equiv α] (p : α → Prop) : has_equiv (subtype p) := ⟨λ s t, s.val ≈ t.val⟩ theorem equiv_iff [has_equiv α] {p : α → Prop} {s t : subtype p} : s ≈ t ↔ s.val ≈ t.val := iff.rfl variables [setoid α] protected theorem refl (s : subtype p) : s ≈ s := setoid.refl s.val protected theorem symm {s t : subtype p} (h : s ≈ t) : t ≈ s := setoid.symm h protected theorem trans {s t u : subtype p} (h₁ : s ≈ t) (h₂ : t ≈ u) : s ≈ u := setoid.trans h₁ h₂ theorem equivalence (p : α → Prop) : equivalence (@has_equiv.equiv (subtype p) _) := mk_equivalence _ subtype.refl (@subtype.symm _ p _) (@subtype.trans _ p _) instance (p : α → Prop) : setoid (subtype p) := setoid.mk (≈) (equivalence p) end subtype namespace subtype variables {α : Type*} {β : Type*} {γ : Type*} {p : α → Prop} @[simp] theorem coe_eta {α : Type*} {p : α → Prop} (a : {a // p a}) (h : p a) : mk ↑a h = a := eta _ _ @[simp] theorem coe_mk {α : Type*} {p : α → Prop} (a h) : (@mk α p a h : α) = a := rfl @[simp, nolint simp_nf] -- built-in reduction doesn't always work theorem mk_eq_mk {α : Type*} {p : α → Prop} {a h a' h'} : @mk α p a h = @mk α p a' h' ↔ a = a' := ⟨λ H, by injection H, λ H, by congr; assumption⟩ @[simp] lemma val_prop {S : set α} (a : {a // a ∈ S}) : a.val ∈ S := a.property @[simp] lemma val_prop' {S : set α} (a : {a // a ∈ S}) : ↑a ∈ S := a.property end subtype
389d1f48e8f9b13befdd3268235968b9814eaf21
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/topology/stone_cech.lean
9f9ceb46aa497dc1f0266f5773d975968f9f6261
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
11,205
lean
/- Copyright (c) 2018 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton Construction of the Stone-Čech compactification using ultrafilters. Parts of the formalization are based on "Ultrafilters and Topology" by Marius Stekelenburg, particularly section 5. -/ import topology.constructions noncomputable theory open filter lattice set universes u v section ultrafilter /- The set of ultrafilters on α carries a natural topology which makes it the Stone-Čech compactification of α (viewed as a discrete space). -/ /-- Basis for the topology on `ultrafilter α`. -/ def ultrafilter_basis (α : Type u) : set (set (ultrafilter α)) := {t | ∃ (s : set α), t = {u | s ∈ u.val}} variables {α : Type u} instance : topological_space (ultrafilter α) := topological_space.generate_from (ultrafilter_basis α) lemma ultrafilter_basis_is_basis : topological_space.is_topological_basis (ultrafilter_basis α) := ⟨begin rintros _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ u ⟨ua, ub⟩, refine ⟨_, ⟨a ∩ b, rfl⟩, u.val.inter_sets ua ub, assume v hv, ⟨_, _⟩⟩; apply v.val.sets_of_superset hv; simp end, eq_univ_of_univ_subset $ subset_sUnion_of_mem $ ⟨univ, eq.symm (eq_univ_of_forall (λ u, u.val.univ_sets))⟩, rfl⟩ /-- The basic open sets for the topology on ultrafilters are open. -/ lemma ultrafilter_is_open_basic (s : set α) : is_open {u : ultrafilter α | s ∈ u.val} := topological_space.is_open_of_is_topological_basis ultrafilter_basis_is_basis ⟨s, rfl⟩ /-- The basic open sets for the topology on ultrafilters are also closed. -/ lemma ultrafilter_is_closed_basic (s : set α) : is_closed {u : ultrafilter α | s ∈ u.val} := begin change is_open (- _), convert ultrafilter_is_open_basic (-s), ext u, exact (ultrafilter_iff_compl_mem_iff_not_mem.mp u.property s).symm end /-- Every ultrafilter `u` on `ultrafilter α` converges to a unique point of `ultrafilter α`, namely `mjoin u`. -/ lemma ultrafilter_converges_iff {u : ultrafilter (ultrafilter α)} {x : ultrafilter α} : u.val ≤ nhds x ↔ x = mjoin u := begin rw [eq_comm, ultrafilter.eq_iff_val_le_val], change u.val ≤ nhds x ↔ x.val.sets ⊆ {a | {v : ultrafilter α | a ∈ v.val} ∈ u.val}, simp only [topological_space.nhds_generate_from, lattice.le_infi_iff, ultrafilter_basis, le_principal_iff], split; intro h, { intros a ha, exact h _ ⟨ha, a, rfl⟩ }, { rintros _ ⟨xi, a, rfl⟩, exact h xi } end instance ultrafilter_compact : compact_space (ultrafilter α) := ⟨compact_iff_ultrafilter_le_nhds.mpr $ assume f uf _, ⟨mjoin ⟨f, uf⟩, trivial, ultrafilter_converges_iff.mpr rfl⟩⟩ instance ultrafilter.t2_space : t2_space (ultrafilter α) := t2_iff_ultrafilter.mpr $ assume f x y u fx fy, have hx : x = mjoin ⟨f, u⟩, from ultrafilter_converges_iff.mp fx, have hy : y = mjoin ⟨f, u⟩, from ultrafilter_converges_iff.mp fy, hx.trans hy.symm lemma ultrafilter_comap_pure_nhds (b : ultrafilter α) : comap pure (nhds b) ≤ b.val := begin rw topological_space.nhds_generate_from, simp only [comap_infi, comap_principal], intros s hs, rw ←le_principal_iff, refine lattice.infi_le_of_le {u | s ∈ u.val} _, refine lattice.infi_le_of_le ⟨hs, ⟨s, rfl⟩⟩ _, rw principal_mono, intros a ha, exact mem_pure_iff.mp ha end section embedding lemma ultrafilter_pure_injective : function.injective (pure : α → ultrafilter α) := begin intros x y h, have : {x} ∈ (pure x : ultrafilter α).val := singleton_mem_pure_sets, rw h at this, exact (mem_singleton_iff.mp (mem_pure_sets.mp this)).symm end open topological_space /-- `pure : α → ultrafilter α` defines a dense inducing of `α` in `ultrafilter α`. -/ lemma dense_inducing_pure : @dense_inducing _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥; exact dense_inducing.mk' pure continuous_bot (assume x, mem_closure_iff_ultrafilter.mpr ⟨x.map ultrafilter.pure, range_mem_map, ultrafilter_converges_iff.mpr (bind_pure x).symm⟩) (assume a s as, ⟨{u | s ∈ u.val}, mem_nhds_sets (ultrafilter_is_open_basic s) (mem_pure_sets.mpr (mem_of_nhds as)), assume b hb, mem_pure_sets.mp hb⟩) -- The following refined version will never be used /-- `pure : α → ultrafilter α` defines a dense embedding of `α` in `ultrafilter α`. -/ lemma dense_embedding_pure : @dense_embedding _ _ ⊥ _ (pure : α → ultrafilter α) := by letI : topological_space α := ⊥ ; exact { inj := ultrafilter_pure_injective, ..dense_inducing_pure } end embedding section extension /- Goal: Any function `α → γ` to a compact Hausdorff space `γ` has a unique extension to a continuous function `ultrafilter α → γ`. We already know it must be unique because `α → ultrafilter α` is a dense embedding and `γ` is Hausdorff. For existence, we will invoke `dense_embedding.continuous_extend`. -/ variables {γ : Type*} [topological_space γ] /-- The extension of a function `α → γ` to a function `ultrafilter α → γ`. When `γ` is a compact Hausdorff space it will be continuous. -/ def ultrafilter.extend (f : α → γ) : ultrafilter α → γ := by letI : topological_space α := ⊥; exact dense_inducing_pure.extend f variables [t2_space γ] lemma ultrafilter_extend_extends (f : α → γ) : ultrafilter.extend f ∘ pure = f := begin letI : topological_space α := ⊥, letI : discrete_topology α := ⟨rfl⟩, exact funext (dense_inducing_pure.extend_eq_of_cont continuous_of_discrete_topology) end variables [compact_space γ] lemma continuous_ultrafilter_extend (f : α → γ) : continuous (ultrafilter.extend f) := have ∀ (b : ultrafilter α), ∃ c, tendsto f (comap ultrafilter.pure (nhds b)) (nhds c) := assume b, -- b.map f is an ultrafilter on γ, which is compact, so it converges to some c in γ. let ⟨c, _, h⟩ := compact_iff_ultrafilter_le_nhds.mp compact_univ (b.map f).val (b.map f).property (by rw [le_principal_iff]; exact univ_mem_sets) in ⟨c, le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h⟩, begin letI : topological_space α := ⊥, letI : normal_space γ := normal_of_compact_t2, exact dense_inducing_pure.continuous_extend this end /-- The value of `ultrafilter.extend f` on an ultrafilter `b` is the unique limit of the ultrafilter `b.map f` in `γ`. -/ lemma ultrafilter_extend_eq_iff {f : α → γ} {b : ultrafilter α} {c : γ} : ultrafilter.extend f b = c ↔ b.val.map f ≤ nhds c := ⟨assume h, begin -- Write b as an ultrafilter limit of pure ultrafilters, and use -- the facts that ultrafilter.extend is a continuous extension of f. let b' : ultrafilter (ultrafilter α) := b.map pure, have t : b'.val ≤ nhds b, from ultrafilter_converges_iff.mpr (by exact (bind_pure _).symm), rw ←h, have := (continuous_ultrafilter_extend f).tendsto b, refine le_trans _ (le_trans (map_mono t) this), change _ ≤ map (ultrafilter.extend f ∘ pure) b.val, rw ultrafilter_extend_extends, exact le_refl _ end, assume h, by letI : topological_space α := ⊥; exact dense_inducing_pure.extend_eq (le_trans (map_mono (ultrafilter_comap_pure_nhds _)) h)⟩ end extension end ultrafilter section stone_cech /- Now, we start with a (not necessarily discrete) topological space α and we want to construct its Stone-Čech compactification. We can build it as a quotient of `ultrafilter α` by the relation which identifies two points if the extension of every continuous function α → γ to a compact Hausdorff space sends the two points to the same point of γ. -/ variables (α : Type u) [topological_space α] instance stone_cech_setoid : setoid (ultrafilter α) := { r := λ x y, ∀ (γ : Type u) [topological_space γ], by exactI ∀ [t2_space γ] [compact_space γ] (f : α → γ) (hf : continuous f), ultrafilter.extend f x = ultrafilter.extend f y, iseqv := ⟨assume x γ tγ h₁ h₂ f hf, rfl, assume x y xy γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).symm, assume x y z xy yz γ tγ h₁ h₂ f hf, by exactI (xy γ f hf).trans (yz γ f hf)⟩ } /-- The Stone-Čech compactification of a topological space. -/ def stone_cech : Type u := quotient (stone_cech_setoid α) variables {α} instance : topological_space (stone_cech α) := by unfold stone_cech; apply_instance /-- The natural map from α to its Stone-Čech compactification. -/ def stone_cech_unit (x : α) : stone_cech α := ⟦pure x⟧ /-- The image of stone_cech_unit is dense. (But stone_cech_unit need not be an embedding, for example if α is not Hausdorff.) -/ lemma stone_cech_unit_dense : closure (range (@stone_cech_unit α _)) = univ := begin convert quotient_dense_of_dense (eq_univ_iff_forall.mp dense_inducing_pure.closure_range), rw [←range_comp], refl end section extension variables {γ : Type u} [topological_space γ] [t2_space γ] [compact_space γ] variables {f : α → γ} (hf : continuous f) local attribute [elab_with_expected_type] quotient.lift /-- The extension of a continuous function from α to a compact Hausdorff space γ to the Stone-Čech compactification of α. -/ def stone_cech_extend : stone_cech α → γ := quotient.lift (ultrafilter.extend f) (λ x y xy, xy γ f hf) lemma stone_cech_extend_extends : stone_cech_extend hf ∘ stone_cech_unit = f := ultrafilter_extend_extends f lemma continuous_stone_cech_extend : continuous (stone_cech_extend hf) := continuous_quot_lift _ (continuous_ultrafilter_extend f) end extension lemma convergent_eqv_pure {u : ultrafilter α} {x : α} (ux : u.val ≤ nhds x) : u ≈ pure x := assume γ tγ h₁ h₂ f hf, begin resetI, transitivity f x, swap, symmetry, all_goals { refine ultrafilter_extend_eq_iff.mpr (le_trans (map_mono _) (hf.tendsto _)) }, { apply pure_le_nhds }, { exact ux } end lemma continuous_stone_cech_unit : continuous (stone_cech_unit : α → stone_cech α) := continuous_iff_ultrafilter.mpr $ λ x g u gx, let g' : ultrafilter α := ⟨g, u⟩ in have (g'.map ultrafilter.pure).val ≤ nhds g', by rw ultrafilter_converges_iff; exact (bind_pure _).symm, have (g'.map stone_cech_unit).val ≤ nhds ⟦g'⟧, from (continuous_at_iff_ultrafilter g').mp (continuous_quotient_mk.tendsto g') _ (ultrafilter_map u) this, by rwa (show ⟦g'⟧ = ⟦pure x⟧, from quotient.sound $ convergent_eqv_pure gx) at this instance stone_cech.t2_space : t2_space (stone_cech α) := begin rw t2_iff_ultrafilter, rintros g ⟨x⟩ ⟨y⟩ u gx gy, apply quotient.sound, intros γ tγ h₁ h₂ f hf, resetI, let ff := stone_cech_extend hf, change ff ⟦x⟧ = ff ⟦y⟧, have lim : ∀ z : ultrafilter α, g ≤ nhds ⟦z⟧ → tendsto ff g (nhds (ff ⟦z⟧)) := assume z gz, calc map ff g ≤ map ff (nhds ⟦z⟧) : map_mono gz ... ≤ nhds (ff ⟦z⟧) : (continuous_stone_cech_extend hf).tendsto _, exact tendsto_nhds_unique u.1 (lim x gx) (lim y gy) end instance stone_cech.compact_space : compact_space (stone_cech α) := quotient.compact_space end stone_cech
a3f01c78523238f16c42fb2db50050cbae59406d
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/for_mathlib/category_theory/equivalence.lean
cc8af05ee752bf26658e935c680fbd35fd6e1430
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
2,907
lean
import category_theory.equivalence open category_theory universes v₁ v₂ u₁ u₂ namespace category_theory.equivalence variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] variables (e : C ≌ D) @[simp] lemma functor_map_inj_iff {X Y : C} (f g : X ⟶ Y) : e.functor.map f = e.functor.map g ↔ f = g := begin split, { intro w, apply e.functor.map_injective, exact w, }, { rintro ⟨rfl⟩, refl, } end @[simp] lemma inverse_map_inj_iff {X Y : D} (f g : X ⟶ Y) : e.inverse.map f = e.inverse.map g ↔ f = g := begin split, { intro w, apply e.inverse.map_injective, exact w, }, { rintro ⟨rfl⟩, refl, } end -- We need special forms of `cancel_nat_iso_hom_right(_assoc)` and `cancel_nat_iso_inv_right(_assoc)` -- for units and counits, because the simplifier can't see that `(𝟭 C).obj X` is the same as `X`. -- We also provide the lemmas for length four compositions, since they're occasionally useful. -- (e.g. in proving that equivalences take monos to monos) @[simp] lemma cancel_unit_right {X Y : C} (f f' : X ⟶ Y) : f ≫ e.unit.app Y = f' ≫ e.unit.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_unit_inv_right {X Y : C} (f f' : X ⟶ e.inverse.obj (e.functor.obj Y)) : f ≫ e.unit_inv.app Y = f' ≫ e.unit_inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_counit_right {X Y : D} (f f' : X ⟶ e.functor.obj (e.inverse.obj Y)) : f ≫ e.counit.app Y = f' ≫ e.counit.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_counit_inv_right {X Y : D} (f f' : X ⟶ Y) : f ≫ e.counit_inv.app Y = f' ≫ e.counit_inv.app Y ↔ f = f' := by simp only [cancel_mono] @[simp] lemma cancel_unit_right_assoc {W X X' Y : C} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) : f ≫ g ≫ e.unit.app Y = f' ≫ g' ≫ e.unit.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_counit_inv_right_assoc {W X X' Y : D} (f : W ⟶ X) (g : X ⟶ Y) (f' : W ⟶ X') (g' : X' ⟶ Y) : f ≫ g ≫ e.counit_inv.app Y = f' ≫ g' ≫ e.counit_inv.app Y ↔ f ≫ g = f' ≫ g' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_unit_right_assoc' {W X X' Y Y' Z : C} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) : f ≫ g ≫ h ≫ e.unit.app Z = f' ≫ g' ≫ h' ≫ e.unit.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' := by simp only [←category.assoc, cancel_mono] @[simp] lemma cancel_counit_inv_right_assoc' {W X X' Y Y' Z : D} (f : W ⟶ X) (g : X ⟶ Y) (h : Y ⟶ Z) (f' : W ⟶ X') (g' : X' ⟶ Y') (h' : Y' ⟶ Z) : f ≫ g ≫ h ≫ e.counit_inv.app Z = f' ≫ g' ≫ h' ≫ e.counit_inv.app Z ↔ f ≫ g ≫ h = f' ≫ g' ≫ h' := by simp only [←category.assoc, cancel_mono] end category_theory.equivalence
842b0d7c10981a03f12f611a058fd2b7936113e3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/maze.lean
a55d9eb6e0bf80f690b06a22ef03fbd156da3c81
[ "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
11,128
lean
import Lean -- Coordinates in a two dimensional grid. ⟨0,0⟩ is the upper left. structure Coords where x : Nat -- column number y : Nat -- row number deriving BEq instance : ToString Coords where toString := (λ ⟨x,y⟩ => String.join ["Coords.mk ", toString x, ", ", toString y]) structure GameState where size : Coords -- coordinates of bottom-right cell position : Coords -- row and column of the player walls : List Coords -- maze cells that are not traversible -- We define custom syntax for GameState. declare_syntax_cat game_cell declare_syntax_cat game_cell_sequence declare_syntax_cat game_row declare_syntax_cat horizontal_border declare_syntax_cat game_top_row declare_syntax_cat game_bottom_row syntax "─" : horizontal_border syntax "\n┌" horizontal_border* "┐\n" : game_top_row syntax "└" horizontal_border* "┘\n" : game_bottom_row syntax "░" : game_cell -- empty syntax "▓" : game_cell -- wall syntax "@" : game_cell -- player syntax "│" game_cell* "│\n" : game_row syntax:max game_top_row game_row* game_bottom_row : term inductive CellContents where | empty : CellContents | wall : CellContents | player : CellContents def update_state_with_row_aux : Nat → Nat → List CellContents → GameState → GameState | currentRowNum, currentColNum, [], oldState => oldState | currentRowNum, currentColNum, cell::contents, oldState => let oldState' := update_state_with_row_aux currentRowNum (currentColNum+1) contents oldState match cell with | CellContents.empty => oldState' | CellContents.wall => {oldState' .. with walls := ⟨currentColNum,currentRowNum⟩::oldState'.walls} | CellContents.player => {oldState' .. with position := ⟨currentColNum,currentRowNum⟩} def update_state_with_row : Nat → List CellContents → GameState → GameState | currentRowNum, rowContents, oldState => update_state_with_row_aux currentRowNum 0 rowContents oldState -- size, current row, remaining cells -> gamestate def game_state_from_cells_aux : Coords → Nat → List (List CellContents) → GameState | size, _, [] => ⟨size, ⟨0,0⟩, []⟩ | size, currentRow, row::rows => let prevState := game_state_from_cells_aux size (currentRow + 1) rows update_state_with_row currentRow row prevState -- size, remaining cells -> gamestate def game_state_from_cells : Coords → List (List CellContents) → GameState | size, cells => game_state_from_cells_aux size 0 cells def termOfCell : Lean.TSyntax `game_cell → Lean.MacroM (Lean.TSyntax `term) | `(game_cell| ░) => `(CellContents.empty) | `(game_cell| ▓) => `(CellContents.wall) | `(game_cell| @) => `(CellContents.player) | _ => Lean.Macro.throwError "unknown game cell" def termOfGameRow : Nat → Lean.TSyntax `game_row → Lean.MacroM (Lean.TSyntax `term) | expectedRowSize, `(game_row| │$cells:game_cell*│) => do if cells.size != expectedRowSize then Lean.Macro.throwError "row has wrong size" let cells' ← Array.mapM termOfCell cells `([$cells',*]) | _, _ => Lean.Macro.throwError "unknown game row" macro_rules | `(┌ $tb:horizontal_border* ┐ $rows:game_row* └ $bb:horizontal_border* ┘) => do let rsize := Lean.Syntax.mkNumLit (toString rows.size) let csize := Lean.Syntax.mkNumLit (toString tb.size) if tb.size != bb.size then Lean.Macro.throwError "top/bottom border mismatch" let rows' ← Array.mapM (termOfGameRow tb.size) rows `(game_state_from_cells ⟨$csize,$rsize⟩ [$rows',*]) --------------------------- -- Now we define a delaborator that will cause GameState to be rendered as a maze. def extractXY : Lean.Expr → Lean.MetaM Coords | e => do let e':Lean.Expr ← (Lean.Meta.whnf e) let sizeArgs := Lean.Expr.getAppArgs e' let x ← Lean.Meta.whnf sizeArgs[0]! let y ← Lean.Meta.whnf sizeArgs[1]! let numCols := (Lean.Expr.natLit? x).get! let numRows := (Lean.Expr.natLit? y).get! return Coords.mk numCols numRows partial def extractWallList : Lean.Expr → Lean.MetaM (List Coords) | exp => do let exp':Lean.Expr ← (Lean.Meta.whnf exp) let f := Lean.Expr.getAppFn exp' if f.constName!.toString == "List.cons" then let consArgs := Lean.Expr.getAppArgs exp' let rest ← extractWallList consArgs[2]! let ⟨wallCol, wallRow⟩ ← extractXY consArgs[1]! return (Coords.mk wallCol wallRow) :: rest else return [] -- "List.nil" partial def extractGameState : Lean.Expr → Lean.MetaM GameState | exp => do let exp': Lean.Expr ← (Lean.Meta.whnf exp) let gameStateArgs := Lean.Expr.getAppArgs exp' let size ← extractXY gameStateArgs[0]! let playerCoords ← extractXY gameStateArgs[1]! let walls ← extractWallList gameStateArgs[2]! pure ⟨size, playerCoords, walls⟩ def update2dArray {α : Type} : Array (Array α) → Coords → α → Array (Array α) | a, ⟨x,y⟩, v => Array.set! a y $ Array.set! (Array.get! a y) x v def update2dArrayMulti {α : Type} : Array (Array α) → List Coords → α → Array (Array α) | a, [], _ => a | a, c::cs, v => let a' := update2dArrayMulti a cs v update2dArray a' c v def delabGameRow : Array (Lean.TSyntax `game_cell) → Lean.PrettyPrinter.Delaborator.DelabM (Lean.TSyntax `game_row) | a => `(game_row| │ $a:game_cell* │) def delabGameState : Lean.Expr → Lean.PrettyPrinter.Delaborator.Delab | e => do guard $ e.getAppNumArgs == 3 let ⟨⟨numCols, numRows⟩, playerCoords, walls⟩ ← try extractGameState e catch err => failure -- can happen if game state has variables in it let topBar := Array.mkArray numCols $ ← `(horizontal_border| ─) let emptyCell ← `(game_cell| ░) let emptyRow := Array.mkArray numCols emptyCell let emptyRowStx ← `(game_row| │$emptyRow:game_cell*│) let allRows := Array.mkArray numRows emptyRowStx let a0 := Array.mkArray numRows $ Array.mkArray numCols emptyCell let a1 := update2dArray a0 playerCoords $ ← `(game_cell| @) let a2 := update2dArrayMulti a1 walls $ ← `(game_cell| ▓) let aa ← Array.mapM delabGameRow a2 `(┌$topBar:horizontal_border*┐ $aa:game_row* └$topBar:horizontal_border*┘) -- The attribute [delab] registers this function as a delaborator for the GameState.mk constructor. @[delab app.GameState.mk] def delabGameStateMk : Lean.PrettyPrinter.Delaborator.Delab := do let e ← Lean.PrettyPrinter.Delaborator.SubExpr.getExpr delabGameState e -- We register the same elaborator for applications of the game_state_from_cells function. @[delab app.game_state_from_cells] def delabGameState' : Lean.PrettyPrinter.Delaborator.Delab := do let e ← Lean.PrettyPrinter.Delaborator.SubExpr.getExpr let e' ← (Lean.Meta.whnf e) delabGameState e' -------------------------- inductive Move where | east : Move | west : Move | north : Move | south : Move @[simp] def make_move : GameState → Move → GameState | ⟨s, ⟨x,y⟩, w⟩, Move.east => if w.notElem ⟨x+1, y⟩ ∧ x + 1 ≤ s.x then ⟨s, ⟨x+1, y⟩, w⟩ else ⟨s, ⟨x,y⟩, w⟩ | ⟨s, ⟨x,y⟩, w⟩, Move.west => if w.notElem ⟨x-1, y⟩ then ⟨s, ⟨x-1, y⟩, w⟩ else ⟨s, ⟨x,y⟩, w⟩ | ⟨s, ⟨x,y⟩, w⟩, Move.north => if w.notElem ⟨x, y-1⟩ then ⟨s, ⟨x, y-1⟩, w⟩ else ⟨s, ⟨x,y⟩, w⟩ | ⟨s, ⟨x,y⟩, w⟩, Move.south => if w.notElem ⟨x, y + 1⟩ ∧ y + 1 ≤ s.y then ⟨s, ⟨x, y+1⟩, w⟩ else ⟨s, ⟨x,y⟩, w⟩ def is_win : GameState → Prop | ⟨⟨sx, sy⟩, ⟨x,y⟩, w⟩ => x = 0 ∨ y = 0 ∨ x + 1 = sx ∨ y + 1 = sy def can_escape (state : GameState) : Prop := ∃ (gs : List Move), is_win (List.foldl make_move state gs) theorem can_still_escape (g : GameState) (m : Move) (hg : can_escape (make_move g m)) : can_escape g := have ⟨pms, hpms⟩ := hg Exists.intro (m::pms) hpms theorem step_west {s: Coords} {x y : Nat} {w: List Coords} (hclear' : w.notElem ⟨x,y⟩) (W : can_escape ⟨s,⟨x,y⟩,w⟩) : can_escape ⟨s,⟨x+1,y⟩,w⟩ := by have hmm : GameState.mk s ⟨x,y⟩ w = make_move ⟨s,⟨x+1, y⟩,w⟩ Move.west := by have h' : x + 1 - 1 = x := rfl simp [h', hclear'] rw [hmm] at W exact can_still_escape ⟨s,⟨x+1,y⟩,w⟩ Move.west W theorem step_east {s: Coords} {x y : Nat} {w: List Coords} (hclear' : w.notElem ⟨x+1,y⟩) (hinbounds : x + 1 ≤ s.x) (E : can_escape ⟨s,⟨x+1,y⟩,w⟩) : can_escape ⟨s,⟨x, y⟩,w⟩ := by have hmm : GameState.mk s ⟨x+1,y⟩ w = make_move ⟨s, ⟨x,y⟩,w⟩ Move.east := by simp [hclear', hinbounds] rw [hmm] at E exact can_still_escape ⟨s, ⟨x,y⟩, w⟩ Move.east E theorem step_north {s: Coords} {x y : Nat} {w: List Coords} (hclear' : w.notElem ⟨x,y⟩) (N : can_escape ⟨s,⟨x,y⟩,w⟩) : can_escape ⟨s,⟨x, y+1⟩,w⟩ := by have hmm : GameState.mk s ⟨x,y⟩ w = make_move ⟨s,⟨x, y+1⟩,w⟩ Move.north := by have h' : y + 1 - 1 = y := rfl simp [h', hclear'] rw [hmm] at N exact can_still_escape ⟨s,⟨x,y+1⟩,w⟩ Move.north N theorem step_south {s: Coords} {x y : Nat} {w: List Coords} (hclear' : w.notElem ⟨x,y+1⟩) (hinbounds : y + 1 ≤ s.y) (S : can_escape ⟨s,⟨x,y+1⟩,w⟩) : can_escape ⟨s,⟨x, y⟩,w⟩ := by have hmm : GameState.mk s ⟨x,y+1⟩ w = make_move ⟨s,⟨x, y⟩,w⟩ Move.south := by simp [hclear', hinbounds] rw [hmm] at S exact can_still_escape ⟨s,⟨x,y⟩,w⟩ Move.south S def escape_west {sx sy : Nat} {y : Nat} {w : List Coords} : can_escape ⟨⟨sx, sy⟩,⟨0, y⟩,w⟩ := ⟨[], Or.inl rfl⟩ def escape_east {sy x y : Nat} {w : List Coords} : can_escape ⟨⟨x+1, sy⟩,⟨x, y⟩,w⟩ := ⟨[], Or.inr $ Or.inr $ Or.inl rfl⟩ def escape_north {sx sy : Nat} {x : Nat} {w : List Coords} : can_escape ⟨⟨sx, sy⟩,⟨x, 0⟩,w⟩ := ⟨[], Or.inr $ Or.inl rfl⟩ def escape_south {sx x y : Nat} {w: List Coords} : can_escape ⟨⟨sx, y+1⟩,⟨x, y⟩,w⟩ := ⟨[], Or.inr $ Or.inr $ Or.inr rfl⟩ -- Define an "or" tactic combinator, like <|> in Lean 3. elab t1:tactic " ⟨|⟩ " t2:tactic : tactic => try Lean.Elab.Tactic.evalTactic t1 catch err => Lean.Elab.Tactic.evalTactic t2 elab "fail" m:term : tactic => throwError m macro "out" : tactic => `(tactic| apply escape_north ⟨|⟩ apply escape_south ⟨|⟩ apply escape_east ⟨|⟩ apply escape_west ⟨|⟩ fail "not currently at maze boundary") def maze1 := ┌───┐ │▓▓▓│ │░@▓│ │▓▓▓│ └───┘ def foo : can_escape maze1 := by apply step_west set_option trace.Meta.debug true in simp out
3be81b1b07d0ed8bc4d0e0328a8cfa735ee35069
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/well_founded_set.lean
7ffd8029384b37cfa859174187ed6d21f6ccd147
[ "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
32,962
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.set.finite import order.well_founded import order.order_iso_nat import algebra.pointwise /-! # Well-founded sets A well-founded subset of an ordered type is one on which the relation `<` is well-founded. ## Main Definitions * `set.well_founded_on s r` indicates that the relation `r` is well-founded when restricted to the set `s`. * `set.is_wf s` indicates that `<` is well-founded when restricted to `s`. * `set.partially_well_ordered_on s r` indicates that the relation `r` is partially well-ordered (also known as well quasi-ordered) when restricted to the set `s`. * `set.is_pwo s` indicates that any infinite sequence of elements in `s` contains an infinite monotone subsequence. Note that ### Definitions for Hahn Series * `set.add_antidiagonal s t a` and `set.mul_antidiagonal s t a` are the sets of pairs of elements from `s` and `t` that add/multiply to `a`. * `finset.add_antidiagonal` and `finset.mul_antidiagonal` are finite versions of `set.add_antidiagonal` and `set.mul_antidiagonal` defined when `s` and `t` are well-founded. ## Main Results * Higman's Lemma, `set.partially_well_ordered_on.partially_well_ordered_on_sublist_forall₂`, shows that if `r` is partially well-ordered on `s`, then `list.sublist_forall₂` is partially well-ordered on the set of lists of elements of `s`. The result was originally published by Higman, but this proof more closely follows Nash-Williams. * `set.well_founded_on_iff` relates `well_founded_on` to the well-foundedness of a relation on the original type, to avoid dealing with subtypes. * `set.is_wf.mono` shows that a subset of a well-founded subset is well-founded. * `set.is_wf.union` shows that the union of two well-founded subsets is well-founded. * `finset.is_wf` shows that all `finset`s are well-founded. ## References * [Higman, *Ordering by Divisibility in Abstract Algebras*][Higman52] * [Nash-Williams, *On Well-Quasi-Ordering Finite Trees*][Nash-Williams63] -/ variables {α : Type*} namespace set /-- `s.well_founded_on r` indicates that the relation `r` is well-founded when restricted to `s`. -/ def well_founded_on (s : set α) (r : α → α → Prop) : Prop := well_founded (λ (a : s) (b : s), r a b) lemma well_founded_on_iff {s : set α} {r : α → α → Prop} : s.well_founded_on r ↔ well_founded (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := begin have f : rel_embedding (λ (a : s) (b : s), r a b) (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := ⟨⟨coe, subtype.coe_injective⟩, λ a b, by simp⟩, refine ⟨λ h, _, f.well_founded⟩, rw well_founded.well_founded_iff_has_min, intros t ht, by_cases hst : (s ∩ t).nonempty, { rw ← subtype.preimage_coe_nonempty at hst, rcases well_founded.well_founded_iff_has_min.1 h (coe ⁻¹' t) hst with ⟨⟨m, ms⟩, mt, hm⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hm ⟨x, xs⟩ xt xm⟩ }, { rcases ht with ⟨m, mt⟩, exact ⟨m, mt, λ x xt ⟨xm, xs, ms⟩, hst ⟨m, ⟨ms, mt⟩⟩⟩ } end lemma well_founded_on.induction {s : set α} {r : α → α → Prop} (hs : s.well_founded_on r) {x : α} (hx : x ∈ s) {P : α → Prop} (hP : ∀ (y ∈ s), (∀ (z ∈ s), r z y → P z) → P y) : P x := begin let Q : s → Prop := λ y, P y, change Q ⟨x, hx⟩, refine well_founded.induction hs ⟨x, hx⟩ _, rintros ⟨y, ys⟩ ih, exact hP _ ys (λ z zs zy, ih ⟨z, zs⟩ zy), end instance is_strict_order.subset {s : set α} {r : α → α → Prop} [is_strict_order α r] : is_strict_order α (λ (a b : α), r a b ∧ a ∈ s ∧ b ∈ s) := { to_is_irrefl := ⟨λ a con, irrefl_of r a con.1 ⟩, to_is_trans := ⟨λ a b c ab bc, ⟨trans_of r ab.1 bc.1, ab.2.1, bc.2.2⟩ ⟩ } theorem well_founded_on_iff_no_descending_seq {s : set α} {r : α → α → Prop} [is_strict_order α r] : s.well_founded_on r ↔ ∀ (f : ((>) : ℕ → ℕ → Prop) ↪r r), ¬ (range f) ⊆ s := begin rw [well_founded_on_iff, rel_embedding.well_founded_iff_no_descending_seq], refine ⟨λ h f con, h begin use f, { exact f.injective }, { intros a b, simp only [con (mem_range_self a), con (mem_range_self b), and_true, gt_iff_lt, function.embedding.coe_fn_mk, f.map_rel_iff] } end, λ h con, _⟩, rcases con with ⟨f, hf⟩, have hfs' : ∀ n : ℕ, f n ∈ s := λ n, (hf.2 n.lt_succ_self).2.2, refine h ⟨f, λ a b, _⟩ (λ n hn, _), { rw ← hf, exact ⟨λ h, ⟨h, hfs' _, hfs' _⟩, λ h, h.1⟩ }, { rcases set.mem_range.1 hn with ⟨m, hm⟩, rw ← hm, apply hfs' } end section has_lt variables [has_lt α] /-- `s.is_wf` indicates that `<` is well-founded when restricted to `s`. -/ def is_wf (s : set α) : Prop := well_founded_on s (<) lemma is_wf_univ_iff : is_wf (univ : set α) ↔ well_founded ((<) : α → α → Prop) := by simp [is_wf, well_founded_on_iff] variables {s t : set α} theorem is_wf.mono (h : is_wf t) (st : s ⊆ t) : is_wf s := begin rw [is_wf, well_founded_on_iff] at *, refine subrelation.wf (λ x y xy, _) h, exact ⟨xy.1, st xy.2.1, st xy.2.2⟩, end end has_lt section partial_order variables [partial_order α] {s t : set α} {a : α} theorem is_wf_iff_no_descending_seq : is_wf s ↔ ∀ (f : (order_dual ℕ) ↪o α), ¬ (range f) ⊆ s := begin haveI : is_strict_order α (λ (a b : α), a < b ∧ a ∈ s ∧ b ∈ s) := { to_is_irrefl := ⟨λ x con, lt_irrefl x con.1⟩, to_is_trans := ⟨λ a b c ab bc, ⟨lt_trans ab.1 bc.1, ab.2.1, bc.2.2⟩⟩, }, rw [is_wf, well_founded_on_iff_no_descending_seq], exact ⟨λ h f, h f.lt_embedding, λ h f, h (order_embedding.of_strict_mono f (λ _ _, f.map_rel_iff.2))⟩, end theorem is_wf.union (hs : is_wf s) (ht : is_wf t) : is_wf (s ∪ t) := begin classical, rw [is_wf_iff_no_descending_seq] at *, rintros f fst, have h : infinite (f ⁻¹' s) ∨ infinite (f ⁻¹' t), { have h : infinite (univ : set ℕ) := infinite_univ, have hpre : f ⁻¹' (s ∪ t) = set.univ, { rw [← image_univ, image_subset_iff, univ_subset_iff] at fst, exact fst }, rw preimage_union at hpre, rw ← hpre at h, rw [infinite, infinite], rw infinite at h, contrapose! h, exact finite.union h.1 h.2, }, rw [← infinite_coe_iff, ← infinite_coe_iff] at h, cases h with inf inf; haveI := inf, { apply hs ((nat.order_embedding_of_set (f ⁻¹' s)).dual.trans f), change range (function.comp f (nat.order_embedding_of_set (f ⁻¹' s))) ⊆ s, rw [range_comp, image_subset_iff], simp }, { apply ht ((nat.order_embedding_of_set (f ⁻¹' t)).dual.trans f), change range (function.comp f (nat.order_embedding_of_set (f ⁻¹' t))) ⊆ t, rw [range_comp, image_subset_iff], simp } end end partial_order end set namespace set /-- A subset is partially well-ordered by a relation `r` when any infinite sequence contains two elements where the first is related to the second by `r`. -/ def partially_well_ordered_on (s) (r : α → α → Prop) : Prop := ∀ (f : ℕ → α), range f ⊆ s → ∃ (m n : ℕ), m < n ∧ r (f m) (f n) /-- A subset of a preorder is partially well-ordered when any infinite sequence contains a monotone subsequence of length 2 (or equivalently, an infinite monotone subsequence). -/ def is_pwo [preorder α] (s) : Prop := partially_well_ordered_on s ((≤) : α → α → Prop) theorem partially_well_ordered_on.mono {s t : set α} {r : α → α → Prop} (ht : t.partially_well_ordered_on r) (hsub : s ⊆ t) : s.partially_well_ordered_on r := λ f hf, ht f (set.subset.trans hf hsub) theorem partially_well_ordered_on.image_of_monotone_on {s : set α} {r : α → α → Prop} {β : Type*} {r' : β → β → Prop} (hs : s.partially_well_ordered_on r) {f : α → β} (hf : ∀ a1 a2 : α, a1 ∈ s → a2 ∈ s → r a1 a2 → r' (f a1) (f a2)) : (f '' s).partially_well_ordered_on r' := λ g hg, begin have h := λ (n : ℕ), ((mem_image _ _ _).1 (hg (mem_range_self n))), obtain ⟨m, n, hlt, hmn⟩ := hs (λ n, classical.some (h n)) _, { refine ⟨m, n, hlt, _⟩, rw [← (classical.some_spec (h m)).2, ← (classical.some_spec (h n)).2], exact hf _ _ (classical.some_spec (h m)).1 (classical.some_spec (h n)).1 hmn }, { rintros _ ⟨n, rfl⟩, exact (classical.some_spec (h n)).1 } end section partial_order variables {s : set α} {t : set α} {r : α → α → Prop} theorem partially_well_ordered_on.exists_monotone_subseq [is_refl α r] [is_trans α r] (h : s.partially_well_ordered_on r) (f : ℕ → α) (hf : range f ⊆ s) : ∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := begin obtain ⟨g, h1 | h2⟩ := exists_increasing_or_nonincreasing_subseq r f, { refine ⟨g, λ m n hle, _⟩, obtain hlt | heq := lt_or_eq_of_le hle, { exact h1 m n hlt, }, { rw [heq], apply refl_of r } }, { exfalso, obtain ⟨m, n, hlt, hle⟩ := h (f ∘ g) (subset.trans (range_comp_subset_range _ _) hf), exact h2 m n hlt hle } end theorem partially_well_ordered_on_iff_exists_monotone_subseq [is_refl α r] [is_trans α r] : s.partially_well_ordered_on r ↔ ∀ f : ℕ → α, range f ⊆ s → ∃ (g : ℕ ↪o ℕ), ∀ m n : ℕ, m ≤ n → r (f (g m)) (f (g n)) := begin classical, split; intros h f hf, { exact h.exists_monotone_subseq f hf }, { obtain ⟨g, gmon⟩ := h f hf, refine ⟨g 0, g 1, g.lt_iff_lt.2 zero_lt_one, gmon _ _ zero_le_one⟩, } end lemma partially_well_ordered_on.well_founded_on [is_partial_order α r] (h : s.partially_well_ordered_on r) : s.well_founded_on (λ a b, r a b ∧ a ≠ b) := begin haveI : is_strict_order α (λ a b, r a b ∧ a ≠ b) := { to_is_irrefl := ⟨λ a con, con.2 rfl⟩, to_is_trans := ⟨λ a b c ab bc, ⟨trans ab.1 bc.1, λ ac, ab.2 (antisymm ab.1 (ac.symm ▸ bc.1))⟩⟩ }, rw well_founded_on_iff_no_descending_seq, intros f con, obtain ⟨m, n, hlt, hle⟩ := h f con, exact (f.map_rel_iff.2 hlt).2 (antisymm hle (f.map_rel_iff.2 hlt).1).symm, end variables [partial_order α] lemma is_pwo.is_wf (h : s.is_pwo) : s.is_wf := begin rw [is_wf], convert h.well_founded_on, ext x y, rw lt_iff_le_and_ne, end theorem is_pwo.exists_monotone_subseq (h : s.is_pwo) (f : ℕ → α) (hf : range f ⊆ s) : ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := h.exists_monotone_subseq f hf theorem is_pwo_iff_exists_monotone_subseq : s.is_pwo ↔ ∀ f : ℕ → α, range f ⊆ s → ∃ (g : ℕ ↪o ℕ), monotone (f ∘ g) := partially_well_ordered_on_iff_exists_monotone_subseq lemma is_pwo.prod (hs : s.is_pwo) (ht : t.is_pwo) : (s.prod t).is_pwo := begin classical, rw is_pwo_iff_exists_monotone_subseq at *, intros f hf, obtain ⟨g1, h1⟩ := hs (prod.fst ∘ f) _, swap, { rw [range_comp, image_subset_iff], refine subset.trans hf _, rintros ⟨x1, x2⟩ hx, simp only [mem_preimage, hx.1] }, obtain ⟨g2, h2⟩ := ht (prod.snd ∘ f ∘ g1) _, refine ⟨g2.trans g1, λ m n mn, _⟩, swap, { rw [range_comp, image_subset_iff], refine subset.trans (range_comp_subset_range _ _) (subset.trans hf _), rintros ⟨x1, x2⟩ hx, simp only [mem_preimage, hx.2] }, simp only [rel_embedding.coe_trans, function.comp_app], exact ⟨h1 (g2.le_iff_le.2 mn), h2 mn⟩, end theorem is_pwo.image_of_monotone {β : Type*} [partial_order β] (hs : s.is_pwo) {f : α → β} (hf : monotone f) : is_pwo (f '' s) := hs.image_of_monotone_on (λ _ _ _ _ ab, hf ab) theorem is_pwo.union (hs : is_pwo s) (ht : is_pwo t) : is_pwo (s ∪ t) := begin classical, rw [is_pwo_iff_exists_monotone_subseq] at *, rintros f fst, have h : infinite (f ⁻¹' s) ∨ infinite (f ⁻¹' t), { have h : infinite (univ : set ℕ) := infinite_univ, have hpre : f ⁻¹' (s ∪ t) = set.univ, { rw [← image_univ, image_subset_iff, univ_subset_iff] at fst, exact fst }, rw preimage_union at hpre, rw ← hpre at h, rw [infinite, infinite], rw infinite at h, contrapose! h, exact finite.union h.1 h.2, }, rw [← infinite_coe_iff, ← infinite_coe_iff] at h, cases h with inf inf; haveI := inf, { obtain ⟨g, hg⟩ := hs (f ∘ (nat.order_embedding_of_set (f ⁻¹' s))) _, { rw [function.comp.assoc, ← rel_embedding.coe_trans] at hg, exact ⟨_, hg⟩ }, rw [range_comp, image_subset_iff], simp }, { obtain ⟨g, hg⟩ := ht (f ∘ (nat.order_embedding_of_set (f ⁻¹' t))) _, { rw [function.comp.assoc, ← rel_embedding.coe_trans] at hg, exact ⟨_, hg⟩ }, rw [range_comp, image_subset_iff], simp } end end partial_order theorem is_wf.is_pwo [linear_order α] {s : set α} (hs : s.is_wf) : s.is_pwo := λ f hf, begin rw [is_wf, well_founded_on_iff] at hs, have hrange : (range f).nonempty := ⟨f 0, mem_range_self 0⟩, let a := hs.min (range f) hrange, obtain ⟨m, hm⟩ := hs.min_mem (range f) hrange, refine ⟨m, m.succ, m.lt_succ_self, le_of_not_lt (λ con, _)⟩, rw hm at con, apply hs.not_lt_min (range f) hrange (mem_range_self m.succ) ⟨con, hf (mem_range_self m.succ), hf _⟩, rw ← hm, apply mem_range_self, end theorem is_wf_iff_is_pwo [linear_order α] {s : set α} : s.is_wf ↔ s.is_pwo := ⟨is_wf.is_pwo, is_pwo.is_wf⟩ end set namespace finset @[simp] theorem partially_well_ordered_on {r : α → α → Prop} [is_refl α r] (f : finset α) : set.partially_well_ordered_on (↑f : set α) r := begin intros g hg, by_cases hinj : function.injective g, { exact (set.infinite_of_injective_forall_mem hinj (set.range_subset_iff.1 hg) f.finite_to_set).elim }, { rw [function.injective] at hinj, push_neg at hinj, obtain ⟨m, n, gmgn, hne⟩ := hinj, cases lt_or_gt_of_ne hne with hlt hlt; { refine ⟨_, _, hlt, _⟩, rw gmgn, exact refl_of r _, } } end @[simp] theorem is_pwo [partial_order α] (f : finset α) : set.is_pwo (↑f : set α) := f.partially_well_ordered_on @[simp] theorem well_founded_on {r : α → α → Prop} [is_strict_order α r] (f : finset α) : set.well_founded_on (↑f : set α) r := begin rw [set.well_founded_on_iff_no_descending_seq], intros g con, apply set.infinite_of_injective_forall_mem g.injective (set.range_subset_iff.1 con), exact f.finite_to_set, end @[simp] theorem is_wf [partial_order α] (f : finset α) : set.is_wf (↑f : set α) := f.is_pwo.is_wf end finset namespace set variables [partial_order α] {s : set α} {a : α} theorem finite.is_pwo (h : s.finite) : s.is_pwo := begin rw ← h.coe_to_finset, exact h.to_finset.is_pwo, end @[simp] theorem fintype.is_pwo [fintype α] : s.is_pwo := (finite.of_fintype s).is_pwo @[simp] theorem is_pwo_empty : is_pwo (∅ : set α) := finite_empty.is_pwo @[simp] theorem is_pwo_singleton (a) : is_pwo ({a} : set α) := (finite_singleton a).is_pwo theorem is_pwo.insert (a) (hs : is_pwo s) : is_pwo (insert a s) := by { rw ← union_singleton, exact hs.union (is_pwo_singleton a) } /-- `is_wf.min` returns a minimal element of a nonempty well-founded set. -/ noncomputable def is_wf.min (hs : is_wf s) (hn : s.nonempty) : α := hs.min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) lemma is_wf.min_mem (hs : is_wf s) (hn : s.nonempty) : hs.min hn ∈ s := (well_founded.min hs univ (nonempty_iff_univ_nonempty.1 hn.to_subtype)).2 lemma is_wf.not_lt_min (hs : is_wf s) (hn : s.nonempty) (ha : a ∈ s) : ¬ a < hs.min hn := hs.not_lt_min univ (nonempty_iff_univ_nonempty.1 hn.to_subtype) (mem_univ (⟨a, ha⟩ : s)) @[simp] lemma is_wf_min_singleton (a) {hs : is_wf ({a} : set α)} {hn : ({a} : set α).nonempty} : hs.min hn = a := eq_of_mem_singleton (is_wf.min_mem hs hn) end set @[simp] theorem finset.is_wf_sup {ι : Type*} [partial_order α] (f : finset ι) (g : ι → set α) (hf : ∀ i : ι, i ∈ f → (g i).is_wf) : (f.sup g).is_wf := begin classical, revert hf, apply f.induction_on, { intro h, simp [set.is_pwo_empty.is_wf], }, { intros s f sf hf hsf, rw finset.sup_insert, exact (hsf s (finset.mem_insert_self _ _)).union (hf (λ s' s'f, hsf _ (finset.mem_insert_of_mem s'f))) } end @[simp] theorem finset.is_pwo_sup {ι : Type*} [partial_order α] (f : finset ι) (g : ι → set α) (hf : ∀ i : ι, i ∈ f → (g i).is_pwo) : (f.sup g).is_pwo := begin classical, revert hf, apply f.induction_on, { intro h, simp [set.is_pwo_empty.is_wf], }, { intros s f sf hf hsf, rw finset.sup_insert, exact (hsf s (finset.mem_insert_self _ _)).union (hf (λ s' s'f, hsf _ (finset.mem_insert_of_mem s'f))) } end namespace set variables [linear_order α] {s t : set α} {a : α} lemma is_wf.min_le (hs : s.is_wf) (hn : s.nonempty) (ha : a ∈ s) : hs.min hn ≤ a := le_of_not_lt (hs.not_lt_min hn ha) lemma is_wf.le_min_iff (hs : s.is_wf) (hn : s.nonempty) : a ≤ hs.min hn ↔ ∀ b, b ∈ s → a ≤ b := ⟨λ ha b hb, le_trans ha (hs.min_le hn hb), λ h, h _ (hs.min_mem _)⟩ lemma is_wf.min_le_min_of_subset {hs : s.is_wf} {hsn : s.nonempty} {ht : t.is_wf} {htn : t.nonempty} (hst : s ⊆ t) : ht.min htn ≤ hs.min hsn := (is_wf.le_min_iff _ _).2 (λ b hb, ht.min_le htn (hst hb)) lemma is_wf.min_union (hs : s.is_wf) (hsn : s.nonempty) (ht : t.is_wf) (htn : t.nonempty) : (hs.union ht).min (union_nonempty.2 (or.intro_left _ hsn)) = min (hs.min hsn) (ht.min htn) := begin refine le_antisymm (le_min (is_wf.min_le_min_of_subset (subset_union_left _ _)) (is_wf.min_le_min_of_subset (subset_union_right _ _))) _, rw min_le_iff, exact ((mem_union _ _ _).1 ((hs.union ht).min_mem (union_nonempty.2 (or.intro_left _ hsn)))).imp (hs.min_le _) (ht.min_le _), end end set namespace set variables {s : set α} {t : set α} @[to_additive] theorem is_pwo.mul [ordered_cancel_comm_monoid α] (hs : s.is_pwo) (ht : t.is_pwo) : is_pwo (s * t) := begin rw ← image_mul_prod, exact (is_pwo.prod hs ht).image_of_monotone (λ _ _ h, mul_le_mul' h.1 h.2), end variable [linear_ordered_cancel_comm_monoid α] @[to_additive] theorem is_wf.mul (hs : s.is_wf) (ht : t.is_wf) : is_wf (s * t) := (hs.is_pwo.mul ht.is_pwo).is_wf @[to_additive] theorem is_wf.min_mul (hs : s.is_wf) (ht : t.is_wf) (hsn : s.nonempty) (htn : t.nonempty) : (hs.mul ht).min (hsn.mul htn) = hs.min hsn * ht.min htn := begin refine le_antisymm (is_wf.min_le _ _ (mem_mul.2 ⟨_, _, hs.min_mem _, ht.min_mem _, rfl⟩)) _, rw is_wf.le_min_iff, rintros _ ⟨x, y, hx, hy, rfl⟩, exact mul_le_mul' (hs.min_le _ hx) (ht.min_le _ hy), end end set namespace set namespace partially_well_ordered_on /-- In the context of partial well-orderings, a bad sequence is a nonincreasing sequence whose range is contained in a particular set `s`. One exists if and only if `s` is not partially well-ordered. -/ def is_bad_seq (r : α → α → Prop) (s : set α) (f : ℕ → α) : Prop := set.range f ⊆ s ∧ ∀ (m n : ℕ), m < n → ¬ r (f m) (f n) lemma iff_forall_not_is_bad_seq (r : α → α → Prop) (s : set α) : s.partially_well_ordered_on r ↔ ∀ f, ¬ is_bad_seq r s f := begin rw [set.partially_well_ordered_on], apply forall_congr (λ f, _), simp [is_bad_seq] end /-- This indicates that every bad sequence `g` that agrees with `f` on the first `n` terms has `rk (f n) ≤ rk (g n)`. -/ def is_min_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) : Prop := ∀ g : ℕ → α, (∀ (m : ℕ), m < n → f m = g m) → rk (g n) < rk (f n) → ¬ is_bad_seq r s g /-- Given a bad sequence `f`, this constructs a bad sequence that agrees with `f` on the first `n` terms and is minimal at `n`. -/ noncomputable def min_bad_seq_of_bad_seq (r : α → α → Prop) (rk : α → ℕ) (s : set α) (n : ℕ) (f : ℕ → α) (hf : is_bad_seq r s f) : { g : ℕ → α // (∀ (m : ℕ), m < n → f m = g m) ∧ is_bad_seq r s g ∧ is_min_bad_seq r rk s n g } := begin classical, have h : ∃ (k : ℕ) (g : ℕ → α), (∀ m, m < n → f m = g m) ∧ is_bad_seq r s g ∧ rk (g n) = k := ⟨_, f, λ _ _, rfl, hf, rfl⟩, obtain ⟨h1, h2, h3⟩ := classical.some_spec (nat.find_spec h), refine ⟨classical.some (nat.find_spec h), h1, by convert h2, λ g hg1 hg2 con, _⟩, refine nat.find_min h _ ⟨g, λ m mn, (h1 m mn).trans (hg1 m mn), by convert con, rfl⟩, rwa ← h3, end lemma exists_min_bad_of_exists_bad (r : α → α → Prop) (rk : α → ℕ) (s : set α) : (∃ f, is_bad_seq r s f) → ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f := begin rintro ⟨f0, (hf0 : is_bad_seq r s f0)⟩, let fs : Π (n : ℕ), { f : ℕ → α // is_bad_seq r s f ∧ is_min_bad_seq r rk s n f }, { refine nat.rec _ _, { exact ⟨(min_bad_seq_of_bad_seq r rk s 0 f0 hf0).1, (min_bad_seq_of_bad_seq r rk s 0 f0 hf0).2.2⟩, }, { exact λ n fn, ⟨(min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).1, (min_bad_seq_of_bad_seq r rk s (n + 1) fn.1 fn.2.1).2.2⟩ } }, have h : ∀ m n, m ≤ n → (fs m).1 m = (fs n).1 m, { intros m n mn, obtain ⟨k, rfl⟩ := exists_add_of_le mn, clear mn, induction k with k ih, { refl }, rw [ih, ((min_bad_seq_of_bad_seq r rk s (m + k).succ (fs (m + k)).1 (fs (m + k)).2.1).2.1 m (nat.lt_succ_iff.2 (nat.add_le_add_left k.zero_le m)))], refl }, refine ⟨λ n, (fs n).1 n, ⟨set.range_subset_iff.2 (λ n, ((fs n).2).1.1 (mem_range_self n)), λ m n mn, _⟩, λ n g hg1 hg2, _⟩, { dsimp, rw [← subtype.val_eq_coe, h m n (le_of_lt mn)], convert (fs n).2.1.2 m n mn }, { convert (fs n).2.2 g (λ m mn, eq.trans _ (hg1 m mn)) (lt_of_lt_of_le hg2 (le_refl _)), rw ← h m n (le_of_lt mn) }, end lemma iff_not_exists_is_min_bad_seq {r : α → α → Prop} (rk : α → ℕ) {s : set α} : s.partially_well_ordered_on r ↔ ¬ ∃ f, is_bad_seq r s f ∧ ∀ n, is_min_bad_seq r rk s n f := begin rw [iff_forall_not_is_bad_seq, ← not_exists, not_congr], split, { apply exists_min_bad_of_exists_bad }, rintro ⟨f, hf1, hf2⟩, exact ⟨f, hf1⟩, end /-- Higman's Lemma, which states that for any reflexive, transitive relation `r` which is partially well-ordered on a set `s`, the relation `list.sublist_forall₂ r` is partially well-ordered on the set of lists of elements of `s`. That relation is defined so that `list.sublist_forall₂ r l₁ l₂` whenever `l₁` related pointwise by `r` to a sublist of `l₂`. -/ lemma partially_well_ordered_on_sublist_forall₂ (r : α → α → Prop) [is_refl α r] [is_trans α r] {s : set α} (h : s.partially_well_ordered_on r) : { l : list α | ∀ x, x ∈ l → x ∈ s }.partially_well_ordered_on (list.sublist_forall₂ r) := begin rcases s.eq_empty_or_nonempty with rfl | ⟨as, has⟩, { apply partially_well_ordered_on.mono (finset.partially_well_ordered_on {list.nil}), { intros l hl, rw [finset.mem_coe, finset.mem_singleton, list.eq_nil_iff_forall_not_mem], exact hl, }, apply_instance }, haveI : inhabited α := ⟨as⟩, rw [iff_not_exists_is_min_bad_seq (list.length)], rintro ⟨f, hf1, hf2⟩, have hnil : ∀ n, f n ≠ list.nil := λ n con, (hf1).2 n n.succ n.lt_succ_self (con.symm ▸ list.sublist_forall₂.nil), obtain ⟨g, hg⟩ := h.exists_monotone_subseq (list.head ∘ f) _, swap, { simp only [set.range_subset_iff, function.comp_apply], exact λ n, hf1.1 (set.mem_range_self n) _ (list.head_mem_self (hnil n)) }, have hf' := hf2 (g 0) (λ n, if n < g 0 then f n else list.tail (f (g (n - g 0)))) (λ m hm, (if_pos hm).symm) _, swap, { simp only [if_neg (lt_irrefl (g 0)), nat.sub_self], rw [list.length_tail, ← nat.pred_eq_sub_one], exact nat.pred_lt (λ con, hnil _ (list.length_eq_zero.1 con)) }, rw [is_bad_seq] at hf', push_neg at hf', obtain ⟨m, n, mn, hmn⟩ := hf' _, swap, { rw set.range_subset_iff, rintro n x hx, split_ifs at hx with hn hn, { exact hf1.1 (set.mem_range_self _) _ hx }, { refine hf1.1 (set.mem_range_self _) _ (list.tail_subset _ hx), } }, by_cases hn : n < g 0, { apply hf1.2 m n mn, rwa [if_pos hn, if_pos (mn.trans hn)] at hmn }, { obtain ⟨n', rfl⟩ := le_iff_exists_add.1 (not_lt.1 hn), rw [if_neg hn, add_comm (g 0) n', nat.add_sub_cancel] at hmn, split_ifs at hmn with hm hm, { apply hf1.2 m (g n') (lt_of_lt_of_le hm (g.monotone n'.zero_le)), exact trans hmn (list.tail_sublist_forall₂_self _) }, { rw [← (nat.sub_lt_left_iff_lt_add (le_of_not_lt hm))] at mn, apply hf1.2 _ _ (g.lt_iff_lt.2 mn), rw [← list.cons_head_tail (hnil (g (m - g 0))), ← list.cons_head_tail (hnil (g n'))], exact list.sublist_forall₂.cons (hg _ _ (le_of_lt mn)) hmn, } } end end partially_well_ordered_on namespace is_pwo @[to_additive] lemma submonoid_closure [ordered_cancel_comm_monoid α] {s : set α} (hpos : ∀ x : α, x ∈ s → 1 ≤ x) (h : s.is_pwo) : is_pwo ((submonoid.closure s) : set α) := begin have hl : ((submonoid.closure s) : set α) ⊆ list.prod '' { l : list α | ∀ x, x ∈ l → x ∈ s }, { intros x hx, rw set_like.mem_coe at hx, refine submonoid.closure_induction hx (λ x hx, ⟨_, λ y hy, _, list.prod_singleton⟩) ⟨_, λ y hy, (list.not_mem_nil _ hy).elim, list.prod_nil⟩ _, { rwa list.mem_singleton.1 hy }, rintros _ _ ⟨l, hl, rfl⟩ ⟨l', hl', rfl⟩, refine ⟨_, λ y hy, _, list.prod_append⟩, cases list.mem_append.1 hy with hy hy, { exact hl _ hy }, { exact hl' _ hy } }, apply ((h.partially_well_ordered_on_sublist_forall₂ (≤)).image_of_monotone_on _).mono hl, intros l1 l2 hl1 hl2 h12, obtain ⟨l, hll1, hll2⟩ := list.sublist_forall₂_iff.1 h12, refine le_trans (list.rel_prod (le_refl 1) (λ a b ab c d cd, mul_le_mul' ab cd) hll1) _, obtain ⟨l', hl'⟩ := hll2.exists_perm_append, rw [hl'.prod_eq, list.prod_append, ← mul_one l.prod, mul_assoc, one_mul], apply mul_le_mul_left', have hl's := λ x hx, hl2 x (list.subset.trans (l.subset_append_right _) hl'.symm.subset hx), clear hl', induction l' with x1 x2 x3 x4 x5, { refl }, rw [list.prod_cons, ← one_mul (1 : α)], exact mul_le_mul' (hpos x1 (hl's x1 (list.mem_cons_self x1 x2))) (x3 (λ x hx, hl's x (list.mem_cons_of_mem _ hx))) end end is_pwo /-- `set.mul_antidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`. -/ @[to_additive "`set.add_antidiagonal s t a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`."] def mul_antidiagonal [monoid α] (s t : set α) (a : α) : set (α × α) := { x | x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t } namespace mul_antidiagonal @[simp, to_additive] lemma mem_mul_antidiagonal [monoid α] {s t : set α} {a : α} {x : α × α} : x ∈ mul_antidiagonal s t a ↔ x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t := iff.refl _ section cancel_comm_monoid variables [cancel_comm_monoid α] {s t : set α} {a : α} @[to_additive] lemma fst_eq_fst_iff_snd_eq_snd {x y : (mul_antidiagonal s t a)} : (x : α × α).fst = (y : α × α).fst ↔ (x : α × α).snd = (y : α × α).snd := ⟨λ h, begin have hx := x.2.1, rw [subtype.val_eq_coe, h] at hx, apply mul_left_cancel (hx.trans y.2.1.symm), end, λ h, begin have hx := x.2.1, rw [subtype.val_eq_coe, h] at hx, apply mul_right_cancel (hx.trans y.2.1.symm), end⟩ @[to_additive] lemma eq_of_fst_eq_fst {x y : (mul_antidiagonal s t a)} (h : (x : α × α).fst = (y : α × α).fst) : x = y := subtype.ext (prod.ext h (mul_antidiagonal.fst_eq_fst_iff_snd_eq_snd.1 h)) @[to_additive] lemma eq_of_snd_eq_snd {x y : (mul_antidiagonal s t a)} (h : (x : α × α).snd = (y : α × α).snd) : x = y := subtype.ext (prod.ext (mul_antidiagonal.fst_eq_fst_iff_snd_eq_snd.2 h) h) end cancel_comm_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid α] (s t : set α) (a : α) @[to_additive] lemma eq_of_fst_le_fst_of_snd_le_snd {x y : (mul_antidiagonal s t a)} (h1 : (x : α × α).fst ≤ (y : α × α).fst) (h2 : (x : α × α).snd ≤ (y : α × α).snd ) : x = y := begin apply eq_of_fst_eq_fst, cases eq_or_lt_of_le h1 with heq hlt, { exact heq }, exfalso, exact ne_of_lt (mul_lt_mul_of_lt_of_le hlt h2) ((mem_mul_antidiagonal.1 x.2).1.trans (mem_mul_antidiagonal.1 y.2).1.symm) end variables {s} {t} @[to_additive] theorem finite_of_is_pwo (hs : s.is_pwo) (ht : t.is_pwo) (a) : (mul_antidiagonal s t a).finite := begin by_contra h, rw [← set.infinite] at h, have h1 : (mul_antidiagonal s t a).partially_well_ordered_on (prod.fst ⁻¹'o (≤)), { intros f hf, refine hs (prod.fst ∘ f) _, rw range_comp, rintros _ ⟨⟨x, y⟩, hxy, rfl⟩, exact (mem_mul_antidiagonal.1 (hf hxy)).2.1 }, have h2 : (mul_antidiagonal s t a).partially_well_ordered_on (prod.snd ⁻¹'o (≤)), { intros f hf, refine ht (prod.snd ∘ f) _, rw range_comp, rintros _ ⟨⟨x, y⟩, hxy, rfl⟩, exact (mem_mul_antidiagonal.1 (hf hxy)).2.2 }, obtain ⟨g, hg⟩ := h1.exists_monotone_subseq (λ x, h.nat_embedding _ x) _, swap, { rintro _ ⟨k, rfl⟩, exact ((infinite.nat_embedding (s.mul_antidiagonal t a) h) _).2 }, obtain ⟨m, n, mn, h2'⟩ := h2 (λ x, (h.nat_embedding _) (g x)) _, swap, { rintro _ ⟨k, rfl⟩, exact ((infinite.nat_embedding (s.mul_antidiagonal t a) h) _).2, }, apply ne_of_lt mn (g.injective ((h.nat_embedding _).injective _)), exact eq_of_fst_le_fst_of_snd_le_snd _ _ _ (hg _ _ (le_of_lt mn)) h2', end end ordered_cancel_comm_monoid @[to_additive] theorem finite_of_is_wf [linear_ordered_cancel_comm_monoid α] {s t : set α} (hs : s.is_wf) (ht : t.is_wf) (a) : (mul_antidiagonal s t a).finite := finite_of_is_pwo hs.is_pwo ht.is_pwo a end mul_antidiagonal end set namespace finset variables [ordered_cancel_comm_monoid α] variables {s t : set α} (hs : s.is_pwo) (ht : t.is_pwo) (a : α) /-- `finset.mul_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in `s` and an element in `t` that multiply to `a`, but its construction requires proofs `hs` and `ht` that `s` and `t` are well-ordered. -/ @[to_additive "`finset.add_antidiagonal_of_is_wf hs ht a` is the set of all pairs of an element in `s` and an element in `t` that add to `a`, but its construction requires proofs `hs` and `ht` that `s` and `t` are well-ordered."] noncomputable def mul_antidiagonal : finset (α × α) := (set.mul_antidiagonal.finite_of_is_pwo hs ht a).to_finset variables {hs} {ht} {u : set α} {hu : u.is_pwo} {a} {x : α × α} @[simp, to_additive] lemma mem_mul_antidiagonal : x ∈ mul_antidiagonal hs ht a ↔ x.1 * x.2 = a ∧ x.1 ∈ s ∧ x.2 ∈ t := by simp [mul_antidiagonal] @[to_additive] lemma mul_antidiagonal_mono_left (hus : u ⊆ s) : (finset.mul_antidiagonal hu ht a) ⊆ (finset.mul_antidiagonal hs ht a) := λ x hx, begin rw mem_mul_antidiagonal at *, exact ⟨hx.1, hus hx.2.1, hx.2.2⟩, end @[to_additive] lemma mul_antidiagonal_mono_right (hut : u ⊆ t) : (finset.mul_antidiagonal hs hu a) ⊆ (finset.mul_antidiagonal hs ht a) := λ x hx, begin rw mem_mul_antidiagonal at *, exact ⟨hx.1, hx.2.1, hut hx.2.2⟩, end @[to_additive] lemma support_mul_antidiagonal_subset_mul : { a : α | (mul_antidiagonal hs ht a).nonempty } ⊆ s * t := (λ x ⟨⟨a1, a2⟩, ha⟩, begin obtain ⟨hmul, h1, h2⟩ := mem_mul_antidiagonal.1 ha, exact ⟨a1, a2, h1, h2, hmul⟩, end) @[to_additive] theorem is_pwo_support_mul_antidiagonal : { a : α | (mul_antidiagonal hs ht a).nonempty }.is_pwo := (hs.mul ht).mono support_mul_antidiagonal_subset_mul @[to_additive] theorem mul_antidiagonal_min_mul_min {α} [linear_ordered_cancel_comm_monoid α] {s t : set α} (hs : s.is_wf) (ht : t.is_wf) (hns : s.nonempty) (hnt : t.nonempty) : mul_antidiagonal hs.is_pwo ht.is_pwo ((hs.min hns) * (ht.min hnt)) = {(hs.min hns, ht.min hnt)} := begin ext ⟨a1, a2⟩, rw [mem_mul_antidiagonal, finset.mem_singleton, prod.ext_iff], split, { rintro ⟨hast, has, hat⟩, cases eq_or_lt_of_le (hs.min_le hns has) with heq hlt, { refine ⟨heq.symm, _⟩, rw heq at hast, exact mul_left_cancel hast }, { contrapose hast, exact ne_of_gt (mul_lt_mul_of_lt_of_le hlt (ht.min_le hnt hat)) } }, { rintro ⟨ha1, ha2⟩, rw [ha1, ha2], exact ⟨rfl, hs.min_mem _, ht.min_mem _⟩ } end end finset lemma well_founded.is_wf [has_lt α] (h : well_founded ((<) : α → α → Prop)) (s : set α) : s.is_wf := (set.is_wf_univ_iff.2 h).mono (set.subset_univ s)
5226ead0022bd1e06bfe05b5be73ba032b6b2ca0
7da5ceac20aaab989eeb795a4be9639982e7b35a
/src/to_mathlib.lean
015d1b3c91f09c27d993e4d6fcfce4d81ef6b978
[ "MIT" ]
permissive
formalabstracts/formalabstracts
46c2f1b3a172e62ca6ffeb46fbbdf1705718af49
b0173da1af45421239d44492eeecd54bf65ee0f6
refs/heads/master
1,606,896,370,374
1,572,988,776,000
1,572,988,776,000
96,763,004
165
28
null
1,555,709,319,000
1,499,680,948,000
Lean
UTF-8
Lean
false
false
1,527
lean
/- Individual results that should be moved to mathlib. If there are many related results, put them in a separate file. -/ import .basic data.finsupp universe variables u v open function /- move to logic -/ def ite_ne_neg {p : Prop} [h : decidable p] {α : Sort u} {x y : α} (h : ite p x y ≠ y) : p := by { by_cases hp : p, exact hp, rw [if_neg hp] at h, contradiction } def ite_ne_pos {p : Prop} [h : decidable p] {α : Sort u} {x y : α} (h : ite p x y ≠ x) : ¬p := by { by_cases hp : p, rw [if_pos hp] at h, contradiction, exact hp } namespace sum lemma injective_inl {α β : Type*} : injective (inl : α → α ⊕ β) := λ x y, inl.inj lemma injective_inr {α β : Type*} : injective (inr : β → α ⊕ β) := λ x y, inr.inj def embedding_inl {α β : Type*} : α ↪ α ⊕ β := ⟨inl, injective_inl⟩ def embedding_inr {α β : Type*} : β ↪ α ⊕ β := ⟨inr, injective_inr⟩ end sum namespace equiv def equiv_embedding_fun {α β : Type*} : (α ≃ β) ↪ (α → β) := ⟨equiv.to_fun, λ f g, eq_of_to_fun_eq⟩ end equiv namespace finsupp /- move to finsupp -/ lemma injective_emb_domain {α β γ : Type*} [has_zero γ] [decidable_eq β] (f : α ↪ β) : injective (emb_domain f : (α →₀ γ) → (β →₀ γ)) := omitted def finsupp_embedding_finsupp_left {α β γ : Type*} [has_zero γ] [decidable_eq β] (f : α ↪ β) : (α →₀ γ) ↪ (β →₀ γ) := ⟨λ g, emb_domain f g, injective_emb_domain f⟩ end finsupp
26202ce582bb5a3ea5695911f414f5b94c327d95
e61a235b8468b03aee0120bf26ec615c045005d2
/tests/compiler/termparsertest1.lean
222ce942ac4661d06d3cb645decb0d2eae1fc5c9
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,604
lean
import Init.Lean.Parser.Term open Lean open Lean.Parser def testParser (input : String) : IO Unit := do env ← mkEmptyEnvironment; stx ← IO.ofExcept $ runParserCategory env `term input "<input>"; IO.println stx def test (is : List String) : IO Unit := is.forM $ fun input => do IO.println input; testParser input def testParserFailure (input : String) : IO Unit := do env ← mkEmptyEnvironment; match runParserCategory env `term input "<input>" with | Except.ok stx => throw (IO.userError ("unexpected success\n" ++ toString stx)) | Except.error msg => IO.println ("failed as expected, error: " ++ msg) def testFailures (is : List String) : IO Unit := is.forM $ fun input => do IO.println input; testParserFailure input def main (xs : List String) : IO Unit := do test [ "Prod.mk", "x.{u, v+1}", "x.{u}", "x", "x.{max u v}", "x.{max u v, 0}", "f 0 1", "f.{u+1} \"foo\" x", "(f x, 0, 1)", "()", "(f x)", "(f x : Type)", "h (f x) (g y)", "if x then f x else g x", "if h : x then f x h else g x h", "have p x y from f x; g this", "suffices h : p x y from f x; g this", "show p x y from f x", "fun x y => f y x", "fun (x y : Nat) => f y x", "fun (x, y) => f y x", "fun z (x, y) => f y x", "fun ⟨x, y⟩ ⟨z, w⟩ => f y x w z", "fun (Prod.mk x y) => f y x", "{ x := 10, y := 20 }", "{ x := 10, y := 20, }", "{ x // p x 10 }", "{ x : Nat // p x 10 }", "{ .. }", "{ fst := 10, .. : Nat × Nat }", "a[i]", "f [10, 20]", "g a[x+2]", "g f.a.1.2.bla x.1.a", "x+y*z < 10/3", "id (α := Nat) 10", "(x : a)", "a -> b", "{x : a} -> b", "{a : Type} -> [HasToString a] -> (x : a) -> b", "f ({x : a} -> b)", "f (x : a) -> b", "f ((x : a) -> b)", "(f : (n : Nat) → Vector Nat n) -> Nat", "∀ x y (z : Nat), x > y -> x > y - z", " match x with | some x => true | none => false", " match x with | some y => match y with | some (a, b) => a + b | none => 1 | none => 0 ", "Type u", "Sort v", "Type 1", "f Type 1", "let x := 0; x + 1", "let x : Nat := 0; x + 1", "let f (x : Nat) := x + 1; f 0", "let f {α : Type} (a : α) : α := a; f 10", "let f (x) := x + 1; f 10 + f 20", "let (x, y) := f 10; x + y", "let { fst := x, .. } := f 10; x + x", "let x.y := f 10; x", "let x.1 := f 10; x", "let x[i].y := f 10; x", "let x[i] := f 20; x", "-x + y", "!x", "¬ a ∧ b", " do x ← f a; x : Nat ← f a; g x; let y := g x; (a, b) <- h x y; let (a, b) := (b, a); pure (a + b)", "do { x ← f a; pure $ a + a }", "let f : Nat → Nat → Nat | 0, a => a + 10 | n+1, b => n * b; f 20", "max a b" ]; testFailures [ "f {x : a} -> b", "(x := 20)", "let x 10; x", "let x := y" ]
4e53efe31400de117b01cc4cc5e905aa97fdbccf
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/algebra/matrix.lean
8662a32a8836cf8853c3d196da4baa6890461f36
[ "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
28,461
lean
/- Copyright (c) 2016 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis Basic properties of matrices and vectors. Proof of Motzkin's transposition theorem. -/ import data.real data.fin algebra.module open nat rat namespace matrix definition matrix [reducible] (A : Type) (m n : ℕ) := fin m → fin n → A notation `M_(`m`, `n`)` := matrix _ m n notation `M[`A`]_(`m`, `n`)` := matrix A m n -- should rvector and cvector just be notation? definition rvector [reducible] (A : Type) (n : ℕ) := M[A]_(1, n) definition cvector [reducible] (A : Type) (m : ℕ) := M[A]_(m, 1) definition mval {A : Type} (M : matrix A 1 1) : A := M !fin.zero !fin.zero -- useful for testing definition cvector_of_list {A : Type} (l : list A) : cvector A (list.length l) := λ i j, list.ith l (fin.val i) !fin.val_lt definition rvector_of_list {A : Type} (l : list A) : rvector A (list.length l) := λ i j, list.ith l (fin.val j) !fin.val_lt section matrix_defs variable {A : Type} variables {m n k : ℕ} definition col_of (M : matrix A m n) (j : fin n) : cvector A m := λ a b, M a j definition row_of (M : matrix A m n) (i : fin m) : rvector A n := λ a b, M i b definition r_ith (v : rvector A n) (i : fin n) := v !fin.zero i definition c_ith (v : cvector A m) (i : fin m) := v i !fin.zero definition nonneg [reducible] [weak_order A] [has_zero A] (M : matrix A m n) := ∀ i j, M i j ≥ 0 definition le [reducible] [has_le A] (M N : matrix A m n) := ∀ i j, M i j ≤ N i j definition lt [reducible] [has_lt A] (M N : matrix A m n) := ∀ i j, M i j < N i j definition r_dot [semiring A] (u v : rvector A n) := Suml (fin.upto n) (λ i, r_ith u i * r_ith v i) definition c_dot [semiring A] (u v : cvector A m) := Suml (fin.upto m) (λ i, c_ith u i * c_ith v i) definition transpose (M : matrix A m n) : matrix A n m := λ a b, M b a notation M`^Tr` := transpose M definition dot [semiring A] (u : rvector A n) (v : cvector A n) := c_dot (u^Tr) v theorem transpose_transpose (M : matrix A m n) : (M^Tr)^Tr = M := rfl theorem c_ith_cvector_of_rvector_eq_c_ith (u : rvector A n) (i : fin n) : c_ith (transpose u) i = r_ith u i := rfl theorem r_dot_zero [semiring A] (u : rvector A n) : r_dot u (λ a b, 0) = 0 := begin unfold r_dot, have H : (λ i, r_ith u i * r_ith (λ (a : fin 1) (b : fin n), 0) i) = (λ i, 0), begin apply funext, intro, rewrite [↑r_ith, mul_zero] end, rewrite H, apply Suml_zero end theorem r_zero_dot [semiring A] (u : rvector A n) : r_dot (λ a b, 0) u = 0 := begin unfold r_dot, have H : (λ i, r_ith (λ (a : fin 1) (b : fin n), 0) i * r_ith u i) = (λ i, 0), begin apply funext, intro, rewrite [↑r_ith, zero_mul] end, rewrite H, apply Suml_zero end theorem c_dot_zero [semiring A] (u : cvector A n) : c_dot u (λ a b, 0) = 0 := begin unfold c_dot, have H : (λ i, c_ith u i * c_ith (λ (a : fin n) (b : fin 1), 0) i) = (λ i, 0), begin apply funext, intro, rewrite [↑c_ith, mul_zero] end, rewrite H, apply Suml_zero end theorem c_zero_dot [semiring A] (u : cvector A n) : c_dot (λ a b, 0) u = 0 := begin unfold c_dot, have H : (λ i, c_ith (λ (a : fin n) (b : fin 1), 0) i * c_ith u i) = (λ i, 0), begin apply funext, intro, rewrite [↑c_ith, zero_mul] end, rewrite H, apply Suml_zero end theorem dot_zero [semiring A] (u : rvector A n) : dot u (λ a b, 0) = 0 := !c_dot_zero theorem zero_dot [semiring A] (u : cvector A n) : dot (λ a b, 0) u = 0 := !c_zero_dot definition mul [semiring A] (M : matrix A m n) (N : matrix A n k) : matrix A m k := λ (a : fin m) (b : fin k), c_dot (transpose (row_of M a)) (col_of N b) infix `⬝` := mul theorem dot_eq_mul [semiring A] (u : rvector A n) (v : cvector A n) : dot u v = (u ⬝ v) !fin.zero !fin.zero := rfl theorem row_of_rvector (v : rvector A n) : row_of v !fin.zero = v := funext (λ x, by rewrite (fin.fin_one_eq_zero x)) theorem col_of_cvector (v : cvector A m) : col_of v !fin.zero = v := begin apply funext, intro x, apply funext, intro y, unfold col_of, rewrite (fin.fin_one_eq_zero y) end theorem row_of_ith (M : matrix A m n) (x : fin m) (y : fin n) : (row_of M x) !fin.zero y = M x y := rfl theorem col_of_ith (M : matrix A m n) (x : fin m) (y : fin n) : (col_of M y) x !fin.zero = M x y := rfl /- Suml theorems. These need a better home, but I'm not sure where. -/ variables {B C T : Type} (l : list T) theorem Suml_assoc [semiring A] (la : list B) (lb : list C) (f : B → C → A) : Suml la (λ a, Suml lb (λ b, f a b)) = Suml lb (λ b, Suml la (λ a, f a b)) := begin induction la with h tt ih, {induction lb with h' tt' ih', {rewrite Suml_nil}, {rewrite [Suml_nil at *, Suml_cons, -ih', add_zero]}}, {induction lb with h' tt' ih', {rewrite [Suml_cons, *Suml_nil at *, ih, add_zero]}, {rewrite [Suml_cons, ih, -Suml_add], congruence, apply funext, intro b, rewrite Suml_cons}} end theorem mul_Suml [semiring A] (a : A) (f : T → A) : a * Suml l f = Suml l (λ k, a * f k) := begin induction l with h tt ih, rewrite [Suml_nil, mul_zero], rewrite [*Suml_cons, left_distrib, ih] end theorem Suml_mul [semiring A] (a : A) (f : T → A) : (Suml l f) * a = Suml l (λ k, f k * a) := begin induction l with h tt ih, rewrite [Suml_nil, zero_mul], rewrite [*Suml_cons, right_distrib, ih] end theorem Suml_nonneg_of_nonneg [ordered_semiring A] (f : T → A) (H : Π (i : ℕ) (Hi : i < list.length l), f (list.ith l i Hi) ≥ 0) : Suml l f ≥ (0 : A) := begin induction l with h tt ih, rewrite Suml_nil, apply le.refl, rewrite Suml_cons, have Hh : f h ≥ 0, begin note Hl := H 0 !list.length_cons_pos, rewrite list.ith_zero at Hl, apply Hl end, have Htt : Suml tt f ≥ 0, begin apply ih, intro i Hi, have Hsucc : succ i < list.length (list.cons h tt), by rewrite list.length_cons; apply nat.add_lt_add_right Hi, note Ho := H (succ i) Hsucc, rewrite list.ith_succ at Ho, apply Ho end, exact add_nonneg Hh Htt end theorem Suml_le_of_le [ordered_semiring A] (f g : T → A) (H : ∀ t : T, f t ≤ g t) : Suml l f ≤ Suml l g := begin induction l, {rewrite *Suml_nil, apply le.refl}, {rewrite *Suml_cons, apply add_le_add, apply H, assumption} end theorem Suml_lt_of_lt [ordered_semiring A] (Hl : l ≠ list.nil) (f g : T → A) (H : ∀ t : T, f t < g t) : Suml l f < Suml l g := begin induction l, {apply absurd !rfl Hl}, {rewrite [*Suml_cons], apply add_lt_add_of_lt_of_le, apply H, induction a_1, rewrite *Suml_nil, apply le.refl, apply le_of_lt, apply v_0_1, contradiction} end theorem eq_of_Suml_eq_Suml_of_le [ordered_ring A] (f g : T → A) (H : ∀ t : T, f t ≤ g t) (HSeq : Suml l f = Suml l g) : ∀ t : T, list.mem t l → f t = g t := begin induction l, intros, contradiction, intro t Ht, rewrite 2 Suml_cons at HSeq, have H1 : Suml a_1 f ≥ Suml a_1 g, from calc Suml a_1 f = -f a + (f a + Suml a_1 f) : by rewrite neg_add_cancel_left ... = (-f a + g a) + Suml a_1 g : by rewrite [HSeq, -add.assoc] ... ≥ Suml a_1 g : begin apply le_add_of_nonneg_left, rewrite add.comm, apply sub_nonneg_of_le !H end, have H2 : Suml a_1 f ≤ Suml a_1 g, by apply Suml_le_of_le; exact H, cases (list.eq_or_mem_of_mem_cons Ht) with Eta Mta, note Heq := eq_of_le_of_ge H2 H1, rewrite [Heq at HSeq, Eta], apply eq_of_add_eq_add_right HSeq, apply v_0, exact eq_of_le_of_ge H2 H1, exact Mta end theorem Suml_le_of_le_strong [ordered_semiring A] (f g : T → A) (H : ∀ t : T, list.mem t l → f t ≤ g t) : Suml l f ≤ Suml l g := begin induction l, {rewrite *Suml_nil, apply le.refl}, {rewrite *Suml_cons, apply add_le_add, apply H, apply list.mem_cons, apply v_0, intros, apply H, apply list.mem_cons_of_mem, assumption} end theorem Suml_mul_Suml_eq_Suml_Suml_mul [semiring A] (l1 : list B) (l2 : list C) (f : B → A) (g : B → C → A) : Suml l1 (λ s, f s * Suml l2 (λ t, g s t)) = Suml l1 (λ s, Suml l2 (λ t, f s * g s t)) := begin congruence, apply funext, intro s, rewrite mul_Suml end /- ------------------------- -/ theorem m_mul_assoc [semiring A] {o p : ℕ} (M : matrix A m n) (N : matrix A n o) (O : matrix A o p) : M ⬝ (N ⬝ O) = (M ⬝ N) ⬝ O := begin rewrite ↑mul, repeat (apply funext; intro), rewrite [↑c_dot, ↑c_ith, ↑row_of, ↑transpose, ↑col_of, Suml_mul_Suml_eq_Suml_Suml_mul, Suml_assoc], congruence, apply funext, intro, rewrite Suml_mul, congruence, apply funext, intro, rewrite mul.assoc end /- order, sign theorems -/ theorem transpose_nonneg_of_nonneg [weak_order A] [has_zero A] {u : rvector A n} (Hu : nonneg u) : nonneg (transpose u) := λ i j, !Hu theorem c_dot_nonneg_of_nonneg [ordered_semiring A] (u v : cvector A m) (Hu : nonneg u) (Hv : nonneg v) : c_dot u v ≥ 0 := begin unfold c_dot, apply Suml_nonneg_of_nonneg, intros, apply mul_nonneg, apply Hu, apply Hv end theorem dot_nonneg_of_nonneg [ordered_semiring A] (u v : cvector A m) (Hu : nonneg u) (Hv : nonneg v) : c_dot u v ≥ 0 := c_dot_nonneg_of_nonneg _ _ Hu Hv theorem row_of_nonneg_of_nonneg [weak_order A] [has_zero A] {M : matrix A m n} (HM : nonneg M) (i : fin m) : nonneg (row_of M i) := λ a b, !HM theorem col_of_nonneg_of_nonneg [weak_order A] [has_zero A] {M : matrix A m n} (HM : nonneg M) (i : fin n) : nonneg (col_of M i) := λ a b, !HM theorem mul_nonneg_of_nonneg [ordered_semiring A] (M : matrix A m n) (N : matrix A n k) (HM : nonneg M) (HN : nonneg N) : nonneg (M ⬝ N) := begin intros, unfold mul, apply c_dot_nonneg_of_nonneg, apply transpose_nonneg_of_nonneg, apply row_of_nonneg_of_nonneg HM, apply col_of_nonneg_of_nonneg HN end theorem dot_le_dot_of_nonneg_of_le [ordered_semiring A] (u : rvector A n) (v1 v2 : cvector A n) (Hu : nonneg u) (Hv : ∀ i, c_ith v1 i ≤ c_ith v2 i) : dot u v1 ≤ dot u v2 := begin unfold [dot, c_dot, transpose], apply Suml_le_of_le, intro, apply mul_le_mul_of_nonneg_left, apply Hv, apply Hu end theorem dot_lt_dot_of_nonneg_of_nonzero_of_lt [linear_ordered_ring A] (u : rvector A n) (v1 v2 : cvector A n) (Hu : nonneg u) (i : fin n) (Hunz : r_ith u i > 0) (Hv : ∀ i, c_ith v1 i < c_ith v2 i) : dot u v1 < dot u v2 := begin apply lt_of_not_ge, intro Hge, have Hle : dot u v1 ≤ dot u v2, begin apply dot_le_dot_of_nonneg_of_le, apply Hu, intro, apply le_of_lt, apply Hv end, note Heq := eq_of_le_of_ge Hle Hge, have Hilt : r_ith u i * c_ith v1 i < r_ith u i * c_ith v2 i, begin apply mul_lt_mul_of_pos_left, apply Hv, apply Hunz end, have Hmsle : ∀ t, r_ith u t * c_ith v1 t ≤ r_ith u t * c_ith v2 t, begin intro, apply mul_le_mul_of_nonneg_left, apply le_of_lt !Hv, apply Hu end, note Hmeq := eq_of_Suml_eq_Suml_of_le _ _ _ Hmsle Heq i !fin.mem_upto, rewrite Hmeq at Hilt, exact !not_lt_self Hilt end end matrix_defs section inst_dec /- instances -/ variables (A : Type) (m n : ℕ) theorem matrix_inhabited [instance] [HA : inhabited A] : inhabited (M[A]_(succ m, succ n)) := inhabited.rec_on HA (λ a, inhabited.mk (λ s t, a)) open list definition decidable_quant [instance] (P : fin n → Prop) [∀ k, decidable (P k)] : decidable (∀ k, P k) := if H : all (fin.upto n) P then decidable.inl (λ k, of_mem_of_all !fin.mem_upto H) else decidable.inr (λ Hpk, H (all_of_forall (λ a Ha, Hpk a))) definition matrix_decidable_eq [instance] [decidable_eq A] : decidable_eq (matrix A m n) := λ M N : matrix A m n, if H : ∀ i : fin m, ∀ j : fin n, M i j = N i j then decidable.inl (funext (λ i, funext (λ j, H i j))) else decidable.inr (begin intro Heq, apply H, intros, congruence, exact Heq end) /- matrix A m n is not a strict order if either m or n is 0. If it would be useful, we could prove order_pair (matrix A (succ m) n) and order_pair (matrix A m (succ n)). -/ definition is_weak_order [instance] [order_pair A] : weak_order (matrix A m n) := begin fapply weak_order.mk, {exact le}, {unfold le, intros, apply le.refl}, {unfold le, intros, apply le.trans !a_1 !a_2}, {unfold le, intros, repeat (apply funext; intro), apply eq_of_le_of_ge !a_1 !a_2} end end inst_dec section matrix_arith_m_n definition m_add {A : Type} [has_add A] {m n : ℕ} (B C : matrix A m n) : matrix A m n := λ x y, B x y + C x y definition m_neg {A : Type} [has_neg A] {m n : ℕ} (B : matrix A m n) : matrix A m n := λ x y, -B x y definition m_smul {A : Type} [has_mul A] {m n : ℕ} (c : A) (B : matrix A m n) : matrix A m n := λ x y, c * B x y definition m_left_module [instance] [reducible] (A : Type) [ring A] (m n : ℕ) : left_module A (matrix A m n) := begin fapply left_module.mk, {exact m_smul}, {exact m_add}, {intros, unfold m_add, repeat (apply funext; intro), rewrite add.assoc}, {exact λ a b, 0}, {intros, unfold m_add, repeat (apply funext; intro), rewrite zero_add}, {intros, unfold m_add, repeat (apply funext; intro), rewrite add_zero}, {exact m_neg}, {intros, rewrite [↑m_neg, ↑m_add], repeat (apply funext; intro), rewrite add.left_inv}, {intros, unfold m_add, repeat (apply funext; intro), rewrite add.comm}, {intros, rewrite [↑m_smul, ↑m_add], repeat (apply funext; intro), rewrite left_distrib}, {intros, rewrite [↑m_smul, ↑m_add], repeat (apply funext; intro), rewrite -right_distrib}, {intros, unfold m_smul, repeat (apply funext; intro), rewrite mul.assoc}, {intro, unfold m_smul, repeat (apply funext; intro), rewrite one_mul} end variables {A : Type} theorem Suml_neg [add_comm_group A] {T : Type} (l : list T) (f : T → A) : -(Suml l f) = Suml l (λ t, - f t) := begin apply neg_eq_of_add_eq_zero, have H : (λ x, f x + -f x) = (λ x, 0), from funext (λ x, !sub_self), rewrite [-Suml_add, H], apply Suml_zero end theorem distrib_dot_right [ring A] (n : ℕ) (M N : rvector A n) (x : cvector A n) : dot (M + N) x = dot M x + dot N x := begin change dot (m_add M N) x = (dot M x) + (dot N x), rewrite [↑dot, ↑c_dot, ↑m_add, ↑transpose, ↑c_ith, -Suml_add], congruence, apply funext, intro, rewrite right_distrib end theorem distrib_smul_right [ring A] (m n o : ℕ) (M N : matrix A m n) (x : matrix A n o) : (M + N) ⬝ x = M ⬝ x + N ⬝ x := begin change (m_add M N) ⬝ x = m_add (M ⬝ x) (N ⬝ x), rewrite [↑mul, ↑c_dot, ↑m_add], repeat (apply funext; intro), rewrite [↑c_ith, ↑row_of, ↑col_of, ↑transpose, -Suml_add], congruence, apply funext, intro, rewrite right_distrib end theorem neg_matrix [ring A] (m n : ℕ) (M : matrix A m n) : -M = (λ a b, -M a b) := rfl theorem zero_matrix [ring A] (m n : ℕ) : (0 : matrix A m n) = (λ a b, 0) := rfl theorem matrix_add_app [ring A] (m n : ℕ) (M N : matrix A m n) (a : fin m) (b : fin n) : (M + N) a b = M a b + N a b := rfl theorem neg_smul [ring A] (m n o : ℕ) (M : matrix A m n) (N : matrix A n o) : (-M) ⬝ N = - (M ⬝ N) := begin rewrite [↑mul], repeat (apply funext; intro), unfold [c_dot, row_of, col_of, c_ith, transpose], rewrite [2 neg_matrix, Suml_neg], congruence, apply funext, intro, rewrite neg_mul_eq_neg_mul end theorem zero_smul [ring A] (l m n : ℕ) (M : matrix A m n) : (0 : matrix A l m) ⬝ M = 0 := begin rewrite [↑mul, 2 zero_matrix], repeat (apply funext; intro), unfold [c_dot, row_of, col_of, transpose, c_ith], have H : (λ i, 0 * M i x_1) = (λ i, 0), from funext (λ i, !zero_mul), rewrite H, apply Suml_zero end theorem smul_zero [ring A] (l m n : ℕ) (M : matrix A l m) : M ⬝ (0 : matrix A m n) = 0 := begin rewrite [↑mul, 2 zero_matrix], repeat (apply funext; intro), unfold [c_dot, row_of, col_of, transpose, c_ith], have H : (λ i, M x i * 0) = (λ i, 0), from funext (λ i, !mul_zero), rewrite H, apply Suml_zero end theorem le_iff_forall_row [weak_order A] {n : ℕ} (u v : rvector A n) : u ≤ v ↔ ∀ i, r_ith u i ≤ r_ith v i := begin replace u ≤ v with le u v, unfold le, apply iff.intro, {intros H i, apply H}, {intros H i j, rewrite fin.fin_one_eq_zero, apply H} end theorem le_iff_forall_col [weak_order A] {n : ℕ} (u v : cvector A n) : u ≤ v ↔ ∀ i, c_ith u i ≤ c_ith v i := begin replace u ≤ v with le u v, unfold le, apply iff.intro, {intros H i, apply H}, {intros H i j, rewrite fin.fin_one_eq_zero, apply H} end -- why doesn't rfl work to prove this? theorem nonneg_iff_le_zero_row [ordered_ring A] {n : ℕ} (u : rvector A n) : nonneg u ↔ (0 : rvector A n) ≤ u := begin change nonneg u ↔ le (λ a b, 0) u, reflexivity end theorem nonneg_iff_le_zero_col [ordered_ring A] {n : ℕ} (u : cvector A n) : nonneg u ↔ (0 : cvector A n) ≤ u := begin change nonneg u ↔ le (0 : cvector A n) u, reflexivity end end matrix_arith_m_n section motzkin_transposition variables {A : Type} [linear_ordered_ring A] /- n variables a strict ineqs P : M[A]_(a, n), p : cvector a b weak ineqs Q : M[A]_(b, n), q : cvector b c eqs R : M[A]_(c, n), r : cvector c There are various ways to express Hsum equivalently: eg, (y ⬝ P) + (z ⬝ Q) + (t ⬝ R) = (0 : rvector A n). -/ variables {a b c n : ℕ} (P : M[A]_(a, n)) (Q : M[A]_(b, n)) (R : M[A]_(c, n)) (p : cvector A a) (q : cvector A b) (r : cvector A c) (y : rvector A a) (z : rvector A b) (t : rvector A c) (Hnny : nonneg y) (Hnnz : nonneg z) (Hsum : ∀ i : fin n, r_ith (y ⬝ P) i + r_ith (z ⬝ Q) i + r_ith (t ⬝ R) i = 0) include Hsum -- .3 seconds to elaborate private theorem dot_eq_zero {x : cvector A n} (HsatR : ∀ i : fin c, c_ith (R⬝x) i = c_ith r i) : dot y (P ⬝ x) + dot z (Q ⬝ x) + dot t r = 0 := begin have Hneg : (y ⬝ P) + (z ⬝ Q) + (t ⬝ R) = (0 : rvector A n), begin change (λ a b, (y⬝P + z⬝Q + t⬝R) a b) = (λ a b, 0), repeat (apply funext; intro), rewrite fin.fin_one_eq_zero, apply Hsum end, have Hr : R⬝x = r, begin repeat (apply funext; intro), rewrite fin.fin_one_eq_zero, apply HsatR end, have Hneg' : ((y ⬝ P) + (z ⬝ Q) + (t ⬝ R)) ⬝ x = 0 ⬝ x, by rewrite Hneg, -- this line and the following take about .1 sec rewrite [2 distrib_smul_right at Hneg', -3 m_mul_assoc at Hneg', Hr at Hneg', zero_smul at Hneg', zero_matrix at Hneg'], have Hneg'' : (λ a b : fin 1, (y⬝(P⬝x) + z⬝(Q⬝x) + t⬝r) a b) = (λ a b : fin 1, 0), from Hneg', have Heqz : (y⬝(P⬝x) + z⬝(Q⬝x) + t⬝r) !fin.zero !fin.zero = 0, by rewrite Hneg'', have Heqz' : (y⬝(P⬝x)) !fin.zero !fin.zero + (z⬝(Q⬝x)) !fin.zero !fin.zero + (t⬝r) !fin.zero !fin.zero = 0, from Heqz, rewrite *dot_eq_mul, exact Heqz' end include Hnny Hnnz theorem motzkin_transposition_with_equalities_lt (Hlt : (c_dot (y^Tr) p + c_dot (z^Tr) q + c_dot (t^Tr) r < 0)) : ¬ ∃ x : cvector A n, (∀ i, c_ith (P ⬝ x) i < c_ith p i) ∧ (∀ i, c_ith (Q ⬝ x) i ≤ c_ith q i) ∧ (∀ i, c_ith (R ⬝ x) i = c_ith r i) := begin intro Hsat, cases Hsat with x Hsat, cases Hsat with HsatP Hsat, cases Hsat with HsatQ HsatR, note Heqz' := dot_eq_zero P Q R r y z t Hsum HsatR, apply not_lt_self (0 : A), rewrite -Heqz' at {1}, have Hdlt : dot y (P⬝x) + dot z (Q⬝x) + dot t r ≤ dot y p + dot z q + dot t r, begin apply add_le_add_right, apply add_le_add, apply dot_le_dot_of_nonneg_of_le, exact Hnny, intro i, apply le_of_lt, apply HsatP, apply dot_le_dot_of_nonneg_of_le, exact Hnnz, exact HsatQ end, apply lt_of_le_of_lt, exact Hdlt, exact Hlt end theorem motzkin_transposition_with_equalities_le (Hyp : (∃ i, r_ith y i > 0) ∧ c_dot (y^Tr) p + c_dot (z^Tr) q + c_dot (t^Tr) r ≤ 0) : ¬ ∃ x : cvector A n, (∀ i, c_ith (P ⬝ x) i < c_ith p i) ∧ (∀ i, c_ith (Q ⬝ x) i ≤ c_ith q i) ∧ (∀ i, c_ith (R ⬝ x) i = c_ith r i) := begin intro Hsat, cases Hsat with x Hsat, cases Hsat with HsatP Hsat, cases Hsat with HsatQ HsatR, note Heqz' := dot_eq_zero P Q R r y z t Hsum HsatR, apply not_lt_self (0 : A), rewrite -Heqz' at {1}, cases Hyp with Hj Hor2, cases Hj with j Hj, have Hdlt : dot y (P⬝x) + dot z (Q⬝x) + dot t r < dot y p + dot z q + dot t r, begin apply add_lt_add_right, apply add_lt_add_of_lt_of_le, apply dot_lt_dot_of_nonneg_of_nonzero_of_lt, exact Hnny, exact Hj, exact HsatP, apply dot_le_dot_of_nonneg_of_le, exact Hnnz, exact HsatQ end, apply lt_of_lt_of_le, exact Hdlt, exact Hor2 end theorem motzkin_transposition_with_equalities (Hor : (c_dot (y^Tr) p + c_dot (z^Tr) q + c_dot (t^Tr) r < 0) ∨ ((∃ i : fin a, r_ith y i > 0) ∧ c_dot (y^Tr) p + c_dot (z^Tr) q + c_dot (t^Tr) r ≤ 0)) : ¬ ∃ x : cvector A n, (∀ i : fin a, c_ith (P ⬝ x) i < c_ith p i) ∧ (∀ i : fin b, c_ith (Q ⬝ x) i ≤ c_ith q i) ∧ (∀ i : fin c, c_ith (R ⬝ x) i = c_ith r i) := begin cases Hor with Hor1 Hor2, {apply motzkin_transposition_with_equalities_lt, exact Hnny, exact Hnnz, exact Hsum, exact Hor1}, {apply motzkin_transposition_with_equalities_le, exact Hnny, exact Hnnz, exact Hsum, exact Hor2} end end motzkin_transposition section matrix_arith_square open fin definition sq_matrix_id (A : Type) [has_zero A] [has_one A] (m : ℕ) : matrix A m m := λ x y, if x = y then 1 else 0 theorem Suml_map {A B C : Type} [add_monoid C] (l : list A) (f : A → B) (g : B → C) : Suml (list.map f l) g = Suml l (λ a, g (f a)) := begin induction l, rewrite Suml_nil, rewrite [list.map_cons, *Suml_cons, v_0] end -- this is annoying! theorem dot_basis_vec {A : Type} [semiring A] {m : ℕ} (k : fin m) (f : fin m → A) : Suml (upto m) (λ j, (f j) * if j = k then 1 else 0) = f k := begin induction m, apply false.elim (false_of_fin_zero k), rewrite [upto_succ, Suml_cons], cases decidable.em (maxi = k) with Heq Hneq, {rewrite [if_pos Heq, -Heq, mul_one, -add_zero (f maxi) at {2}], congruence, have H : (λ a_1 : fin a, f (lift_succ a_1) * ite (lift_succ a_1 = maxi) 1 0) = (λ a_1, 0), begin apply funext, intro b, rewrite [if_neg lift_succ_ne_max, mul_zero] end, rewrite [Suml_map, H, Suml_zero]}, {rewrite [if_neg Hneq, mul_zero, zero_add, Suml_map], note Hlt := lt_max_of_ne_max (ne.symm Hneq), have Hfk : f k = f (lift_succ (fin.mk (val k) Hlt)), begin induction k with kv Hkv, exact rfl end, rewrite [Hfk, -(v_0 (fin.mk (val k) Hlt) (λ v, f (lift_succ v)))], congruence, apply funext, intro j, cases decidable.em (lift_succ j = k) with Hjk Hnjk, have Hjk' : j = mk (val k) Hlt, begin induction j with vj Hvj, congruence, rewrite -Hjk end, rewrite [if_pos Hjk, if_pos Hjk'], have Hjk' : j ≠ mk (val k) Hlt, begin intro Hjk, apply Hnjk, induction k, rewrite Hjk end, rewrite [if_neg Hnjk, if_neg Hjk']} end theorem b_vec_dot' {A : Type} [semiring A] {m : ℕ} (k : fin m) (f : fin m → A) : Suml (upto m) (λ j, (if k = j then 1 else 0) * f j) = f k := begin have H : (λ j, (if k = j then 1 else 0) * f j) = (λ j, (f j) * if j = k then 1 else 0), begin apply funext, intro, cases decidable.em (k = x) with Heq Hneq, rewrite [if_pos Heq, if_pos (eq.symm Heq), mul_one, one_mul], rewrite [if_neg Hneq, if_neg (ne.symm Hneq), mul_zero, zero_mul] end, rewrite [H, dot_basis_vec] end theorem sq_matrix_mul_one {A : Type} [semiring A] {m : ℕ} (M : matrix A m m) : mul M (sq_matrix_id A m) = M := begin rewrite [↑sq_matrix_id, ↑mul], repeat (apply funext; intro), rewrite [↑row_of, ↑transpose, ↑col_of, ↑c_dot, ↑c_ith, dot_basis_vec] end theorem sq_matrix_one_mul {A : Type} [semiring A] {m : ℕ} (M : matrix A m m) : mul (sq_matrix_id A m) M = M := begin rewrite [↑sq_matrix_id, ↑mul], repeat (apply funext; intro), rewrite [↑row_of, ↑transpose, ↑col_of, ↑c_dot, ↑c_ith, b_vec_dot'] end theorem sq_matrix_left_distrib {A : Type} [semiring A] {m : ℕ} (M N O : matrix A m m) : mul M (m_add N O) = m_add (mul M N) (mul M O) := begin rewrite [↑mul, ↑m_add], repeat (apply funext; intros), rewrite [↑c_dot, ↑transpose, ↑row_of, ↑col_of, ↑c_ith, -Suml_add], congruence, apply funext, intro, rewrite left_distrib end theorem sq_matrix_right_distrib {A : Type} [semiring A] {m : ℕ} (M N O : matrix A m m) : mul (m_add N O) M = m_add (mul N M) (mul O M) := begin rewrite [↑mul, ↑m_add], repeat (apply funext; intros), rewrite [↑c_dot, ↑transpose, ↑row_of, ↑col_of, ↑c_ith, -Suml_add], congruence, apply funext, intro, rewrite right_distrib end definition m_square_ring [instance] [reducible] (A : Type) [ring A] (m : ℕ) : ring (matrix A m m) := ⦃ring, m_left_module A m m, mul := λ B C, mul B C, mul_assoc := λ B C D, eq.symm !m_mul_assoc, one := sq_matrix_id A m, one_mul := sq_matrix_one_mul, mul_one := sq_matrix_mul_one, left_distrib := sq_matrix_left_distrib, right_distrib := by intros; apply sq_matrix_right_distrib⦄ end matrix_arith_square /- section test open list rat int -- why aren't rats pretty printing right? definition c1 : cvector ℕ _ := cvector_of_list [3, 4, 2] definition c2 : rvector ℕ _ := rvector_of_list [1, 0, 2] definition f1 : fin 2 := fin.mk 1 dec_trivial definition m1 : matrix ℤ 2 2 := λ a b, fin.val a + fin.val b eval col_of m1 (fin.mk 1 dec_trivial) definition m2 : matrix ℤ 2 2 := λ a b, fin.val a * fin.val b + 3 definition m10 : matrix ℕ 10 10 := λ a b, fin.val a * fin.val b + 3 definition prd := m1 * m2 definition prd' := (m1 * m2) + 3 eval prd f1 f1 eval (m1 * m2) f1 f1 eval (3 : matrix ℤ 2 2) f1 !fin.zero example : has_mul (matrix ℤ 2 2) := _ check m1 * m2 eval ((m1 * m2) ) eval c_dot c1 (transpose c2) example : row_of c2 !fin.zero !fin.zero (fin.mk 1 dec_trivial) = c2 !fin.zero (fin.mk 1 dec_trivial) := rfl example : row_of c2 !fin.zero = c2 := rfl eval (c2 ⬝ c1) !fin.zero !fin.zero --example : m10 * !sq_matrix_id = m10 := dec_trivial definition poly_sum (x : ℕ) := Suml (upto 10) (λ a, (a + 3) * x) example (b : ℕ) : Suml [b, b] (λ a, a) = 0 + b + b := rfl --definition lin_poly (x : ℕ → ℕ) := 0 + 5 * x 0 + 2 * x 1 + 3 * x 2 + 11 * x 3 definition lin_poly (x : ℕ → ℕ) := 0 + 11 * x 3 + 3 * x 2 + 2 * x 1 + 5 * x 0 definition coeff_row : rvector ℕ _ := rvector_of_list [5, 2, 3, 11] open fin definition var_row (x : ℕ → ℕ) : rvector ℕ 4 := λ i j, x j example (x : ℕ → ℕ) : r_dot coeff_row (var_row x) = lin_poly x := rfl definition xs (x : ℕ) : rvector ℕ 10 := λ a b, x example (x : ℕ) : r_dot (row_of m10 (fin.mk 1 dec_trivial)) (xs x) = poly_sum x := rfl definition mep : rvector ℕ 0 := λ a b, 2 definition map : matrix ℕ 0 3 := λ a b, 1 eval (mep ⬝ map) !fin.zero !fin.zero end test-/ end matrix
30b947741178be14e9813766ce030a3bba02847c
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/order.lean
9f04a145685f1f72db99a1ac7a42d3c897132def
[ "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
29,937
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 topology.tactic /-! # Ordering on topologies and (co)induced topologies Topologies on a fixed type `α` are ordered, by reverse inclusion. That is, for topologies `t₁` and `t₂` on `α`, we write `t₁ ≤ t₂` if every set open in `t₂` is also open in `t₁`. (One also calls `t₁` finer than `t₂`, and `t₂` coarser than `t₁`.) Any function `f : α → β` induces `induced f : topological_space β → topological_space α` and `coinduced f : topological_space α → topological_space β`. Continuity, the ordering on topologies and (co)induced topologies are related as follows: * The identity map (α, t₁) → (α, t₂) is continuous iff t₁ ≤ t₂. * A map f : (α, t) → (β, u) is continuous iff t ≤ induced f u (`continuous_iff_le_induced`) iff coinduced f t ≤ u (`continuous_iff_coinduced_le`). Topologies on α form a complete lattice, with ⊥ the discrete topology and ⊤ the indiscrete topology. For a function f : α → β, (coinduced f, induced f) is a Galois connection between topologies on α and topologies on β. ## Implementation notes There is a Galois insertion between topologies on α (with the inclusion ordering) and all collections of sets in α. The complete lattice structure on topologies on α is defined as the reverse of the one obtained via this Galois insertion. ## Tags finer, coarser, induced topology, coinduced topology -/ open set filter classical open_locale classical topological_space filter universes u v w namespace topological_space variables {α : Type u} /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set α)) : topological_space α := { is_open := generate_open g, is_open_univ := generate_open.univ, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, 𝓟 s) := by rw nhds_def; exact le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, begin revert as, clear_, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ 𝓟 s ⊓ 𝓟 t : le_inf (hs has) (ht hat) ... = _ : inf_principal }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ 𝓟 t : hk t htk hat ... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk } end) lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β} (h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f) : tendsto m f (@nhds β (generate_from g) b) := by rw [nhds_generate_from]; exact (tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs) /-- Construct a topology on α given the filter of neighborhoods of each point of α. -/ protected def mk_of_nhds (n : α → filter α) : topological_space α := { is_open := λs, ∀a∈s, s ∈ n a, is_open_univ := assume x h, univ_mem_sets, is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt), is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) } lemma nhds_mk_of_nhds (n : α → filter α) (a : α) (h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ n a → ∃ t ∈ n a, t ⊆ s ∧ ∀a' ∈ t, s ∈ n a') : @nhds α (topological_space.mk_of_nhds n) a = n a := begin letI := topological_space.mk_of_nhds n, refine le_antisymm (assume s hs, _) (assume s hs, _), { have h₀ : {b | s ∈ n b} ⊆ s := assume b hb, mem_pure_sets.1 $ h₀ b hb, have h₁ : {b | s ∈ n b} ∈ 𝓝 a, { refine is_open.mem_nhds (assume b (hb : s ∈ n b), _) hs, rcases h₁ hb with ⟨t, ht, hts, h⟩, exact mem_sets_of_superset ht h }, exact mem_sets_of_superset h₁ h₀ }, { rcases (@mem_nhds_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩, exact (n a).sets_of_superset (ht _ hat) hts }, end end topological_space section lattice variables {α : Type u} {β : Type v} /-- The inclusion ordering on topologies on α. We use it to get a complete lattice instance via the Galois insertion method, but the partial order that we will eventually impose on `topological_space α` is the reverse one. -/ def tmp_order : partial_order (topological_space α) := { le := λt s, t.is_open ≤ s.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ } local attribute [instance] tmp_order /- We'll later restate this lemma in terms of the correct order on `topological_space α`. -/ private lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} : topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} := iff.intro (assume ht s hs, ht _ $ topological_space.generate_open.basic s hs) (assume hg s hs, hs.rec_on (assume v hv, hg hv) t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k)) /-- If `s` equals the collection of open sets in the topology it generates, then `s` defines a topology. -/ protected def mk_of_closure (s : set (set α)) (hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α := { is_open := λu, u ∈ s, is_open_univ := hs ▸ topological_space.generate_open.univ, is_open_inter := hs ▸ topological_space.generate_open.inter, is_open_sUnion := hs ▸ topological_space.generate_open.sUnion } lemma mk_of_closure_sets {s : set (set α)} {hs : {u | (topological_space.generate_from s).is_open u} = s} : mk_of_closure s hs = topological_space.generate_from s := topological_space_eq hs.symm /-- The Galois insertion between `set (set α)` and `topological_space α` whose lower part sends a collection of subsets of α to the topology they generate, and whose upper part sends a topology to its collection of open subsets. -/ def gi_generate_from (α : Type*) : galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) := { gc := assume g t, generate_from_le_iff_subset_is_open, le_l_u := assume ts s hs, topological_space.generate_open.basic s hs, choice := λg hg, mk_of_closure g (subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) : topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ := (gi_generate_from _).gc.monotone_l h /-- The complete lattice of topological spaces, but built on the inclusion ordering. -/ def tmp_complete_lattice {α : Type u} : complete_lattice (topological_space α) := (gi_generate_from α).lift_complete_lattice /-- The ordering on topologies on the type `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (topological_space α) := { le := λ t s, s.is_open ≤ t.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, le_trans h₂ h₁ } lemma le_generate_from_iff_subset_is_open {g : set (set α)} {t : topological_space α} : t ≤ topological_space.generate_from g ↔ g ⊆ {s | t.is_open s} := generate_from_le_iff_subset_is_open /-- Topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of topologies is the topology generated by all their open sets, while the supremem is the topology whose open sets are those sets open in every member of the collection. -/ instance : complete_lattice (topological_space α) := @order_dual.complete_lattice _ tmp_complete_lattice /-- A topological space is discrete if every set is open, that is, its topology equals the discrete topology `⊥`. -/ class discrete_topology (α : Type*) [t : topological_space α] : Prop := (eq_bot [] : t = ⊥) @[priority 100] instance discrete_topology_bot (α : Type*) : @discrete_topology α ⊥ := { eq_bot := rfl } @[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) : is_open s := (discrete_topology.eq_bot α).symm ▸ trivial @[simp] lemma is_closed_discrete [topological_space α] [discrete_topology α] (s : set α) : is_closed s := is_open_compl_iff.1 $ (discrete_topology.eq_bot α).symm ▸ trivial lemma continuous_of_discrete_topology [topological_space α] [discrete_topology α] [topological_space β] {f : α → β} : continuous f := continuous_def.2 $ λs hs, is_open_discrete _ lemma nhds_bot (α : Type*) : (@nhds α ⊥) = pure := begin refine le_antisymm _ (@pure_le_nhds α ⊥), assume a s hs, exact @is_open.mem_nhds α ⊥ a s trivial hs end lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure := (discrete_topology.eq_bot α).symm ▸ nhds_bot α lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x ≤ @nhds α t₂ x) : t₁ ≤ t₂ := assume s, show @is_open α t₂ s → @is_open α t₁ s, by { simp only [is_open_iff_nhds, le_principal_iff], exact assume hs a ha, h _ $ hs _ ha } lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x = @nhds α t₂ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) lemma eq_bot_of_singletons_open {t : topological_space α} (h : ∀ x, t.is_open {x}) : t = ⊥ := bot_unique $ λ s hs, bUnion_of_singleton s ▸ is_open_bUnion (λ x _, h x) lemma forall_open_iff_discrete {X : Type*} [topological_space X] : (∀ s : set X, is_open s) ↔ discrete_topology X := ⟨λ h, ⟨by { ext U , show is_open U ↔ true, simp [h U] }⟩, λ a, @is_open_discrete _ _ a⟩ lemma singletons_open_iff_discrete {X : Type*} [topological_space X] : (∀ a : X, is_open ({a} : set X)) ↔ discrete_topology X := ⟨λ h, ⟨eq_bot_of_singletons_open h⟩, λ a _, @is_open_discrete _ _ a _⟩ end lattice section galois_connection variables {α : Type*} {β : Type*} {γ : Type*} /-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of sets that are preimages of some open set in `β`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { is_open := λs, ∃s', t.is_open s' ∧ f ⁻¹' s' = s, is_open_univ := ⟨univ, t.is_open_univ, preimage_univ⟩, is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩; exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩, is_open_sUnion := assume s h, begin simp only [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right)], refine ⟨_, rfl⟩, exact (@is_open_Union β _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left) end } lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_open α (t.induced f) s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) := iff.rfl lemma is_open_induced_iff' [t : topological_space β] {s : set α} {f : α → β} : (t.induced f).is_open s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) := iff.rfl lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ f ⁻¹' t = s) := begin simp only [← is_open_compl_iff, is_open_induced_iff], exact ⟨λ ⟨t, ht, heq⟩, ⟨tᶜ, by rwa compl_compl, by simp [preimage_compl, heq, compl_compl]⟩, λ ⟨t, ht, heq⟩, ⟨tᶜ, ht, by simp only [preimage_compl, heq.symm]⟩⟩ end /-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { is_open := λs, t.is_open (f ⁻¹' s), is_open_univ := by rw preimage_univ; exact t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} : @is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) := iff.rfl lemma preimage_nhds_coinduced [topological_space α] {π : α → β} {s : set β} {a : α} (hs : s ∈ @nhds β (topological_space.coinduced π ‹_›) (π a)) : π ⁻¹' s ∈ 𝓝 a := begin letI := topological_space.coinduced π ‹_›, rcases mem_nhds_iff.mp hs with ⟨V, hVs, V_op, mem_V⟩, exact mem_nhds_iff.mpr ⟨π ⁻¹' V, set.preimage_mono hVs, V_op, mem_V⟩ end variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α} lemma continuous.coinduced_le (h : @continuous α β t t' f) : t.coinduced f ≤ t' := λ s hs, (continuous_def.1 h s hs : _) lemma coinduced_le_iff_le_induced {f : α → β} {tα : topological_space α} {tβ : topological_space β} : tα.coinduced f ≤ tβ ↔ tα ≤ tβ.induced f := iff.intro (assume h s ⟨t, ht, hst⟩, hst ▸ h _ ht) (assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) lemma continuous.le_induced (h : @continuous α β t t' f) : t ≤ t'.induced f := coinduced_le_iff_le_induced.1 h.coinduced_le lemma gc_coinduced_induced (f : α → β) : galois_connection (topological_space.coinduced f) (topological_space.induced f) := assume f g, coinduced_le_iff_le_induced lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g := (gc_coinduced_induced g).monotone_u h lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f := (gc_coinduced_induced f).monotone_l h @[simp] lemma induced_top : (⊤ : topological_space α).induced g = ⊤ := (gc_coinduced_induced g).u_top @[simp] lemma induced_inf : (t₁ ⊓ t₂).induced g = t₁.induced g ⊓ t₂.induced g := (gc_coinduced_induced g).u_inf @[simp] lemma induced_infi {ι : Sort w} {t : ι → topological_space α} : (⨅i, t i).induced g = (⨅i, (t i).induced g) := (gc_coinduced_induced g).u_infi @[simp] lemma coinduced_bot : (⊥ : topological_space α).coinduced f = ⊥ := (gc_coinduced_induced f).l_bot @[simp] lemma coinduced_sup : (t₁ ⊔ t₂).coinduced f = t₁.coinduced f ⊔ t₂.coinduced f := (gc_coinduced_induced f).l_sup @[simp] lemma coinduced_supr {ι : Sort w} {t : ι → topological_space α} : (⨆i, t i).coinduced f = (⨆i, (t i).coinduced f) := (gc_coinduced_induced f).l_supr lemma induced_id [t : topological_space α] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tγ : topological_space γ] {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁ ▸ h₂ ▸ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ lemma induced_const [t : topological_space α] {x : α} : t.induced (λ y : β, x) = ⊤ := le_antisymm le_top (@continuous_const β α ⊤ t x).le_induced lemma coinduced_id [t : topological_space α] : t.coinduced id = t := topological_space_eq rfl lemma coinduced_compose [tα : topological_space α] {f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) := topological_space_eq rfl end galois_connection /- constructions using the complete lattice structure -/ section constructions open topological_space variables {α : Type u} {β : Type v} instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ @[priority 100] instance subsingleton.unique_topological_space [subsingleton α] : unique (topological_space α) := { default := ⊥, uniq := λ t, eq_bot_of_singletons_open $ λ x, subsingleton.set_cases (@is_open_empty _ t) (@is_open_univ _ t) ({x} : set α) } @[priority 100] instance subsingleton.discrete_topology [t : topological_space α] [subsingleton α] : discrete_topology α := ⟨unique.eq_default t⟩ instance : topological_space empty := ⊥ instance : discrete_topology empty := ⟨rfl⟩ instance : topological_space pempty := ⊥ instance : discrete_topology pempty := ⟨rfl⟩ instance : topological_space punit := ⊥ instance : discrete_topology punit := ⟨rfl⟩ instance : topological_space bool := ⊥ instance : discrete_topology bool := ⟨rfl⟩ instance : topological_space ℕ := ⊥ instance : discrete_topology ℕ := ⟨rfl⟩ instance : topological_space ℤ := ⊥ instance : discrete_topology ℤ := ⟨rfl⟩ instance sierpinski_space : topological_space Prop := generate_from {{true}} lemma le_generate_from {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) : t ≤ generate_from g := le_generate_from_iff_subset_is_open.2 h lemma induced_generate_from_eq {α β} {b : set (set β)} {f : α → β} : (generate_from b).induced f = topological_space.generate_from (preimage f '' b) := le_antisymm (le_generate_from $ ball_image_iff.2 $ assume s hs, ⟨s, generate_open.basic _ hs, rfl⟩) (coinduced_le_iff_le_induced.1 $ le_generate_from $ assume s hs, generate_open.basic _ $ mem_image_of_mem _ hs) lemma le_induced_generate_from {α β} [t : topological_space α] {b : set (set β)} {f : α → β} (h : ∀ (a : set β), a ∈ b → is_open (f ⁻¹' a)) : t ≤ induced f (generate_from b) := begin rw induced_generate_from_eq, apply le_generate_from, simp only [mem_image, and_imp, forall_apply_eq_imp_iff₂, exists_imp_distrib], exact h, end /-- This construction is left adjoint to the operation sending a topology on `α` to its neighborhood filter at a fixed point `a : α`. -/ protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α := { is_open := λs, a ∈ s → s ∈ f, is_open_univ := assume s, univ_mem_sets, is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat), is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) } lemma gc_nhds (a : α) : galois_connection (topological_space.nhds_adjoint a) (λt, @nhds α t a) := assume f t, by { rw le_nhds_iff, exact ⟨λ H s hs has, H _ has hs, λ H s has hs, H _ hs has⟩ } lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₁ a ≤ @nhds α t₂ a := (gc_nhds a).monotone_u h lemma nhds_infi {ι : Sort*} {t : ι → topological_space α} {a : α} : @nhds α (infi t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).u_infi lemma nhds_Inf {s : set (topological_space α)} {a : α} : @nhds α (Inf s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).u_Inf lemma nhds_inf {t₁ t₂ : topological_space α} {a : α} : @nhds α (t₁ ⊓ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).u_inf lemma nhds_top {a : α} : @nhds α ⊤ a = ⊤ := (gc_nhds a).u_top local notation `cont` := @continuous _ _ local notation `tspace` := topological_space open topological_space variables {γ : Type*} {f : α → β} {ι : Sort*} lemma continuous_iff_coinduced_le {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ coinduced f t₁ ≤ t₂ := continuous_def.trans iff.rfl lemma continuous_iff_le_induced {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ t₁ ≤ induced f t₂ := iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _) theorem continuous_generated_from {t : tspace α} {b : set (set β)} (h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f := continuous_iff_coinduced_le.2 $ le_generate_from h @[continuity] lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f := by { rw continuous_def, assume s h, exact ⟨_, h, rfl⟩ } lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ} (h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g := begin rw continuous_def, rintros s ⟨t, ht, s_eq⟩, simpa [← s_eq] using continuous_def.1 h t ht, end lemma continuous_induced_rng' [topological_space α] [topological_space β] [topological_space γ] {g : γ → α} (f : α → β) (H : ‹topological_space α› = ‹topological_space β›.induced f) (h : continuous (f ∘ g)) : continuous g := H.symm ▸ continuous_induced_rng h lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f := by { rw continuous_def, assume s h, exact h } lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ} (h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g := begin rw continuous_def at h ⊢, assume s hs, exact h _ hs end lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : t₂ ≤ t₁) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f := begin rw continuous_def at h₂ ⊢, assume s h, exact h₁ _ (h₂ s h) end lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : t₂ ≤ t₃) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f := begin rw continuous_def at h₂ ⊢, assume s h, exact h₂ s (h₁ s h) end lemma continuous_sup_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊔ t₂) t₃ f := begin rw continuous_def at h₁ h₂ ⊢, assume s h, exact ⟨h₁ s h, h₂ s h⟩ end lemma continuous_sup_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₂ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_left lemma continuous_sup_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₃ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_right lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β} (h : ∀t∈t₁, cont t t₂ f) : cont (Sup t₁) t₂ f := continuous_iff_le_induced.2 $ Sup_le $ assume t ht, continuous_iff_le_induced.1 $ h t ht lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β} (h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Sup t₂) f := continuous_iff_coinduced_le.2 $ le_Sup_of_le h₁ $ continuous_iff_coinduced_le.1 hf lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β} (h : ∀i, cont (t₁ i) t₂ f) : cont (supr t₁) t₂ f := continuous_Sup_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq ▸ h i lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι} (h : cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f := continuous_Sup_rng ⟨i, rfl⟩ h lemma continuous_inf_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊓ t₃) f := continuous_iff_coinduced_le.2 $ le_inf (continuous_iff_coinduced_le.1 h₁) (continuous_iff_coinduced_le.1 h₂) lemma continuous_inf_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₁ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_left lemma continuous_inf_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₂ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_right lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) : cont t t₂ f → cont (Inf t₁) t₂ f := continuous_le_dom $ Inf_le h₁ lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)} (h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Inf t₂) f := continuous_iff_coinduced_le.2 $ le_Inf $ assume b hb, continuous_iff_coinduced_le.1 $ h b hb lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} : cont (t₁ i) t₂ f → cont (infi t₁) t₂ f := continuous_le_dom $ infi_le _ _ lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β} (h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f := continuous_iff_coinduced_le.2 $ le_infi $ assume i, continuous_iff_coinduced_le.1 $ h i @[continuity] lemma continuous_bot {t : tspace β} : cont ⊥ t f := continuous_iff_le_induced.2 $ bot_le @[continuity] lemma continuous_top {t : tspace α} : cont t ⊤ f := continuous_iff_coinduced_le.2 $ le_top /- 𝓝 in the induced topology -/ theorem mem_nhds_induced [T : topological_space α] (f : β → α) (a : β) (s : set β) : s ∈ @nhds β (topological_space.induced f T) a ↔ ∃ u ∈ 𝓝 (f a), f ⁻¹' u ⊆ s := begin simp only [mem_nhds_iff, is_open_induced_iff, exists_prop, set.mem_set_of_eq], split, { rintros ⟨u, usub, ⟨v, openv, ueq⟩, au⟩, exact ⟨v, ⟨v, set.subset.refl v, openv, by rwa ←ueq at au⟩, by rw ueq; exact usub⟩ }, rintros ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩, exact ⟨f ⁻¹' v, set.subset.trans (set.preimage_mono vsubu) finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩ end theorem nhds_induced [T : topological_space α] (f : β → α) (a : β) : @nhds β (topological_space.induced f T) a = comap f (𝓝 (f a)) := by { ext s, rw [mem_nhds_induced, mem_comap_sets] } lemma induced_iff_nhds_eq [tα : topological_space α] [tβ : topological_space β] (f : β → α) : tβ = tα.induced f ↔ ∀ b, 𝓝 b = comap f (𝓝 $ f b) := ⟨λ h a, h.symm ▸ nhds_induced f a, λ h, eq_of_nhds_eq_nhds $ λ x, by rw [h, nhds_induced]⟩ theorem map_nhds_induced_of_surjective [T : topological_space α] {f : β → α} (hf : function.surjective f) (a : β) : map f (@nhds β (topological_space.induced f T) a) = 𝓝 (f a) := by rw [nhds_induced, map_comap_of_surjective hf] end constructions section induced open topological_space variables {α : Type*} {β : Type*} variables [t : topological_space β] {f : α → β} theorem is_open_induced_eq {s : set α} : @is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} := iff.rfl theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) := ⟨s, h, rfl⟩ lemma map_nhds_induced_eq (a : α) : map f (@nhds α (induced f t) a) = 𝓝[range f] (f a) := by rw [nhds_induced, filter.map_comap, nhds_within] lemma map_nhds_induced_of_mem {a : α} (h : range f ∈ 𝓝 (f a)) : map f (@nhds α (induced f t) a) = 𝓝 (f a) := by rw [nhds_induced, filter.map_comap_of_mem h] lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} : a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := by simp only [mem_closure_iff_frequently, nhds_induced, frequently_comap, mem_image, and_comm] end induced section sierpinski variables {α : Type*} [topological_space α] @[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) := topological_space.generate_open.basic _ (by simp) lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} := ⟨assume h : continuous p, have is_open (p ⁻¹' {true}), from is_open_singleton_true.preimage h, by simp [preimage, eq_true] at this; assumption, assume h : is_open {x | p x}, continuous_generated_from $ assume s (hs : s ∈ {{true}}), by simp at hs; simp [hs, preimage, eq_true, h]⟩ lemma is_open_iff_continuous_mem {s : set α} : is_open s ↔ continuous (λ x, x ∈ s) := continuous_Prop.symm end sierpinski section infi variables {α : Type u} {ι : Type v} {t : ι → topological_space α} lemma is_open_supr_iff {s : set α} : @is_open _ (⨆ i, t i) s ↔ ∀ i, @is_open _ (t i) s := begin -- s defines a map from α to Prop, which is continuous iff s is open. suffices : @continuous _ _ (⨆ i, t i) _ s ↔ ∀ i, @continuous _ _ (t i) _ s, { simpa only [continuous_Prop] using this }, simp only [continuous_iff_le_induced, supr_le_iff] end lemma is_closed_infi_iff {s : set α} : @is_closed _ (⨆ i, t i) s ↔ ∀ i, @is_closed _ (t i) s := by simp [← is_open_compl_iff, is_open_supr_iff] end infi
d964cdc8b6524b97123153deb3d2f8c8645a7164
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/rules/ex3sigmod92.lean
77d7f1c065589bb579ead78e0af4f09e28babd32
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,887
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..cosette_tactics open Expr open Proj open Pred open SQL variables i0 i468 : const datatypes.int theorem rule : forall (Γ scm_itl scm_itp : Schema) (rel_itl : relation scm_itl) (rel_itp : relation scm_itp) (itl_itemn : Column datatypes.int scm_itl) (itl_wkcen : Column datatypes.int scm_itl) (itl_locan : Column datatypes.int scm_itl) (itp_itemn : Column datatypes.int scm_itp) (itp_ponum : Column datatypes.int scm_itp) (ik: isKey itp_itemn rel_itp), denoteSQL (SELECT * FROM1 table rel_itp WHERE (EXISTS (SELECT * FROM1 table rel_itl WHERE (and (and (equal (uvariable (right⋅itl_itemn)) (uvariable (left⋅right⋅itp_itemn))) (equal (uvariable (right⋅itl_wkcen)) (constantExpr i468))) (equal (uvariable (right⋅itl_locan)) (constantExpr i0))))) : SQL Γ _) = denoteSQL (DISTINCT (SELECT1 (right⋅left⋅star) FROM1 (product (table rel_itp) (table rel_itl)) WHERE (and (and (equal (uvariable (right⋅left⋅itp_itemn)) (uvariable (right⋅right⋅itl_itemn))) (equal (uvariable (right⋅right⋅itl_wkcen)) (constantExpr i468))) (equal (uvariable (right⋅right⋅itl_locan)) (constantExpr i0)))) : SQL Γ _) := begin intros, unfold isKey at *, unfold_all_denotations, funext, simp, sorry end
bb3ebe9445a5f655e16cc3711e13064a15316f12
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/655c.lean
c71ead1c42af91ff9b0fbc977f85da8e95ca8884
[ "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
715
lean
universes u v w -- fails to create a helper definition -- TODO -- def foldr_cps {α β γ : Sort*} (g : α → β → β) (z : β) : list α → (β → γ) → γ -- | list.nil k := k z -- | (list.cons x xs) k := foldr_cps xs (λz', k (g x z')) -- succeeds def foldr_cps' {α β γ : Sort*} (g : α → β → β) (z : β) (l : list α) : (β → γ) → γ := @list.rec_on α (λ _, (β → γ) → γ) l (λ k : β → γ, k z) (λ x xs r k, r (λ z', k (g x z'))) -- fails to create a helper definition def foldr_cps'' {α : Type u} {β : Sort v} {γ : Sort w} (g : α → β → β) (z : β) : list α → (β → γ) → γ | list.nil k := k z | (list.cons x xs) k := foldr_cps'' xs (λz', k (g x z'))
5441138ab4534210e8ae52df407a8c6011d9efff
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/category_theory/sites/sheaf_of_types.lean
2b51247d5cf5cc21723631509d9e3f9491f00ffb
[ "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
35,527
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.sites.pretopology import category_theory.limits.shapes.types import category_theory.full_subcategory /-! # Sheaves of types on a Grothendieck topology Defines the notion of a sheaf of types (usually called a sheaf of sets by mathematicians) on a category equipped with a Grothendieck topology, as well as a range of equivalent conditions useful in different situations. First define what it means for a presheaf `P : Cᵒᵖ ⥤ Type v` to be a sheaf *for* a particular presieve `R` on `X`: * A *family of elements* `x` for `P` at `R` is an element `x_f` of `P Y` for every `f : Y ⟶ X` in `R`. See `family_of_elements`. * The family `x` is *compatible* if, for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` both in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂` such that `g₁ ≫ f₁ = g₂ ≫ f₂`, the restriction of `x_f₁` along `g₁` agrees with the restriction of `x_f₂` along `g₂`. See `family_of_elements.compatible`. * An *amalgamation* `t` for the family is an element of `P X` such that for every `f : Y ⟶ X` in `R`, the restriction of `t` on `f` is `x_f`. See `family_of_elements.is_amalgamation`. We then say `P` is *separated* for `R` if every compatible family has at most one amalgamation, and it is a *sheaf* for `R` if every compatible family has a unique amalgamation. See `is_separated_for` and `is_sheaf_for`. In the special case where `R` is a sieve, the compatibility condition can be simplified: * The family `x` is *compatible* if, for any `f : Y ⟶ X` in `R` and `g : Z ⟶ Y`, the restriction of `x_f` along `g` agrees with `x_(g ≫ f)` (which is well defined since `g ≫ f` is in `R`). See `family_of_elements.sieve_compatible` and `compatible_iff_sieve_compatible`. In the special case where `C` has pullbacks, the compatibility condition can be simplified: * The family `x` is *compatible* if, for any `f : Y ⟶ X` and `g : Z ⟶ X` both in `R`, the restriction of `x_f` along `π₁ : pullback f g ⟶ Y` agrees with the restriction of `x_g` along `π₂ : pullback f g ⟶ Z`. See `family_of_elements.pullback_compatible` and `pullback_compatible_iff`. Now given a Grothendieck topology `J`, `P` is a sheaf if it is a sheaf for every sieve in the topology. See `is_sheaf`. In the case where the topology is generated by a basis, it suffices to check `P` is a sheaf for every sieve in the pretopology. See `is_sheaf_pretopology`. We also provide equivalent conditions to satisfy alternate definitions given in the literature. * Stacks: In `equalizer.presieve.sheaf_condition`, the sheaf condition at a presieve is shown to be equivalent to that of https://stacks.math.columbia.edu/tag/00VM (and combined with `is_sheaf_pretopology`, this shows the notions of `is_sheaf` are exactly equivalent.) The condition of https://stacks.math.columbia.edu/tag/00Z8 is virtually identical to the statement of `yoneda_condition_iff_sheaf_condition` (since the bijection described there carries the same information as the unique existence.) * Maclane-Moerdijk [MM92]: Using `compatible_iff_sieve_compatible`, the definitions of `is_sheaf` are equivalent. There are also alternate definitions given: - Yoneda condition: Defined in `yoneda_sheaf_condition` and equivalence in `yoneda_condition_iff_sheaf_condition`. - Equalizer condition (Equation 3): Defined in the `equalizer.sieve` namespace, and equivalence in `equalizer.sieve.sheaf_condition`. - Matching family for presieves with pullback: `pullback_compatible_iff`. - Sheaf for a pretopology (Prop 1): `is_sheaf_pretopology` combined with the previous. - Sheaf for a pretopology as equalizer (Prop 1, bis): `equalizer.presieve.sheaf_condition` combined with the previous. ## Implementation The sheaf condition is given as a proposition, rather than a subsingleton in `Type (max u v)`. This doesn't seem to make a big difference, other than making a couple of definitions noncomputable, but it means that equivalent conditions can be given as `↔` statements rather than `≃` statements, which can be convenient. ## References * [MM92]: *Sheaves in geometry and logic*, Saunders MacLane, and Ieke Moerdijk: Chapter III, Section 4. * [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.1. * https://stacks.math.columbia.edu/tag/00VL (sheaves on a pretopology or site) * https://stacks.math.columbia.edu/tag/00ZB (sheaves on a topology) -/ universes v u namespace category_theory open opposite category_theory category limits sieve classical namespace presieve variables {C : Type u} [category.{v} C] variables {P : Cᵒᵖ ⥤ Type v} variables {X Y : C} {S : sieve X} {R : presieve X} variables (J J₂ : grothendieck_topology C) /-- A family of elements for a presheaf `P` given a collection of arrows `R` with fixed codomain `X` consists of an element of `P Y` for every `f : Y ⟶ X` in `R`. A presheaf is a sheaf (resp, separated) if every *compatible* family of elements has exactly one (resp, at most one) amalgamation. This data is referred to as a `family` in [MM92], Chapter III, Section 4. It is also a concrete version of the elements of the middle object in https://stacks.math.columbia.edu/tag/00VM which is more useful for direct calculations. It is also used implicitly in Definition C2.1.2 in [Elephant]. -/ def family_of_elements (P : Cᵒᵖ ⥤ Type v) (R : presieve X) := Π ⦃Y : C⦄ (f : Y ⟶ X), R f → P.obj (op Y) instance : inhabited (family_of_elements P (⊥ : presieve X)) := ⟨λ Y f, false.elim⟩ /-- A family of elements for a presheaf on the presieve `R₂` can be restricted to a smaller presieve `R₁`. -/ def family_of_elements.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) : family_of_elements P R₂ → family_of_elements P R₁ := λ x Y f hf, x f (h _ hf) /-- A family of elements for the arrow set `R` is *compatible* if for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂`, if the square `g₁ ≫ f₁ = g₂ ≫ f₂` commutes then the elements of `P Z` obtained by restricting the element of `P Y₁` along `g₁` and restricting the element of `P Y₂` along `g₂` are the same. In special cases, this condition can be simplified, see `pullback_compatible_iff` and `compatible_iff_sieve_compatible`. This is referred to as a "compatible family" in Definition C2.1.2 of [Elephant], and on nlab: https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents -/ def family_of_elements.compatible (x : family_of_elements P R) : Prop := ∀ ⦃Y₁ Y₂ Z⦄ (g₁ : Z ⟶ Y₁) (g₂ : Z ⟶ Y₂) ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂), g₁ ≫ f₁ = g₂ ≫ f₂ → P.map g₁.op (x f₁ h₁) = P.map g₂.op (x f₂ h₂) /-- If the category `C` has pullbacks, this is an alternative condition for a family of elements to be compatible: For any `f : Y ⟶ X` and `g : Z ⟶ X` in the presieve `R`, the restriction of the given elements for `f` and `g` to the pullback agree. This is equivalent to being compatible (provided `C` has pullbacks), shown in `pullback_compatible_iff`. This is the definition for a "matching" family given in [MM92], Chapter III, Section 4, Equation (5). Viewing the type `family_of_elements` as the middle object of the fork in https://stacks.math.columbia.edu/tag/00VM, this condition expresses that `pr₀* (x) = pr₁* (x)`, using the notation defined there. -/ def family_of_elements.pullback_compatible (x : family_of_elements P R) [has_pullbacks C] : Prop := ∀ ⦃Y₁ Y₂⦄ ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂), P.map (pullback.fst : pullback f₁ f₂ ⟶ _).op (x f₁ h₁) = P.map pullback.snd.op (x f₂ h₂) lemma pullback_compatible_iff (x : family_of_elements P R) [has_pullbacks C] : x.compatible ↔ x.pullback_compatible := begin split, { intros t Y₁ Y₂ f₁ f₂ hf₁ hf₂, apply t, apply pullback.condition }, { intros t Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm, rw [←pullback.lift_fst _ _ comm, op_comp, functor_to_types.map_comp_apply, t hf₁ hf₂, ←functor_to_types.map_comp_apply, ←op_comp, pullback.lift_snd] } end /-- The restriction of a compatible family is compatible. -/ lemma family_of_elements.compatible.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) {x : family_of_elements P R₂} : x.compatible → (x.restrict h).compatible := λ q Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, q g₁ g₂ (h _ h₁) (h _ h₂) comm /-- Extend a family of elements to the sieve generated by an arrow set. This is the construction described as "easy" in Lemma C2.1.3 of [Elephant]. -/ noncomputable def family_of_elements.sieve_extend (x : family_of_elements P R) : family_of_elements P (generate R) := λ Z f hf, P.map (some (some_spec hf)).op (x _ (some_spec (some_spec (some_spec hf))).1) /-- The extension of a compatible family to the generated sieve is compatible. -/ lemma family_of_elements.compatible.sieve_extend (x : family_of_elements P R) (hx : x.compatible) : x.sieve_extend.compatible := begin intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, rw [←(some_spec (some_spec (some_spec h₁))).2, ←(some_spec (some_spec (some_spec h₂))).2, ←assoc, ←assoc] at comm, dsimp [family_of_elements.sieve_extend], rw [← functor_to_types.map_comp_apply, ← functor_to_types.map_comp_apply], apply hx _ _ _ _ comm, end /-- The extension of a family agrees with the original family. -/ lemma extend_agrees {x : family_of_elements P R} (t : x.compatible) {f : Y ⟶ X} (hf : R f) : x.sieve_extend f ⟨_, 𝟙 _, f, hf, id_comp _⟩ = x f hf := begin have h : (generate R) f := ⟨_, _, _, hf, id_comp _⟩, change P.map (some (some_spec h)).op (x _ _) = x f hf, rw t (some (some_spec h)) (𝟙 _) _ hf _, { simp }, simp_rw [id_comp], apply (some_spec (some_spec (some_spec h))).2, end /-- The restriction of an extension is the original. -/ @[simp] lemma restrict_extend {x : family_of_elements P R} (t : x.compatible) : x.sieve_extend.restrict (le_generate R) = x := begin ext Y f hf, exact extend_agrees t hf, end /-- If the arrow set for a family of elements is actually a sieve (i.e. it is downward closed) then the consistency condition can be simplified. This is an equivalent condition, see `compatible_iff_sieve_compatible`. This is the notion of "matching" given for families on sieves given in [MM92], Chapter III, Section 4, Equation 1, and nlab: https://ncatlab.org/nlab/show/matching+family. See also the discussion before Lemma C2.1.4 of [Elephant]. -/ def family_of_elements.sieve_compatible (x : family_of_elements P S) : Prop := ∀ ⦃Y Z⦄ (f : Y ⟶ X) (g : Z ⟶ Y) (hf), x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf) lemma compatible_iff_sieve_compatible (x : family_of_elements P S) : x.compatible ↔ x.sieve_compatible := begin split, { intros h Y Z f g hf, simpa using h (𝟙 _) g (S.downward_closed hf g) hf (id_comp _) }, { intros h Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ k, simp_rw [← h f₁ g₁ h₁, k, h f₂ g₂ h₂] } end lemma family_of_elements.compatible.to_sieve_compatible {x : family_of_elements P S} (t : x.compatible) : x.sieve_compatible := (compatible_iff_sieve_compatible x).1 t /-- Two compatible families on the sieve generated by a presieve `R` are equal if and only if they are equal when restricted to `R`. -/ lemma restrict_inj {x₁ x₂ : family_of_elements P (generate R)} (t₁ : x₁.compatible) (t₂ : x₂.compatible) : x₁.restrict (le_generate R) = x₂.restrict (le_generate R) → x₁ = x₂ := begin intro h, ext Z f ⟨Y, f, g, hg, rfl⟩, rw compatible_iff_sieve_compatible at t₁ t₂, erw [t₁ g f ⟨_, _, g, hg, id_comp _⟩, t₂ g f ⟨_, _, g, hg, id_comp _⟩], congr' 1, apply congr_fun (congr_fun (congr_fun h _) g) hg, end /-- Given a family of elements `x` for the sieve `S` generated by a presieve `R`, if `x` is restricted to `R` and then extended back up to `S`, the resulting extension equals `x`. -/ @[simp] lemma extend_restrict {x : family_of_elements P (generate R)} (t : x.compatible) : (x.restrict (le_generate R)).sieve_extend = x := begin apply restrict_inj, { exact (t.restrict (le_generate R)).sieve_extend _ }, { exact t }, rw restrict_extend, exact t.restrict (le_generate R), end /-- The given element `t` of `P.obj (op X)` is an *amalgamation* for the family of elements `x` if every restriction `P.map f.op t = x_f` for every arrow `f` in the presieve `R`. This is the definition given in https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents, and https://ncatlab.org/nlab/show/matching+family, as well as [MM92], Chapter III, Section 4, equation (2). -/ def family_of_elements.is_amalgamation (x : family_of_elements P R) (t : P.obj (op X)) : Prop := ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : R f), P.map f.op t = x f h lemma is_compatible_of_exists_amalgamation (x : family_of_elements P R) (h : ∃ t, x.is_amalgamation t) : x.compatible := begin cases h with t ht, intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, rw [←ht _ h₁, ←ht _ h₂, ←functor_to_types.map_comp_apply, ←op_comp, comm], simp, end lemma is_amalgamation_restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) (x : family_of_elements P R₂) (t : P.obj (op X)) (ht : x.is_amalgamation t) : (x.restrict h).is_amalgamation t := λ Y f hf, ht f (h Y hf) lemma is_amalgamation_sieve_extend {R : presieve X} (x : family_of_elements P R) (t : P.obj (op X)) (ht : x.is_amalgamation t) : x.sieve_extend.is_amalgamation t := begin intros Y f hf, dsimp [family_of_elements.sieve_extend], rw [←ht _, ←functor_to_types.map_comp_apply, ←op_comp, (some_spec (some_spec (some_spec hf))).2], end /-- A presheaf is separated for a presieve if there is at most one amalgamation. -/ def is_separated_for (P : Cᵒᵖ ⥤ Type v) (R : presieve X) : Prop := ∀ (x : family_of_elements P R) (t₁ t₂), x.is_amalgamation t₁ → x.is_amalgamation t₂ → t₁ = t₂ lemma is_separated_for.ext {R : presieve X} (hR : is_separated_for P R) {t₁ t₂ : P.obj (op X)} (h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), P.map f.op t₁ = P.map f.op t₂) : t₁ = t₂ := hR (λ Y f hf, P.map f.op t₂) t₁ t₂ (λ Y f hf, h hf) (λ Y f hf, rfl) lemma is_separated_for_iff_generate : is_separated_for P R ↔ is_separated_for P (generate R) := begin split, { intros h x t₁ t₂ ht₁ ht₂, apply h (x.restrict (le_generate R)) t₁ t₂ _ _, { exact is_amalgamation_restrict _ x t₁ ht₁ }, { exact is_amalgamation_restrict _ x t₂ ht₂ } }, { intros h x t₁ t₂ ht₁ ht₂, apply h (x.sieve_extend), { exact is_amalgamation_sieve_extend x t₁ ht₁ }, { exact is_amalgamation_sieve_extend x t₂ ht₂ } } end lemma is_separated_for_top (P : Cᵒᵖ ⥤ Type v) : is_separated_for P (⊤ : presieve X) := λ x t₁ t₂ h₁ h₂, begin have q₁ := h₁ (𝟙 X) (by simp), have q₂ := h₂ (𝟙 X) (by simp), simp only [op_id, functor_to_types.map_id_apply] at q₁ q₂, rw [q₁, q₂], end /-- We define `P` to be a sheaf for the presieve `R` if every compatible family has a unique amalgamation. This is the definition of a sheaf for the given presieve given in C2.1.2 of [Elephant], and https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents. Using `compatible_iff_sieve_compatible`, this is equivalent to the definition of a sheaf in [MM92], Chapter III, Section 4. -/ def is_sheaf_for (P : Cᵒᵖ ⥤ Type v) (R : presieve X) : Prop := ∀ (x : family_of_elements P R), x.compatible → ∃! t, x.is_amalgamation t /-- This is an equivalent condition to be a sheaf, which is useful for the abstraction to local operators on elementary toposes. However this definition is defined only for sieves, not presieves. The equivalence between this and `is_sheaf_for` is given in `yoneda_condition_iff_sheaf_condition`. This version is also useful to establish that being a sheaf is preserved under isomorphism of presheaves. See the discussion before Equation (3) of [MM92], Chapter III, Section 4. See also C2.1.4 of [Elephant]. This is also a direct reformulation of https://stacks.math.columbia.edu/tag/00Z8. -/ def yoneda_sheaf_condition (P : Cᵒᵖ ⥤ Type v) (S : sieve X) : Prop := ∀ (f : S.functor ⟶ P), ∃! g, S.functor_inclusion ≫ g = f /-- (Implementation). This is a (primarily internal) equivalence between natural transformations and compatible families. Cf the discussion after Lemma 7.47.10 in https://stacks.math.columbia.edu/tag/00YW. See also the proof of C2.1.4 of [Elephant], and the discussion in [MM92], Chapter III, Section 4. -/ def nat_trans_equiv_compatible_family : (S.functor ⟶ P) ≃ {x : family_of_elements P S // x.compatible} := { to_fun := λ α, begin refine ⟨λ Y f hf, _, _⟩, { apply α.app (op Y) ⟨_, hf⟩ }, { rw compatible_iff_sieve_compatible, intros Y Z f g hf, dsimp, rw ← functor_to_types.naturality _ _ α g.op, refl } end, inv_fun := λ t, { app := λ Y f, t.1 _ f.2, naturality' := λ Y Z g, begin ext ⟨f, hf⟩, apply t.2.to_sieve_compatible _, end }, left_inv := λ α, begin ext X ⟨_, _⟩, refl end, right_inv := begin rintro ⟨x, hx⟩, refl, end } /-- (Implementation). A lemma useful to prove `yoneda_condition_iff_sheaf_condition`. -/ lemma extension_iff_amalgamation (x : S.functor ⟶ P) (g : yoneda.obj X ⟶ P) : S.functor_inclusion ≫ g = x ↔ (nat_trans_equiv_compatible_family x).1.is_amalgamation (yoneda_equiv g) := begin change _ ↔ ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : S f), P.map f.op (yoneda_equiv g) = x.app (op Y) ⟨f, h⟩, split, { rintro rfl Y f hf, rw yoneda_equiv_naturality, dsimp, simp }, -- See note [dsimp, simp]. { intro h, ext Y ⟨f, hf⟩, have : _ = x.app Y _ := h f hf, rw yoneda_equiv_naturality at this, rw ← this, dsimp, simp }, -- See note [dsimp, simp]. end /-- The yoneda version of the sheaf condition is equivalent to the sheaf condition. C2.1.4 of [Elephant]. -/ lemma is_sheaf_for_iff_yoneda_sheaf_condition : is_sheaf_for P S ↔ yoneda_sheaf_condition P S := begin rw [is_sheaf_for, yoneda_sheaf_condition], simp_rw [extension_iff_amalgamation], rw equiv.forall_congr_left' nat_trans_equiv_compatible_family, rw subtype.forall, apply ball_congr, intros x hx, rw equiv.exists_unique_congr_left _, simp, end /-- If `P` is a sheaf for the sieve `S` on `X`, a natural transformation from `S` (viewed as a functor) to `P` can be (uniquely) extended to all of `yoneda.obj X`. f S → P ↓ ↗ yX -/ noncomputable def is_sheaf_for.extend (h : is_sheaf_for P S) (f : S.functor ⟶ P) : yoneda.obj X ⟶ P := classical.some (is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists /-- Show that the extension of `f : S.functor ⟶ P` to all of `yoneda.obj X` is in fact an extension, ie that the triangle below commutes, provided `P` is a sheaf for `S` f S → P ↓ ↗ yX -/ @[simp, reassoc] lemma is_sheaf_for.functor_inclusion_comp_extend (h : is_sheaf_for P S) (f : S.functor ⟶ P) : S.functor_inclusion ≫ h.extend f = f := classical.some_spec (is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists /-- The extension of `f` to `yoneda.obj X` is unique. -/ lemma is_sheaf_for.unique_extend (h : is_sheaf_for P S) {f : S.functor ⟶ P} (t : yoneda.obj X ⟶ P) (ht : S.functor_inclusion ≫ t = f) : t = h.extend f := ((is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).unique ht (h.functor_inclusion_comp_extend f)) /-- If `P` is a sheaf for the sieve `S` on `X`, then if two natural transformations from `yoneda.obj X` to `P` agree when restricted to the subfunctor given by `S`, they are equal. -/ lemma is_sheaf_for.hom_ext (h : is_sheaf_for P S) (t₁ t₂ : yoneda.obj X ⟶ P) (ht : S.functor_inclusion ≫ t₁ = S.functor_inclusion ≫ t₂) : t₁ = t₂ := (h.unique_extend t₁ ht).trans (h.unique_extend t₂ rfl).symm /-- `P` is a sheaf for `R` iff it is separated for `R` and there exists an amalgamation. -/ lemma is_separated_for_and_exists_is_amalgamation_iff_sheaf_for : is_separated_for P R ∧ (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) ↔ is_sheaf_for P R := begin rw [is_separated_for, ←forall_and_distrib], apply forall_congr, intro x, split, { intros z hx, exact exists_unique_of_exists_of_unique (z.2 hx) z.1 }, { intros h, refine ⟨_, (exists_of_exists_unique ∘ h)⟩, intros t₁ t₂ ht₁ ht₂, apply (h _).unique ht₁ ht₂, exact is_compatible_of_exists_amalgamation x ⟨_, ht₂⟩ } end /-- If `P` is separated for `R` and every family has an amalgamation, then `P` is a sheaf for `R`. -/ lemma is_separated_for.is_sheaf_for (t : is_separated_for P R) : (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) → is_sheaf_for P R := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, exact and.intro t, end /-- If `P` is a sheaf for `R`, it is separated for `R`. -/ lemma is_sheaf_for.is_separated_for : is_sheaf_for P R → is_separated_for P R := λ q, (is_separated_for_and_exists_is_amalgamation_iff_sheaf_for.2 q).1 /-- Get the amalgamation of the given compatible family, provided we have a sheaf. -/ noncomputable def is_sheaf_for.amalgamate (t : is_sheaf_for P R) (x : family_of_elements P R) (hx : x.compatible) : P.obj (op X) := classical.some (t x hx).exists lemma is_sheaf_for.is_amalgamation (t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) : x.is_amalgamation (t.amalgamate x hx) := classical.some_spec (t x hx).exists @[simp] lemma is_sheaf_for.valid_glue (t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) (f : Y ⟶ X) (Hf : R f) : P.map f.op (t.amalgamate x hx) = x f Hf := t.is_amalgamation hx f Hf /-- C2.1.3 in [Elephant] -/ lemma is_sheaf_for_iff_generate (R : presieve X) : is_sheaf_for P R ↔ is_sheaf_for P (generate R) := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, rw ← is_separated_for_iff_generate, apply and_congr (iff.refl _), split, { intros q x hx, apply exists_imp_exists _ (q _ (hx.restrict (le_generate R))), intros t ht, simpa [hx] using is_amalgamation_sieve_extend _ _ ht }, { intros q x hx, apply exists_imp_exists _ (q _ (hx.sieve_extend _)), intros t ht, simpa [hx] using is_amalgamation_restrict (le_generate R) _ _ ht }, end /-- Every presheaf is a sheaf for the family {𝟙 X}. [Elephant] C2.1.5(i) -/ lemma is_sheaf_for_singleton_iso (P : Cᵒᵖ ⥤ Type v) : is_sheaf_for P (presieve.singleton (𝟙 X)) := begin intros x hx, refine ⟨x _ (presieve.singleton_self _), _, _⟩, { rintro _ _ ⟨rfl, rfl⟩, simp }, { intros t ht, simpa using ht _ (presieve.singleton_self _) } end /-- Every presheaf is a sheaf for the maximal sieve. [Elephant] C2.1.5(ii) -/ lemma is_sheaf_for_top_sieve (P : Cᵒᵖ ⥤ Type v) : is_sheaf_for P ((⊤ : sieve X) : presieve X) := begin rw ← generate_of_singleton_split_epi (𝟙 X), rw ← is_sheaf_for_iff_generate, apply is_sheaf_for_singleton_iso, end /-- If `P` is a sheaf for `S`, and it is iso to `P'`, then `P'` is a sheaf for `S`. This shows that "being a sheaf for a presieve" is a mathematical or hygenic property. -/ lemma is_sheaf_for_iso {P' : Cᵒᵖ ⥤ Type v} (i : P ≅ P') : is_sheaf_for P R → is_sheaf_for P' R := begin rw [is_sheaf_for_iff_generate R, is_sheaf_for_iff_generate R], intro h, rw [is_sheaf_for_iff_yoneda_sheaf_condition], intro f, refine ⟨h.extend (f ≫ i.inv) ≫ i.hom, by simp, _⟩, intros g' hg', rw [← i.comp_inv_eq, h.unique_extend (g' ≫ i.inv) (by rw reassoc_of hg')], end /-- If a presieve `R` on `X` has a subsieve `S` such that: * `P` is a sheaf for `S`. * For every `f` in `R`, `P` is separated for the pullback of `S` along `f`, then `P` is a sheaf for `R`. This is closely related to [Elephant] C2.1.6(i). -/ lemma is_sheaf_for_subsieve_aux (P : Cᵒᵖ ⥤ Type v) {S : sieve X} {R : presieve X} (h : (S : presieve X) ≤ R) (hS : is_sheaf_for P S) (trans : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, R f → is_separated_for P (S.pullback f)) : is_sheaf_for P R := begin rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for, split, { intros x t₁ t₂ ht₁ ht₂, exact hS.is_separated_for _ _ _ (is_amalgamation_restrict h x t₁ ht₁) (is_amalgamation_restrict h x t₂ ht₂) }, { intros x hx, use hS.amalgamate _ (hx.restrict h), intros W j hj, apply (trans hj).ext, intros Y f hf, rw [←functor_to_types.map_comp_apply, ←op_comp, hS.valid_glue (hx.restrict h) _ hf, family_of_elements.restrict, ←hx (𝟙 _) f _ _ (id_comp _)], simp }, end /-- If `P` is a sheaf for every pullback of the sieve `S`, then `P` is a sheaf for any presieve which contains `S`. This is closely related to [Elephant] C2.1.6. -/ lemma is_sheaf_for_subsieve (P : Cᵒᵖ ⥤ Type v) {S : sieve X} {R : presieve X} (h : (S : presieve X) ≤ R) (trans : Π ⦃Y⦄ (f : Y ⟶ X), is_sheaf_for P (S.pullback f)) : is_sheaf_for P R := is_sheaf_for_subsieve_aux P h (by simpa using trans (𝟙 _)) (λ Y f hf, (trans f).is_separated_for) /-- A presheaf is separated for a topology if it is separated for every sieve in the topology. -/ def is_separated (P : Cᵒᵖ ⥤ Type v) : Prop := ∀ {X} (S : sieve X), S ∈ J X → is_separated_for P S /-- A presheaf is a sheaf for a topology if it is a sheaf for every sieve in the topology. If the given topology is given by a pretopology, `is_sheaf_for_pretopology` shows it suffices to check the sheaf condition at presieves in the pretopology. -/ def is_sheaf (P : Cᵒᵖ ⥤ Type v) : Prop := ∀ ⦃X⦄ (S : sieve X), S ∈ J X → is_sheaf_for P S lemma is_sheaf.is_sheaf_for {P : Cᵒᵖ ⥤ Type v} (hp : is_sheaf J P) (R : presieve X) (hr : generate R ∈ J X) : is_sheaf_for P R := (is_sheaf_for_iff_generate R).2 $ hp _ hr lemma is_sheaf_of_le (P : Cᵒᵖ ⥤ Type v) {J₁ J₂ : grothendieck_topology C} : J₁ ≤ J₂ → is_sheaf J₂ P → is_sheaf J₁ P := λ h t X S hS, t S (h _ hS) lemma is_separated_of_is_sheaf (P : Cᵒᵖ ⥤ Type v) (h : is_sheaf J P) : is_separated J P := λ X S hS, (h S hS).is_separated_for /-- The property of being a sheaf is preserved by isomorphism. -/ lemma is_sheaf_iso {P' : Cᵒᵖ ⥤ Type v} (i : P ≅ P') (h : is_sheaf J P) : is_sheaf J P' := λ X S hS, is_sheaf_for_iso i (h S hS) lemma is_sheaf_of_yoneda (h : ∀ {X} (S : sieve X), S ∈ J X → yoneda_sheaf_condition P S) : is_sheaf J P := λ X S hS, is_sheaf_for_iff_yoneda_sheaf_condition.2 (h _ hS) /-- For a topology generated by a basis, it suffices to check the sheaf condition on the basis presieves only. -/ lemma is_sheaf_pretopology [has_pullbacks C] (K : pretopology C) : is_sheaf (K.to_grothendieck C) P ↔ (∀ {X : C} (R : presieve X), R ∈ K X → is_sheaf_for P R) := begin split, { intros PJ X R hR, rw is_sheaf_for_iff_generate, apply PJ (sieve.generate R) ⟨_, hR, le_generate R⟩ }, { rintro PK X S ⟨R, hR, RS⟩, have gRS : ⇑(generate R) ≤ S, { apply gi_generate.gc.monotone_u, rwa sets_iff_generate }, apply is_sheaf_for_subsieve P gRS _, intros Y f, rw [← pullback_arrows_comm, ← is_sheaf_for_iff_generate], exact PK (pullback_arrows f R) (K.pullbacks f R hR) } end /-- Any presheaf is a sheaf for the bottom (trivial) grothendieck topology. -/ lemma is_sheaf_bot : is_sheaf (⊥ : grothendieck_topology C) P := λ X, by simp [is_sheaf_for_top_sieve] end presieve namespace equalizer variables {C : Type v} [small_category C] (P : Cᵒᵖ ⥤ Type v) {X : C} (R : presieve X) (S : sieve X) noncomputable theory /-- The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of https://stacks.math.columbia.edu/tag/00VM. -/ def first_obj : Type v := ∏ (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) /-- Show that `first_obj` is isomorphic to `family_of_elements`. -/ @[simps] def first_obj_eq_family : first_obj P R ≅ R.family_of_elements P := { hom := λ t Y f hf, pi.π (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) ⟨_, _, hf⟩ t, inv := pi.lift (λ f x, x _ f.2.2), hom_inv_id' := begin ext ⟨Y, f, hf⟩ p, simpa, end, inv_hom_id' := begin ext x Y f hf, apply limits.types.limit.lift_π_apply, end } instance : inhabited (first_obj P (⊥ : presieve X)) := ((first_obj_eq_family P _).to_equiv).inhabited /-- The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram of https://stacks.math.columbia.edu/tag/00VM. -/ def fork_map : P.obj (op X) ⟶ first_obj P R := pi.lift (λ f, P.map f.2.1.op) /-! This section establishes the equivalence between the sheaf condition of Equation (3) [MM92] and the definition of `is_sheaf_for`. -/ namespace sieve /-- The rightmost object of the fork diagram of Equation (3) [MM92], which contains the data used to check a family is compatible. -/ def second_obj : Type v := ∏ (λ (f : Σ Y Z (g : Z ⟶ Y), {f' : Y ⟶ X // S f'}), P.obj (op f.2.1)) /-- The map `p` of Equations (3,4) [MM92]. -/ def first_map : first_obj P S ⟶ second_obj P S := pi.lift (λ fg, pi.π _ (⟨_, _, S.downward_closed fg.2.2.2.2 fg.2.2.1⟩ : Σ Y, {f : Y ⟶ X // S f})) instance : inhabited (second_obj P (⊥ : sieve X)) := ⟨first_map _ _ (default _)⟩ /-- The map `a` of Equations (3,4) [MM92]. -/ def second_map : first_obj P S ⟶ second_obj P S := pi.lift (λ fg, pi.π _ ⟨_, fg.2.2.2⟩ ≫ P.map fg.2.2.1.op) lemma w : fork_map P S ≫ first_map P S = fork_map P S ≫ second_map P S := begin apply limit.hom_ext, rintro ⟨Y, Z, g, f, hf⟩, simp [first_map, second_map, fork_map], end /-- The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map` map it to the same point. -/ lemma compatible_iff (x : first_obj P S) : ((first_obj_eq_family P S).hom x).compatible ↔ first_map P S x = second_map P S x := begin rw presieve.compatible_iff_sieve_compatible, split, { intro t, ext ⟨Y, Z, g, f, hf⟩, simpa [first_map, second_map] using t _ g hf }, { intros t Y Z f g hf, rw types.limit_ext_iff at t, simpa [first_map, second_map] using t ⟨Y, Z, g, f, hf⟩ } end /-- `P` is a sheaf for `S`, iff the fork given by `w` is an equalizer. -/ lemma equalizer_sheaf_condition : presieve.is_sheaf_for P S ↔ nonempty (is_limit (fork.of_ι _ (w P S))) := begin rw [types.type_equalizer_iff_unique, ← equiv.forall_congr_left (first_obj_eq_family P S).to_equiv.symm], simp_rw ← compatible_iff, simp only [inv_hom_id_apply, iso.to_equiv_symm_fun], apply ball_congr, intros x tx, apply exists_unique_congr, intro t, rw ← iso.to_equiv_symm_fun, rw equiv.eq_symm_apply, split, { intros q, ext Y f hf, simpa [first_obj_eq_family, fork_map] using q _ _ }, { intros q Y f hf, rw ← q, simp [first_obj_eq_family, fork_map] } end end sieve /-! This section establishes the equivalence between the sheaf condition of https://stacks.math.columbia.edu/tag/00VM and the definition of `is_sheaf_for`. -/ namespace presieve variables [has_pullbacks C] /-- The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which contains the data used to check a family of elements for a presieve is compatible. -/ def second_obj : Type v := ∏ (λ (fg : (Σ Y, {f : Y ⟶ X // R f}) × (Σ Z, {g : Z ⟶ X // R g})), P.obj (op (pullback fg.1.2.1 fg.2.2.1))) /-- The map `pr₀*` of https://stacks.math.columbia.edu/tag/00VL. -/ def first_map : first_obj P R ⟶ second_obj P R := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op) instance : inhabited (second_obj P (⊥ : presieve X)) := ⟨first_map _ _ (default _)⟩ /-- The map `pr₁*` of https://stacks.math.columbia.edu/tag/00VL. -/ def second_map : first_obj P R ⟶ second_obj P R := pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op) lemma w : fork_map P R ≫ first_map P R = fork_map P R ≫ second_map P R := begin apply limit.hom_ext, rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩, simp only [first_map, second_map, fork_map], simp only [limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk, subtype.val_eq_coe], rw [← P.map_comp, ← op_comp, pullback.condition], simp, end /-- The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map` map it to the same point. -/ lemma compatible_iff (x : first_obj P R) : ((first_obj_eq_family P R).hom x).compatible ↔ first_map P R x = second_map P R x := begin rw presieve.pullback_compatible_iff, split, { intro t, ext ⟨⟨Y, f, hf⟩, Z, g, hg⟩, simpa [first_map, second_map] using t hf hg }, { intros t Y Z f g hf hg, rw types.limit_ext_iff at t, simpa [first_map, second_map] using t ⟨⟨Y, f, hf⟩, Z, g, hg⟩ } end /-- `P` is a sheaf for `R`, iff the fork given by `w` is an equalizer. See https://stacks.math.columbia.edu/tag/00VM. -/ lemma sheaf_condition : R.is_sheaf_for P ↔ nonempty (is_limit (fork.of_ι _ (w P R))) := begin rw types.type_equalizer_iff_unique, erw ← equiv.forall_congr_left (first_obj_eq_family P R).to_equiv.symm, simp_rw [← compatible_iff, ← iso.to_equiv_fun, equiv.apply_symm_apply], apply ball_congr, intros x hx, apply exists_unique_congr, intros t, rw equiv.eq_symm_apply, split, { intros q, ext Y f hf, simpa [fork_map] using q _ _ }, { intros q Y f hf, rw ← q, simp [fork_map] } end end presieve end equalizer variables {C : Type u} [category.{v} C] variables (J : grothendieck_topology C) /-- The category of sheaves on a grothendieck topology. -/ @[derive category] def SheafOfTypes (J : grothendieck_topology C) : Type (max u (v+1)) := {P : Cᵒᵖ ⥤ Type v // presieve.is_sheaf J P} /-- The inclusion functor from sheaves to presheaves. -/ @[simps, derive [full, faithful]] def SheafOfTypes_to_presheaf : SheafOfTypes J ⥤ (Cᵒᵖ ⥤ Type v) := full_subcategory_inclusion (presieve.is_sheaf J) /-- The category of sheaves on the bottom (trivial) grothendieck topology is equivalent to the category of presheaves. -/ @[simps] def SheafOfTypes_bot_equiv : SheafOfTypes (⊥ : grothendieck_topology C) ≌ (Cᵒᵖ ⥤ Type v) := { functor := SheafOfTypes_to_presheaf _, inverse := { obj := λ P, ⟨P, presieve.is_sheaf_bot⟩, map := λ P₁ P₂ f, (SheafOfTypes_to_presheaf _).preimage f }, unit_iso := { hom := { app := λ _, 𝟙 _ }, inv := { app := λ _, 𝟙 _ } }, counit_iso := iso.refl _ } instance : inhabited (SheafOfTypes (⊥ : grothendieck_topology C)) := ⟨SheafOfTypes_bot_equiv.inverse.obj ((functor.const _).obj punit)⟩ end category_theory
e10ff6bae595680d11994954a1f5084f87ec7c49
6b7c9c6393bac7cb1c64582a1c62597e24f5bb80
/src/tactic/autoname/autoname.lean
dd7ea2e98bf52cd9174e622c29cfbdc5b7dff37c
[ "Apache-2.0" ]
permissive
alreadydone/lean-gptf
56a7d9cbd9400af72fb143d60c8774b8cfbc09cb
b4ab1eb2da0178f3dcdc49771d9fed6b50e35d98
refs/heads/master
1,679,371,993,063
1,614,479,778,000
1,614,479,778,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,608
lean
import tactic.gptf.basic import tactic.gptf.backends.openai import tactic.gptf.utils.util import tactic.gptf.gptf import tactic.finish open openai namespace tactic meta def autoname_core (e : expr) (cfg : interactive.GPTSuggestConfig := {}) : tactic (list name) := do { let cfg := {prompt_token := "PREDICTNAME", ..cfg}, let req := { n := cfg.n, temperature := cfg.temp, prompt_token := cfg.prompt_token, prompt_prefix := cfg.pfx, replace_prefix := cfg.postprocess, .. default_partial_req }, api_key ← get_openai_api_key, completion_request ← (autoname_serialize_ts_core e req), response_msg ← tactic.unsafe_run_io $ (openai_api cfg.engine_id api_key).query completion_request, responses ← list.map prod.fst <$> ((list.qsort (λ x y : string × native.float, prod.snd x > prod.snd y) <$> unwrap_lm_response_logprobs "" none "autonamer" response_msg) >>= list.dedup'), eval_trace format! "[autoname_core] RESPONSES: {responses}", list.filter_map id <$> responses.mmap (λ x, (optional $ lean.parser.run $ prod.fst <$> lean.parser.with_input lean.parser.ident x)) } namespace interactive meta def autoname (cfg : GPTSuggestConfig := {n := 12, temp := 1.0}) : tactic unit := do { ts ← tactic.read, e ← ts.fully_qualified >>= λ x, do { tactic.write x, extract_fully_bound_goal }, tactic.pp e >>= λ e, tactic.trace format! "[autoname] Suggested names for goal\n------\n{e}\n------\n", tactic.write ts, nms ← autoname_core e cfg, nms.mmap' $ λ nm, tactic.trythis nm.to_string } end interactive end tactic
fa3f521731d7b052bbde03e70b4791a589bd16fd
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/rescale/CLC.lean
8b03b85ed58a0cfc454cf8b731f2b8474d70d1f3
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,106
lean
import pseudo_normed_group.CLC import rescale.LC open_locale classical nnreal open opposite ProFiltPseuNormGrpWithTinv open SemiNormedGroup opposite Profinite pseudo_normed_group category_theory breen_deligne open profinitely_filtered_pseudo_normed_group universe variable u variables (r : ℝ≥0) (V : SemiNormedGroup) (r' : ℝ≥0) [fact (0 < r')] variables (c c₁ c₂ c₃ c₄ : ℝ≥0) (m n : ℕ) @[simp] theorem CLCFP_rescale (N : ℝ≥0) (M) [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] : (CLCFP V r' c n).obj (op (of r' (rescale N M))) = (CLCFP V r' (c * N⁻¹) n).obj (op (of r' M)) := rfl namespace breen_deligne namespace universal_map variables (ϕ : universal_map m n) theorem eval_CLCFP_rescale [ϕ.suitable c₂ c₁] (N : ℝ≥0) (M : ProFiltPseuNormGrpWithTinv r') : arrow.mk ((eval_CLCFP V r' c₁ c₂ ϕ).app (op (of r' (rescale N M)))) = arrow.mk ((eval_CLCFP V r' (c₁ * N⁻¹) (c₂ * N⁻¹) ϕ).app (op M)) := by { dsimp only [eval_CLCFP, whisker_right_app], rw eval_LCFP_rescale, cases M, refl } end universal_map end breen_deligne
4b404717c201306093066618fc4c4801b647430b
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/group/units.lean
59c9025c07bb87de76d8103c45162041b2fb0934
[ "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
15,036
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker -/ import algebra.group.basic import logic.nontrivial /-! # Units (i.e., invertible elements) of a multiplicative monoid -/ universe u variable {α : Type u} /-- Units of a monoid, bundled version. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) /-- Units of an add_monoid, bundled version. An element of an add_monoid is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] := (val : α) (neg : α) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive add_units] units section has_elem @[to_additive] lemma unique_has_one {α : Type*} [unique α] [has_one α] : default α = 1 := unique.default_eq 1 end has_elem namespace units variables [monoid α] @[to_additive] instance : has_coe (units α) α := ⟨val⟩ @[to_additive] instance : has_inv (units α) := ⟨λ u, ⟨u.2, u.1, u.4, u.3⟩⟩ /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe (u : units α) : α := u /-- See Note [custom simps projection] -/ @[to_additive /-" See Note [custom simps projection] "-/] def simps.coe_inv (u : units α) : α := ↑(u⁻¹) initialize_simps_projections units (val → coe as_prefix, inv → coe_inv as_prefix) initialize_simps_projections add_units (val → coe as_prefix, neg → coe_neg as_prefix) @[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : units α → α) | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ @[norm_cast, to_additive] theorem eq_iff {a b : units α} : (a : α) = b ↔ a = b := ext.eq_iff @[to_additive] theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b := eq_iff.symm @[to_additive] instance [decidable_eq α] : decidable_eq (units α) := λ a b, decidable_of_iff' _ ext_iff @[simp, to_additive] theorem mk_coe (u : units α) (y h₁ h₂) : mk (u : α) y h₁ h₂ = u := ext rfl /-- Copy a unit, adjusting definition equalities. -/ @[to_additive /-"Copy an `add_unit`, adjusting definitional equalities."-/, simps] def copy (u : units α) (val : α) (hv : val = u) (inv : α) (hi : inv = ↑(u⁻¹)) : units α := { val := val, inv := inv, inv_val := hv.symm ▸ hi.symm ▸ u.inv_val, val_inv := hv.symm ▸ hi.symm ▸ u.val_inv } @[to_additive] lemma copy_eq (u : units α) (val hv inv hi) : u.copy val hv inv hi = u := ext hv /-- Units of a monoid form a group. -/ @[to_additive] instance : group (units α) := { mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, by rw [mul_assoc, ← mul_assoc u₂.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ← mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, mul_one := λ u, ext $ mul_one u, one_mul := λ u, ext $ one_mul u, mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃, inv := has_inv.inv, mul_left_inv := λ u, ext u.inv_val } variables (a b : units α) {c : units α} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : units α) : α) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_eq_one {a : units α} : (a : α) = 1 ↔ a = 1 := by rw [←units.coe_one, eq_iff] @[simp, to_additive] lemma inv_mk (x y : α) (h₁ h₂) : (mk x y h₁ h₂)⁻¹ = mk y x h₂ h₁ := rfl @[simp, to_additive] lemma val_eq_coe : a.val = (↑a : α) := rfl @[simp, to_additive] lemma inv_eq_coe_inv : a.inv = ((a⁻¹ : units α) : α) := rfl @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[to_additive] lemma inv_mul_of_eq {u : units α} {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by { rw [←h, u.inv_mul], } @[to_additive] lemma mul_inv_of_eq {u : units α} {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by { rw [←h, u.mul_inv], } @[simp, to_additive] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[to_additive] instance : inhabited (units α) := ⟨1⟩ @[to_additive] instance {α} [comm_monoid α] : comm_group (units α) := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } @[to_additive] instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩ @[simp, to_additive] theorem mul_right_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : a = b * ↑c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq {a c : α} : a = ↑b⁻¹ * c ↔ ↑b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul {b c : α} : ↑a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul {a c : α} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ lemma inv_eq_of_mul_eq_one {u : units α} {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = ↑u⁻¹ * ↑u * a : by rw [←h, ←mul_assoc] ... = a : by rw [u.inv_mul, one_mul] lemma inv_unique {u₁ u₂ : units α} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ := inv_eq_of_mul_eq_one $ by rw [h, u₂.mul_inv] end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : α) = a := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : units α) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_inv (u : units α) : a /ₚ u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj _ theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : units α) : (x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] theorem divp_eq_iff_mul_eq {x : α} {u : units α} {y : α} : x /ₚ u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ theorem divp_eq_one_iff_eq {a : α} {u : units α} : a /ₚ u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid section comm_monoid variables [comm_monoid α] theorem divp_eq_divp_iff {x y : α} {ux uy : units α} : x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, mul_comm, ← divp_assoc, divp_eq_iff_mul_eq, mul_comm y ux] theorem divp_mul_divp (x y : α) (ux uy : units α) : (x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) := by rw [← divp_divp_eq_divp_mul, divp_assoc, mul_comm x, divp_assoc, mul_comm] end comm_monoid /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ section is_unit variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : units M`, where `units M` is a bundled version of `is_unit`. -/ @[to_additive is_add_unit "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : units M, (u : M) = a @[nontriviality] lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a := ⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩ instance [monoid M] [subsingleton M] : unique (units M) := { default := 1, uniq := λ a, units.coe_eq_one.mp $ subsingleton.elim (a : M) 1 } @[simp, to_additive is_add_unit_add_unit] protected lemma units.is_unit [monoid M] (u : units M) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive is_add_unit_zero] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive is_add_unit_of_add_eq_zero] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit.exists_neg] theorem is_unit.exists_right_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, a * b = 1 := by { rcases h with ⟨⟨a, b, hab, _⟩, rfl⟩, exact ⟨b, hab⟩ } @[to_additive is_add_unit.exists_neg'] theorem is_unit.exists_left_inv [monoid M] {a : M} (h : is_unit a) : ∃ b, b * a = 1 := by { rcases h with ⟨⟨a, b, _, hba⟩, rfl⟩, exact ⟨b, hba⟩ } @[to_additive is_add_unit_iff_exists_neg] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨λ h, h.exists_right_inv, λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive is_add_unit_iff_exists_neg'] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] /-- Multiplication by a `u : units M` doesn't affect `is_unit`. -/ @[simp, to_additive is_add_unit_add_add_units "Addition of a `u : add_units M` doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : units M) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (assume ⟨v, hv⟩, hv ▸ ⟨v * u, (units.coe_mul v u).symm⟩) @[to_additive] lemma is_unit.mul [monoid M] {x y : M} : is_unit x → is_unit y → is_unit (x * y) := by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ } @[to_additive is_add_unit_of_add_is_add_unit_left] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm @[simp] lemma is_unit.mul_iff [comm_monoid M] {x y : M} : is_unit (x * y) ↔ is_unit x ∧ is_unit y := ⟨λ h, ⟨is_unit_of_mul_is_unit_left h, is_unit_of_mul_is_unit_right h⟩, λ h, is_unit.mul h.1 h.2⟩ @[to_additive] theorem is_unit.mul_right_inj [monoid M] {a b c : M} (ha : is_unit a) : a * b = a * c ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_right_inj] @[to_additive] theorem is_unit.mul_left_inj [monoid M] {a b c : M} (ha : is_unit a) : b * a = c * a ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_left_inj] /-- The element of the group of units, corresponding to an element of a monoid which is a unit. -/ noncomputable def is_unit.unit [monoid M] {a : M} (h : is_unit a) : units M := (classical.some h).copy a (classical.some_spec h).symm _ rfl lemma is_unit.unit_spec [monoid M] {a : M} (h : is_unit a) : ↑h.unit = a := rfl lemma is_unit.coe_inv_mul [monoid M] {a : M} (h : is_unit a) : ↑(h.unit)⁻¹ * a = 1 := units.mul_inv _ lemma is_unit.mul_coe_inv [monoid M] {a : M} (h : is_unit a) : a * ↑(h.unit)⁻¹ = 1 := begin convert units.mul_inv _, simp [h.unit_spec] end end is_unit section noncomputable_defs variables {M : Type*} /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ noncomputable def group_of_is_unit [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) : comm_group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } end noncomputable_defs
452ad2fc93b5ab2e9fc88fc499d1756ac4fd75b1
968e2f50b755d3048175f176376eff7139e9df70
/examples/pred_logic/unnamed_653.lean
cdfe508da5900071f6fc26d56a77e55351ad3d74
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
1,326
lean
import tactic.interactive variables {U : Type*} {P : U → Prop} namespace hidden -- BEGIN theorem not_exists : ¬(∃ x, P x) ↔ ∀ x, ¬P x := begin -- By iff intro., it suffices to prove 1. `¬(∃ x, P x) → ∀ x, ¬P x` and 2. `∀ x, ¬P x → ¬(∃ x, P x)` split, { intro h₁, -- Case 1. Assume `h₁ : ¬(∃ x, P x)`. By `→` intro, it suffices to prove `∀ x, ¬P x`. intro u, -- Assume `u : U`. By for all intro., it suffices to show `¬P u`. intro h₂, -- Assume `h₂ : P u`. By negation introduction, it suffices to prove `false`. apply h₁, -- By false introduction on `h₁`, it suffices to prove `∃ x, P x`. use u, -- By `∃` intro on `u`, it suffices to prove `P u`. exact h₂, }, -- This follows by reiteration on `h₂`. { intro h₁, -- Assume `h₁ : ∀ x, ¬P x`. It suffices to prove `¬∃ x, P x`. intro h₂, --- Assume `h₂ : ∃ x, P x`. By negation introduction, it suffices to prove `false`. -- By `∃` elim. on `h₂`, it suffices to prove `false` assuming `u : U` and `hu : P u`. cases h₂ with u hu, have h₃ : ¬P u, from h₁ u, -- By `∀` elim. on `h₁` applied to `u`, we have `h₃ : ¬P u`. exact h₃ hu, }, -- We show the goal by false introduction on `h₃` and `hu`. end -- END end hidden
f27f6230e3338f473267768f467d6e3a97f94d67
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/real/basic.lean
bb5e5168ef7d0dfec42f5452ce9e89a950547c68
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,987
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn The (classical) real numbers ℝ. This is a direct construction from Cauchy sequences. -/ import order.conditionally_complete_lattice import data.real.cau_seq_completion import algebra.archimedean import algebra.star.basic /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure real := of_cauchy :: (cauchy : @cau_seq.completion.Cauchy ℚ _ _ _ abs _) notation `ℝ` := real attribute [pp_using_anonymous_constructor] real namespace real open cau_seq cau_seq.completion variables {x y : ℝ} lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩ ⟨b⟩ := by split; cc lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy := ⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 @[irreducible] private def zero : ℝ := ⟨0⟩ @[irreducible] private def one : ℝ := ⟨1⟩ @[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ instance : has_zero ℝ := ⟨zero⟩ instance : has_one ℝ := ⟨one⟩ instance : has_add ℝ := ⟨add⟩ instance : has_neg ℝ := ⟨neg⟩ instance : has_mul ℝ := ⟨mul⟩ lemma zero_cauchy : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero lemma one_cauchy : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one lemma add_cauchy {a b} : (⟨a⟩ + ⟨b⟩ : ℝ) = ⟨a + b⟩ := show add _ _ = _, by rw add lemma neg_cauchy {a} : (-⟨a⟩ : ℝ) = ⟨-a⟩ := show neg _ = _, by rw neg lemma mul_cauchy {a b} : (⟨a⟩ * ⟨b⟩ : ℝ) = ⟨a * b⟩ := show mul _ _ = _, by rw mul instance : comm_ring ℝ := begin refine_struct { zero := 0, one := 1, mul := (*), add := (+), neg := @has_neg.neg ℝ _, sub := λ a b, a + (-b) }, all_goals { repeat { rintro ⟨_⟩, }, simp [← zero_cauchy, ← one_cauchy, add_cauchy, neg_cauchy, mul_cauchy], apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|> apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip }, end /- Extra instances to short-circuit type class resolution -/ 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 instance : has_sub ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ /-- The real numbers are a *-ring, with the trivial *-structure. -/ instance : star_ring ℝ := star_ring_of_comm /-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this is `cau_seq.completion.of_rat`, not `rat.cast`. -/ def of_rat : ℚ →+* ℝ := by refine_struct { to_fun := of_cauchy ∘ of_rat }; simp [of_rat_one, of_rat_zero, of_rat_mul, of_rat_add, one_cauchy, zero_cauchy, ← mul_cauchy, ← add_cauchy] lemma of_rat_apply (x : ℚ) : of_rat x = of_cauchy (cau_seq.completion.of_rat x) := rfl /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩ theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := ext_cauchy_iff.trans mk_eq @[irreducible] private def lt : ℝ → ℝ → Prop | ⟨x⟩ ⟨y⟩ := quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩ instance : has_lt ℝ := ⟨lt⟩ lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := lt_cauchy lemma mk_zero : mk 0 = 0 := by rw ← zero_cauchy; refl lemma mk_one : mk 1 = 1 := by rw ← one_cauchy; refl lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, add_cauchy] lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, mul_cauchy] lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, neg_cauchy] @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f)) @[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨le⟩ private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by simp [le_def, mk_eq]; refl @[elab_as_eliminator] protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x := begin cases x with x, induction x using quot.induction_on with x, exact h x end theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := begin induction a using real.ind_mk, induction b using real.ind_mk, induction c using real.ind_mk, simp only [mk_lt, ← mk_add], show pos _ ↔ pos _, rw add_sub_add_left_eq_sub end instance : partial_order ℝ := { le := (≤), lt := (<), lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_refl := λ a, a.ind_mk (by intro a; rw mk_le), le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c, by simpa using le_trans, lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b } instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := begin rw [mk_lt] {md := tactic.transparency.semireducible}, exact const_lt end protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert of_rat_lt.2 zero_lt_one; simp protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := begin induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos end instance : ordered_ring ℝ := { add_le_add_left := begin simp only [le_iff_eq_or_lt], rintros a b ⟨rfl, h⟩, { simp }, { exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) } end, zero_le_one := le_of_lt real.zero_lt_one, mul_pos := @real.mul_pos, .. real.comm_ring, .. real.partial_order, .. real.semiring } instance : ordered_semiring ℝ := by apply_instance instance : ordered_add_comm_group ℝ := by apply_instance instance : ordered_cancel_add_comm_monoid ℝ := by apply_instance instance : ordered_add_comm_monoid ℝ := by apply_instance instance : nontrivial ℝ := ⟨⟨0, 1, ne_of_lt real.zero_lt_one⟩⟩ open_locale classical noncomputable instance : linear_order ℝ := { le_total := begin intros a b, induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa using le_total a b, end, decidable_le := by apply_instance, .. real.partial_order } noncomputable instance : linear_ordered_comm_ring ℝ := { .. real.nontrivial, .. real.ordered_ring, .. real.comm_ring, .. real.linear_order } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_ring ℝ := by apply_instance noncomputable instance : linear_ordered_semiring ℝ := by apply_instance instance : domain ℝ := { .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.to_domain } /-- The real numbers are an ordered *-ring, with the trivial *-structure. -/ instance : star_ordered_ring ℝ := { star_mul_self_nonneg := λ r, mul_self_nonneg r, } @[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩ noncomputable instance : has_inv ℝ := ⟨inv'⟩ lemma inv_cauchy {f} : (⟨f⟩ : ℝ)⁻¹ = ⟨f⁻¹⟩ := show inv' _ = _, by rw inv' noncomputable instance : linear_ordered_field ℝ := { inv := has_inv.inv, mul_inv_cancel := begin rintros ⟨a⟩ h, rw mul_comm, simp only [inv_cauchy, mul_cauchy, ← one_cauchy, ← zero_cauchy, ne.def] at *, exact cau_seq.completion.inv_mul_cancel h, end, inv_zero := by simp [← zero_cauchy, inv_cauchy], ..real.linear_ordered_comm_ring, ..real.domain } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance noncomputable instance field : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance : integral_domain ℝ := by apply_instance noncomputable instance : distrib_lattice ℝ := by apply_instance noncomputable instance : lattice ℝ := by apply_instance noncomputable instance : semilattice_inf ℝ := by apply_instance noncomputable instance : semilattice_sup ℝ := by apply_instance noncomputable instance : has_inf ℝ := by apply_instance noncomputable instance : has_sup ℝ := by apply_instance noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := of_rat.eq_rat_cast theorem le_mk_of_forall_le {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := begin intro h, induction x using real.ind_mk with x, apply le_of_not_lt, rw mk_lt, rintro ⟨K, K0, hK⟩, obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)), apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, rw [mk_lt] {md := tactic.transparency.semireducible}, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x := begin cases h with i H, rw [← neg_le_neg_iff, ← mk_neg], exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ end theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, real.ind_mk x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) : ∃ h', real.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) → ∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y | ⟨L, hL⟩ ⟨U, hU⟩ := begin choose f hf using begin refine λ d : ℕ, @int.exists_greatest_of_bdd (λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _, { cases exists_int_gt U with k hk, refine ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (le_trans hy _), simp, exact mul_le_mul_of_nonneg_right (le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) }, { exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ } end, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := lt_of_lt_of_le (sub_one_lt_floor _) (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ }, intros ε ε0, suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) end noncomputable instance : has_Sup ℝ := ⟨λ S, if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0⟩ lemma Sup_def (S : set ℝ) : Sup S = if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0 := rfl theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y := by simp [Sup_def, h₁, h₂]; exact classical.some_spec (exists_sup S h₁ h₂) y theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : y < Sup S ↔ ∃ z ∈ S, y < z := by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y) theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S := (Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub := (Sup_le S h₁ ⟨_, h₂⟩).2 h₂ protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) : is_lub s (Sup s) := ⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs, λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩ noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup {x | -x ∈ S}⟩ lemma Inf_def (S : set ℝ) : Inf S = -Sup {x | -x ∈ S} := rfl theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z := begin refine le_neg.trans ((Sup_le _ _ _).trans _), { cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ }, { cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ }, split; intros H z hz, { exact neg_le_neg_iff.1 (H _ $ by simp [hz]) }, { exact le_neg.2 (H _ hz) } end section -- this proof times out without this local attribute [instance, priority 1000] classical.prop_decidable theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : Inf S < y ↔ ∃ z ∈ S, z < y := by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y) end theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x := (le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S := (le_Inf S h₁ ⟨_, h₂⟩).2 h₂ noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := has_Sup.Sup, Inf := has_Inf.Inf, le_cSup := assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s), show a ≤ Sup s, from le_Sup s ‹bdd_above s› ‹a ∈ s›, cSup_le := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, b ≤ a), show Sup s ≤ a, from Sup_le_ub s ‹s.nonempty› H, cInf_le := assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s), show Inf s ≤ a, from Inf_le s ‹bdd_below s› ‹a ∈ s›, le_cInf := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, a ≤ b), show a ≤ Inf s, from lb_le_Inf s ‹s.nonempty› H, ..real.linear_order, ..real.lattice} theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Sup_univ : Sup (@set.univ ℝ) = 0 := real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _) theorem Inf_empty : Inf (∅ : set ℝ) = 0 := by simp [Inf_def, Sup_empty] theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 := have bdd_above {x | -x ∈ s} → bdd_below s, from assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb $ by simp [hxs]⟩, have ¬ bdd_above {x | -x ∈ s}, from mt this hs, neg_eq_zero.2 $ Sup_of_not_bdd_above $ this theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (Sup_le_ub S lb (ub' _ _)) (sub_lt_self _ (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (le_Sup S ub _) ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ end real
ef15f8ab2bf704fdf37b21608f6f2d64eb758d0d
63abd62053d479eae5abf4951554e1064a4c45b4
/src/computability/tm_computable.lean
1bec3d8af86dbaec76f945c282e9a62d32d2e74c
[ "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
11,303
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 (k = tm.k₀) (tm.K_decidable_eq k tm.k₀) (list (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 (k = tm.k₁) (tm.K_decidable_eq k tm.k₁) (list (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
5a155a2d9e7fba9feabfb05892189528c43d91c7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/ring/prod.lean
bb9030e0ae894d15353c8d2cb2695d57067694c1
[]
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,266
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Chris Hughes, Mario Carneiro, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group.prod import Mathlib.algebra.ring.basic import Mathlib.data.equiv.ring import Mathlib.PostPort universes u_1 u_3 u_5 u_2 u_4 namespace Mathlib /-! # Semiring, ring etc structures on `R × S` In this file we define two-binop (`semiring`, `ring` etc) structures on `R × S`. We also prove trivial `simp` lemmas, and define the following operations on `ring_hom`s: * `fst R S : R × S →+* R`, `snd R S : R × S →+* R`: projections `prod.fst` and `prod.snd` as `ring_hom`s; * `f.prod g : `R →+* S × T`: sends `x` to `(f x, g x)`; * `f.prod_map g : `R × S → R' × S'`: `prod.map f g` as a `ring_hom`, sends `(x, y)` to `(f x, g y)`. -/ namespace prod /-- Product of two semirings is a semiring. -/ protected instance semiring {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] : semiring (R × S) := semiring.mk add_comm_monoid.add sorry add_comm_monoid.zero sorry sorry sorry monoid.mul sorry monoid.one sorry sorry sorry sorry sorry sorry /-- Product of two commutative semirings is a commutative semiring. -/ protected instance comm_semiring {R : Type u_1} {S : Type u_3} [comm_semiring R] [comm_semiring S] : comm_semiring (R × S) := comm_semiring.mk semiring.add sorry semiring.zero sorry sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry sorry sorry sorry /-- Product of two rings is a ring. -/ protected instance ring {R : Type u_1} {S : Type u_3} [ring R] [ring S] : ring (R × S) := ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry semiring.mul sorry semiring.one sorry sorry sorry sorry /-- Product of two commutative rings is a commutative ring. -/ protected instance comm_ring {R : Type u_1} {S : Type u_3} [comm_ring R] [comm_ring S] : comm_ring (R × S) := comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry sorry sorry sorry end prod namespace ring_hom /-- Given semirings `R`, `S`, the natural projection homomorphism from `R × S` to `R`.-/ def fst (R : Type u_1) (S : Type u_3) [semiring R] [semiring S] : R × S →+* R := mk prod.fst sorry sorry sorry sorry /-- Given semirings `R`, `S`, the natural projection homomorphism from `R × S` to `S`.-/ def snd (R : Type u_1) (S : Type u_3) [semiring R] [semiring S] : R × S →+* S := mk prod.snd sorry sorry sorry sorry @[simp] theorem coe_fst {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] : ⇑(fst R S) = prod.fst := rfl @[simp] theorem coe_snd {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] : ⇑(snd R S) = prod.snd := rfl /-- Combine two ring homomorphisms `f : R →+* S`, `g : R →+* T` into `f.prod g : R →+* S × T` given by `(f.prod g) x = (f x, g x)` -/ protected def prod {R : Type u_1} {S : Type u_3} {T : Type u_5} [semiring R] [semiring S] [semiring T] (f : R →+* S) (g : R →+* T) : R →+* S × T := mk (fun (x : R) => (coe_fn f x, coe_fn g x)) sorry sorry sorry sorry @[simp] theorem prod_apply {R : Type u_1} {S : Type u_3} {T : Type u_5} [semiring R] [semiring S] [semiring T] (f : R →+* S) (g : R →+* T) (x : R) : coe_fn (ring_hom.prod f g) x = (coe_fn f x, coe_fn g x) := rfl @[simp] theorem fst_comp_prod {R : Type u_1} {S : Type u_3} {T : Type u_5} [semiring R] [semiring S] [semiring T] (f : R →+* S) (g : R →+* T) : comp (fst S T) (ring_hom.prod f g) = f := ext fun (x : R) => rfl @[simp] theorem snd_comp_prod {R : Type u_1} {S : Type u_3} {T : Type u_5} [semiring R] [semiring S] [semiring T] (f : R →+* S) (g : R →+* T) : comp (snd S T) (ring_hom.prod f g) = g := ext fun (x : R) => rfl theorem prod_unique {R : Type u_1} {S : Type u_3} {T : Type u_5} [semiring R] [semiring S] [semiring T] (f : R →+* S × T) : ring_hom.prod (comp (fst S T) f) (comp (snd S T) f) = f := sorry /-- `prod.map` as a `ring_hom`. -/ def prod_map {R : Type u_1} {R' : Type u_2} {S : Type u_3} {S' : Type u_4} [semiring R] [semiring S] [semiring R'] [semiring S'] (f : R →+* R') (g : S →+* S') : R × S →* R' × S' := ↑(ring_hom.prod (comp f (fst R S)) (comp g (snd R S))) theorem prod_map_def {R : Type u_1} {R' : Type u_2} {S : Type u_3} {S' : Type u_4} [semiring R] [semiring S] [semiring R'] [semiring S'] (f : R →+* R') (g : S →+* S') : prod_map f g = ↑(ring_hom.prod (comp f (fst R S)) (comp g (snd R S))) := rfl @[simp] theorem coe_prod_map {R : Type u_1} {R' : Type u_2} {S : Type u_3} {S' : Type u_4} [semiring R] [semiring S] [semiring R'] [semiring S'] (f : R →+* R') (g : S →+* S') : ⇑(prod_map f g) = prod.map ⇑f ⇑g := rfl theorem prod_comp_prod_map {R : Type u_1} {R' : Type u_2} {S : Type u_3} {S' : Type u_4} {T : Type u_5} [semiring R] [semiring S] [semiring R'] [semiring S'] [semiring T] (f : T →* R) (g : T →* S) (f' : R →* R') (g' : S →* S') : monoid_hom.comp (monoid_hom.prod_map f' g') (monoid_hom.prod f g) = monoid_hom.prod (monoid_hom.comp f' f) (monoid_hom.comp g' g) := rfl end ring_hom namespace ring_equiv /-- Swapping components as an equivalence of (semi)rings. -/ def prod_comm {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] : R × S ≃+* S × R := mk (add_equiv.to_fun add_equiv.prod_comm) (add_equiv.inv_fun add_equiv.prod_comm) sorry sorry sorry sorry @[simp] theorem coe_prod_comm {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] : ⇑prod_comm = prod.swap := rfl @[simp] theorem coe_prod_comm_symm {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] : ⇑(ring_equiv.symm prod_comm) = prod.swap := rfl @[simp] theorem fst_comp_coe_prod_comm {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] : ring_hom.comp (ring_hom.fst S R) ↑prod_comm = ring_hom.snd R S := ring_hom.ext fun (_x : R × S) => rfl @[simp] theorem snd_comp_coe_prod_comm {R : Type u_1} {S : Type u_3} [semiring R] [semiring S] : ring_hom.comp (ring_hom.snd S R) ↑prod_comm = ring_hom.fst R S := ring_hom.ext fun (_x : R × S) => rfl
34ee508c1ec4f32003dc156cd09d028871b79763
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebraic_topology/simplicial_object.lean
b6fc69fe884ccae9891daeb254db73c3f28de00f
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
19,533
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison, Adam Topaz -/ import algebraic_topology.simplex_category import category_theory.arrow import category_theory.limits.functor_category import category_theory.opposites /-! # Simplicial objects in a category. A simplicial object in a category `C` is a `C`-valued presheaf on `simplex_category`. (Similarly a cosimplicial object is functor `simplex_category ⥤ C`.) Use the notation `X _[n]` in the `simplicial` locale to obtain the `n`-th term of a (co)simplicial object `X`, where `n` is a natural number. -/ open opposite open category_theory open category_theory.limits universes v u v' u' namespace category_theory variables (C : Type u) [category.{v} C] /-- The category of simplicial objects valued in a category `C`. This is the category of contravariant functors from `simplex_category` to `C`. -/ @[derive category, nolint has_nonempty_instance] def simplicial_object := simplex_categoryᵒᵖ ⥤ C namespace simplicial_object localized "notation (name := simplicial_object.at) X ` _[`:1000 n `]` := (X : category_theory.simplicial_object hole!).obj (opposite.op (simplex_category.mk n))" in simplicial instance {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (simplicial_object C) := by {dsimp [simplicial_object], apply_instance} instance [has_limits C] : has_limits (simplicial_object C) := ⟨infer_instance⟩ instance {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (simplicial_object C) := by {dsimp [simplicial_object], apply_instance} instance [has_colimits C] : has_colimits (simplicial_object C) := ⟨infer_instance⟩ variables {C} (X : simplicial_object C) /-- Face maps for a simplicial object. -/ def δ {n} (i : fin (n+2)) : X _[n+1] ⟶ X _[n] := X.map (simplex_category.δ i).op /-- Degeneracy maps for a simplicial object. -/ def σ {n} (i : fin (n+1)) : X _[n] ⟶ X _[n+1] := X.map (simplex_category.σ i).op /-- Isomorphisms from identities in ℕ. -/ def eq_to_iso {n m : ℕ} (h : n = m) : X _[n] ≅ X _[m] := X.map_iso (eq_to_iso (by rw h)) @[simp] lemma eq_to_iso_refl {n : ℕ} (h : n = n) : X.eq_to_iso h = iso.refl _ := by { ext, simp [eq_to_iso], } /-- The generic case of the first simplicial identity -/ lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) : X.δ j.succ ≫ X.δ i = X.δ i.cast_succ ≫ X.δ j := by { dsimp [δ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_δ H] } /-- The special case of the first simplicial identity -/ lemma δ_comp_δ_self {n} {i : fin (n+2)} : X.δ i.cast_succ ≫ X.δ i = X.δ i.succ ≫ X.δ i := by { dsimp [δ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_δ_self] } /-- The second simplicial identity -/ lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) : X.σ j.succ ≫ X.δ i.cast_succ = X.δ i ≫ X.σ j := by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_of_le H] } /-- The first part of the third simplicial identity -/ lemma δ_comp_σ_self {n} {i : fin (n+1)} : X.σ i ≫ X.δ i.cast_succ = 𝟙 _ := begin dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_self, op_id, X.map_id], end /-- The second part of the third simplicial identity -/ lemma δ_comp_σ_succ {n} {i : fin (n+1)} : X.σ i ≫ X.δ i.succ = 𝟙 _ := begin dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_succ, op_id, X.map_id], end /-- The fourth simplicial identity -/ lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : X.σ j.cast_succ ≫ X.δ i.succ = X.δ i ≫ X.σ j := by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.δ_comp_σ_of_gt H] } /-- The fifth simplicial identity -/ lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) : X.σ j ≫ X.σ i.cast_succ = X.σ i ≫ X.σ j.succ := by { dsimp [δ, σ], simp only [←X.map_comp, ←op_comp, simplex_category.σ_comp_σ H] } variable (C) /-- Functor composition induces a functor on simplicial objects. -/ @[simps] def whiskering (D : Type*) [category D] : (C ⥤ D) ⥤ simplicial_object C ⥤ simplicial_object D := whiskering_right _ _ _ /-- Truncated simplicial objects. -/ @[derive category, nolint has_nonempty_instance] def truncated (n : ℕ) := (simplex_category.truncated n)ᵒᵖ ⥤ C variable {C} namespace truncated instance {n} {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (simplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_limits C] : has_limits (simplicial_object.truncated C n) := ⟨infer_instance⟩ instance {n} {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (simplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_colimits C] : has_colimits (simplicial_object.truncated C n) := ⟨infer_instance⟩ variable (C) /-- Functor composition induces a functor on truncated simplicial objects. -/ @[simps] def whiskering {n} (D : Type*) [category D] : (C ⥤ D) ⥤ truncated C n ⥤ truncated D n := whiskering_right _ _ _ variable {C} end truncated section skeleton /-- The skeleton functor from simplicial objects to truncated simplicial objects. -/ def sk (n : ℕ) : simplicial_object C ⥤ simplicial_object.truncated C n := (whiskering_left _ _ _).obj simplex_category.truncated.inclusion.op end skeleton variable (C) /-- The constant simplicial object is the constant functor. -/ abbreviation const : C ⥤ simplicial_object C := category_theory.functor.const _ /-- The category of augmented simplicial objects, defined as a comma category. -/ @[derive category, nolint has_nonempty_instance] def augmented := comma (𝟭 (simplicial_object C)) (const C) variable {C} namespace augmented /-- Drop the augmentation. -/ @[simps] def drop : augmented C ⥤ simplicial_object C := comma.fst _ _ /-- The point of the augmentation. -/ @[simps] def point : augmented C ⥤ C := comma.snd _ _ /-- The functor from augmented objects to arrows. -/ @[simps] def to_arrow : augmented C ⥤ arrow C := { obj := λ X, { left := (drop.obj X) _[0], right := (point.obj X), hom := X.hom.app _ }, map := λ X Y η, { left := (drop.map η).app _, right := (point.map η), w' := begin dsimp, rw ← nat_trans.comp_app, erw η.w, refl, end } } variable (C) /-- Functor composition induces a functor on augmented simplicial objects. -/ @[simp] def whiskering_obj (D : Type*) [category D] (F : C ⥤ D) : augmented C ⥤ augmented D := { obj := λ X, { left := ((whiskering _ _).obj F).obj (drop.obj X), right := F.obj (point.obj X), hom := whisker_right X.hom F ≫ (functor.const_comp _ _ _).hom }, map := λ X Y η, { left := whisker_right η.left _, right := F.map η.right, w' := begin ext, dsimp, rw [category.comp_id, category.comp_id, ← F.map_comp, ← F.map_comp, ← nat_trans.comp_app], erw η.w, refl, end } } /-- Functor composition induces a functor on augmented simplicial objects. -/ @[simps] def whiskering (D : Type u') [category.{v'} D] : (C ⥤ D) ⥤ augmented C ⥤ augmented D := { obj := whiskering_obj _ _, map := λ X Y η, { app := λ A, { left := whisker_left _ η, right := η.app _, w' := begin ext n, dsimp, rw [category.comp_id, category.comp_id, η.naturality], end }, }, } variable {C} end augmented open_locale simplicial /-- Augment a simplicial object with an object. -/ @[simps] def augment (X : simplicial_object C) (X₀ : C) (f : X _[0] ⟶ X₀) (w : ∀ (i : simplex_category) (g₁ g₂ : [0] ⟶ i), X.map g₁.op ≫ f = X.map g₂.op ≫ f) : simplicial_object.augmented C := { left := X, right := X₀, hom := { app := λ i, X.map (simplex_category.const i.unop 0).op ≫ f, naturality' := begin intros i j g, dsimp, rw ← g.op_unop, simpa only [← X.map_comp, ← category.assoc, category.comp_id, ← op_comp] using w _ _ _, end } } @[simp] lemma augment_hom_zero (X : simplicial_object C) (X₀ : C) (f : X _[0] ⟶ X₀) (w) : (X.augment X₀ f w).hom.app (op [0]) = f := by { dsimp, rw [simplex_category.hom_zero_zero ([0].const 0), op_id, X.map_id, category.id_comp] } end simplicial_object /-- Cosimplicial objects. -/ @[derive category, nolint has_nonempty_instance] def cosimplicial_object := simplex_category ⥤ C namespace cosimplicial_object localized "notation (name := cosimplicial_object.at) X ` _[`:1000 n `]` := (X : category_theory.cosimplicial_object hole!).obj (simplex_category.mk n)" in simplicial instance {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (cosimplicial_object C) := by {dsimp [cosimplicial_object], apply_instance} instance [has_limits C] : has_limits (cosimplicial_object C) := ⟨infer_instance⟩ instance {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (cosimplicial_object C) := by {dsimp [cosimplicial_object], apply_instance} instance [has_colimits C] : has_colimits (cosimplicial_object C) := ⟨infer_instance⟩ variables {C} (X : cosimplicial_object C) /-- Coface maps for a cosimplicial object. -/ def δ {n} (i : fin (n+2)) : X _[n] ⟶ X _[n+1] := X.map (simplex_category.δ i) /-- Codegeneracy maps for a cosimplicial object. -/ def σ {n} (i : fin (n+1)) : X _[n+1] ⟶ X _[n] := X.map (simplex_category.σ i) /-- Isomorphisms from identities in ℕ. -/ def eq_to_iso {n m : ℕ} (h : n = m) : X _[n] ≅ X _[m] := X.map_iso (eq_to_iso (by rw h)) @[simp] lemma eq_to_iso_refl {n : ℕ} (h : n = n) : X.eq_to_iso h = iso.refl _ := by { ext, simp [eq_to_iso], } /-- The generic case of the first cosimplicial identity -/ lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) : X.δ i ≫ X.δ j.succ = X.δ j ≫ X.δ i.cast_succ := by { dsimp [δ], simp only [←X.map_comp, simplex_category.δ_comp_δ H], } /-- The special case of the first cosimplicial identity -/ lemma δ_comp_δ_self {n} {i : fin (n+2)} : X.δ i ≫ X.δ i.cast_succ = X.δ i ≫ X.δ i.succ := by { dsimp [δ], simp only [←X.map_comp, simplex_category.δ_comp_δ_self] } /-- The second cosimplicial identity -/ lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) : X.δ i.cast_succ ≫ X.σ j.succ = X.σ j ≫ X.δ i := by { dsimp [δ, σ], simp only [←X.map_comp, simplex_category.δ_comp_σ_of_le H] } /-- The first part of the third cosimplicial identity -/ lemma δ_comp_σ_self {n} {i : fin (n+1)} : X.δ i.cast_succ ≫ X.σ i = 𝟙 _ := begin dsimp [δ, σ], simp only [←X.map_comp, simplex_category.δ_comp_σ_self, X.map_id], end /-- The second part of the third cosimplicial identity -/ lemma δ_comp_σ_succ {n} {i : fin (n+1)} : X.δ i.succ ≫ X.σ i = 𝟙 _ := begin dsimp [δ, σ], simp only [←X.map_comp, simplex_category.δ_comp_σ_succ, X.map_id], end /-- The fourth cosimplicial identity -/ lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : X.δ i.succ ≫ X.σ j.cast_succ = X.σ j ≫ X.δ i := by { dsimp [δ, σ], simp only [←X.map_comp, simplex_category.δ_comp_σ_of_gt H] } /-- The fifth cosimplicial identity -/ lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) : X.σ i.cast_succ ≫ X.σ j = X.σ j.succ ≫ X.σ i := by { dsimp [δ, σ], simp only [←X.map_comp, simplex_category.σ_comp_σ H] } variable (C) /-- Functor composition induces a functor on cosimplicial objects. -/ @[simps] def whiskering (D : Type*) [category D] : (C ⥤ D) ⥤ cosimplicial_object C ⥤ cosimplicial_object D := whiskering_right _ _ _ /-- Truncated cosimplicial objects. -/ @[derive category, nolint has_nonempty_instance] def truncated (n : ℕ) := simplex_category.truncated n ⥤ C variable {C} namespace truncated instance {n} {J : Type v} [small_category J] [has_limits_of_shape J C] : has_limits_of_shape J (cosimplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_limits C] : has_limits (cosimplicial_object.truncated C n) := ⟨infer_instance⟩ instance {n} {J : Type v} [small_category J] [has_colimits_of_shape J C] : has_colimits_of_shape J (cosimplicial_object.truncated C n) := by {dsimp [truncated], apply_instance} instance {n} [has_colimits C] : has_colimits (cosimplicial_object.truncated C n) := ⟨infer_instance⟩ variable (C) /-- Functor composition induces a functor on truncated cosimplicial objects. -/ @[simps] def whiskering {n} (D : Type*) [category D] : (C ⥤ D) ⥤ truncated C n ⥤ truncated D n := whiskering_right _ _ _ variable {C} end truncated section skeleton /-- The skeleton functor from cosimplicial objects to truncated cosimplicial objects. -/ def sk (n : ℕ) : cosimplicial_object C ⥤ cosimplicial_object.truncated C n := (whiskering_left _ _ _).obj simplex_category.truncated.inclusion end skeleton variable (C) /-- The constant cosimplicial object. -/ abbreviation const : C ⥤ cosimplicial_object C := category_theory.functor.const _ /-- Augmented cosimplicial objects. -/ @[derive category, nolint has_nonempty_instance] def augmented := comma (const C) (𝟭 (cosimplicial_object C)) variable {C} namespace augmented /-- Drop the augmentation. -/ @[simps] def drop : augmented C ⥤ cosimplicial_object C := comma.snd _ _ /-- The point of the augmentation. -/ @[simps] def point : augmented C ⥤ C := comma.fst _ _ /-- The functor from augmented objects to arrows. -/ @[simps] def to_arrow : augmented C ⥤ arrow C := { obj := λ X, { left := (point.obj X), right := (drop.obj X) _[0], hom := X.hom.app _ }, map := λ X Y η, { left := (point.map η), right := (drop.map η).app _, w' := begin dsimp, rw ← nat_trans.comp_app, erw ← η.w, refl, end } } variable (C) /-- Functor composition induces a functor on augmented cosimplicial objects. -/ @[simp] def whiskering_obj (D : Type*) [category D] (F : C ⥤ D) : augmented C ⥤ augmented D := { obj := λ X, { left := F.obj (point.obj X), right := ((whiskering _ _).obj F).obj (drop.obj X), hom := (functor.const_comp _ _ _).inv ≫ whisker_right X.hom F }, map := λ X Y η, { left := F.map η.left, right := whisker_right η.right _, w' := begin ext, dsimp, rw [category.id_comp, category.id_comp, ← F.map_comp, ← F.map_comp, ← nat_trans.comp_app], erw ← η.w, refl, end } } /-- Functor composition induces a functor on augmented cosimplicial objects. -/ @[simps] def whiskering (D : Type u') [category.{v'} D] : (C ⥤ D) ⥤ augmented C ⥤ augmented D := { obj := whiskering_obj _ _, map := λ X Y η, { app := λ A, { left := η.app _, right := whisker_left _ η, w' := begin ext n, dsimp, rw [category.id_comp, category.id_comp, η.naturality], end }, }, } variable {C} end augmented open_locale simplicial /-- Augment a cosimplicial object with an object. -/ @[simps] def augment (X : cosimplicial_object C) (X₀ : C) (f : X₀ ⟶ X.obj [0]) (w : ∀ (i : simplex_category) (g₁ g₂ : [0] ⟶ i), f ≫ X.map g₁ = f ≫ X.map g₂) : cosimplicial_object.augmented C := { left := X₀, right := X, hom := { app := λ i, f ≫ X.map (simplex_category.const i 0), naturality' := begin intros i j g, dsimp, simpa [← X.map_comp] using w _ _ _, end } } @[simp] lemma augment_hom_zero (X : cosimplicial_object C) (X₀ : C) (f : X₀ ⟶ X.obj [0]) (w) : (X.augment X₀ f w).hom.app [0] = f := by { dsimp, rw [simplex_category.hom_zero_zero ([0].const 0), X.map_id, category.comp_id] } end cosimplicial_object /-- The anti-equivalence between simplicial objects and cosimplicial objects. -/ @[simps] def simplicial_cosimplicial_equiv : (simplicial_object C)ᵒᵖ ≌ (cosimplicial_object Cᵒᵖ) := functor.left_op_right_op_equiv _ _ /-- The anti-equivalence between cosimplicial objects and simplicial objects. -/ @[simps] def cosimplicial_simplicial_equiv : (cosimplicial_object C)ᵒᵖ ≌ (simplicial_object Cᵒᵖ) := functor.op_unop_equiv _ _ variable {C} /-- Construct an augmented cosimplicial object in the opposite category from an augmented simplicial object. -/ @[simps] def simplicial_object.augmented.right_op (X : simplicial_object.augmented C) : cosimplicial_object.augmented Cᵒᵖ := { left := opposite.op X.right, right := X.left.right_op, hom := X.hom.right_op } /-- Construct an augmented simplicial object from an augmented cosimplicial object in the opposite category. -/ @[simps] def cosimplicial_object.augmented.left_op (X : cosimplicial_object.augmented Cᵒᵖ) : simplicial_object.augmented C := { left := X.right.left_op, right := X.left.unop, hom := X.hom.left_op } /-- Converting an augmented simplicial object to an augmented cosimplicial object and back is isomorphic to the given object. -/ @[simps] def simplicial_object.augmented.right_op_left_op_iso (X : simplicial_object.augmented C) : X.right_op.left_op ≅ X := comma.iso_mk X.left.right_op_left_op_iso (eq_to_iso $ by simp) (by tidy) /-- Converting an augmented cosimplicial object to an augmented simplicial object and back is isomorphic to the given object. -/ @[simps] def cosimplicial_object.augmented.left_op_right_op_iso (X : cosimplicial_object.augmented Cᵒᵖ) : X.left_op.right_op ≅ X := comma.iso_mk (eq_to_iso $ by simp) X.right.left_op_right_op_iso (by tidy) variable (C) /-- A functorial version of `simplicial_object.augmented.right_op`. -/ @[simps] def simplicial_to_cosimplicial_augmented : (simplicial_object.augmented C)ᵒᵖ ⥤ cosimplicial_object.augmented Cᵒᵖ := { obj := λ X, X.unop.right_op, map := λ X Y f, { left := f.unop.right.op, right := f.unop.left.right_op, w' := begin ext x, dsimp, simp_rw ← op_comp, congr' 1, exact (congr_app f.unop.w (op x)).symm, end } } /-- A functorial version of `cosimplicial_object.augmented.left_op`. -/ @[simps] def cosimplicial_to_simplicial_augmented : cosimplicial_object.augmented Cᵒᵖ ⥤ (simplicial_object.augmented C)ᵒᵖ := { obj := λ X, opposite.op X.left_op, map := λ X Y f, quiver.hom.op $ { left := f.right.left_op, right := f.left.unop, w' := begin ext x, dsimp, simp_rw ← unop_comp, congr' 1, exact (congr_app f.w x.unop).symm, end} } /-- The contravariant categorical equivalence between augmented simplicial objects and augmented cosimplicial objects in the opposite category. -/ @[simps] def simplicial_cosimplicial_augmented_equiv : (simplicial_object.augmented C)ᵒᵖ ≌ cosimplicial_object.augmented Cᵒᵖ := { functor := simplicial_to_cosimplicial_augmented _, inverse := cosimplicial_to_simplicial_augmented _, unit_iso := nat_iso.of_components (λ X, X.unop.right_op_left_op_iso.op) begin intros X Y f, dsimp, rw (show f = f.unop.op, by simp), simp_rw ← op_comp, congr' 1, tidy, end, counit_iso := nat_iso.of_components (λ X, X.left_op_right_op_iso) (by tidy) } end category_theory
5d9d25bb5e496cc47f2503f4cf8bc333b15751c4
bf532e3e865883a676110e756f800e0ddeb465be
/data/multiset.lean
07aceb23bccd7ca3eaa4d5513bd225bc79bb1687
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
91,006
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Multisets. -/ import logic.function data.list.basic data.list.perm data.list.sort order.boolean_algebra algebra.order_functions data.quot algebra.group_power algebra.ordered_group open list subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} local infix ` • `:73 := add_monoid.smul instance list.perm.setoid (α : Type*) : setoid (list α) := setoid.mk perm ⟨perm.refl, @perm.symm _, @perm.trans _⟩ /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.perm.setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe (l₁ l₂ : list α) : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /- empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl /- cons -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound ((perm_cons a).2 p)) notation a :: b := cons a b instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a::s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a::l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a::s = b::s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) {s t : multiset α} : a::s = a::t ↔ s = t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp [perm_cons] @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) (s) : p s := quot.induction_on s $ λ l, by induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, list.rec_heq_of_perm h (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a::m)) (C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)} {C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s := mem_cons.2 (or.inl rfl) theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_of_forall_not_mem H; refl theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end end mem /- subset -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ end subset /- multiset order -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := λ s, quot.induction_on s $ λ l, subperm.refl _, le_trans := λ s t u, quotient.induction_on₃ s t u $ @subperm.trans _, le_antisymm := λ s t, quotient.induction_on₂ s t $ λ l₁ l₂ h₁ h₂, quot.sound (subperm.antisymm h₁ h₂) } theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨subperm_of_sublist (sublist_cons _ _), λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s := le_of_lt $ lt_cons_self _ _ theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t := (cons_le_cons_iff a).2 theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $ (sublist_or_mem_of_sublist s).resolve_right m₁) end /- cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card (s : multiset α) : ℕ := quot.lift_on s length $ λ l₁ l₂, perm_length @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl @[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card ({a} : multiset α) = 1 := calc card ({a} : multiset α) = card (0 : multiset α) + 1 : multiset.card_cons a 0 ... = 1 : by simp theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem @[elab_as_eliminator] lemma strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /- singleton -/ @[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _ theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _ @[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ /- add -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl protected theorem add_comm (s t : multiset α) : s + t = t + s := quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm protected theorem zero_add (s : multiset α) : 0 + s = s := quot.induction_on s $ λ l, rfl theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _ protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u := le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h)) ((multiset.add_le_add_left _).1 (le_of_eq h.symm)) instance : ordered_cancel_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := multiset.add_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := multiset.zero_add, add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add], add_left_cancel := multiset.add_left_cancel, add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $ by simpa [multiset.add_comm] using h, add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h, le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1, ..@multiset.partial_order α } @[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) := by rw [add_comm, cons_add, add_comm] theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s @[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t := quotient.induction_on₂ s t length_append @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩, λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩ instance : canonically_ordered_monoid (multiset α) := { lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _, le_iff_exists_add := @le_iff_exists_add _, ..multiset.ordered_cancel_comm_monoid } /- repeat -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩ /- range -/ /-- `range n` is the multiset lifted from the list `range n`, that is, the set `{0, 1, ..., n-1}`. -/ def range (n : ℕ) : multiset ℕ := range n @[simp] theorem range_zero (n : ℕ) : range 0 = 0 := rfl @[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n := by rw [range, range_concat, ← coe_add, add_comm]; refl @[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _ theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self /- erase -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (erase_perm_erase a p)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l) @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h) theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /- map -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (perm_map f p)) @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s := quot.induction_on s $ λ l, rfl @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ @[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_inj H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ map_map _ _ _ @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ @[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s := quot.induction_on s $ λ l H, congr_arg coe $ map_congr H lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr hf] end theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ /- fold -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, foldl_eq_of_perm H p b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, foldr_eq_of_perm H p b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm /-- Product of a multiset given a commutative monoid structure on `α`. `prod {a, b, c} = a * b * c` -/ def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 attribute [to_additive multiset.sum._proof_1] prod._proof_1 attribute [to_additive multiset.sum] prod @[to_additive multiset.sum_eq_foldr] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive multiset.sum_eq_foldl] theorem prod_eq_foldl [comm_monoid α] (s : multiset α) : prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s := (foldr_swap _ _ _ _).trans (by simp [mul_comm]) @[simp, to_additive multiset.coe_sum] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive multiset.sum_zero] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive multiset.sum_cons] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[simp, to_additive multiset.sum_add] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp @[simp, to_additive multiset.sum_repeat] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = monoid.pow a n := by simp [repeat, list.prod_repeat] @[simp, to_additive multiset.sum_map_add] lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} : prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc) @[to_additive multiset.sum_map_sum_map] lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} : prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) := multiset.induction_on m (by simp) (assume a m ih, by simp [ih]) /- join -/ /-- `join S`, where `S` is a multiset of multisets, is the lift of the list join operation, that is, the union of all the sets. join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/ def join : multiset (multiset α) → multiset α := sum theorem coe_join : ∀ L : list (list α), join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join | [] := rfl | (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L) @[simp] theorem join_zero : @join α 0 = 0 := rfl @[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S := sum_cons _ _ @[simp] theorem join_add (S T) : @join α (S + T) = join S + join T := sum_add _ _ @[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s := multiset.induction_on S (by simp) $ by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt} @[simp] theorem card_join (S) : card (@join α S) = sum (map card S) := multiset.induction_on S (by simp) (by simp) /- bind -/ /-- `bind s f` is the monad bind operation, defined as `join (map f s)`. It is the union of `f a` as `a` ranges over `s`. -/ def bind (s : multiset α) (f : α → multiset β) : multiset β := join (map f s) @[simp] theorem coe_bind (l : list α) (f : α → list β) : @bind α β l (λ a, f a) = l.bind f := by rw [list.bind, ← coe_join, list.map_map]; refl @[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl @[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f := by simp [bind] @[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f := by simp [bind] @[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a := by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm]; rw exists_swap; simp [and_assoc] @[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) := by simp [bind] lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g := by simp [bind] {contextual := tt} lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' := begin subst h, simp at hf, simp [bind_congr hf] end lemma map_bind [decidable_eq γ] (m : multiset α) (n : α → multiset β) (f : β → γ) : map f (bind m n) = bind m (λa, map f (n a)) := multiset.induction_on m (by simp) (by simp {contextual := tt}) /- product -/ /-- The multiplicity of `(a, b)` in `product s t` is the product of the multiplicity of `a` in `s` and `b` in `t`. -/ def product (s : multiset α) (t : multiset β) : multiset (α × β) := s.bind $ λ a, t.map $ prod.mk a @[simp] theorem coe_product (l₁ : list α) (l₂ : list β) : @product α β l₁ l₂ = l₁.product l₂ := by rw [product, list.product, ← coe_bind]; simp @[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl @[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) : product (a :: s) t = map (prod.mk a) t + product s t := by simp [product] @[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl @[simp] theorem add_product (s t : multiset α) (u : multiset β) : product (s + t) u = product s u + product t u := by simp [product] @[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β, product s (t + u) = product s t + product s u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_product, IH]; simp @[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t | (a, b) := by simp [product, and.left_comm] @[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t := by simp [product, (∘), mul_comm] /- sigma -/ section variable {σ : α → Type*} /-- `sigma s t` is the dependent version of `product`. It is the sum of `(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/ protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) := s.bind $ λ a, (t a).map $ sigma.mk a @[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : @multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ := by rw [multiset.sigma, list.sigma, ← coe_bind]; simp @[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl @[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) : (a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t := by simp [multiset.sigma] @[simp] theorem sigma_singleton (a : α) (b : α → β) : (a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl @[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) : (s + t).sigma u = s.sigma u + t.sigma u := by simp [multiset.sigma] @[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a), s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u := multiset.induction_on s (λ t u, rfl) $ λ a s IH t u, by rw [cons_sigma, IH]; simp @[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a}, p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1 | ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm] @[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) : card (s.sigma t) = sum (map (λ a, card (t a)) s) := by simp [multiset.sigma, (∘)] end /- map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ perm_pmap f pp @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_multiset variables {m : multiset α} protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] : decidable (∀a∈m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp) instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] : decidable (∀a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈m, β a) := assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) end decidable_pi_multiset /- subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a`. -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _ @[simp] theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t := begin revert t, refine multiset.induction_on s (by simp) (λ a s IH t h, _), have := cons_erase (mem_of_le h (mem_cons_self _ _)), rw [cons_add, sub_cons, IH, this], exact (cons_le_cons_iff a).1 (this.symm ▸ h) end theorem sub_add' : s - (t + u) = s - t - u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _ theorem sub_add_cancel (h : t ≤ s) : s - t + t = s := by rw [add_comm, add_sub_of_le h] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t := multiset.induction_on s (by simp) (λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH]) theorem add_sub_cancel (s t : multiset α) : s + t - t = s := by rw [add_comm, add_sub_cancel_left] theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u := by revert s t h; exact multiset.induction_on u (by simp {contextual := tt}) (λ a u IH s t h, by simp [IH, erase_le_erase a h]) theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s := le_induction_on h $ λ l₁ l₂ h, begin induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u, { refl }, { rw [← cons_coe, sub_cons], exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) }, { rw [← cons_coe, sub_cons, ← cons_coe, sub_cons], exact IH _ } end theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) theorem le_sub_add (s t : multiset α) : s ≤ s - t + t := sub_le_iff_le_add.1 (le_refl _) theorem sub_le_self (s t : multiset α) : s - t ≤ s := sub_le_iff_le_add.2 (le_add_right _ _) @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm /- union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _ theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (sub_le_sub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ /- inter -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a :: s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ bag_inter_sublist_left _ _ theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff instance : semilattice_inf_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t, by rw [add_comm t, sub_add', add_sub_cancel] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) := by simpa using add_union_distrib (a::0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)] end /- filter -/ section variables {p : α → Prop} [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ perm_filter p h) @[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p] (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _ @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩ @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter $ inter_le_left _ _) (filter_le_filter $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _) (filter_le _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ /- filter_map -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $perm_filter_map f h) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a :: s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a :: s) = b :: filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_map_sublist_filter_map _ h /- powerset -/ def powerset_aux (l : list α) : list (multiset α) := 0 :: sublists_aux l (λ x y, x :: y) theorem powerset_aux_eq_map_coe {l : list α} : powerset_aux l = (sublists l).map coe := by simp [powerset_aux, sublists]; rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) = sublists_aux l (λ x, list.cons ↑x), from sublists_aux₁_eq_sublists_aux _ _, sublists_aux_cons_eq_sublists_aux₁, ← bind_ret_eq_map, sublists_aux₁_bind]; refl def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe theorem powerset_aux_perm_powerset_aux' {l : list α} : powerset_aux l ~ powerset_aux' l := by rw powerset_aux_eq_map_coe; exact perm_map _ (sublists_perm_sublists' _) @[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl @[simp] theorem powerset_aux'_cons (a : α) (l : list α) : powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) := by simp [powerset_aux']; refl theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux' l₁ ~ powerset_aux' l₂ := begin induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp}, { simp, exact perm_app IH (perm_map _ IH) }, { simp, apply perm_app_right, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_app_left _ perm_app_comm }, { exact IH₁.trans IH₂ } end theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_aux l₁ ~ powerset_aux l₂ := powerset_aux_perm_powerset_aux'.trans $ (powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm def powerset (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_aux l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_aux_perm h)) theorem powerset_coe (l : list α) : @powerset α l = ((sublists l).map coe : list (multiset α)) := congr_arg coe powerset_aux_eq_map_coe @[simp] theorem powerset_coe' (l : list α) : @powerset α l = ((sublists' l).map coe : list (multiset α)) := quot.sound powerset_aux_perm_powerset_aux' @[simp] theorem mem_powerset {s t : multiset α} : s ∈ powerset t ↔ s ≤ t := quotient.induction_on₂ s t $ by simp [subperm, and.comm] theorem map_single_le_powerset (s : multiset α) : s.map (λ a, a::0) ≤ powerset s := quotient.induction_on s $ λ l, begin simp [powerset_coe], show l.map (coe ∘ list.ret) <+~ (sublists l).map coe, rw ← list.map_map, exact subperm_of_sublist (map_sublist_map _ (map_ret_sublist_sublists _)) end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp /- countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 := quot.induction_on s countp_cons_of_pos @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s := quot.induction_on s countp_cons_of_neg theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, countp_eq_length_filter _ @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := by simp [countp_eq_card_filter, card_pos_iff_exists_mem] @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h) end /- count -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s := countp_cons_of_neg _ h theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) := count_le_of_le _ (le_cons_self _ _) theorem count_singleton (a : α) : count a (a::0) = 1 := by simp @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add @[simp] theorem count_smul (a : α) (s n) : count a (s • n) = count a s * n := by induction n; simp [*, smul_succ', mul_succ] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] @[simp] theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero @[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a::erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, sub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, sub_add_min], end lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} : count a (bind m f) = sum (m.map $ λb, count a $ f b) := multiset.induction_on m (by simp) (by simp) theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count lemma bind_bind [decidable_eq γ] (m : multiset α) (n : multiset β) {f : α → β → multiset γ} : (bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) := by simp [multiset.ext, count_bind, multiset.sum_map_sum_map m n] theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp [max_min_distrib_left], ..multiset.lattice.lattice } instance : semilattice_sup_bot (multiset α) := { bot := 0, bot_le := zero_le, ..multiset.lattice.lattice } end /- disjoint -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ @[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := disjoint_comm.trans $ by simp [disjoint_append_left] @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ (a::0) s t).trans $ by simp @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp [disjoint_cons_left] theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] /- nodup -/ /-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of any element is at most 1. -/ def nodup (s : multiset α) : Prop := quot.lift_on s nodup (λ s t p, propext $ perm_nodup p) @[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl @[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l := ⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩ @[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil _ @[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s := quot.induction_on s $ λ l, nodup_cons theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s := (nodup_cons.1 h).1 theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s := le_induction_on h $ λ l₁ l₂, nodup_of_sublist theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s := quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a, not_congr (@repeat_le_coe _ a 2 _).symm theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 := quot.induction_on s $ λ l, nodup_iff_count_le_one @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α} (d : nodup s) (h : a ∈ s) : count a s = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t := quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t := (nodup_add.1 d).2.2 theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t := by simp [nodup_add, d₁, d₂] theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s := quot.induction_on s $ λ l, nodup_of_nodup_map f theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) → nodup s → nodup (map f s) := quot.induction_on s $ λ l, nodup_map_on theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) := nodup_map_on (λ x _ y _ h, hf h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) := quot.induction_on s $ λ l, nodup_filter p @[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s := quot.induction_on s $ λ l, nodup_attach theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) := quot.induction_on s (λ l H, nodup_pmap hf) H instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) := quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s := quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_le (erase_le _ _) theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) : a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l := by rw nodup_erase_eq_filter b d; simp [and_comm] theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a := by rw mem_erase_iff_of_nodup h; simp theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂] theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} : nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) := quot.induction_on s $ λ l₁, let l₂ (a) : list (σ a) := classical.some (quotient.exists_rep (t a)) in have t = λ a, l₂ a, from eq.symm $ funext $ λ a, classical.some_spec (quotient.exists_rep (t a)), by rw [this]; simpa using nodup_sigma theorem nodup_filter_map (f : α → option β) {s : multiset α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup s → nodup (filter_map f s) := quot.induction_on s $ λ l, nodup_filter_map H theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _ theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) := nodup_of_le $ inter_le_left _ _ theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) := nodup_of_le $ inter_le_right _ _ @[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t := ⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩, λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩ @[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s := ⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h), quotient.induction_on s $ λ l h, by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact λ x sx y sy e, (perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1 (quotient.exact e)⟩ theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂ theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) := quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩ theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n := (le_iff_subset (nodup_range _)).trans range_subset theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) : a ∈ s - t ↔ a ∈ s ∧ a ∉ t := ⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h', by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le]; exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩, λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩ section variable [decidable_eq α] /- erase_dup -/ /-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/ def erase_dup (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.erase_dup : multiset α)) (λ s t p, quot.sound (perm_erase_dup_of_perm p)) @[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl @[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl @[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s := quot.induction_on s $ λ l, mem_erase_dup @[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s → erase_dup (a::s) = erase_dup s := quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m @[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s → erase_dup (a::s) = a :: erase_dup s := quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s := quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _ theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s := subset_of_le $ erase_dup_le _ theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s := λ a, mem_erase_dup.2 @[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t := ⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩ @[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t := ⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩ @[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) := quot.induction_on s nodup_erase_dup theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s := ⟨λ e, e ▸ nodup_erase_dup s, quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩ theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s := ⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩, λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩ theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t := by simp [nodup_ext] theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) : erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext] /- finset insert -/ /-- `ndinsert a s` is the lift of the list `insert` operation. This operation does not respect multiplicities, unlike `cons`, but it is suitable as an insert operation on `finset`. -/ def ndinsert (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (l.insert a : multiset α)) (λ s t p, quot.sound (perm_insert a p)) @[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl @[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl @[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h @[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s := quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h @[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, mem_insert_iff @[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s := quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _ @[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s := mem_ndinsert.2 (or.inl rfl) @[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s := mem_ndinsert.2 (or.inr h) @[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) : card (ndinsert a s) = card s := by simp [h] @[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) : card (ndinsert a s) = card s + 1 := by simp [h] theorem erase_dup_cons {a : α} {s : multiset α} : erase_dup (a::s) = ndinsert a (erase_dup s) := by by_cases a ∈ s; simp [h] theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) := quot.induction_on s $ λ l, nodup_insert theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t := ⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩, λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff, ← le_cons_of_not_mem h, cons_erase m]; exact l⟩ @[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} : disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t := iff.trans (by simp [disjoint]) disjoint_cons_left @[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} : disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t := disjoint_comm.trans $ by simp /- finset union -/ /-- `ndunion s t` is the lift of the list `union` operation. This operation does not respect multiplicities, unlike `s ∪ t`, but it is suitable as a union operation on `finset`. (`s ∪ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndunion (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_union p₁ p₂ @[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl @[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s := quot.induction_on s $ λ l, rfl @[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, rfl @[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _ theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _ theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u := multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt}) theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t := λ a h, mem_ndunion.2 $ or.inl h theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t := (le_iff_subset d).2 $ subset_ndunion_left _ _ theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t := ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩ theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) := quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _ @[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t := le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _) theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _ /- finset inter -/ /-- `ndinter s t` is the lift of the list `∩` operation. This operation does not respect multiplicities, unlike `s ∩ t`, but it is suitable as an intersection operation on `finset`. (`s ∩ t` would also work as a union operation on finset, but this is more efficient.) -/ def ndinter (s t : multiset α) : multiset α := filter (∈ t) s @[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl @[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl @[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) : ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h] @[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) : ndinter (a::s) t = ndinter s t := by simp [ndinter, h] @[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t := mem_filter theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) := nodup_filter _ theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u := by simp [ndinter, le_filter, subset_iff] theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s := (le_ndinter.1 (le_refl _)).1 theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t := (le_ndinter.1 (le_refl _)).2 theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t := (le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _) theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t := le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩ @[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t := le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _) theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] end /- fold -/ section fold variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op] local notation a * b := op a b include hc ha /-- `fold op b s` folds a commutative associative operation `op` over the multiset `s`. -/ def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc) theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl @[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b := (coe_foldr_swap op _ b l).trans $ by simp [hc.comm] theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s := quot.induction_on s $ λ l, coe_fold_l _ _ _ @[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl @[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α), (a :: s).fold op b = a * s.fold op b := foldr_cons _ _ theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a := by simp [hc.comm] theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) := by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl] theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) := by rw [fold_cons'_right, hc.comm] theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ := multiset.induction_on s₂ (by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op]) (by simp {contextual := tt}; cc) theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) : (s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ := multiset.induction_on s (by simp) (by simp {contextual := tt}; cc) theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op'] {m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) : (s.map m).fold op' (m b) = m (s.fold op b) := multiset.induction_on s (by simp) (by simp [hm] {contextual := tt}) theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) : (s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ := by rw [← fold_add op, union_add_inter, fold_add op] @[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) : (erase_dup s).fold op b = s.fold op b := multiset.induction_on s (by simp) $ λ a s IH, begin by_cases a ∈ s; simp [IH, h], show fold op b s = op a (fold op b s), rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent], end end fold theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) : ∃ n : ℕ, s ≤ erase_dup s • n := ⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin rw count_smul, by_cases a ∈ s, { refine le_trans _ (mul_le_mul_right _ $ count_pos.2 $ mem_erase_dup.2 h), have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a)); [simp [le_max_left], simpa [cons_erase h]] }, { simp [count_eq_zero.2 h, nat.zero_le] } end⟩ section sort variables (r : α → α → Prop) [decidable_rel r] [tr : is_trans α r] [an : is_antisymm α r] [to : is_total α r] include tr an to /-- `sort s` constructs a sorted list from the multiset `s`. (Uses merge sort algorithm.) -/ def sort (s : multiset α) : list α := quot.lift_on s (merge_sort r) $ λ a b h, eq_of_sorted_of_perm tr.trans an.antisymm ((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm) (sorted_merge_sort r to.total tr.trans _) (sorted_merge_sort r to.total tr.trans _) @[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl @[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) := quot.induction_on s $ λ l, sorted_merge_sort r to.total tr.trans _ @[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s := quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _ end sort section pi variables [decidable_eq α] {δ : α → Type*} [∀a, decidable_eq (δ a)] open function def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) . lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) := begin apply hfunext, { refl }, intros a'' _ h, subst h, apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h, by_cases h₁ : a'' = a; by_cases h₂ : a'' = a'; simp [*, pi.cons_same, pi.cons_ne] at *, { subst h₁, rw [pi.cons_same, pi.cons_same] }, { subst h₂, rw [pi.cons_same, pi.cons_same] } end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) := m.rec_on { pi.empty δ } (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = {pi.empty δ} := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) : pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) : ∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := multiset.induction_on m begin assume f, have : f = pi.empty δ, { funext a ha, exact ha.elim }, subst this, split, { intros _ a ha, exact ha.elim }, { intros, simp, exact mem_cons_self _ 0 } end begin assume a m ih f, simp [iff_def], split, { intros b hb f' hf' eq a' ha', subst eq, rw [ih] at hf', by_cases a' = a, { subst h, rw [pi.cons_same], exact hb }, { rw [pi.cons_ne _ h], exact hf' _ _ } }, { assume hf, refine ⟨f a (mem_cons_self a _), hf a (mem_cons_self a _), (λa ha, f a (mem_cons_of_mem ha)), _, _⟩, { rw [ih], assume a' h', exact hf _ _ }, { funext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } } } end end pi end multiset
25d30e4b8d32439f0d8be25e3f4754151339a966
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/letrec1.lean
440f382af6c5580c726ed8ad117bfce10d206174
[ "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
666
lean
def f1.g := 10 def f1 (x : Nat) : Nat := let rec g : Nat → Nat -- Error f1.g has already been declared | 0 => x | y+1 => 2 * g y; g (g x) axiom Ax {α} : α def f2 (x : Nat) : Nat := let rec g : Nat → Nat | 0 => 1 | y+1 => (h y).val, h : (x : Nat) → { y : Nat // y < g x } -- unknown identifier `g` | 0 => ⟨10, Ax⟩ | _ => ⟨20, Ax⟩; 10 mutual def f (x : Nat) : Nat := let rec g (y : Nat) (h : y = f x) : Nat := -- error type is using 'f' f y + 1; x + 1 end mutual def f (x : Nat) : Nat := let rec g (y : Nat) : Nat := let rec h (z : Nat) (h : z = g z) : Nat := z + 1; -- error type is using 'g' f y + 1; x + 1 end
3c191d3fae14472c898ba2efc85e079de42892a9
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/ring_theory/principal_ideal_domain.lean
920ae580637a6e66c968351ac31f750e36d4cab6
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,146
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Morenikeji Neri -/ import ring_theory.unique_factorization_domain /-! # Principal ideal rings and principal ideal domains A principal ideal ring (PIR) is a ring in which all left ideals are principal. A principal ideal domain (PID) is an integral domain which is a principal ideal ring. # Main definitions Note that for principal ideal domains, one should use `[integral_domain R] [is_principal_ideal_ring R]`. There is no explicit definition of a PID. Theorems about PID's are in the `principal_ideal_ring` namespace. - `is_principal_ideal_ring`: a predicate on rings, saying that every left ideal is principal. - `generator`: a generator of a principal ideal (or more generally submodule) - `to_unique_factorization_monoid`: a PID is a unique factorization domain # Main results - `to_maximal_ideal`: a non-zero prime ideal in a PID is maximal. - `euclidean_domain.to_principal_ideal_domain` : a Euclidean domain is a PID. -/ universes u v variables {R : Type u} {M : Type v} open set function open submodule open_locale classical section variables [ring R] [add_comm_group M] [module R M] /-- An `R`-submodule of `M` is principal if it is generated by one element. -/ class submodule.is_principal (S : submodule R M) : Prop := (principal [] : ∃ a, S = span R {a}) instance bot_is_principal : (⊥ : submodule R M).is_principal := ⟨⟨0, by simp⟩⟩ instance top_is_principal : (⊤ : submodule R R).is_principal := ⟨⟨1, ideal.span_singleton_one.symm⟩⟩ variables (R) /-- A ring is a principal ideal ring if all (left) ideals are principal. -/ class is_principal_ideal_ring (R : Type u) [ring R] : Prop := (principal : ∀ (S : ideal R), S.is_principal) attribute [instance] is_principal_ideal_ring.principal @[priority 100] instance division_ring.is_principal_idea_ring (K : Type u) [division_ring K] : is_principal_ideal_ring K := { principal := λ S, by rcases ideal.eq_bot_or_top S with (rfl|rfl); apply_instance } end namespace submodule.is_principal variables [add_comm_group M] section ring variables [ring R] [module R M] /-- `generator I`, if `I` is a principal submodule, is an `x ∈ M` such that `span R {x} = I` -/ noncomputable def generator (S : submodule R M) [S.is_principal] : M := classical.some (principal S) lemma span_singleton_generator (S : submodule R M) [S.is_principal] : span R {generator S} = S := eq.symm (classical.some_spec (principal S)) @[simp] lemma generator_mem (S : submodule R M) [S.is_principal] : generator S ∈ S := by { conv_rhs { rw ← span_singleton_generator S }, exact subset_span (mem_singleton _) } lemma mem_iff_eq_smul_generator (S : submodule R M) [S.is_principal] {x : M} : x ∈ S ↔ ∃ s : R, x = s • generator S := by simp_rw [@eq_comm _ x, ← mem_span_singleton, span_singleton_generator] lemma eq_bot_iff_generator_eq_zero (S : submodule R M) [S.is_principal] : S = ⊥ ↔ generator S = 0 := by rw [← @span_singleton_eq_bot R M, span_singleton_generator] end ring section comm_ring variables [comm_ring R] [module R M] lemma mem_iff_generator_dvd (S : ideal R) [S.is_principal] {x : R} : x ∈ S ↔ generator S ∣ x := (mem_iff_eq_smul_generator S).trans (exists_congr (λ a, by simp only [mul_comm, smul_eq_mul])) lemma prime_generator_of_is_prime (S : ideal R) [submodule.is_principal S] [is_prime : S.is_prime] (ne_bot : S ≠ ⊥) : prime (generator S) := ⟨λ h, ne_bot ((eq_bot_iff_generator_eq_zero S).2 h), λ h, is_prime.ne_top (S.eq_top_of_is_unit_mem (generator_mem S) h), by simpa only [← mem_iff_generator_dvd S] using is_prime.2⟩ end comm_ring end submodule.is_principal namespace is_prime open submodule.is_principal ideal -- TODO -- for a non-ID one could perhaps prove that if p < q are prime then q maximal; -- 0 isn't prime in a non-ID PIR but the Krull dimension is still <= 1. -- The below result follows from this, but we could also use the below result to -- prove this (quotient out by p). lemma to_maximal_ideal [integral_domain R] [is_principal_ideal_ring R] {S : ideal R} [hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S := is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin assume T x hST hxS hxT, cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz, cases hpi.mem_or_mem (show generator T * z ∈ S, from hz ▸ generator_mem S), { have hTS : T ≤ S, rwa [← span_singleton_generator T, submodule.span_le, singleton_subset_iff], exact (hxS $ hTS hxT).elim }, cases (mem_iff_generator_dvd _).1 h with y hy, have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS, rw [← mul_one (generator S), hy, mul_left_comm, mul_right_inj' this] at hz, exact hz.symm ▸ T.mul_mem_right _ (generator_mem T) end⟩ end is_prime section open euclidean_domain variable [euclidean_domain R] lemma mod_mem_iff {S : ideal R} {x y : R} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S := ⟨λ hxy, div_add_mod x y ▸ S.add_mem (S.mul_mem_right _ hy) hxy, λ hx, (mod_eq_sub_mul_div x y).symm ▸ S.sub_mem hx (S.mul_mem_right _ hy)⟩ @[priority 100] -- see Note [lower instance priority] instance euclidean_domain.to_principal_ideal_domain : is_principal_ideal_ring R := { principal := λ S, by exactI ⟨if h : {x : R | x ∈ S ∧ x ≠ 0}.nonempty then have wf : well_founded (euclidean_domain.r : R → R → Prop) := euclidean_domain.r_well_founded, have hmin : well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ∈ S ∧ well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ≠ 0, from well_founded.min_mem wf {x : R | x ∈ S ∧ x ≠ 0} h, ⟨well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h, submodule.ext $ λ x, ⟨λ hx, div_add_mod x (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ▸ (ideal.mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $ have (x % (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ∉ {x : R | x ∈ S ∧ x ≠ 0}), from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2), have x % well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h = 0, by finish [(mod_mem_iff hmin.1).2 hx], by simp *), λ hx, let ⟨y, hy⟩ := ideal.mem_span_singleton.1 hx in hy.symm ▸ S.mul_mem_right _ hmin.1⟩⟩ else ⟨0, submodule.ext $ λ a, by rw [← @submodule.bot_coe R R _ _ _, span_eq, submodule.mem_bot]; exact ⟨λ haS, by_contradiction $ λ ha0, h ⟨a, ⟨haS, ha0⟩⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩⟩ } end lemma is_field.is_principal_ideal_ring {R : Type*} [integral_domain R] (h : is_field R) : is_principal_ideal_ring R := @euclidean_domain.to_principal_ideal_domain R (@field.to_euclidean_domain R (h.to_field R)) namespace principal_ideal_ring open is_principal_ideal_ring @[priority 100] -- see Note [lower instance priority] instance is_noetherian_ring [ring R] [is_principal_ideal_ring R] : is_noetherian_ring R := is_noetherian_ring_iff.2 ⟨assume s : ideal R, begin rcases (is_principal_ideal_ring.principal s).principal with ⟨a, rfl⟩, rw [← finset.coe_singleton], exact ⟨{a}, set_like.coe_injective rfl⟩ end⟩ lemma is_maximal_of_irreducible [comm_ring R] [is_principal_ideal_ring R] {p : R} (hp : irreducible p) : ideal.is_maximal (span R ({p} : set R)) := ⟨⟨mt ideal.span_singleton_eq_top.1 hp.1, λ I hI, begin rcases principal I with ⟨a, rfl⟩, erw ideal.span_singleton_eq_top, unfreezingI { rcases ideal.span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩ }, refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)), erw [ideal.span_singleton_le_span_singleton, is_unit.mul_right_dvd hb] end⟩⟩ variables [integral_domain R] [is_principal_ideal_ring R] lemma irreducible_iff_prime {p : R} : irreducible p ↔ prime p := ⟨λ hp, (ideal.span_singleton_prime hp.ne_zero).1 $ (is_maximal_of_irreducible hp).is_prime, prime.irreducible⟩ lemma associates_irreducible_iff_prime : ∀{p : associates R}, irreducible p ↔ prime p := associates.irreducible_iff_prime_iff.1 (λ _, irreducible_iff_prime) section open_locale classical /-- `factors a` is a multiset of irreducible elements whose product is `a`, up to units -/ noncomputable def factors (a : R) : multiset R := if h : a = 0 then ∅ else classical.some (wf_dvd_monoid.exists_factors a h) lemma factors_spec (a : R) (h : a ≠ 0) : (∀b∈factors a, irreducible b) ∧ associated (factors a).prod a := begin unfold factors, rw [dif_neg h], exact classical.some_spec (wf_dvd_monoid.exists_factors a h) end lemma ne_zero_of_mem_factors {R : Type v} [integral_domain R] [is_principal_ideal_ring R] {a b : R} (ha : a ≠ 0) (hb : b ∈ factors a) : b ≠ 0 := irreducible.ne_zero ((factors_spec a ha).1 b hb) lemma mem_submonoid_of_factors_subset_of_units_subset (s : submonoid R) {a : R} (ha : a ≠ 0) (hfac : ∀ b ∈ factors a, b ∈ s) (hunit : ∀ c : units R, (c : R) ∈ s) : a ∈ s := begin rcases ((factors_spec a ha).2) with ⟨c, hc⟩, rw [← hc], exact submonoid.mul_mem _ (submonoid.multiset_prod_mem _ _ hfac) (hunit _), end /-- If a `ring_hom` maps all units and all factors of an element `a` into a submonoid `s`, then it also maps `a` into that submonoid. -/ lemma ring_hom_mem_submonoid_of_factors_subset_of_units_subset {R S : Type*} [integral_domain R] [is_principal_ideal_ring R] [semiring S] (f : R →+* S) (s : submonoid S) (a : R) (ha : a ≠ 0) (h : ∀ b ∈ factors a, f b ∈ s) (hf: ∀ c : units R, f c ∈ s) : f a ∈ s := mem_submonoid_of_factors_subset_of_units_subset (s.comap f.to_monoid_hom) ha h hf /-- A principal ideal domain has unique factorization -/ @[priority 100] -- see Note [lower instance priority] instance to_unique_factorization_monoid : unique_factorization_monoid R := { irreducible_iff_prime := λ _, principal_ideal_ring.irreducible_iff_prime .. (is_noetherian_ring.wf_dvd_monoid : wf_dvd_monoid R) } end end principal_ideal_ring
c62ac317b05d7592e4aceeca5aaf49f93d8da430
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/limits/bdd_monos_converge.lean
bdc2b28d8e0ad660492515840ecd211bb07d1af3
[ "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
4,426
lean
import game.limits.seq_bdd_iff_range_bdd namespace xena --hide /- Bounded monotone sequences converge -/ def is_increasing (a : ℕ → ℝ) := ∀ n : ℕ, a n ≤ a (n+1) def is_decreasing (a : ℕ → ℝ) := ∀ n : ℕ, a (n + 1) ≤ a n def is_monotone (a : ℕ → ℝ) := is_increasing a ∨ is_decreasing a -- begin hide -- Note: later we use (n ≤ k) → (a n ≤ a k) for `a` monotone increasing -- and (n ≤ k) → (a k ≤ a n) for decreasing. Should these be proved first, -- or use mathlib's versions of monotone? --https://leanprover-community.github.io/mathlib_docs/order/basic.html theorem is_increasing' (a : ℕ → ℝ) : is_increasing a ↔ (∀ m n : ℕ, m ≤ n → a m ≤ a n) := begin split, intros inc m n, {intro hyp, induction hyp with k hyp ihyp, exact le_refl (a m), exact le_trans ihyp (inc k),}, intros hyp p, exact (hyp p (p + 1)) (nat.le_succ p), end theorem is_decreasing' (a : ℕ → ℝ) : is_decreasing a ↔ (∀ m n : ℕ, m ≤ n → a n ≤ a m) := begin split, intros dec m n, {intro hyp, induction hyp with k hyp ihyp, exact le_refl (a m), exact le_trans (dec k) ihyp,}, intros hyp p, exact (hyp p (p + 1)) (nat.le_succ p), end -- end hide /- Lemma Bounded monotone sequences converge. -/ theorem bdd_mono_converges (a : ℕ → ℝ) (h1 : is_bounded a) (h2 : is_monotone a): is_convergent a := begin -- As before, M is the set of terms of our sequence a let M := set.range a, -- The increasing and the decreasing cases will be similar cases h2 with increasing decreasing, -- monotone increasing case { have fact1: has_lub M, -- We use the completeness axiom (least upper bound property) -- to show that M has a sup. refine produces two subgoals that we -- will need to prove to show that the sup exists. refine lub_property_reals M _, split, -- As our sequence `a` is a function from the nonempty set ℕ, -- its range is nonempty { exact set.range_nonempty a, }, -- We use the → (.mp) direction of our previous `trivial` lemma -- to prove that M is bounded above {exact ((seq_bdd_iff_range_bdd a).mp h1).left, }, -- So M has a lub, call it s. cases fact1 with s hyp_s, -- It seems reasonable to assume that s is the limit of a use s, intros e hype, -- We show that s - e cannot be an upper bound for M (our set of terms) have fact2: ¬ is_upper_bound M (s - e), by_contradiction claim, -- hyp_s.right says if y is any upper bound of M, then s ≤ y -- (supremum condition) let forcontra := hyp_s.right (s - e) claim, --forcontra says that s ≤ s - e. But e is positive, so linarith closes. linarith, -- we now unfold the fact that s - e is not an upper bound for M, -- and prove that s is the limit of our increasing sequence unfold is_upper_bound at fact2, push_neg at fact2, cases fact2 with l hypl, -- hypl.right is a proof that s - e < l, for some l ∈ M -- we want l expressed in the form a N0 for some N0, cases hypl.left with N0 hypN0, use N0, intros k hypk, -- applying the theorem proved above rw is_increasing' at increasing, have fact3:= (increasing N0 k) hypk, refine abs_lt.mpr _, split, linarith, have fact4: a k ≤ s, exact hyp_s.left (a k) (set.mem_range_self k), linarith, }, --monotone decreasing case, using the same strategy { have fact3: has_glb M, refine glb_property_reals M _, split, { exact set.range_nonempty a, }, { exact ((seq_bdd_iff_range_bdd a).mp h1).right, }, cases fact3 with i hyp_i, use i, intros e hype, -- We show that i + e cannot be a lower bound for M (our set of terms) have fact4: ¬ is_lower_bound M (i + e), by_contradiction claim, let forcontra := hyp_i.right (i + e) claim, linarith, unfold is_lower_bound at fact4, push_neg at fact4, cases fact4 with m hypm, cases hypm.left with N0 hypN0, use N0, intros k hypk, -- applying the theorem proved above rw is_decreasing' at decreasing, have fact5:= (decreasing N0 k) hypk, refine abs_lt.mpr _, split, have fact4: i ≤ a k, exact hyp_i.left (a k) (set.mem_range_self k), linarith, linarith, }, end end xena -- hide
23558a8c461e732db07f38e8e4a0801848767683
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/topology/uniform_space/separation.lean
c719eb3f5b8cb6602d076d95d75eca3b79cfae8e
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,518
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, Patrick Massot -/ import topology.uniform_space.basic import tactic.apply_fun /-! # Hausdorff properties of uniform spaces. Separation quotient. This file studies uniform spaces whose underlying topological spaces are separated (also known as Hausdorff or T₂). This turns out to be equivalent to asking that the intersection of all entourages is the diagonal only. This condition actually implies the stronger separation property that the space is regular (T₃), hence those conditions are equivalent for topologies coming from a uniform structure. More generally, the intersection `𝓢 X` of all entourages of `X`, which has type `set (X × X)` is an equivalence relation on `X`. Points which are equivalent under the relation are basically undistinguishable from the point of view of the uniform structure. For instance any uniformly continuous function will send equivalent points to the same value. The quotient `separation_quotient X` of `X` by `𝓢 X` has a natural uniform structure which is separated, and satisfies a universal property: every uniformly continuous function from `X` to a separated uniform space uniquely factors through `separation_quotient X`. As usual, this allows to turn `separation_quotient` into a functor (but we don't use the category theory library in this file). These notions admit relative versions, one can ask that `s : set X` is separated, this is equivalent to asking that the uniform structure induced on `s` is separated. ## Main definitions * `separation_relation X : set (X × X)`: the separation relation * `separated_space X`: a predicate class asserting that `X` is separated * `is_separated s`: a predicate asserting that `s : set X` is separated * `separation_quotient X`: the maximal separated quotient of `X`. * `separation_quotient.lift f`: factors a map `f : X → Y` through the separation quotient of `X`. * `separation_quotient.map f`: turns a map `f : X → Y` into a map between the separation quotients of `X` and `Y`. ## Main results * `separated_iff_t2`: the equivalence between being separated and being Hausdorff for uniform spaces. * `separation_quotient.uniform_continuous_lift`: factoring a uniformly continuous map through the separation quotient gives a uniformly continuous map. * `separation_quotient.uniform_continuous_map`: maps induced between separation quotients are uniformly continuous. ## Notations Localized in `uniformity`, we have the notation `𝓢 X` for the separation relation on a uniform space `X`, ## Implementation notes The separation setoid `separation_setoid` is not declared as a global instance. It is made a local instance while building the theory of `separation_quotient`. The factored map `separation_quotient.lift f` is defined without imposing any condition on `f`, but returns junk if `f` is not uniformly continuous (constant junk hence it is always uniformly continuous). -/ open filter topological_space set classical function uniform_space open_locale classical topological_space uniformity filter noncomputable theory set_option eqn_compiler.zeta true universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] /-! ### Separated uniform spaces -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (𝓤 α).sets localized "notation `𝓢` := separation_rel" in uniformity lemma separated_equiv : equivalence (λx y, (x, y) ∈ 𝓢 α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ 𝓢 α) (hyz : (y, z) ∈ 𝓢 α) s (hs : s ∈ 𝓤 α), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ /-- A uniform space is separated if its separation relation is trivial (each point is related only to itself). -/ class separated_space (α : Type u) [uniform_space α] : Prop := (out : 𝓢 α = id_rel) theorem separated_space_iff {α : Type u} [uniform_space α] : separated_space α ↔ 𝓢 α = id_rel := ⟨λ h, h.1, λ h, ⟨h⟩⟩ theorem separated_def {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, (∀ r ∈ 𝓤 α, (x, y) ∈ r) → x = y := by simp [separated_space_iff, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated_space α ↔ ∀ x y, x ≠ y → ∃ r ∈ 𝓤 α, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [not_forall] lemma eq_of_uniformity {α : Type*} [uniform_space α] [separated_space α] {x y : α} (h : ∀ {V}, V ∈ 𝓤 α → (x, y) ∈ V) : x = y := separated_def.mp ‹separated_space α› x y (λ _, h) lemma eq_of_uniformity_basis {α : Type*} [uniform_space α] [separated_space α] {ι : Type*} {p : ι → Prop} {s : ι → set (α × α)} (hs : (𝓤 α).has_basis p s) {x y : α} (h : ∀ {i}, p i → (x, y) ∈ s i) : x = y := eq_of_uniformity (λ V V_in, let ⟨i, hi, H⟩ := hs.mem_iff.mp V_in in H (h hi)) lemma eq_of_forall_symmetric {α : Type*} [uniform_space α] [separated_space α] {x y : α} (h : ∀ {V}, V ∈ 𝓤 α → symmetric_rel V → (x, y) ∈ V) : x = y := eq_of_uniformity_basis has_basis_symmetric (by simpa [and_imp] using λ _, h) lemma id_rel_sub_separation_relation (α : Type*) [uniform_space α] : id_rel ⊆ 𝓢 α := begin unfold separation_rel, rw id_rel_subset, intros x, suffices : ∀ t ∈ 𝓤 α, (x, x) ∈ t, by simpa only [refl_mem_uniformity], exact λ t, refl_mem_uniformity, end lemma separation_rel_comap {f : α → β} (h : ‹uniform_space α› = uniform_space.comap f ‹uniform_space β›) : 𝓢 α = (prod.map f f) ⁻¹' 𝓢 β := begin dsimp [separation_rel], rw [uniformity_comap h, (filter.comap_has_basis (prod.map f f) (𝓤 β)).sInter_sets, ← preimage_bInter, sInter_eq_bInter], refl, end protected lemma filter.has_basis.separation_rel {ι : Type*} {p : ι → Prop} {s : ι → set (α × α)} (h : has_basis (𝓤 α) p s) : 𝓢 α = ⋂ i ∈ set_of p, s i := by { unfold separation_rel, rw h.sInter_sets } lemma separation_rel_eq_inter_closure : 𝓢 α = ⋂₀ (closure '' (𝓤 α).sets) := by simp [uniformity_has_basis_closure.separation_rel] lemma is_closed_separation_rel : is_closed (𝓢 α) := begin rw separation_rel_eq_inter_closure, apply is_closed_sInter, rintros _ ⟨t, t_in, rfl⟩, exact is_closed_closure, end lemma separated_iff_t2 : separated_space α ↔ t2_space α := begin classical, split ; intro h, { rw [t2_iff_is_closed_diagonal, ← show 𝓢 α = diagonal α, from h.1], exact is_closed_separation_rel }, { rw separated_def', intros x y hxy, have : 𝓝 x ⊓ 𝓝 y = ⊥, { rw t2_iff_nhds at h, by_contra H, exact hxy (h ⟨H⟩) }, rcases inf_eq_bot_iff.mp this with ⟨U, U_in, V, V_in, H⟩, rcases uniform_space.mem_nhds_iff.mp U_in with ⟨S, S_in, S_sub⟩, use [S, S_in], change y ∉ ball x S, intro y_in, have : y ∈ U ∩ V := ⟨S_sub y_in, mem_of_mem_nhds V_in⟩, rwa H at this }, end @[priority 100] -- see Note [lower instance priority] instance separated_regular [separated_space α] : regular_space α := { t0 := by { haveI := separated_iff_t2.mp ‹_›, exact t1_space.t0_space.t0 }, regular := λs a hs ha, have sᶜ ∈ 𝓝 a, from is_open.mem_nhds hs.is_open_compl ha, have {p : α × α | p.1 = a → p.2 ∈ sᶜ} ∈ 𝓤 α, from mem_nhds_uniformity_iff_right.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ 𝓤 α, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ sᶜ, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ 𝓝 a, from (𝓝 a).sets_of_superset (mem_nhds_left a hd) subset_closure, have 𝓝 a ⊓ 𝓟 (closure e)ᶜ = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (𝓟 (closure e)ᶜ) (𝓟 (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨(closure e)ᶜ, is_closed_closure.is_open_compl, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..@t2_space.t1_space _ _ (separated_iff_t2.mp ‹_›) } lemma is_closed_of_spaced_out [separated_space α] {V₀ : set (α × α)} (V₀_in : V₀ ∈ 𝓤 α) {s : set α} (hs : ∀ {x y}, x ∈ s → y ∈ s → (x, y) ∈ V₀ → x = y) : is_closed s := begin rcases comp_symm_mem_uniformity_sets V₀_in with ⟨V₁, V₁_in, V₁_symm, h_comp⟩, apply is_closed_of_closure_subset, intros x hx, rw mem_closure_iff_ball at hx, rcases hx V₁_in with ⟨y, hy, hy'⟩, suffices : x = y, by rwa this, apply eq_of_forall_symmetric, intros V V_in V_symm, rcases hx (inter_mem V₁_in V_in) with ⟨z, hz, hz'⟩, suffices : z = y, { rw ← this, exact ball_inter_right x _ _ hz }, exact hs hz' hy' (h_comp $ mem_comp_of_mem_ball V₁_symm (ball_inter_left x _ _ hz) hy) end /-! ### Separated sets -/ /-- A set `s` in a uniform space `α` is separated if the separation relation `𝓢 α` induces the trivial relation on `s`. -/ def is_separated (s : set α) : Prop := ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y lemma is_separated_def (s : set α) : is_separated s ↔ ∀ x y ∈ s, (x, y) ∈ 𝓢 α → x = y := iff.rfl lemma is_separated_def' (s : set α) : is_separated s ↔ (s.prod s) ∩ 𝓢 α ⊆ id_rel := begin rw is_separated_def, split, { rintros h ⟨x, y⟩ ⟨⟨x_in, y_in⟩, H⟩, simp [h x y x_in y_in H] }, { intros h x y x_in y_in xy_in, rw ← mem_id_rel, exact h ⟨mk_mem_prod x_in y_in, xy_in⟩ } end lemma univ_separated_iff : is_separated (univ : set α) ↔ separated_space α := begin simp only [is_separated, mem_univ, true_implies_iff, separated_space_iff], split, { intro h, exact subset.antisymm (λ ⟨x, y⟩ xy_in, h x y xy_in) (id_rel_sub_separation_relation α), }, { intros h x y xy_in, rwa h at xy_in }, end lemma is_separated_of_separated_space [separated_space α] (s : set α) : is_separated s := begin rw [is_separated, separated_space.out], tauto, end lemma is_separated_iff_induced {s : set α} : is_separated s ↔ separated_space s := begin rw separated_space_iff, change _ ↔ 𝓢 {x // x ∈ s} = _, rw [separation_rel_comap rfl, is_separated_def'], split; intro h, { ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩, suffices : (x, y) ∈ 𝓢 α ↔ x = y, by simpa only [mem_id_rel], refine ⟨λ H, h ⟨mk_mem_prod x_in y_in, H⟩, _⟩, rintro rfl, exact id_rel_sub_separation_relation α rfl }, { rintros ⟨x, y⟩ ⟨⟨x_in, y_in⟩, hS⟩, have A : (⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩ : ↥s × ↥s) ∈ prod.map (coe : s → α) (coe : s → α) ⁻¹' 𝓢 α, from hS, simpa using h.subset A } end lemma eq_of_uniformity_inf_nhds_of_is_separated {s : set α} (hs : is_separated s) : ∀ {x y : α}, x ∈ s → y ∈ s → cluster_pt (x, y) (𝓤 α) → x = y := begin intros x y x_in y_in H, have : ∀ V ∈ 𝓤 α, (x, y) ∈ closure V, { intros V V_in, rw mem_closure_iff_cluster_pt, have : 𝓤 α ≤ 𝓟 V, by rwa le_principal_iff, exact H.mono this }, apply hs x y x_in y_in, simpa [separation_rel_eq_inter_closure], end lemma eq_of_uniformity_inf_nhds [separated_space α] : ∀ {x y : α}, cluster_pt (x, y) (𝓤 α) → x = y := begin have : is_separated (univ : set α), { rw univ_separated_iff, assumption }, introv, simpa using eq_of_uniformity_inf_nhds_of_is_separated this, end /-! ### Separation quotient -/ namespace uniform_space /-- The separation relation of a uniform space seen as a setoid. -/ def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ 𝓢 α, separated_equiv⟩ local attribute [instance] separation_setoid instance separation_setoid.uniform_space {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_map.comp tendsto_swap_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) u.uniformity).lift' (λs, comp_rel s s) = u.uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ u.uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ 𝓢 α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (u.uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, u.uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, u.uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : 𝓤 (quotient (separation_setoid α)) = (𝓤 α).map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ 𝓢 α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ 𝓢 α → (c, d) ∈ 𝓢 β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma comap_quotient_le_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ (𝓤 α) := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (𝓤 α).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = 𝓤 α := le_antisymm comap_quotient_le_uniformity le_comap_map instance separated_separation : separated_space (quotient (separation_setoid α)) := ⟨set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (𝓤 $ quotient $ separation_setoid α).comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)), from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp [preimage], exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated_space β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h /-- The maximal separated quotient of a uniform space `α`. -/ def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance [inhabited α] : inhabited (separation_quotient α) := by unfold separation_quotient; apply_instance /-- Factoring functions to a separated space through the separation quotient. -/ def lift [separated_space β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (nonempty.some ⟨x.out⟩) lemma lift_mk [separated_space β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated_space β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end /-- The separation quotient functor acting on functions. -/ def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (uniform_continuous_quotient_mk.comp h)] lemma uniform_continuous_map (f : α → β) : uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hg.comp hf) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, rfl⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated_space α] [separated_space β] : separated_space (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end uniform_space
b903aef85182b38c0e7e3a0b305359763b256f92
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/topology/metric_space/emetric_space.lean
a32564bc2001e8c24ebdd839e968d557a8b69d05
[ "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
31,674
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Extended metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel This file is devoted to the definition and study of `emetric_spaces`, i.e., metric spaces in which the distance is allowed to take the value ∞. This extended distance is called `edist`, and takes values in `ennreal`. Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity The class `emetric_space` therefore extends `uniform_space` (and `topological_space`). -/ import data.real.nnreal data.real.ennreal import topology.uniform_space.separation topology.uniform_space.uniform_embedding open lattice set filter classical noncomputable theory local notation `𝓤` := uniformity universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Characterizing uniformities associated to a (generalized) distance function `D` in terms of the elements of the uniformity. -/ theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) : U = ⨅ ε>z, principal {p:α×α | D p.1 p.2 < ε} := le_antisymm (le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩) (λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h) class has_edist (α : Type*) := (edist : α → α → ennreal) export has_edist (edist) /- Design note: one could define an `emetric_space` just by giving `edist`, and then derive an instance of `uniform_space` by taking the natural uniform structure associated to the distance. This creates diamonds problem for products, as the uniform structure on the product of two emetric spaces could be obtained first by obtaining two uniform spaces and then taking their products, or by taking the product of the emetric spaces and then the associated uniform structure. The two uniform structure we have just described are equal, but not defeq, which creates a lot of problem. The idea is to add, in the very definition of an `emetric_space`, a uniform structure with a uniformity which equal to the one given by the distance, but maybe not defeq. And the instance from `emetric_space` to `uniform_space` uses this uniformity. In this way, when we create the product of emetric spaces, we put in the product the uniformity corresponding to the product of the uniformities. There is one more proof obligation, that this product uniformity is equal to the uniformity corresponding to the product metric. But the diamond problem disappears. The same trick is used in the definition of a metric space, where one stores as well a uniform structure and an edistance. -/ /-- Creating a uniform space from an extended distance. -/ def uniform_space_of_edist (edist : α → α → ennreal) (edist_self : ∀ x : α, edist x x = 0) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, have (2 : ennreal) = (2 : ℕ) := by simp, have A : 0 < ε / 2 := ennreal.div_pos_iff.2 ⟨ne_of_gt h, this ▸ ennreal.nat_ne_top 2⟩, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $ have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε, from assume a b c hac hcb, calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _ ... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb ... = ε : by rw [ennreal.add_halves], 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 [edist_comm] } /-- Extended metric spaces, with an extended distance `edist` possibly taking the value ∞ Each emetric 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 an `emetric_space` structure, the uniformity fields are not necessary, they will be filled in by default. There is a default value for the uniformity, that can be substituted in cases of interest, for instance when instantiating an `emetric_space` structure on a product. Continuity of `edist` is finally proving in `topology.instances.ennreal` -/ class emetric_space (α : Type u) extends has_edist α : Type u := (edist_self : ∀ x : α, edist x x = 0) (eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y) (edist_comm : ∀ x y : α, edist x y = edist y x) (edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) (to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle) (uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} . control_laws_tac) /- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated namespace, while notions associated to metric spaces are mostly in the root namespace. -/ variables [emetric_space α] instance emetric_space.to_uniform_space' : uniform_space α := emetric_space.to_uniform_space α export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle) attribute [simp] edist_self /-- Characterize the equality of points by the vanishing of their extended distance -/ @[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y := iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _) @[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y := iff.intro (assume h, eq_of_edist_eq_zero (h.symm)) (assume : x = y, this ▸ (edist_self _).symm) /-- Triangle inequality for the extended distance -/ theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y := by rw edist_comm z; apply edist_triangle theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z := by rw edist_comm y; apply edist_triangle lemma edist_triangle4 (x y z t : α) : edist x t ≤ edist x y + edist y z + edist z t := calc edist x t ≤ edist x z + edist z t : edist_triangle x z t ... ≤ (edist x y + edist y z) + edist z t : add_le_add_right' (edist_triangle x y z) /-- Two points coincide if their distance is `< ε` for all positive ε -/ theorem eq_of_forall_edist_le {x y : α} (h : ∀ε, ε > 0 → edist x y ≤ ε) : x = y := eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense (by simp) h) /-- Reformulation of the uniform structure in terms of the extended distance -/ theorem uniformity_edist' : 𝓤 α = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) := emetric_space.uniformity_edist _ /-- Reformulation of the uniform structure in terms of the extended distance on a subtype -/ theorem uniformity_edist'' : 𝓤 α = (⨅ε:{ε:ennreal // ε>0}, principal {p:α×α | edist p.1 p.2 < ε.val}) := by simp [infi_subtype]; exact uniformity_edist' theorem uniformity_edist_nnreal : 𝓤 α = (⨅(ε:nnreal) (h : ε > 0), principal {p:α×α | edist p.1 p.2 < ε}) := begin rw [uniformity_edist', ennreal.infi_ennreal, inf_of_le_left], { congr, funext ε, refine infi_congr_Prop ennreal.coe_pos _, assume h, refl }, refine le_infi (assume h, infi_le_of_le 1 $ infi_le_of_le ennreal.zero_lt_one $ _), exact principal_mono.2 (assume p h, lt_of_lt_of_le h le_top) end /-- Characterization of the elements of the uniformity in terms of the extended distance -/ theorem mem_uniformity_edist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) := begin rw [uniformity_edist'', 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, ennreal.zero_lt_one⟩⟩ end /-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/ theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) : {p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩ namespace emetric /-- ε-δ characterization of uniform continuity on emetric spaces -/ theorem uniform_continuous_iff [emetric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε := uniform_continuous_def.trans ⟨λ H ε ε0, mem_uniformity_edist.1 $ H _ $ edist_mem_uniformity ε0, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in mem_uniformity_edist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩ /-- ε-δ characterization of uniform embeddings on emetric spaces -/ theorem uniform_embedding_iff [emetric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- ε-δ characterization of Cauchy sequences on emetric spaces -/ protected lemma cauchy_iff {f : filter α} : cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε := cauchy_iff.trans $ and_congr iff.rfl ⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (edist_mem_uniformity ε0) in ⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩, λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, tf, h⟩ := H ε ε0 in ⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩ end emetric open emetric /-- An emetric space is separated -/ instance to_separated : separated α := separated_def.2 $ λ x y h, eq_of_forall_edist_le $ λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0)) /-- Auxiliary function to replace the uniformity on an emetric space with a uniformity which is equal to the original one, but maybe not defeq. This is useful if one wants to construct an emetric space with a specified uniformity. -/ def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α) (H : @uniformity _ U = @uniformity _ (emetric_space.to_uniform_space α)) : emetric_space α := { edist := @edist _ m.to_has_edist, edist_self := edist_self, eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _, edist_comm := edist_comm, edist_triangle := edist_triangle, to_uniform_space := U, uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) } /-- The extended metric induced by an injective function taking values in an emetric space. -/ def emetric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : emetric_space β) : emetric_space α := { edist := λ x y, edist (f x) (f y), edist_self := λ x, edist_self _, eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h), edist_comm := λ x y, edist_comm _ _, edist_triangle := λ x y z, edist_triangle _ _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_edist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } /-- Emetric space instance on subsets of emetric spaces -/ instance {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) := t.induced subtype.val (λ x y, subtype.eq) /-- The extended distance on a subset of an emetric space is the restriction of the original distance, by definition -/ theorem subtype.edist_eq {p : α → Prop} [t : emetric_space α] (x y : subtype p) : edist x y = edist x.1 y.1 := rfl /-- The product of two emetric spaces, with the max distance, is an extended metric spaces. We make sure that the uniform structure thus constructed is the one corresponding to the product of uniform spaces, to avoid diamond problems. -/ instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) := { edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_self := λ x, by simp, eq_of_edist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, have A : x.fst = y.fst := eq_of_edist_eq_zero (by simpa using h₁), have B : x.snd = y.snd := eq_of_edist_eq_zero (by simpa using h₂), exact prod.ext_iff.2 ⟨A, B⟩ end, edist_comm := λ x y, by simp [edist_comm], edist_triangle := λ x y z, max_le (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_left _ _) (le_max_left _ _))) (le_trans (edist_triangle _ _ _) (add_le_add' (le_max_right _ _) (le_max_right _ _))), uniformity_edist := begin refine uniformity_prod.trans _, simp [emetric_space.uniformity_edist, 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 } section pi open finset variables {π : β → Type*} [fintype β] /-- The product of a finite number of emetric spaces, with the max distance, is still an emetric space. This construction would also work for infinite products, but it would not give rise to the product topology. Hence, we only formalize it in the good situation of finitely many spaces. -/ instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) := { edist := λ f g, finset.sup univ (λb, edist (f b) (g b)), edist_self := assume f, bot_unique $ finset.sup_le $ by simp, edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _, edist_triangle := assume f g h, begin simp only [finset.sup_le_iff], assume b hb, exact le_trans (edist_triangle _ (g b) _) (add_le_add' (le_sup hb) (le_sup hb)) end, eq_of_edist_eq_zero := assume f g eq0, begin have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0, simp only [finset.sup_le_iff] at eq1, exact (funext $ assume b, eq_of_edist_eq_zero $ bot_unique $ eq1 b $ mem_univ b), end } end pi namespace emetric variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α} /-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/ def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl /-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/ def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist 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 (zero_le _) hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show edist x x < ε, by rw edist_self; assumption theorem mem_closed_ball_self : x ∈ closed_ball x ε := show edist x x ≤ ε, by rw edist_self; exact bot_le theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [edist_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 (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (edist_triangle_left x y z) (lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h) theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, calc edist z y ≤ edist z x + edist x y : edist_triangle _ _ _ ... = edist x y + edist z x : add_comm _ _ ... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx ... ≤ ε₂ : h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := begin have : 0 < ε - edist y x := by simpa using h, refine ⟨ε - edist y x, this, ball_subset _ _⟩, { rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _}, { have : edist y x ≠ ⊤ := lattice.ne_top_of_lt h, apply lt_top_iff_ne_top.2 this } end theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 := eq_empty_iff_forall_not_mem.trans ⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))), λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩ theorem nhds_eq : nhds x = (⨅ε:{ε:ennreal // ε>0}, principal (ball x ε.val)) := begin rw [nhds_eq_uniformity, uniformity_edist'', lift'_infi], { apply congr_arg, funext ε, rw [lift'_principal], { simp [ball, edist_comm] }, { exact monotone_preimage } }, { exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ }, { intros, refl } end theorem mem_nhds_iff : s ∈ nhds 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, ennreal.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 : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ nhds x := mem_nhds_sets is_open_ball (mem_ball_self ε0) /-- ε-characterization of the closure in emetric spaces -/ theorem mem_closure_iff' : x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε := ⟨begin intros hx ε hε, have A : ball x ε ∩ s ≠ ∅ := mem_closure_iff.1 hx _ is_open_ball (mem_ball_self hε), cases ne_empty_iff_exists_mem.1 A with y hy, simp, exact ⟨y, ⟨hy.2, by have B := hy.1; simpa [mem_ball'] using B⟩⟩ end, begin intros H, apply mem_closure_iff.2, intros o ho xo, rcases is_open_iff.1 ho x xo with ⟨ε, ⟨εpos, hε⟩⟩, rcases H ε εpos with ⟨y, ⟨ys, ydist⟩⟩, have B : y ∈ o ∩ s := ⟨hε (by simpa [edist_comm]), ys⟩, apply ne_empty_of_mem B end⟩ theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (nhds a) ↔ ∀ ε > 0, ∃ n ∈ f, ∀x ∈ n, edist (u x) a < ε := ⟨λ H ε ε0, ⟨u⁻¹' (ball a ε), H (ball_mem_nhds _ ε0), by simp⟩, λ H s hs, let ⟨ε, ε0, hε⟩ := mem_nhds_iff.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in f.sets_of_superset δ0 (λx xδ, hε (hδ x xδ))⟩ theorem tendsto_at_top [inhabited β] [semilattice_sup β] (u : β → α) {a : α} : tendsto u at_top (nhds a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε := begin rw tendsto_nhds, apply forall_congr, intro ε, apply forall_congr, intro hε, simp, exact ⟨λ ⟨s, ⟨N, hN⟩, hs⟩, ⟨N, λn hn, hs _ (hN _ hn)⟩, λ ⟨N, hN⟩, ⟨{n | n ≥ N}, ⟨⟨N, by simp⟩, hN⟩⟩⟩, end /-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually, the edistance between its elements is arbitrarily small -/ theorem cauchy_seq_iff [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u n) (u m) < ε := begin simp only [cauchy_seq, emetric.cauchy_iff, 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 _ hn) (hN _ hm)⟩ }, { intros H ε εpos, rcases H (ε/2) (ennreal.half_pos εpos) with ⟨N, hN⟩, existsi ball (u N) (ε/2), split, { exact ⟨N, λx hx, hN _ _ (le_refl N) hx⟩ }, { exact λx y hx hy, calc edist x y ≤ edist x (u N) + edist y (u N) : edist_triangle_right _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add hx hy ... = ε : ennreal.add_halves _ } } end /-- A variation around the emetric characterization of Cauchy sequences -/ theorem cauchy_seq_iff' [inhabited β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε := begin rw cauchy_seq_iff, split, { intros H ε εpos, rcases H ε εpos with ⟨N, hN⟩, exact ⟨N, λn hn, hN _ _ (le_refl N) hn⟩ }, { intros H ε εpos, rcases H (ε/2) (ennreal.half_pos εpos) with ⟨N, hN⟩, exact ⟨N, λ m n hm hn, calc edist (u n) (u m) ≤ edist (u n) (u N) + edist (u m) (u N) : edist_triangle_right _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add (hN _ hn) (hN _ hm) ... = ε : ennreal.add_halves _⟩ } end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ theorem totally_bounded_iff' {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru, ⟨t, _, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ section compact /-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/ lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : compact s) : ∃ t ⊆ s, (countable t ∧ s = closure t) := begin have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) := totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1, -- assume e, finite_cover_balls_of_compact hs, have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)), { intro e, cases le_or_gt e 0 with h, { exact ⟨∅, by finish⟩ }, { rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }}, /-The desired countable set is obtained by taking for each `n` the centers of a finite cover by balls of radius `1/n`, and then the union over `n`. -/ choose T T_in_s finite_T using B, let t := ⋃n:ℕ, T n⁻¹, have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end, have T₂ : countable t := by finish [countable_Union, countable_finite], have T₃ : s ⊆ closure t, { intros x x_in_s, apply mem_closure_iff'.2, intros ε εpos, rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩, have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) := mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos), rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩, simp at Dxy, -- Dxy : edist x y < 1 / ↑n have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)), have : edist x y < ε := lt_trans Dxy hn, exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ }, have T₄ : closure t ⊆ s := calc closure t ⊆ closure s : closure_mono T₁ ... = s : closure_eq_of_is_closed (closed_of_compact _ hs), exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩ end end compact section first_countable instance (α : Type u) [emetric_space α] : topological_space.first_countable_topology α := ⟨assume a, ⟨⋃ i:ℕ, {ball a i⁻¹}, countable_Union $ assume n, countable_singleton _, suffices (⨅ i:{ i : ennreal // i > 0}, principal (ball a i)) = ⨅ (n : ℕ), principal (ball a n⁻¹), by simpa [nhds_eq, @infi_comm _ _ ℕ], begin apply le_antisymm, { refine le_infi (assume n, infi_le_of_le _ _), exact ⟨n⁻¹, by apply bot_lt_iff_ne_bot.2; simp⟩, exact le_refl _ }, refine le_infi (assume ε, _), rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 ε.2) with ⟨n, εn⟩, exact infi_le_of_le n (principal_mono.2 $ ball_subset_ball $ le_of_lt εn) end⟩⟩ end first_countable section second_countable open topological_space /-- A separable emetric space is second countable: one obtains a countable basis by taking the balls centered at points in a dense subset, and with rational radii. We do not register this as an instance, as there is already an instance going in the other direction from second countable spaces to separable spaces, and we want to avoid loops. -/ lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] : second_countable_topology α := let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ α in ⟨⟨⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, ⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}, { apply countable_bUnion S_countable, intros a aS, apply countable_Union, simp }, show uniform_space.to_topological_space α = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}), { have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u, { simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib], intros u x hx i u_ball, rw [u_ball], exact is_open_ball }, have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))), { refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _), rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩, have : ε / 2 > 0 := ennreal.half_pos εpos, /- The ball `ball a ε` is included in `u`. We need to find one of our balls `ball x (n⁻¹)` containing `a` and contained in `ball a ε`. For this, we take `n` larger than `2/ε`, and then `x` in `S` at distance at most `n⁻¹` of `a` -/ rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩, have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot], have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp, rcases mem_closure_iff'.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩, existsi ball x (↑n)⁻¹, have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc edist y a = edist a y : edist_comm _ _ ... ≤ edist a x + edist y x : edist_triangle_right _ _ _ ... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist ... < ε/2 + ε/2 : ennreal.add_lt_add εn εn ... = ε : ennreal.add_halves _, simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff], exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ }, exact B.2.2 }⟩⟩⟩ end second_countable section diam /-- The diameter of a set in an emetric space, named `emetric.diam` -/ def diam (s : set α) := Sup ((λp : α × α, edist p.1 p.2) '' (set.prod s s)) /-- If two points belong to some set, their edistance is bounded by the diameter of the set -/ lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s := le_Sup ((mem_image _ _ _).2 ⟨(⟨x, y⟩ : α × α), by simp [hx, hy]⟩) /-- 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_edist_le {d : ennreal} (h : ∀x y ∈ s, edist x y ≤ d) : diam s ≤ d := begin apply Sup_le _, simp only [and_imp, set.mem_image, set.mem_prod, exists_imp_distrib, prod.exists], assume b x y xs ys dxy, rw ← dxy, exact h x y xs ys end /-- The diameter of the empty set vanishes -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := by simp [diam] /-- The diameter of a singleton vanishes -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := by simp [diam] /-- The diameter is monotonous with respect to inclusion -/ lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t := begin refine Sup_le_Sup (λp hp, _), simp only [set.mem_image, set.mem_prod, prod.exists] at hp, rcases hp with ⟨x, y, ⟨⟨xs, ys⟩, dxy⟩⟩, exact (mem_image _ _ _).2 ⟨⟨x, y⟩, ⟨⟨h xs, h ys⟩, dxy⟩⟩ end /-- The diameter of a union is controlled by the diameter of the sets, and the edistance between two points in the sets. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t := begin have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _ ... ≤ diam s + edist x y + diam t : add_le_add' (add_le_add' (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb), refine diam_le_of_forall_edist_le (λa b ha hb, _), cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b, { calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b ... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _) ... = diam s + edist 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 [edist_comm] at Z }, { calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b ... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) } end lemma diam_union' {t : set α} (h : s ∩ t ≠ ∅) : diam (s ∪ t) ≤ diam s + diam t := let ⟨x, ⟨xs, xt⟩⟩ := ne_empty_iff_exists_mem.1 h in by simpa using diam_union xs xt lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_edist_le $ λa b ha hb, calc edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _ ... ≤ r + r : add_le_add' ha hb ... = 2 * r : by simp [mul_two, mul_comm] lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball end diam end emetric --namespace
83ea47656078a1583285c07bfd24710057084a73
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/special_functions/gaussian.lean
5825b1f8a1398a54554c95e917f386db92576796
[ "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
28,488
lean
/- Copyright (c) 2022 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.special_functions.gamma import analysis.special_functions.polar_coord import analysis.convex.complex import analysis.complex.cauchy_integral import analysis.fourier.poisson_summation /-! # Gaussian integral We prove various versions of the formula for the Gaussian integral: * `integral_gaussian`: for real `b` we have `∫ x:ℝ, exp (-b * x^2) = sqrt (π / b)`. * `integral_gaussian_complex`: for complex `b` with `0 < re b` we have `∫ x:ℝ, exp (-b * x^2) = (π / b) ^ (1 / 2)`. * `integral_gaussian_Ioi` and `integral_gaussian_complex_Ioi`: variants for integrals over `Ioi 0`. * `complex.Gamma_one_half_eq`: the formula `Γ (1 / 2) = √π`. We also prove, more generally, that the Fourier transform of the Gaussian is another Gaussian: * `integral_cexp_neg_mul_sq_add_const`: for all complex `b` and `c` with `0 < re b` we have `∫ (x : ℝ), exp (-b * (x + c) ^ 2) = (π / b) ^ (1 / 2)`. * `fourier_transform_gaussian`: for all complex `b` and `t` with `0 < re b`, we have `∫ x:ℝ, exp (I * t * x) * exp (-b * x^2) = (π / b) ^ (1 / 2) * exp (-t ^ 2 / (4 * b))`. * `fourier_transform_gaussian_pi`: a variant with `b` and `t` scaled to give a more symmetric statement, and formulated in terms of the Fourier transform operator `𝓕`. As an application, in `real.tsum_exp_neg_mul_int_sq` and `complex.tsum_exp_neg_mul_int_sq`, we use Poisson summation to prove the identity `∑' (n : ℤ), exp (-π * a * n ^ 2) = 1 / a ^ (1 / 2) * ∑' (n : ℤ), exp (-π / a * n ^ 2)` for positive real `a`, or complex `a` with positive real part. (See also `number_theory.modular_forms.jacobi_theta`.) -/ noncomputable theory open real set measure_theory filter asymptotics open_locale real topology fourier_transform open complex (hiding exp continuous_exp abs_of_nonneg sq_abs) notation `cexp` := complex.exp notation `rexp` := real.exp lemma exp_neg_mul_sq_is_o_exp_neg {b : ℝ} (hb : 0 < b) : (λ x:ℝ, exp (-b * x^2)) =o[at_top] (λ x:ℝ, exp (-x)) := begin have A : (λ (x : ℝ), -x - -b * x ^ 2) = (λ x, x * (b * x + (- 1))), by { ext x, ring }, rw [is_o_exp_comp_exp_comp, A], apply tendsto.at_top_mul_at_top tendsto_id, apply tendsto_at_top_add_const_right at_top (-1 : ℝ), exact tendsto.const_mul_at_top hb tendsto_id, end lemma rpow_mul_exp_neg_mul_sq_is_o_exp_neg {b : ℝ} (hb : 0 < b) (s : ℝ) : (λ x:ℝ, x ^ s * exp (-b * x^2)) =o[at_top] (λ x:ℝ, exp (-(1/2) * x)) := begin apply ((is_O_refl (λ x:ℝ, x ^ s) at_top).mul_is_o (exp_neg_mul_sq_is_o_exp_neg hb)).trans, convert Gamma_integrand_is_o s, simp_rw [mul_comm], end lemma integrable_on_rpow_mul_exp_neg_mul_sq {b : ℝ} (hb : 0 < b) {s : ℝ} (hs : -1 < s) : integrable_on (λ x:ℝ, x ^ s * exp (-b * x^2)) (Ioi 0) := begin rw [← Ioc_union_Ioi_eq_Ioi (zero_le_one : (0 : ℝ) ≤ 1), integrable_on_union], split, { rw [←integrable_on_Icc_iff_integrable_on_Ioc], refine integrable_on.mul_continuous_on _ _ is_compact_Icc, { refine (interval_integrable_iff_integrable_Icc_of_le zero_le_one).mp _, exact interval_integral.interval_integrable_rpow' hs }, { exact (continuous_exp.comp (continuous_const.mul (continuous_pow 2))).continuous_on } }, { have B : (0 : ℝ) < 1/2, by norm_num, apply integrable_of_is_O_exp_neg B _ (is_o.is_O (rpow_mul_exp_neg_mul_sq_is_o_exp_neg hb _)), assume x hx, have N : x ≠ 0, { refine (zero_lt_one.trans_le _).ne', exact hx }, apply ((continuous_at_rpow_const _ _ (or.inl N)).mul _).continuous_within_at, exact (continuous_exp.comp (continuous_const.mul (continuous_pow 2))).continuous_at }, end lemma integrable_rpow_mul_exp_neg_mul_sq {b : ℝ} (hb : 0 < b) {s : ℝ} (hs : -1 < s) : integrable (λ x:ℝ, x ^ s * exp (-b * x^2)) := begin rw [← integrable_on_univ, ← @Iio_union_Ici _ _ (0 : ℝ), integrable_on_union, integrable_on_Ici_iff_integrable_on_Ioi], refine ⟨_, integrable_on_rpow_mul_exp_neg_mul_sq hb hs⟩, rw ← (measure.measure_preserving_neg (volume : measure ℝ)).integrable_on_comp_preimage ((homeomorph.neg ℝ).to_measurable_equiv.measurable_embedding), simp only [function.comp, neg_sq, neg_preimage, preimage_neg_Iio, neg_neg, neg_zero], apply integrable.mono' (integrable_on_rpow_mul_exp_neg_mul_sq hb hs), { apply measurable.ae_strongly_measurable, exact (measurable_id'.neg.pow measurable_const).mul ((measurable_id'.pow measurable_const).const_mul (-b)).exp }, { have : measurable_set (Ioi (0 : ℝ)) := measurable_set_Ioi, filter_upwards [ae_restrict_mem this] with x hx, have h'x : 0 ≤ x := le_of_lt hx, rw [real.norm_eq_abs, abs_mul, abs_of_nonneg (exp_pos _).le], apply mul_le_mul_of_nonneg_right _ (exp_pos _).le, simpa [abs_of_nonneg h'x] using abs_rpow_le_abs_rpow (-x) s } end lemma integrable_exp_neg_mul_sq {b : ℝ} (hb : 0 < b) : integrable (λ x:ℝ, exp (-b * x^2)) := by simpa using integrable_rpow_mul_exp_neg_mul_sq hb (by norm_num : (-1 : ℝ) < 0) lemma integrable_on_Ioi_exp_neg_mul_sq_iff {b : ℝ} : integrable_on (λ x:ℝ, exp (-b * x^2)) (Ioi 0) ↔ 0 < b := begin refine ⟨λ h, _, λ h, (integrable_exp_neg_mul_sq h).integrable_on⟩, by_contra' hb, have : ∫⁻ x:ℝ in Ioi 0, 1 ≤ ∫⁻ x:ℝ in Ioi 0, ‖exp (-b * x^2)‖₊, { apply lintegral_mono (λ x, _), simp only [neg_mul, ennreal.one_le_coe_iff, ← to_nnreal_one, to_nnreal_le_iff_le_coe, real.norm_of_nonneg (exp_pos _).le, coe_nnnorm, one_le_exp_iff, right.nonneg_neg_iff], exact mul_nonpos_of_nonpos_of_nonneg hb (sq_nonneg _) }, simpa using this.trans_lt h.2, end lemma integrable_exp_neg_mul_sq_iff {b : ℝ} : integrable (λ x:ℝ, exp (-b * x^2)) ↔ 0 < b := ⟨λ h, integrable_on_Ioi_exp_neg_mul_sq_iff.mp h.integrable_on, integrable_exp_neg_mul_sq⟩ lemma integrable_mul_exp_neg_mul_sq {b : ℝ} (hb : 0 < b) : integrable (λ x:ℝ, x * exp (-b * x^2)) := by simpa using integrable_rpow_mul_exp_neg_mul_sq hb (by norm_num : (-1 : ℝ) < 1) lemma norm_cexp_neg_mul_sq (b : ℂ) (x : ℝ) : ‖complex.exp (-b * x^2)‖ = exp (-b.re * x^2) := by rw [complex.norm_eq_abs, complex.abs_exp, ←of_real_pow, mul_comm (-b) _, of_real_mul_re, neg_re, mul_comm] lemma integrable_cexp_neg_mul_sq {b : ℂ} (hb : 0 < b.re) : integrable (λ x:ℝ, cexp (-b * x^2)) := begin refine ⟨(complex.continuous_exp.comp (continuous_const.mul (continuous_of_real.pow 2))).ae_strongly_measurable, _⟩, rw ←has_finite_integral_norm_iff, simp_rw norm_cexp_neg_mul_sq, exact (integrable_exp_neg_mul_sq hb).2, end lemma integrable_mul_cexp_neg_mul_sq {b : ℂ} (hb : 0 < b.re) : integrable (λ x:ℝ, ↑x * cexp (-b * x^2)) := begin refine ⟨(continuous_of_real.mul (complex.continuous_exp.comp _)).ae_strongly_measurable, _⟩, { exact continuous_const.mul (continuous_of_real.pow 2) }, have := (integrable_mul_exp_neg_mul_sq hb).has_finite_integral, rw ←has_finite_integral_norm_iff at this ⊢, convert this, ext1 x, rw [norm_mul, norm_mul, norm_cexp_neg_mul_sq b, complex.norm_eq_abs, abs_of_real, real.norm_eq_abs, norm_of_nonneg (exp_pos _).le], end lemma integral_mul_cexp_neg_mul_sq {b : ℂ} (hb : 0 < b.re) : ∫ r:ℝ in Ioi 0, (r : ℂ) * cexp (-b * r ^ 2) = (2 * b)⁻¹ := begin have hb' : b ≠ 0 := by { contrapose! hb, rw [hb, zero_re], }, have A : ∀ x:ℂ, has_deriv_at (λ x, - (2 * b)⁻¹ * cexp (-b * x^2)) (x * cexp (- b * x^2)) x, { intro x, convert (((has_deriv_at_pow 2 x)).const_mul (-b)).cexp.const_mul (- (2 * b)⁻¹) using 1, field_simp [hb'], ring }, have B : tendsto (λ (y : ℝ), -(2 * b)⁻¹ * cexp (-b * ↑y ^ 2)) at_top (𝓝 (-(2 * b)⁻¹ * 0)), { refine (tendsto.const_mul _ (tendsto_zero_iff_norm_tendsto_zero.mpr _)), simp_rw norm_cexp_neg_mul_sq b, exact tendsto_exp_at_bot.comp (tendsto.neg_const_mul_at_top (neg_lt_zero.2 hb) (tendsto_pow_at_top two_ne_zero)) }, convert integral_Ioi_of_has_deriv_at_of_tendsto' (λ x hx, (A ↑x).comp_of_real) (integrable_mul_cexp_neg_mul_sq hb).integrable_on B, simp only [mul_zero, of_real_zero, zero_pow', ne.def, bit0_eq_zero, nat.one_ne_zero, not_false_iff, complex.exp_zero, mul_one, sub_neg_eq_add, zero_add], end /-- The *square* of the Gaussian integral `∫ x:ℝ, exp (-b * x^2)` is equal to `π / b`. -/ lemma integral_gaussian_sq_complex {b : ℂ} (hb : 0 < b.re) : (∫ x:ℝ, cexp (-b * x^2)) ^ 2 = π / b := begin /- We compute `(∫ exp (-b x^2))^2` as an integral over `ℝ^2`, and then make a polar change of coordinates. We are left with `∫ r * exp (-b r^2)`, which has been computed in `integral_mul_cexp_neg_mul_sq` using the fact that this function has an obvious primitive. -/ calc (∫ x:ℝ, cexp (-b * (x:ℂ)^2)) ^ 2 = ∫ p : ℝ × ℝ, cexp (-b * ((p.1) : ℂ) ^ 2) * cexp (-b * ((p.2) : ℂ) ^ 2) : by { rw [pow_two, ← integral_prod_mul], refl } ... = ∫ p : ℝ × ℝ, cexp (- b * (p.1 ^ 2 + p.2 ^ 2)) : by { congr, ext1 p, rw [← complex.exp_add, mul_add], } ... = ∫ p in polar_coord.target, (p.1) • cexp (- b * ((p.1 * cos p.2) ^ 2 + (p.1 * sin p.2)^2)) : begin rw ← integral_comp_polar_coord_symm, simp only [polar_coord_symm_apply, of_real_mul, of_real_cos, of_real_sin], end ... = (∫ r in Ioi (0 : ℝ), r * cexp (-b * r^2)) * (∫ θ in Ioo (-π) π, 1) : begin rw ← set_integral_prod_mul, congr' with p : 1, rw mul_one, congr, conv_rhs { rw [← one_mul ((p.1 : ℂ)^2), ← sin_sq_add_cos_sq (p.2 : ℂ)], }, ring_exp, end ... = ↑π / b : begin have : 0 ≤ π + π, by linarith [real.pi_pos], simp only [integral_const, measure.restrict_apply', measurable_set_Ioo, univ_inter, volume_Ioo, sub_neg_eq_add, ennreal.to_real_of_real, this], rw [←two_mul, real_smul, mul_one, of_real_mul, of_real_bit0, of_real_one, integral_mul_cexp_neg_mul_sq hb], field_simp [(by { contrapose! hb, rw [hb, zero_re] } : b ≠ 0)], ring, end end theorem integral_gaussian (b : ℝ) : ∫ x, exp (-b * x^2) = sqrt (π / b) := begin /- First we deal with the crazy case where `b ≤ 0`: then both sides vanish. -/ rcases le_or_lt b 0 with hb|hb, { rw [integral_undef, sqrt_eq_zero_of_nonpos], { exact div_nonpos_of_nonneg_of_nonpos pi_pos.le hb }, { simpa only [not_lt, integrable_exp_neg_mul_sq_iff] using hb } }, /- Assume now `b > 0`. Then both sides are non-negative and their squares agree. -/ refine (sq_eq_sq _ (sqrt_nonneg _)).1 _, { exact integral_nonneg (λ x, (exp_pos _).le) }, rw [←of_real_inj, of_real_pow, ←integral_of_real, sq_sqrt (div_pos pi_pos hb).le, of_real_div], convert integral_gaussian_sq_complex (by rwa of_real_re : 0 < (b:ℂ).re), ext1 x, rw [of_real_exp, of_real_mul, of_real_pow, of_real_neg], end lemma continuous_at_gaussian_integral (b : ℂ) (hb : 0 < re b) : continuous_at (λ c:ℂ, ∫ x:ℝ, cexp (-c * x^2)) b := begin let f : ℂ → ℝ → ℂ := λ (c : ℂ) (x : ℝ), cexp (-c * x ^ 2), obtain ⟨d, hd, hd'⟩ := exists_between hb, have f_meas : ∀ (c:ℂ), ae_strongly_measurable (f c) volume := λ c, by { apply continuous.ae_strongly_measurable, exact complex.continuous_exp.comp (continuous_const.mul (continuous_of_real.pow 2)) }, have f_int : integrable (f b) volume, { simp_rw [←integrable_norm_iff (f_meas b), norm_cexp_neg_mul_sq b], exact integrable_exp_neg_mul_sq hb, }, have f_cts : ∀ (x : ℝ), continuous_at (λ c, f c x) b := λ x, (complex.continuous_exp.comp (continuous_id'.neg.mul continuous_const)).continuous_at, have f_le_bd : ∀ᶠ (c : ℂ) in 𝓝 b, ∀ᵐ (x : ℝ), ‖f c x‖ ≤ exp (-d * x ^ 2), { refine eventually_of_mem ((continuous_re.is_open_preimage _ is_open_Ioi).mem_nhds hd') _, refine λ c hc, ae_of_all _ (λ x, _), rw [norm_cexp_neg_mul_sq, exp_le_exp], exact mul_le_mul_of_nonneg_right (neg_le_neg (le_of_lt hc)) (sq_nonneg _) }, exact continuous_at_of_dominated (eventually_of_forall f_meas) f_le_bd (integrable_exp_neg_mul_sq hd) (ae_of_all _ f_cts), end theorem integral_gaussian_complex {b : ℂ} (hb : 0 < re b) : ∫ x:ℝ, cexp (-b * x^2) = (π / b) ^ (1 / 2 : ℂ) := begin have nv : ∀ {b : ℂ}, (0 < re b) → (b ≠ 0), { intros b hb, contrapose! hb, rw hb, simp }, refine (convex_halfspace_re_gt 0).is_preconnected.eq_of_sq_eq _ _ (λ c hc, _) (λ c hc, _) (by simp : 0 < re (1 : ℂ)) _ hb, { -- integral is continuous exact continuous_at.continuous_on continuous_at_gaussian_integral, }, { -- `(π / b) ^ (1 / 2 : ℂ)` is continuous refine continuous_at.continuous_on (λ b hb, (continuous_at_cpow_const (or.inl _)).comp (continuous_at_const.div continuous_at_id (nv hb))), rw [div_re, of_real_im, of_real_re, zero_mul, zero_div, add_zero], exact div_pos (mul_pos pi_pos hb) (norm_sq_pos.mpr (nv hb)), }, { -- squares of both sides agree dsimp only [pi.pow_apply], rw [integral_gaussian_sq_complex hc, sq], conv_lhs { rw ←cpow_one (↑π / c)}, rw ← cpow_add _ _ (div_ne_zero (of_real_ne_zero.mpr pi_ne_zero) (nv hc)), norm_num }, { -- RHS doesn't vanish rw [ne.def, cpow_eq_zero_iff, not_and_distrib], exact or.inl (div_ne_zero (of_real_ne_zero.mpr pi_ne_zero) (nv hc)) }, { -- equality at 1 have : ∀ (x : ℝ), cexp (-1 * x ^ 2) = exp (-1 * x ^ 2), { intro x, simp only [of_real_exp, neg_mul, one_mul, of_real_neg, of_real_pow] }, simp_rw [this, integral_of_real], conv_rhs { congr, rw [←of_real_one, ←of_real_div], skip, rw [←of_real_one, ←of_real_bit0, ←of_real_div] }, rw [←of_real_cpow, of_real_inj], convert integral_gaussian (1 : ℝ), { rwa [sqrt_eq_rpow] }, { rw [div_one], exact pi_pos.le } }, end /- The Gaussian integral on the half-line, `∫ x in Ioi 0, exp (-b * x^2)`, for complex `b`. -/ lemma integral_gaussian_complex_Ioi {b : ℂ} (hb : 0 < re b) : ∫ x:ℝ in Ioi 0, cexp (-b * x^2) = (π / b) ^ (1 / 2 : ℂ) / 2 := begin have full_integral := integral_gaussian_complex hb, have : measurable_set (Ioi (0:ℝ)) := measurable_set_Ioi, rw [←integral_add_compl this (integrable_cexp_neg_mul_sq hb), compl_Ioi] at full_integral, suffices : ∫ x:ℝ in Iic 0, cexp (-b * x^2) = ∫ x:ℝ in Ioi 0, cexp (-b * x^2), { rw [this, ←mul_two] at full_integral, rwa eq_div_iff, exact two_ne_zero }, have : ∀ (c : ℝ), ∫ x in 0 .. c, cexp (-b * x^2) = ∫ x in -c .. 0, cexp (-b * x^2), { intro c, have := @interval_integral.integral_comp_sub_left _ _ _ _ 0 c (λ x, cexp (-b * x^2)) 0, simpa [zero_sub, neg_sq, neg_zero] using this }, have t1 := interval_integral_tendsto_integral_Ioi _ ((integrable_cexp_neg_mul_sq hb).integrable_on) tendsto_id, have t2 : tendsto (λ c:ℝ, ∫ x:ℝ in 0..c, cexp (-b * x^2)) at_top (𝓝 ∫ x:ℝ in Iic 0, cexp (-b * x^2)), { simp_rw this, refine interval_integral_tendsto_integral_Iic _ _ tendsto_neg_at_top_at_bot, apply (integrable_cexp_neg_mul_sq hb).integrable_on }, exact tendsto_nhds_unique t2 t1, end /- The Gaussian integral on the half-line, `∫ x in Ioi 0, exp (-b * x^2)`, for real `b`. -/ lemma integral_gaussian_Ioi (b : ℝ) : ∫ x in Ioi 0, exp (-b * x^2) = sqrt (π / b) / 2 := begin rcases le_or_lt b 0 with hb|hb, { rw [integral_undef, sqrt_eq_zero_of_nonpos, zero_div], exact div_nonpos_of_nonneg_of_nonpos pi_pos.le hb, rwa [←integrable_on, integrable_on_Ioi_exp_neg_mul_sq_iff, not_lt] }, rw [←of_real_inj, ←integral_of_real], convert integral_gaussian_complex_Ioi (by rwa of_real_re : 0 < (b:ℂ).re), { ext1 x, simp, }, { rw [sqrt_eq_rpow, ←of_real_div, of_real_div, of_real_cpow], norm_num, exact (div_pos pi_pos hb).le, } end /-- The special-value formula `Γ(1/2) = √π`, which is equivalent to the Gaussian integral. -/ lemma real.Gamma_one_half_eq : real.Gamma (1 / 2) = sqrt π := begin rw [Gamma_eq_integral one_half_pos, ←integral_comp_rpow_Ioi_of_pos zero_lt_two], convert congr_arg (λ x:ℝ, 2 * x) (integral_gaussian_Ioi 1), { rw ←integral_mul_left, refine set_integral_congr measurable_set_Ioi (λ x hx, _), dsimp only, have : (x ^ (2:ℝ)) ^ (1 / (2:ℝ) - 1) = x⁻¹, { rw ←rpow_mul (le_of_lt hx), norm_num, rw [rpow_neg (le_of_lt hx), rpow_one] }, rw [smul_eq_mul, this], field_simp [(ne_of_lt hx).symm], norm_num, ring }, { rw [div_one, ←mul_div_assoc, mul_comm, mul_div_cancel _ (two_ne_zero' ℝ)], } end /-- The special-value formula `Γ(1/2) = √π`, which is equivalent to the Gaussian integral. -/ lemma complex.Gamma_one_half_eq : complex.Gamma (1 / 2) = π ^ (1 / 2 : ℂ) := begin convert congr_arg coe real.Gamma_one_half_eq, { simpa only [one_div, of_real_inv, of_real_bit0] using Gamma_of_real (1 / 2)}, { rw [sqrt_eq_rpow, of_real_cpow pi_pos.le, of_real_div, of_real_bit0, of_real_one] } end namespace gaussian_fourier /-! ## Fourier transform of the Gaussian integral -/ open interval_integral open_locale real variables {b : ℂ} /-- The integral of the Gaussian function over the vertical edges of a rectangle with vertices at `(±T, 0)` and `(±T, c)`. -/ def vertical_integral (b : ℂ) (c T : ℝ) : ℂ := ∫ (y : ℝ) in 0..c, I * (cexp (-b * (T + y * I) ^ 2) - cexp (-b * (T - y * I) ^ 2)) /-- Explicit formula for the norm of the Gaussian function along the vertical edges. -/ lemma norm_cexp_neg_mul_sq_add_mul_I (b : ℂ) (c T : ℝ) : ‖cexp (-b * (T + c * I) ^ 2)‖ = exp (-(b.re * T ^ 2 - 2 * b.im * c * T - b.re * c ^ 2)) := begin rw [complex.norm_eq_abs, complex.abs_exp, neg_mul, neg_re, ←re_add_im b], simp only [sq, re_add_im, mul_re, mul_im, add_re, add_im, of_real_re, of_real_im, I_re, I_im], ring_nf, end lemma norm_cexp_neg_mul_sq_add_mul_I' (hb : b.re ≠ 0) (c T : ℝ) : ‖cexp (-b * (T + c * I) ^ 2)‖ = exp (-(b.re * (T - b.im * c / b.re) ^ 2 - c ^ 2 * (b.im ^ 2 / b.re + b.re))) := begin have : (b.re * T ^ 2 - 2 * b.im * c * T - b.re * c ^ 2) = b.re * (T - b.im * c / b.re) ^ 2 - c ^ 2 * (b.im ^ 2 / b.re + b.re), { field_simp, ring }, rw [norm_cexp_neg_mul_sq_add_mul_I, this], end lemma vertical_integral_norm_le (hb : 0 < b.re) (c : ℝ) {T : ℝ} (hT : 0 ≤ T) : ‖vertical_integral b c T‖ ≤ 2 * |c| * exp (-(b.re * T ^ 2 - 2 * |b.im| * |c| * T - b.re * c ^ 2)) := begin -- first get uniform bound for integrand have vert_norm_bound : ∀ {T : ℝ}, 0 ≤ T → ∀ {c y : ℝ}, |y| ≤ |c| → ‖cexp (-b * (T + y * I) ^ 2)‖ ≤ exp (-(b.re * T ^ 2 - 2 * |b.im| * |c| * T - b.re * c ^ 2)), { intros T hT c y hy, rw [norm_cexp_neg_mul_sq_add_mul_I b, exp_le_exp, neg_le_neg_iff], refine sub_le_sub (sub_le_sub (le_refl _) (mul_le_mul_of_nonneg_right _ hT)) _, { conv_lhs {rw mul_assoc}, conv_rhs {rw mul_assoc}, refine mul_le_mul_of_nonneg_left ((le_abs_self _).trans _) zero_le_two, rw abs_mul, exact mul_le_mul_of_nonneg_left hy (abs_nonneg _), }, { refine mul_le_mul_of_nonneg_left _ hb.le, rwa sq_le_sq, } }, -- now main proof refine (interval_integral.norm_integral_le_of_norm_le_const _).trans _, swap 3, { rw sub_zero, conv_lhs { rw mul_comm }, conv_rhs { conv { congr, rw mul_comm }, rw mul_assoc } }, { intros y hy, have absy : |y| ≤ |c|, { rcases le_or_lt 0 c, { rw uIoc_of_le h at hy, rw [abs_of_nonneg h, abs_of_pos hy.1], exact hy.2, }, { rw uIoc_of_lt h at hy, rw [abs_of_neg h, abs_of_nonpos hy.2, neg_le_neg_iff], exact hy.1.le } }, rw [norm_mul, complex.norm_eq_abs, abs_I, one_mul, two_mul], refine (norm_sub_le _ _).trans (add_le_add (vert_norm_bound hT absy) _), rw ←abs_neg y at absy, simpa only [neg_mul, of_real_neg] using vert_norm_bound hT absy }, end lemma tendsto_vertical_integral (hb : 0 < b.re) (c : ℝ) : tendsto (vertical_integral b c) at_top (𝓝 0) := begin -- complete proof using squeeze theorem: rw tendsto_zero_iff_norm_tendsto_zero, refine tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds _ (eventually_of_forall (λ _, norm_nonneg _)) ((eventually_ge_at_top (0:ℝ)).mp (eventually_of_forall (λ T hT, vertical_integral_norm_le hb c hT))), rw (by ring : 0 = 2 * |c| * 0), refine (tendsto_exp_at_bot.comp (tendsto_neg_at_top_at_bot.comp _)).const_mul _ , apply tendsto_at_top_add_const_right, simp_rw [sq, ←mul_assoc, ←sub_mul], refine tendsto.at_top_mul_at_top (tendsto_at_top_add_const_right _ _ _) tendsto_id, exact (tendsto_const_mul_at_top_of_pos hb).mpr tendsto_id, end lemma integrable_cexp_neg_mul_sq_add_real_mul_I (hb : 0 < b.re) (c : ℝ) : integrable (λ (x : ℝ), cexp (-b * (x + c * I) ^ 2)) := begin refine ⟨(complex.continuous_exp.comp (continuous_const.mul ((continuous_of_real.add continuous_const).pow 2))).ae_strongly_measurable, _⟩, rw ←has_finite_integral_norm_iff, simp_rw [norm_cexp_neg_mul_sq_add_mul_I' hb.ne', neg_sub _ (c ^ 2 * _), sub_eq_add_neg _ (b.re * _), real.exp_add], suffices : integrable (λ (x : ℝ), exp (-(b.re * x ^ 2))), { exact (integrable.comp_sub_right this (b.im * c / b.re)).has_finite_integral.const_mul _, }, simp_rw ←neg_mul, apply integrable_exp_neg_mul_sq hb, end lemma integral_cexp_neg_mul_sq_add_real_mul_I (hb : 0 < b.re) (c : ℝ) : ∫ (x : ℝ), cexp (-b * (x + c * I) ^ 2) = (π / b) ^ (1 / 2 : ℂ) := begin refine tendsto_nhds_unique (interval_integral_tendsto_integral (integrable_cexp_neg_mul_sq_add_real_mul_I hb c) tendsto_neg_at_top_at_bot tendsto_id) _, set I₁ := (λ T, ∫ (x : ℝ) in -T..T, cexp (-b * (x + c * I) ^ 2)) with HI₁, let I₂ := λ (T : ℝ), ∫ (x : ℝ) in -T..T, cexp (-b * x ^ 2), let I₄ := λ (T : ℝ), ∫ (y : ℝ) in 0..c, cexp (-b * (T + y * I) ^ 2), let I₅ := λ (T : ℝ), ∫ (y : ℝ) in 0..c, cexp (-b * (-T + y * I) ^ 2), have C : ∀ (T : ℝ), I₂ T - I₁ T + I * I₄ T - I * I₅ T = 0, { assume T, have := integral_boundary_rect_eq_zero_of_differentiable_on (λ z, cexp (-b * z ^ 2)) (-T) (T + c * I) (by { refine differentiable.differentiable_on (differentiable.const_mul _ _).cexp, exact differentiable_pow 2, }), simpa only [neg_im, of_real_im, neg_zero, of_real_zero, zero_mul, add_zero, neg_re, of_real_re, add_re, mul_re, I_re, mul_zero, I_im, tsub_zero, add_im, mul_im, mul_one, zero_add, algebra.id.smul_eq_mul, of_real_neg] using this }, simp_rw [id.def, ←HI₁], have : I₁ = λ (T : ℝ), I₂ T + vertical_integral b c T, { ext1 T, specialize C T, rw sub_eq_zero at C, unfold vertical_integral, rw [integral_const_mul, interval_integral.integral_sub], { simp_rw (λ a b, by { rw sq, ring_nf } : ∀ (a b : ℂ), (a - b * I)^2 = (- a + b * I)^2), change I₁ T = I₂ T + I * (I₄ T - I₅ T), rw [mul_sub, ←C], abel }, all_goals { apply continuous.interval_integrable, continuity }, }, rw [this, ←add_zero ((π / b : ℂ) ^ (1 / 2 : ℂ)), ←integral_gaussian_complex hb], refine tendsto.add _ (tendsto_vertical_integral hb c), exact interval_integral_tendsto_integral (integrable_cexp_neg_mul_sq hb) tendsto_neg_at_top_at_bot tendsto_id, end lemma _root_.integral_cexp_neg_mul_sq_add_const (hb : 0 < b.re) (c : ℂ) : ∫ (x : ℝ), cexp (-b * (x + c) ^ 2) = (π / b) ^ (1 / 2 : ℂ) := begin rw ←re_add_im c, simp_rw [←add_assoc, ←of_real_add], rw integral_add_right_eq_self (λ(x : ℝ), cexp (-b * (↑x + ↑(c.im) * I) ^ 2)), { apply integral_cexp_neg_mul_sq_add_real_mul_I hb }, { apply_instance }, end lemma _root_.fourier_transform_gaussian (hb : 0 < b.re) (t : ℂ) : ∫ (x : ℝ), cexp (I * t * x) * cexp (-b * x ^ 2) = cexp (-t^2 / (4 * b)) * (π / b) ^ (1 / 2 : ℂ) := begin have : b ≠ 0, { contrapose! hb, rw [hb, zero_re] }, simp_rw [←complex.exp_add], have : ∀ (x : ℂ), I * t * x + (-b * x ^ 2) = -t ^ 2 / (4 * b) + -b * (x + (-I * t / 2 / b)) ^ 2, { intro x, ring_nf SOP, rw I_sq, field_simp, ring }, simp_rw [this, complex.exp_add, integral_mul_left, integral_cexp_neg_mul_sq_add_const hb] end lemma _root_.fourier_transform_gaussian_pi (hb : 0 < b.re) : 𝓕 (λ x : ℝ, cexp (-π * b * x ^ 2)) = λ t : ℝ, 1 / b ^ (1 / 2 : ℂ) * cexp (-π / b * t ^ 2) := begin ext1 t, simp_rw [fourier_integral_eq_integral_exp_smul, smul_eq_mul], have h1 : 0 < re (π * b) := by { rw of_real_mul_re, exact mul_pos pi_pos hb }, have h2 : b ≠ 0 := by { contrapose! hb, rw [hb, zero_re], }, convert _root_.fourier_transform_gaussian h1 (-2 * π * t) using 1, { congr' 1 with x:1, congr' 2, all_goals { push_cast, ring } }, { conv_lhs { rw mul_comm }, congr' 2, { field_simp [of_real_ne_zero.mpr pi_ne_zero], ring, }, { rw [←div_div, div_self (of_real_ne_zero.mpr pi_ne_zero), one_div, one_div b, inv_cpow], rw [ne.def, arg_eq_pi_iff, not_and_distrib, not_lt], exact or.inl hb.le } }, end end gaussian_fourier section gaussian_poisson /-! ## Poisson summation applied to the Gaussian -/ variables {E : Type*} [normed_add_comm_group E] lemma tendsto_rpow_abs_mul_exp_neg_mul_sq_cocompact {a : ℝ} (ha : 0 < a) (s : ℝ) : tendsto (λ x : ℝ, |x| ^ s * rexp (-a * x ^ 2)) (cocompact ℝ) (𝓝 0) := begin conv in (rexp _) { rw ←sq_abs }, rw [cocompact_eq, ←comap_abs_at_top, @tendsto_comap'_iff _ _ _ (λ y, y ^ s * rexp (-a * y ^ 2)) _ _ _ (mem_at_top_sets.mpr ⟨0, λ b hb, ⟨b, abs_of_nonneg hb⟩⟩)], exact (rpow_mul_exp_neg_mul_sq_is_o_exp_neg ha s).tendsto_zero_of_tendsto (tendsto_exp_at_bot.comp $ tendsto_id.neg_const_mul_at_top (neg_lt_zero.mpr one_half_pos)), end lemma is_o_exp_neg_mul_sq_cocompact {a : ℂ} (ha : 0 < a.re) (s : ℝ) : (λ x : ℝ, complex.exp (-a * x ^ 2)) =o[cocompact ℝ] (λ x : ℝ, |x| ^ s) := begin rw ←is_o_norm_left, simp_rw norm_cexp_neg_mul_sq, apply is_o_of_tendsto', { refine eventually.filter_mono cocompact_le_cofinite _, refine (eventually_cofinite_ne 0).mp (eventually_of_forall (λ x hx h, _)), exact ((rpow_pos_of_pos (abs_pos.mpr hx) _).ne' h).elim }, { refine tendsto.congr' (eventually.filter_mono cocompact_le_cofinite _) (tendsto_zero_iff_norm_tendsto_zero.mp $ tendsto_rpow_abs_mul_exp_neg_mul_sq_cocompact ha (-s)), refine (eventually_cofinite_ne 0).mp (eventually_of_forall (λ x hx, _)), rw [norm_mul, norm_of_nonneg (rpow_nonneg_of_nonneg (abs_nonneg _) _), mul_comm, rpow_neg (abs_nonneg x), div_eq_mul_inv, norm_of_nonneg (exp_pos _).le] }, end lemma complex.tsum_exp_neg_mul_int_sq {a : ℂ} (ha : 0 < a.re) : ∑' (n : ℤ), cexp (-π * a * n ^ 2) = 1 / a ^ (1 / 2 : ℂ) * ∑' (n : ℤ), cexp (-π / a * n ^ 2) := begin let f := λ x : ℝ, cexp (-π * a * x ^ 2), have h1 : 0 < (↑π * a).re, { rw [of_real_mul_re], exact mul_pos pi_pos ha }, have h2 : 0 < (↑π / a).re, { rw [div_eq_mul_inv, of_real_mul_re, inv_re], refine mul_pos pi_pos (div_pos ha $ norm_sq_pos.mpr _), contrapose! ha, rw [ha, zero_re] }, have f_bd : f =O[cocompact ℝ] (λ x, |x| ^ (-2 : ℝ)), { convert (is_o_exp_neg_mul_sq_cocompact h1 _).is_O, ext1 x, dsimp only [f], congr' 1, ring }, have Ff_bd : 𝓕 f =O[cocompact ℝ] (λ x, |x| ^ (-2 : ℝ)), { rw fourier_transform_gaussian_pi ha, convert (is_o_exp_neg_mul_sq_cocompact h2 _).is_O.const_mul_left _, ext1 x, congr' 1, ring_nf }, simpa only [fourier_transform_gaussian_pi ha, tsum_mul_left] using real.tsum_eq_tsum_fourier_integral_of_rpow_decay (complex.continuous_exp.comp (continuous_const.mul (continuous_of_real.pow 2)) : continuous f) one_lt_two f_bd Ff_bd end lemma real.tsum_exp_neg_mul_int_sq {a : ℝ} (ha : 0 < a) : ∑' (n : ℤ), exp (-π * a * n ^ 2) = 1 / a ^ (1 / 2 : ℝ) * ∑' (n : ℤ), exp (-π / a * n ^ 2) := by simpa only [←of_real_inj, of_real_mul, of_real_tsum, of_real_exp, of_real_div, of_real_pow, of_real_int_cast, of_real_neg, of_real_cpow ha.le, of_real_bit0, of_real_one] using complex.tsum_exp_neg_mul_int_sq (by rwa [of_real_re] : 0 < (a : ℂ).re) end gaussian_poisson
ba557be24399aafe5db06723ed2294a6937db683
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/direct_sum/basic.lean
7169e3051b4400a01d17b499559ac342561fe2b1
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
11,081
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 data.dfinsupp.basic import group_theory.submonoid.operations import group_theory.subgroup.basic /-! # Direct sum This file defines the direct sum of abelian groups, indexed by a discrete type. ## Notation `⨁ i, β i` is the n-ary direct sum `direct_sum`. This notation is in the `direct_sum` locale, accessible after `open_locale direct_sum`. ## References * https://en.wikipedia.org/wiki/Direct_sum -/ open_locale big_operators universes u v w u₁ variables (ι : Type v) [dec_ι : decidable_eq ι] (β : ι → Type w) /-- `direct_sum β` is the direct sum of a family of additive commutative monoids `β i`. Note: `open_locale direct_sum` will enable the notation `⨁ i, β i` for `direct_sum β`. -/ @[derive [add_comm_monoid, inhabited]] def direct_sum [Π i, add_comm_monoid (β i)] : Type* := Π₀ i, β i instance [Π i, add_comm_monoid (β i)] : has_coe_to_fun (direct_sum ι β) (λ _, Π i : ι, β i) := dfinsupp.has_coe_to_fun localized "notation (name := direct_sum) `⨁` binders `, ` r:(scoped f, direct_sum _ f) := r" in direct_sum namespace direct_sum variables {ι} section add_comm_group variables [Π i, add_comm_group (β i)] instance : add_comm_group (direct_sum ι β) := dfinsupp.add_comm_group variables {β} @[simp] lemma sub_apply (g₁ g₂ : ⨁ i, β i) (i : ι) : (g₁ - g₂) i = g₁ i - g₂ i := rfl end add_comm_group variables [Π i, add_comm_monoid (β i)] @[simp] lemma zero_apply (i : ι) : (0 : ⨁ i, β i) i = 0 := rfl variables {β} @[simp] lemma add_apply (g₁ g₂ : ⨁ i, β i) (i : ι) : (g₁ + g₂) i = g₁ i + g₂ i := rfl variables (β) include dec_ι /-- `mk β s x` is the element of `⨁ i, β i` that is zero outside `s` and has coefficient `x i` for `i` in `s`. -/ def mk (s : finset ι) : (Π i : (↑s : set ι), β i.1) →+ ⨁ i, β i := { to_fun := dfinsupp.mk s, map_add' := λ _ _, dfinsupp.mk_add, map_zero' := dfinsupp.mk_zero, } /-- `of i` is the natural inclusion map from `β i` to `⨁ i, β i`. -/ def of (i : ι) : β i →+ ⨁ i, β i := dfinsupp.single_add_hom β i @[simp] lemma of_eq_same (i : ι) (x : β i) : (of _ i x) i = x := dfinsupp.single_eq_same lemma of_eq_of_ne (i j : ι) (x : β i) (h : i ≠ j) : (of _ i x) j = 0 := dfinsupp.single_eq_of_ne h @[simp] lemma support_zero [Π (i : ι) (x : β i), decidable (x ≠ 0)] : (0 : ⨁ i, β i).support = ∅ := dfinsupp.support_zero @[simp] lemma support_of [Π (i : ι) (x : β i), decidable (x ≠ 0)] (i : ι) (x : β i) (h : x ≠ 0) : (of _ i x).support = {i} := dfinsupp.support_single_ne_zero h lemma support_of_subset [Π (i : ι) (x : β i), decidable (x ≠ 0)] {i : ι} {b : β i} : (of _ i b).support ⊆ {i} := dfinsupp.support_single_subset lemma sum_support_of [Π (i : ι) (x : β i), decidable (x ≠ 0)] (x : ⨁ i, β i) : ∑ i in x.support, of β i (x i) = x := dfinsupp.sum_single variables {β} theorem mk_injective (s : finset ι) : function.injective (mk β s) := dfinsupp.mk_injective s theorem of_injective (i : ι) : function.injective (of β i) := dfinsupp.single_injective @[elab_as_eliminator] protected theorem induction_on {C : (⨁ i, β i) → Prop} (x : ⨁ i, β i) (H_zero : C 0) (H_basic : ∀ (i : ι) (x : β i), C (of β i x)) (H_plus : ∀ x y, C x → C y → C (x + y)) : C x := begin apply dfinsupp.induction x H_zero, intros i b f h1 h2 ih, solve_by_elim end /-- If two additive homomorphisms from `⨁ i, β i` are equal on each `of β i y`, then they are equal. -/ lemma add_hom_ext {γ : Type*} [add_monoid γ] ⦃f g : (⨁ i, β i) →+ γ⦄ (H : ∀ (i : ι) (y : β i), f (of _ i y) = g (of _ i y)) : f = g := dfinsupp.add_hom_ext H /-- If two additive homomorphisms from `⨁ i, β i` are equal on each `of β i y`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma add_hom_ext' {γ : Type*} [add_monoid γ] ⦃f g : (⨁ i, β i) →+ γ⦄ (H : ∀ (i : ι), f.comp (of _ i) = g.comp (of _ i)) : f = g := add_hom_ext $ λ i, add_monoid_hom.congr_fun $ H i variables {γ : Type u₁} [add_comm_monoid γ] section to_add_monoid variables (φ : Π i, β i →+ γ) (ψ : (⨁ i, β i) →+ γ) /-- `to_add_monoid φ` is the natural homomorphism from `⨁ i, β i` to `γ` induced by a family `φ` of homomorphisms `β i → γ`. -/ def to_add_monoid : (⨁ i, β i) →+ γ := (dfinsupp.lift_add_hom φ) @[simp] lemma to_add_monoid_of (i) (x : β i) : to_add_monoid φ (of β i x) = φ i x := dfinsupp.lift_add_hom_apply_single φ i x theorem to_add_monoid.unique (f : ⨁ i, β i) : ψ f = to_add_monoid (λ i, ψ.comp (of β i)) f := by {congr, ext, simp [to_add_monoid, of]} end to_add_monoid section from_add_monoid /-- `from_add_monoid φ` is the natural homomorphism from `γ` to `⨁ i, β i` induced by a family `φ` of homomorphisms `γ → β i`. Note that this is not an isomorphism. Not every homomorphism `γ →+ ⨁ i, β i` arises in this way. -/ def from_add_monoid : (⨁ i, γ →+ β i) →+ (γ →+ ⨁ i, β i) := to_add_monoid $ λ i, add_monoid_hom.comp_hom (of β i) @[simp] lemma from_add_monoid_of (i : ι) (f : γ →+ β i) : from_add_monoid (of _ i f) = (of _ i).comp f := by { rw [from_add_monoid, to_add_monoid_of], refl } lemma from_add_monoid_of_apply (i : ι) (f : γ →+ β i) (x : γ) : from_add_monoid (of _ i f) x = of _ i (f x) := by rw [from_add_monoid_of, add_monoid_hom.coe_comp] end from_add_monoid variables (β) /-- `set_to_set β S T h` is the natural homomorphism `⨁ (i : S), β i → ⨁ (i : T), β i`, where `h : S ⊆ T`. -/ -- TODO: generalize this to remove the assumption `S ⊆ T`. def set_to_set (S T : set ι) (H : S ⊆ T) : (⨁ (i : S), β i) →+ (⨁ (i : T), β i) := to_add_monoid $ λ i, of (λ (i : subtype T), β i) ⟨↑i, H i.prop⟩ variables {β} omit dec_ι instance unique [∀ i, subsingleton (β i)] : unique (⨁ i, β i) := dfinsupp.unique /-- A direct sum over an empty type is trivial. -/ instance unique_of_is_empty [is_empty ι] : unique (⨁ i, β i) := dfinsupp.unique_of_is_empty /-- The natural equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/ protected def id (M : Type v) (ι : Type* := punit) [add_comm_monoid M] [unique ι] : (⨁ (_ : ι), M) ≃+ M := { to_fun := direct_sum.to_add_monoid (λ _, add_monoid_hom.id M), inv_fun := of (λ _, M) default, left_inv := λ x, direct_sum.induction_on x (by rw [add_monoid_hom.map_zero, add_monoid_hom.map_zero]) (λ p x, by rw [unique.default_eq p, to_add_monoid_of]; refl) (λ x y ihx ihy, by rw [add_monoid_hom.map_add, add_monoid_hom.map_add, ihx, ihy]), right_inv := λ x, to_add_monoid_of _ _ _, ..direct_sum.to_add_monoid (λ _, add_monoid_hom.id M) } section congr_left variables {κ : Type*} /--Reindexing terms of a direct sum.-/ def equiv_congr_left (h : ι ≃ κ) : (⨁ i, β i) ≃+ ⨁ k, β (h.symm k) := { map_add' := dfinsupp.comap_domain'_add _ _, ..dfinsupp.equiv_congr_left h } @[simp] lemma equiv_congr_left_apply (h : ι ≃ κ) (f : ⨁ i, β i) (k : κ) : equiv_congr_left h f k = f (h.symm k) := dfinsupp.comap_domain'_apply _ _ _ _ end congr_left section option variables {α : option ι → Type w} [Π i, add_comm_monoid (α i)] include dec_ι /--Isomorphism obtained by separating the term of index `none` of a direct sum over `option ι`.-/ @[simps] noncomputable def add_equiv_prod_direct_sum : (⨁ i, α i) ≃+ α none × ⨁ i, α (some i) := { map_add' := dfinsupp.equiv_prod_dfinsupp_add, ..dfinsupp.equiv_prod_dfinsupp } end option section sigma variables {α : ι → Type u} {δ : Π i, α i → Type w} [Π i j, add_comm_monoid (δ i j)] /--The natural map between `⨁ (i : Σ i, α i), δ i.1 i.2` and `⨁ i (j : α i), δ i j`.-/ noncomputable def sigma_curry : (⨁ (i : Σ i, _), δ i.1 i.2) →+ ⨁ i j, δ i j := { to_fun := @dfinsupp.sigma_curry _ _ δ _, map_zero' := dfinsupp.sigma_curry_zero, map_add' := λ f g, @dfinsupp.sigma_curry_add _ _ δ _ f g } @[simp] lemma sigma_curry_apply (f : ⨁ (i : Σ i, _), δ i.1 i.2) (i : ι) (j : α i) : sigma_curry f i j = f ⟨i, j⟩ := @dfinsupp.sigma_curry_apply _ _ δ _ f i j /--The natural map between `⨁ i (j : α i), δ i j` and `Π₀ (i : Σ i, α i), δ i.1 i.2`, inverse of `curry`.-/ noncomputable def sigma_uncurry : (⨁ i j, δ i j) →+ ⨁ (i : Σ i, _), δ i.1 i.2 := { to_fun := dfinsupp.sigma_uncurry, map_zero' := dfinsupp.sigma_uncurry_zero, map_add' := dfinsupp.sigma_uncurry_add } @[simp] lemma sigma_uncurry_apply (f : ⨁ i j, δ i j) (i : ι) (j : α i) : sigma_uncurry f ⟨i, j⟩ = f i j := dfinsupp.sigma_uncurry_apply f i j /--The natural map between `⨁ (i : Σ i, α i), δ i.1 i.2` and `⨁ i (j : α i), δ i j`.-/ noncomputable def sigma_curry_equiv : (⨁ (i : Σ i, _), δ i.1 i.2) ≃+ ⨁ i j, δ i j := { ..sigma_curry, ..dfinsupp.sigma_curry_equiv } end sigma /-- The canonical embedding from `⨁ i, A i` to `M` where `A` is a collection of `add_submonoid M` indexed by `ι`. When `S = submodule _ M`, this is available as a `linear_map`, `direct_sum.coe_linear_map`. -/ protected def coe_add_monoid_hom {M S : Type*} [decidable_eq ι] [add_comm_monoid M] [set_like S M] [add_submonoid_class S M] (A : ι → S) : (⨁ i, A i) →+ M := to_add_monoid (λ i, add_submonoid_class.subtype (A i)) @[simp] lemma coe_add_monoid_hom_of {M S : Type*} [decidable_eq ι] [add_comm_monoid M] [set_like S M] [add_submonoid_class S M] (A : ι → S) (i : ι) (x : A i) : direct_sum.coe_add_monoid_hom A (of (λ i, A i) i x) = x := to_add_monoid_of _ _ _ lemma coe_of_apply {M S : Type*} [decidable_eq ι] [add_comm_monoid M] [set_like S M] [add_submonoid_class S M] {A : ι → S} (i j : ι) (x : A i) : (of _ i x j : M) = if i = j then x else 0 := begin obtain rfl | h := decidable.eq_or_ne i j, { rw [direct_sum.of_eq_same, if_pos rfl], }, { rw [direct_sum.of_eq_of_ne _ _ _ _ h, if_neg h, zero_mem_class.coe_zero], }, end /-- The `direct_sum` formed by a collection of additive submonoids (or subgroups, or submodules) of `M` is said to be internal if the canonical map `(⨁ i, A i) →+ M` is bijective. For the alternate statement in terms of independence and spanning, see `direct_sum.subgroup_is_internal_iff_independent_and_supr_eq_top` and `direct_sum.is_internal_submodule_iff_independent_and_supr_eq_top`. -/ def is_internal {M S : Type*} [decidable_eq ι] [add_comm_monoid M] [set_like S M] [add_submonoid_class S M] (A : ι → S) : Prop := function.bijective (direct_sum.coe_add_monoid_hom A) lemma is_internal.add_submonoid_supr_eq_top {M : Type*} [decidable_eq ι] [add_comm_monoid M] (A : ι → add_submonoid M) (h : is_internal A) : supr A = ⊤ := begin rw [add_submonoid.supr_eq_mrange_dfinsupp_sum_add_hom, add_monoid_hom.mrange_top_iff_surjective], exact function.bijective.surjective h, end end direct_sum
f03ad1110cc7078da2bfb881ed51a23944e64b6c
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/ring_theory/ideals.lean
cd62ca15700181d91b7eaa3292af0a2fe8a5b35f
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
11,286
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 -/ import algebra.module tactic.ring linear_algebra.quotient_module universes u v variables {α : Type u} {β : Type v} [comm_ring α] {a b : α} open set function local attribute [instance] classical.prop_decidable class is_ideal {α : Type u} [comm_ring α] (S : set α) extends is_submodule S : Prop namespace is_ideal protected lemma zero (S : set α) [is_ideal S] : (0 : α) ∈ S := is_submodule.zero_ α S protected lemma add {S : set α} [is_ideal S] : a ∈ S → b ∈ S → a + b ∈ S := is_submodule.add_ α lemma neg_iff {S : set α} [is_ideal S] : a ∈ S ↔ -a ∈ S := ⟨is_submodule.neg, λ h, neg_neg a ▸ is_submodule.neg h⟩ protected lemma sub {S : set α} [is_ideal S] : a ∈ S → b ∈ S → a - b ∈ S := is_submodule.sub lemma mul_left {S : set α} [is_ideal S] : b ∈ S → a * b ∈ S := @is_submodule.smul α α _ _ _ _ a _ lemma mul_right {S : set α} [is_ideal S] : a ∈ S → a * b ∈ S := mul_comm b a ▸ mul_left def trivial (α : Type*) [comm_ring α] : set α := {0} @[simp] lemma mem_trivial : a ∈ trivial α ↔ a = 0 := by simp [trivial] instance : is_ideal (trivial α) := by refine {..}; simp [trivial] {contextual := tt} instance univ : is_ideal (@univ α) := {} instance span (S : set α) : is_ideal (span S) := {} end is_ideal class is_proper_ideal {α : Type u} [comm_ring α] (S : set α) extends is_ideal S : Prop := (ne_univ : S ≠ set.univ) lemma is_proper_ideal_iff_one_not_mem {S : set α} [hS : is_ideal S] : is_proper_ideal S ↔ (1 : α) ∉ S := ⟨λ h h1, by exactI is_proper_ideal.ne_univ S (eq_univ_iff_forall.2 (λ a, mul_one a ▸ is_ideal.mul_left h1)), λ h, {ne_univ := mt eq_univ_iff_forall.1 (λ ha, h (ha _)), ..hS}⟩ class is_prime_ideal {α : Type u} [comm_ring α] (S : set α) extends is_proper_ideal S : Prop := (mem_or_mem_of_mul_mem : ∀ {x y : α}, x * y ∈ S → x ∈ S ∨ y ∈ S) theorem mem_or_mem_of_mul_eq_zero {α : Type u} [comm_ring α] (S : set α) [is_prime_ideal S] : ∀ {x y : α}, x * y = 0 → x ∈ S ∨ y ∈ S := λ x y hxy, have x * y ∈ S, by rw hxy; from (@is_submodule.zero α α _ _ S _ : (0:α) ∈ S), is_prime_ideal.mem_or_mem_of_mul_mem this class is_maximal_ideal {α : Type u} [comm_ring α] (S : set α) extends is_proper_ideal S : Prop := mk' :: (eq_or_univ_of_subset : ∀ (T : set α) [is_ideal T], S ⊆ T → T = S ∨ T = set.univ) theorem is_maximal_ideal.mk {α : Type u} [comm_ring α] (S : set α) [is_ideal S] (h₁ : (1:α) ∉ S) (h₂ : ∀ x (T : set α) [is_ideal T], S ⊆ T → x ∉ S → x ∈ T → (1:α) ∈ T) : is_maximal_ideal S := { ne_univ := assume hu, have (1:α) ∈ S, by rw hu; trivial, h₁ this, eq_or_univ_of_subset := assume T ht hst, classical.or_iff_not_imp_left.2 $ assume (hnst : T ≠ S), let ⟨x, hxt, hxns⟩ := set.exists_of_ssubset ⟨hst, hnst.symm⟩ in @@is_submodule.univ_of_one_mem _ T (by resetI; apply_instance) $ @@h₂ x T ht hst hxns hxt} instance is_maximal_ideal.is_prime_ideal (S : set α) [hS : is_maximal_ideal S] : is_prime_ideal S := { mem_or_mem_of_mul_mem := λ x y hxy, or_iff_not_imp_left.2 (λ h, have (span (insert x S)) = univ := or.resolve_left (is_maximal_ideal.eq_or_univ_of_subset _ (subset.trans (subset_insert _ _) subset_span)) (λ hS, h $ hS ▸ subset_span (mem_insert _ _)), have (1 : α) ∈ span (insert x S) := this.symm ▸ mem_univ _, let ⟨a, ha⟩ := mem_span_insert.1 this in have hy : y * (1 + a • x) - a * (x * y) = y := by rw smul_eq_mul; ring, hy ▸ is_ideal.sub (is_ideal.mul_left (span_eq_of_is_submodule (show is_submodule S, by apply_instance) ▸ ha)) (is_ideal.mul_left hxy)), ..hS } def nonunits (α : Type u) [monoid α] : set α := { x | ¬∃ y, y * x = 1 } theorem not_unit_of_mem_proper_ideal {α : Type u} [comm_ring α] (S : set α) [is_proper_ideal S] : S ⊆ nonunits α := λ x hx ⟨y, hxy⟩, is_proper_ideal.ne_univ S $ is_submodule.eq_univ_of_contains_unit S x y hx hxy class local_ring (α : Type u) [comm_ring α] := (S : set α) (max : is_maximal_ideal S) (unique : ∀ T [is_maximal_ideal T], S = T) def local_of_nonunits_ideal {α : Type u} [comm_ring α] (hnze : (0:α) ≠ 1) (h : ∀ x y ∈ nonunits α, x + y ∈ nonunits α) : local_ring α := have hi : is_ideal (nonunits α), from { zero_ := λ ⟨y, hy⟩, hnze $ by simpa using hy, add_ := h, smul := λ x y hy ⟨z, hz⟩, hy ⟨x * z, by rw [← hz]; simp [mul_left_comm, mul_assoc]⟩ }, { S := nonunits α, max := @@is_maximal_ideal.mk _ (nonunits α) hi (λ ho, ho ⟨1, mul_one 1⟩) $ λ x T ht hst hxns hxt, let ⟨y, hxy⟩ := classical.by_contradiction hxns in by rw [← hxy]; by exactI is_ideal.mul_left hxt, unique := λ T hmt, or.cases_on (@@is_maximal_ideal.eq_or_univ_of_subset _ hmt (nonunits α) hi $ λ z hz, @@not_unit_of_mem_proper_ideal _ T (by resetI; apply_instance) hz) id (λ htu, false.elim $ ((set.ext_iff _ _).1 htu 1).2 trivial ⟨1, mul_one 1⟩) } instance is_ideal.preimage [comm_ring β] (S : set β) (f : α → β) [is_ring_hom f] [is_ideal S] : is_ideal (f ⁻¹' S) := { to_is_submodule := { zero_ := show f 0 ∈ S, by rw is_ring_hom.map_zero f; exact is_ideal.zero _, add_ := λ x y hx hy, show f (x + y) ∈ S, by rw is_ring_hom.map_add f; exact is_ideal.add hx hy, smul := λ c x hx, show f (c * x) ∈ S, by rw is_ring_hom.map_mul f; exact is_ideal.mul_left hx } } instance is_proper_ideal.preimage [comm_ring β] (S : set β) (f : α → β) [is_ring_hom f] [hT : is_proper_ideal S] : is_proper_ideal (f ⁻¹' S) := { ne_univ := mt eq_univ_iff_forall.1 (λ h, is_proper_ideal_iff_one_not_mem.1 hT (is_ring_hom.map_one f ▸ h _)), ..is_ideal.preimage S f } instance is_prime_ideal.preimage [comm_ring β] (S : set β) (f : α → β) [is_ring_hom f] [is_prime_ideal S] : is_prime_ideal (f ⁻¹' S) := { mem_or_mem_of_mul_mem := λ x y (hxy : f (x * y) ∈ S), show f x ∈ S ∨ f y ∈ S, from is_prime_ideal.mem_or_mem_of_mul_mem (by rwa ← is_ring_hom.map_mul f), ..is_proper_ideal.preimage S f } namespace quotient_ring open is_ideal def quotient_rel (S : set α) [is_ideal S] := is_submodule.quotient_rel S def quotient (S : set α) [is_ideal S] := quotient (quotient_rel S) def mk {S : set α} [is_ideal S] (a : α) : quotient S := quotient.mk' a instance {S : set α} [is_ideal S] : has_coe α (quotient S) := ⟨mk⟩ protected lemma eq {S : set α} [is_ideal S] {a b : α} : (a : quotient S) = b ↔ a - b ∈ S := quotient.eq' instance (S : set α) [is_ideal S] : comm_ring (quotient S) := { mul := λ a b, quotient.lift_on₂' a b (λ a b, ((a * b : α) : quotient S)) (λ a₁ a₂ b₁ b₂ (h₁ : a₁ - b₁ ∈ S) (h₂ : a₂ - b₂ ∈ S), quotient.sound' (show a₁ * a₂ - b₁ * b₂ ∈ S, from have h : a₂ * (a₁ - b₁) + (a₂ - b₂) * b₁ = a₁ * a₂ - b₁ * b₂, by ring, h ▸ is_ideal.add (mul_left h₁) (mul_right h₂))), mul_assoc := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg mk (mul_assoc a b c), mul_comm := λ a b, quotient.induction_on₂' a b $ λ a b, congr_arg mk (mul_comm a b), one := (1 : α), one_mul := λ a, quotient.induction_on' a $ λ a, congr_arg mk (one_mul a), mul_one := λ a, quotient.induction_on' a $ λ a, congr_arg mk (mul_one a), left_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg mk (left_distrib a b c), right_distrib := λ a b c, quotient.induction_on₃' a b c $ λ a b c, congr_arg mk (right_distrib a b c), ..is_submodule.quotient.add_comm_group S } instance is_ring_hom_mk (S : set α) [is_ideal S] : @is_ring_hom _ (quotient S) _ _ mk := ⟨λ _ _, rfl, λ _ _, rfl, rfl⟩ instance (S T : set α) [is_ideal S] [is_ideal T] : is_ideal (mk '' S : set (quotient T)) := { to_is_submodule := { zero_ := ⟨0, is_ideal.zero _, rfl⟩, add_ := λ x y ⟨a, ha⟩ ⟨b, hb⟩, ⟨a + b, is_ideal.add ha.1 hb.1, ha.2 ▸ hb.2 ▸ rfl⟩, smul := λ c x ⟨a, ha⟩, quotient.induction_on' c (λ c, ⟨c * a, mul_left ha.1, ha.2 ▸ rfl⟩) } } @[simp] lemma coe_zero (S : set α) [is_ideal S] : ((0 : α) : quotient S) = 0 := rfl @[simp] lemma coe_one (S : set α) [is_ideal S] : ((1 : α) : quotient S) = 1 := rfl @[simp] lemma coe_add (S : set α) [is_ideal S] (a b : α) : ((a + b : α) : quotient S) = a + b := rfl @[simp] lemma coe_mul (S : set α) [is_ideal S] (a b : α) : ((a * b : α) : quotient S) = a * b := rfl @[simp] lemma coe_neg (S : set α) [is_ideal S] (a : α) : ((-a : α) : quotient S) = -a := rfl @[simp] lemma coe_sub (S : set α) [is_ideal S] (a b : α) : ((a - b : α) : quotient S) = a - b := rfl @[simp] lemma coe_pow (S : set α) [is_ideal S] (a : α) (n : ℕ) : ((a ^ n : α) : quotient S) = a ^ n := by induction n; simp [*, pow_succ] lemma eq_zero_iff_mem {S : set α} [is_ideal S] : (a : quotient S) = 0 ↔ a ∈ S := by conv {to_rhs, rw ← sub_zero a }; exact quotient.eq' instance (S : set α) [is_proper_ideal S] : nonzero_comm_ring (quotient S) := { zero_ne_one := ne.symm $ mt eq_zero_iff_mem.1 (is_proper_ideal_iff_one_not_mem.1 (by apply_instance)), ..quotient_ring.comm_ring S } instance (S : set α) [is_prime_ideal S] : integral_domain (quotient S) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b, quotient.induction_on₂' a b $ λ a b hab, (is_prime_ideal.mem_or_mem_of_mul_mem (eq_zero_iff_mem.1 hab)).elim (or.inl ∘ eq_zero_iff_mem.2) (or.inr ∘ eq_zero_iff_mem.2), ..quotient_ring.nonzero_comm_ring S } lemma exists_inv {S : set α} [is_maximal_ideal S] {a : quotient S} : a ≠ 0 → ∃ b : quotient S, a * b = 1 := quotient.induction_on' a $ λ a ha, classical.by_contradiction $ λ h, have haS : a ∉ S := mt eq_zero_iff_mem.2 ha, by haveI hS : is_proper_ideal (span (set.insert a S)) := is_proper_ideal_iff_one_not_mem.2 (mt mem_span_insert.1 $ λ ⟨b, hb⟩, h ⟨-b, quotient_ring.eq.2 (neg_iff.2 (begin rw [neg_sub, mul_neg_eq_neg_mul_symm, sub_eq_add_neg, neg_neg, mul_comm], rw span_eq_of_is_submodule (show is_submodule S, by apply_instance) at hb, exact hb end))⟩); exact have span (set.insert a S) = S := or.resolve_right (is_maximal_ideal.eq_or_univ_of_subset (span (set.insert a S)) (subset.trans (subset_insert _ _) subset_span)) (is_proper_ideal.ne_univ _), haS (this ▸ subset_span (mem_insert _ _)) /-- quotient by maximal ideal is a field. def rather than instance, since users will have computable inverses in some applications -/ protected noncomputable def field (S : set α) [is_maximal_ideal S] : field (quotient S) := { 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_mul_cancel := λ a (ha : a ≠ 0), show dite _ _ _ * a = _, by rw [mul_comm, dif_neg ha]; exact classical.some_spec (exists_inv ha), ..quotient_ring.integral_domain S } end quotient_ring
a5ff654e3b19788188539bf482a18bf784ab94c4
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/string/ops.lean
62adbb6915c53453b605ff6e6e2744fbc9bdc8d7
[ "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,777
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.data.bool.lemmas import init.data.string.basic import init.meta.well_founded_tactics namespace string namespace iterator @[simp] lemma next_to_string_mk_iterator (s : string) : s.mk_iterator.next_to_string = s := by induction s; refl @[simp] lemma length_next_to_string_next (it : iterator) : it.next.next_to_string.length = it.next_to_string.length - 1 := by cases it; cases it_snd; simp [iterator.next, iterator.next_to_string, string.length, nat.add_sub_cancel_left] lemma zero_lt_length_next_to_string_of_has_next {it : iterator} : it.has_next → 0 < it.next_to_string.length := by cases it; cases it_snd; simp [iterator.has_next, iterator.next_to_string, string.length, nat.zero_lt_one_add, nat.add_comm, false_implies_iff] end iterator -- TODO(Sebastian): generalize to something like -- https://doc.rust-lang.org/std/primitive.str.html#method.split private def split_core (p : char → bool) : iterator → iterator → list string | start stop := if h : stop.has_next then -- wf hint have stop.next_to_string.length - 1 < stop.next_to_string.length, from nat.sub_lt (iterator.zero_lt_length_next_to_string_of_has_next h) dec_trivial, if p stop.curr then let rest := stop.next.next_to_string in (start.extract stop).get_or_else "" :: split_core stop.next stop.next else split_core start stop.next else [start.next_to_string] using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ e, e.2.next_to_string.length)⟩] } def split (p : char → bool) (s : string) : list string := split_core p s.mk_iterator s.mk_iterator end string
cb46d678aa67eb3851ce9c3f49615adf2198d29a
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/category_theory/limits/shapes/types.lean
e06536e35e0c8c5aec125f86862fb329cdd2f424
[ "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
4,251
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.types import category_theory.limits.shapes.products import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal /-! # Special shapes for limits in `Type`. The general shape (co)limits defined in `category_theory.limits.types` are intended for use through the limits API, and the actual implementation should mostly be considered "sealed". In this file, we provide definitions of the "standard" special shapes of limits in `Type`, giving the expected definitional implementation: * the terminal object is `punit` * the binary product of `X` and `Y` is `X × Y` * the product of a family `f : J → Type` is `Π j, f j`. Because these are not intended for use with the `has_limit` API, we instead construct terms of `limit_data`. As an example, when setting up the monoidal category structure on `Type` we use the `types_has_terminal` and `types_has_binary_products` instances. -/ universes u open category_theory open category_theory.limits namespace category_theory.limits.types /-- A restatement of `types.lift_π_apply` that uses `pi.π` and `pi.lift`. -/ @[simp] lemma pi_lift_π_apply {β : Type u} (f : β → Type u) {P : Type u} (s : Π b, P ⟶ f b) (b : β) (x : P) : (pi.π f b : (∏ f) → f b) (@pi.lift β _ _ f _ P s x) = s b x := congr_fun (limit.lift_π (fan.mk s) b) x /-- A restatement of `types.map_π_apply` that uses `pi.π` and `pi.map`. -/ @[simp] lemma pi_map_π_apply {β : Type u} {f g : β → Type u} (α : Π j, f j ⟶ g j) (b : β) (x) : (pi.π g b : (∏ g) → g b) (pi.map α x) = α b ((pi.π f b : (∏ f) → f b) x) := map_π_apply _ _ _ /-- The category of types has `punit` as a terminal object. -/ def terminal_limit_cone : limits.limit_cone (functor.empty (Type u)) := { cone := { X := punit, π := by tidy, }, is_limit := by tidy, } /-- The category of types has `pempty` as an initial object. -/ def initial_limit_cone : limits.colimit_cocone (functor.empty (Type u)) := { cocone := { X := pempty, ι := by tidy, }, is_colimit := by tidy, } open category_theory.limits.walking_pair local attribute [tidy] tactic.case_bash /-- The category of types has `X × Y`, the usual cartesian product, as the binary product of `X` and `Y`. -/ def binary_product_limit_cone (X Y : Type u) : limits.limit_cone (pair X Y) := { cone := { X := X × Y, π := { app := by { rintro ⟨_|_⟩, exact prod.fst, exact prod.snd, } }, }, is_limit := { lift := λ s x, (s.π.app left x, s.π.app right x), uniq' := λ s m w, begin ext, exact congr_fun (w left) x, exact congr_fun (w right) x, end }, } /-- The category of types has `X ⊕ Y`, as the binary coproduct of `X` and `Y`. -/ def binary_coproduct_limit_cone (X Y : Type u) : limits.colimit_cocone (pair X Y) := { cocone := { X := X ⊕ Y, ι := { app := by { rintro ⟨_|_⟩, exact sum.inl, exact sum.inr, } }, }, is_colimit := { desc := λ s x, sum.elim (s.ι.app left) (s.ι.app right) x, uniq' := λ s m w, begin ext (x|x), exact (congr_fun (w left) x : _), exact (congr_fun (w right) x : _), end }, } /-- The category of types has `Π j, f j` as the product of a type family `f : J → Type`. -/ def product_limit_cone {J : Type u} (F : J → Type u) : limits.limit_cone (discrete.functor F) := { cone := { X := Π j, F j, π := { app := λ j f, f j }, }, is_limit := { lift := λ s x j, s.π.app j x, uniq' := λ s m w, begin ext x j, have := congr_fun (w j) x, exact this, end }, } /-- The category of types has `Σ j, f j` as the coproduct of a type family `f : J → Type`. -/ def coproduct_limit_cone {J : Type u} (F : J → Type u) : limits.colimit_cocone (discrete.functor F) := { cocone := { X := Σ j, F j, ι := { app := λ j x, ⟨j, x⟩ }, }, is_colimit := { desc := λ s x, s.ι.app x.1 x.2, uniq' := λ s m w, begin ext ⟨j, x⟩, have := congr_fun (w j) x, exact this, end }, } end category_theory.limits.types
afac7f0644e928cf658c94d0776783f941e2ad50
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/convex/cone.lean
75e5aacea2444f1ac43f03a738996129a90c20fa
[ "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
23,970
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.convex.basic import analysis.normed_space.inner_product /-! # Convex cones In a vector space `E` over `ℝ`, we define a convex cone as a subset `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 also 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` ## Implementation notes While `convex` is a predicate on sets, `convex_cone` is a bundled convex cone. ## References * https://en.wikipedia.org/wiki/Convex_cone -/ universes u v open set linear_map open_locale classical variables (E : Type*) [add_comm_group E] [module ℝ E] {F : Type*} [add_comm_group F] [module ℝ F] {G : Type*} [add_comm_group G] [module ℝ G] /-! ### Definition of `convex_cone` and basic properties -/ /-- A convex cone is a subset `s` of a vector space over `ℝ` such that `a • x + b • y ∈ s` whenever `a, b > 0` and `x, y ∈ s`. -/ structure convex_cone := (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) variable {E} namespace convex_cone variables (S T : convex_cone E) instance : has_coe (convex_cone E) (set E) := ⟨convex_cone.carrier⟩ instance : has_mem E (convex_cone E) := ⟨λ m S, m ∈ S.carrier⟩ instance : has_le (convex_cone E) := ⟨λ S T, S.carrier ⊆ T.carrier⟩ instance : has_lt (convex_cone E) := ⟨λ S T, S.carrier ⊂ T.carrier⟩ @[simp, norm_cast] lemma mem_coe {x : E} : x ∈ (S : set E) ↔ x ∈ S := iff.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 the underlying subsets are equal. -/ theorem ext' {S T : convex_cone E} (h : (S : set E) = T) : S = T := by cases S; cases T; congr' /-- Two `convex_cone`s are equal if and only if the underlying subsets are equal. -/ protected theorem ext'_iff {S T : convex_cone E} : (S : set E) = T ↔ S = T := ⟨ext', λ h, h ▸ 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 := ext' $ set.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 lemma smul_mem_iff {c : ℝ} (hc : 0 < c) {x : E} : c • x ∈ S ↔ x ∈ S := ⟨λ h, by simpa only [smul_smul, inv_mul_cancel (ne_of_gt hc), one_smul] using S.smul_mem (inv_pos.2 hc) h, λ h, S.smul_mem hc h⟩ lemma convex : convex (S : set E) := convex_iff_forall_pos.2 $ λ x y hx hy a b ha hb hab, S.add_mem (S.smul_mem ha hx) (S.smul_mem hb hy) 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⟩⟩⟩ 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 $ by apply mem_bInter_iff.1 hx s hs, λ x hx y hy, mem_bInter $ λ s hs, s.add_mem (by apply mem_bInter_iff.1 hx s hs) (by apply mem_bInter_iff.1 hy s hs)⟩⟩ lemma mem_Inf {x : E} {S : set (convex_cone E)} : x ∈ Inf S ↔ ∀ s ∈ S, x ∈ s := mem_bInter_iff 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 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 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, .. partial_order.lift (coe : convex_cone E → set E) (λ a b, ext') } instance : inhabited (convex_cone E) := ⟨⊥⟩ /-- The image of a convex cone under an `ℝ`-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₂) } lemma map_map (g : F →ₗ[ℝ] G) (f : E →ₗ[ℝ] F) (S : convex_cone E) : (S.map f).map g = S.map (g.comp f) := ext' $ image_image g f S @[simp] lemma map_id : S.map linear_map.id = S := ext' $ image_id _ /-- The preimage of a convex cone under an `ℝ`-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 comap_id : S.comap linear_map.id = S := ext' 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) := ext' $ 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 /-- 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_module {M : Type*} [ordered_add_comm_group M] [module ℝ M] (S : convex_cone M) (h : ∀ x y : M, x ≤ y ↔ y - x ∈ S) : ordered_module ℝ M := ordered_module.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 (le_of_lt xy)) end /-! ### Convex cones with extra properties -/ /-- 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 /-- A convex cone is flat if it contains some nonzero vector `x` and its opposite `-x`. -/ def flat (S : convex_cone E) : 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 (S : convex_cone E) : Prop := ∀ x ∈ S, x ≠ (0 : E) → -x ∉ S lemma pointed_iff_not_blunt (S : convex_cone E) : pointed S ↔ ¬blunt S := ⟨λ h₁ h₂, h₂ h₁, λ h, not_not.mp h⟩ lemma salient_iff_not_flat (S : convex_cone E) : salient S ↔ ¬flat S := 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 /-- A blunt cone (one not containing 0) is always salient. -/ lemma salient_of_blunt (S : convex_cone E) : blunt S → salient S := begin intro h₁, rw [salient_iff_not_flat], intro h₂, obtain ⟨x, xs, H₁, H₂⟩ := h₂, have hkey : (0 : E) ∈ S := by rw [(show 0 = x + (-x), by simp)]; exact add_mem S xs H₂, exact h₁ hkey, end /-- A pointed convex cone defines a preorder. -/ def to_preorder (S : convex_cone E) (h₁ : pointed S) : 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 simp [(show z - x = z - y + (y - x), by abel), add_mem S zy xy] } /-- A pointed and salient cone defines a partial order. -/ def to_partial_order (S : convex_cone E) (h₁ : pointed S) (h₂ : salient S) : 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 (S : convex_cone E) (h₁ : pointed S) (h₂ : salient S) : 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 } /-! ### Positive cone of an ordered module -/ section positive_cone variables (M : Type*) [ordered_add_comm_group M] [module ℝ M] [ordered_module ℝ M] /-- The positive cone is the convex cone formed by the set of nonnegative elements in an ordered module. -/ def positive_cone : convex_cone M := { carrier := {x | 0 ≤ x}, smul_mem' := begin intros c hc x hx, have := smul_le_smul_of_nonneg (show 0 ≤ x, by exact hx) (le_of_lt hc), have h' : c • (0 : M) = 0, { simp only [smul_zero] }, rwa [h'] at this end, add_mem' := λ x hx y hy, add_nonneg (show 0 ≤ x, by exact hx) (show 0 ≤ y, by exact hy) } /-- The positive cone of an ordered module is always salient. -/ lemma salient_of_positive_cone : salient (positive_cone M) := begin intros x xs hx hx', have := calc 0 < x : lt_of_le_of_ne xs hx.symm ... ≤ x + (-x) : (le_add_iff_nonneg_right x).mpr hx' ... = 0 : by rw [tactic.ring.add_neg_eq_sub x x]; exact sub_self x, exact lt_irrefl 0 this, end /-- The positive cone of an ordered module is always pointed. -/ lemma pointed_of_positive_cone : pointed (positive_cone M) := le_refl 0 end positive_cone end convex_cone /-! ### Cone over a convex set -/ 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 > 0, (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 (le_of_lt cx_pos) (le_of_lt cy_pos) this, _⟩, simp only [smul_add, smul_smul, mul_div_assoc', mul_div_cancel_left _ (ne_of_gt this)] } end variables {s : set E} (hs : convex s) {x : E} lemma mem_to_cone : x ∈ hs.to_cone s ↔ ∃ (c > 0) (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 : ℝ) • 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 (ne_of_gt hc), one_smul]⟩ }, { rintros ⟨c, hc, hcx⟩, exact ⟨c⁻¹, inv_pos.2 hc, _, hcx, by rw [smul_smul, inv_mul_cancel (ne_of_gt hc), 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, λ h, subset.trans (subset_convex_hull s) h⟩ end lemma convex_hull_to_cone_eq_Inf (s : set E) : (convex_convex_hull s).to_cone _ = Inf {t : convex_cone E | s ⊆ t} := (convex_hull_to_cone_is_least s).is_glb.Inf_eq.symm /-! ### 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. -/ namespace riesz_extension open submodule variables (s : convex_cone E) (f : linear_pmap ℝ 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 rcases set_like.exists_of_lt (lt_top_iff_ne_top.2 hdom) with ⟨y, hy', hy⟩, clear hy', 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, 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, ← 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 (ne_of_lt hr), 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_eq_neg_mul, ← neg_mul_eq_neg_mul, neg_le_neg_iff, f.map_smul, smul_eq_mul, ← mul_assoc, mul_inv_cancel (ne_of_lt hr), 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 (ne_of_gt hr), 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 (ne_of_gt hr), one_mul] at this } } end theorem exists_top (p : linear_pmap ℝ 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.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, le_of_lt hqr, ne_of_gt hqr⟩ }, { 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 : linear_pmap ℝ 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.comp (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 : linear_pmap ℝ 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 (le_of_lt hc), add_mem' := λ x hx y hy, le_trans (N_add _ _) (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*} [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 ⟫`. -/ noncomputable 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 (le_of_lt hc) (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 } lemma mem_inner_dual_cone (y : H) (s : set H) : y ∈ s.inner_dual_cone ↔ ∀ x ∈ s, 0 ≤ ⟪ x, y ⟫ := by refl @[simp] lemma inner_dual_cone_empty : (∅ : set H).inner_dual_cone = ⊤ := convex_cone.ext' (eq_univ_of_forall (λ x y hy, false.elim (set.not_mem_empty _ hy))) 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 end dual
82b9703ee6e9da806a717d24295999e733b96711
6065973b1fa7bbacba932011c9e2f32bf7bdd6c1
/src/analysis/convex/basic.lean
d7311be2e70f8fd6e6fc4ed5c32aeecdd28142fc
[ "Apache-2.0" ]
permissive
khmacdonald/mathlib
90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb
3669cb35c578441812ad30fd967d21a94b6f387e
refs/heads/master
1,675,863,801,090
1,609,761,876,000
1,609,761,876,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
58,022
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov -/ import data.set.intervals.ord_connected import data.set.intervals.image_preimage import data.complex.module import linear_algebra.affine_space.affine_map import algebra.module.ordered /-! # Convex sets and functions on real vector spaces In a real vector space, we define the following objects and properties. * `segment x y` is the closed segment joining `x` and `y`. * A set `s` is `convex` if for any two points `x y ∈ s` it includes `segment x y`; * A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph of `f`; equivalently, `convex_on f s` means that the epigraph `{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set; * Center mass of a finite set of points with prescribed weights. * Convex hull of a set `s` is the minimal convex set that includes `s`. * Standard simplex `std_simplex ι [fintype ι]` is the intersection of the positive quadrant with the hyperplane `s.sum = 1` in the space `ι → ℝ`. We also provide various equivalent versions of the definitions above, prove that some specific sets are convex, and prove Jensen's inequality. Note: To define convexity for functions `f : E → β`, we need `β` to be an ordered vector space, defined using the instance `ordered_semimodule ℝ β`. ## Notations We use the following local notations: * `I = Icc (0:ℝ) 1`; * `[x, y] = segment x y`. They are defined using `local notation`, so they are not available outside of this file. -/ universes u' u v v' w x variables {E : Type u} {F : Type v} {ι : Type w} {ι' : Type x} {α : Type v'} [add_comm_group E] [vector_space ℝ E] [add_comm_group F] [vector_space ℝ F] [linear_ordered_field α] {s : set E} open set linear_map open_locale classical big_operators local notation `I` := (Icc 0 1 : set ℝ) section sets /-! ### Segment -/ /-- Segments in a vector space -/ def segment (x y : E) : set E := {z : E | ∃ (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z} local notation `[`x `, ` y `]` := segment x y lemma segment_symm (x y : E) : [x, y] = [y, x] := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma left_mem_segment (x y : E) : x ∈ [x, y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x, y] := segment_symm y x ▸ left_mem_segment y x lemma segment_same (x : E) : [x, x] = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ left_mem_segment z z⟩ lemma segment_eq_image (x y : E) : segment x y = (λ (θ : ℝ), (1 - θ) • x + θ • y) '' I := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image' (x y : E) : segment x y = (λ (θ : ℝ), x + θ • (y - x)) '' I := by { convert segment_eq_image x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_eq_image₂ (x y : E) : segment x y = (λ p:ℝ×ℝ, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_eq_Icc {a b : ℝ} (h : a ≤ b) : [a, b] = Icc a b := begin rw [segment_eq_image'], show (((+) a) ∘ (λ t, t * (b - a))) '' Icc 0 1 = Icc a b, rw [image_comp, image_mul_right_Icc (@zero_le_one ℝ _) (sub_nonneg.2 h), image_const_add_Icc], simp end lemma segment_eq_Icc' (a b : ℝ) : [a, b] = Icc (min a b) (max a b) := by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *] lemma segment_eq_interval (a b : ℝ) : segment a b = interval a b := segment_eq_Icc' _ _ lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b, a + c] ↔ x ∈ [b, c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj] end lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b, a + c] = [b, c] := set.ext $ λ x, mem_segment_translate a lemma segment_translate_image (a b c: E) : (λx, a + x) '' [b, c] = [a + b, a + c] := segment_translate_preimage a b c ▸ image_preimage_eq _ $ add_left_surjective a /-! ### Convexity of sets -/ /-- Convexity of sets -/ def convex (s : set E) := ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s lemma convex_iff_forall_pos : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s := begin refine ⟨λ h x y hx hy a b ha hb hab, h hx hy (le_of_lt ha) (le_of_lt hb) hab, _⟩, intros h x y hx hy a b ha hb hab, cases eq_or_lt_of_le ha with ha ha, { subst a, rw [zero_add] at hab, simp [hab, hy] }, cases eq_or_lt_of_le hb with hb hb, { subst b, rw [add_zero] at hab, simp [hab, hx] }, exact h hx hy ha hb hab end lemma convex_iff_segment_subset : convex s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x, y] ⊆ s := by simp only [convex, segment_eq_image₂, subset_def, ball_image_iff, prod.forall, mem_set_of_eq, and_imp] lemma convex.segment_subset (h : convex s) {x y:E} (hx : x ∈ s) (hy : y ∈ s) : [x, y] ⊆ s := convex_iff_segment_subset.1 h hx hy /-- Alternative definition of set convexity, in terms of pointwise set operations. -/ lemma convex_iff_pointwise_add_subset: convex s ↔ ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s := iff.intro begin rintros hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩, exact hA hu hv ha hb hab end (λ h x y hx hy a b ha hb hab, (h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩)) /-- Alternative definition of set convexity, using division -/ lemma convex_iff_div: convex s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • x + (b/(a+b)) • y ∈ s := ⟨begin assume h x y hx hy a b ha hb hab, apply h hx hy, have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at ha', have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)), rwa [mul_zero, ←div_eq_inv_mul] at hb', rw [←add_div], exact div_self (ne_of_lt hab).symm end, begin assume h x y hx hy a b ha hb hab, have h', from h hx hy ha hb, rw [hab, div_one, div_one] at h', exact h' zero_lt_one end⟩ /-! ### Examples of convex sets -/ lemma convex_empty : convex (∅ : set E) := by finish lemma convex_singleton (c : E) : convex ({c} : set E) := begin intros x y hx hy a b ha hb hab, rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, ←add_smul, hab, one_smul], exact mem_singleton c end lemma convex_univ : convex (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s ∩ t) := λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), ⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩ lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex s) : convex (⋂₀ S) := assume x y hx hy a b ha hb hab s hs, h s hs (hx s hs) (hy s hs) ha hb hab lemma convex_Inter {ι : Sort*} {s: ι → set E} (h: ∀ i : ι, convex (s i)) : convex (⋂ i, s i) := (sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) : convex (s.prod t) := begin intros x y hx hy a b ha hb hab, apply mem_prod.2, exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab, ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩ end lemma convex.combo_to_vadd {a b : ℝ} {x y : E} (h : a + b = 1) : a • x + b • y = b • (y - x) + x := eq.symm (calc b • (y - x) + x = b • (y - x) + (1 : ℝ) • x : by rw [one_smul] ... = b • (y - x) + (a + b) • x : by rw [h] ... = (b • y - b • x) + (a • x + b • x) : by rw [add_smul, smul_sub] ... = a • x + b • y : by abel ) /-- Applying an affine map to an affine combination of two points yields an affine combination of the images. -/ lemma convex.combo_affine_apply {a b : ℝ} {x y : E} {f : E →ᵃ[ℝ] F} (h : a + b = 1) : f (a • x + b • y) = a • f x + b • f y := begin simp only [convex.combo_to_vadd h, ← vsub_eq_sub], exact f.apply_line_map _ _ _, end /-- The preimage of a convex set under an affine map is convex. -/ lemma convex.affine_preimage (f : E →ᵃ[ℝ] F) {s : set F} (hs : convex s) : convex (f ⁻¹' s) := begin intros x y xs ys a b ha hb hab, rw [mem_preimage, convex.combo_affine_apply hab], exact hs xs ys ha hb hab, end /-- The image of a convex set under an affine map is convex. -/ lemma convex.affine_image (f : E →ᵃ[ℝ] F) {s : set E} (hs : convex s) : convex (f '' s) := begin rintros x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab, refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩, rw [convex.combo_affine_apply hab, hx'f, hy'f] end lemma convex.linear_image (hs : convex s) (f : E →ₗ[ℝ] F) : convex (image f s) := hs.affine_image f.to_affine_map lemma convex.is_linear_image (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (f '' s) := hs.linear_image $ hf.mk' f lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E →ₗ[ℝ] F) : convex (preimage f s) := hs.affine_preimage f.to_affine_map lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E → F} (hf : is_linear_map ℝ f) : convex (preimage f s) := hs.linear_preimage $ hf.mk' f lemma convex.neg (hs : convex s) : convex ((λ z, -z) '' s) := hs.is_linear_image is_linear_map.is_linear_map_neg lemma convex.neg_preimage (hs : convex s) : convex ((λ z, -z) ⁻¹' s) := hs.is_linear_preimage is_linear_map.is_linear_map_neg lemma convex.smul (c : ℝ) (hs : convex s) : convex (c • s) := hs.linear_image (linear_map.lsmul _ _ c) lemma convex.smul_preimage (c : ℝ) (hs : convex s) : convex ((λ z, c • z) ⁻¹' s) := hs.linear_preimage (linear_map.lsmul _ _ c) lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) := by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add } lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) : convex ((λx : E × E, x.1 - x.2) '' (s.prod t)) := (hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub lemma convex.translate (hs : convex s) (z : E) : convex ((λx, z + x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex -/ lemma convex.translate_preimage_right (hs : convex s) (a : E) : convex ((λ z, a + z) ⁻¹' s) := hs.affine_preimage $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- The translation of a convex set is also convex -/ lemma convex.translate_preimage_left (hs : convex s) (a : E) : convex ((λ z, z + a) ⁻¹' s) := by simpa only [add_comm] using hs.translate_preimage_right a lemma convex.affinity (hs : convex s) (z : E) (c : ℝ) : convex ((λx, z + c • x) '' s) := hs.affine_image $ affine_map.const ℝ E z +ᵥ c • affine_map.id ℝ E lemma real.convex_iff_ord_connected {s : set ℝ} : convex s ↔ ord_connected s := begin simp only [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset], exact forall_congr (λ x, forall_swap) end alias real.convex_iff_ord_connected ↔ convex.ord_connected set.ord_connected.convex lemma convex_Iio (r : ℝ) : convex (Iio r) := ord_connected_Iio.convex lemma convex_Ioi (r : ℝ) : convex (Ioi r) := ord_connected_Ioi.convex lemma convex_Iic (r : ℝ) : convex (Iic r) := ord_connected_Iic.convex lemma convex_Ici (r : ℝ) : convex (Ici r) := ord_connected_Ici.convex lemma convex_Ioo (r s : ℝ) : convex (Ioo r s) := ord_connected_Ioo.convex lemma convex_Ico (r s : ℝ) : convex (Ico r s) := ord_connected_Ico.convex lemma convex_Ioc (r : ℝ) (s : ℝ) : convex (Ioc r s) := ord_connected_Ioc.convex lemma convex_Icc (r : ℝ) (s : ℝ) : convex (Icc r s) := ord_connected_Icc.convex lemma convex_interval (r : ℝ) (s : ℝ) : convex (interval r s) := ord_connected_interval.convex lemma convex_segment (a b : E) : convex [a, b] := begin have : (λ (t : ℝ), a + t • (b - a)) = (λz : E, a + z) ∘ (λt:ℝ, t • (b - a)) := rfl, rw [segment_eq_image', this, image_comp], refine ((convex_Icc _ _).is_linear_image _).translate _, exact is_linear_map.is_linear_map_smul' _ end lemma convex_halfspace_lt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w < r} := (convex_Iio r).is_linear_preimage h lemma convex_halfspace_le {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w ≤ r} := (convex_Iic r).is_linear_preimage h lemma convex_halfspace_gt {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r < f w} := (convex_Ioi r).is_linear_preimage h lemma convex_halfspace_ge {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | r ≤ f w} := (convex_Ici r).is_linear_preimage h lemma convex_hyperplane {f : E → ℝ} (h : is_linear_map ℝ f) (r : ℝ) : convex {w | f w = r} := begin show convex (f ⁻¹' {p | p = r}), rw set_of_eq_eq_singleton, exact (convex_singleton r).is_linear_preimage h end lemma convex_halfspace_re_lt (r : ℝ) : convex {c : ℂ | c.re < r} := convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_le (r : ℝ) : convex {c : ℂ | c.re ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_gt (r : ℝ) : convex {c : ℂ | r < c.re } := convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_re_lge (r : ℝ) : convex {c : ℂ | r ≤ c.re} := convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _ lemma convex_halfspace_im_lt (r : ℝ) : convex {c : ℂ | c.im < r} := convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_le (r : ℝ) : convex {c : ℂ | c.im ≤ r} := convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_gt (r : ℝ) : convex {c : ℂ | r < c.im } := convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _ lemma convex_halfspace_im_lge (r : ℝ) : convex {c : ℂ | r ≤ c.im} := convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _ /- Convex combinations in intervals -/ lemma convex.combo_self (a : α) {x y : α} (h : x + y = 1) : a = x * a + y * a := calc a = 1 * a : by rw [one_mul] ... = (x + y) * a : by rw [h] ... = x * a + y * a : by rw [add_mul] /-- If x is in an Ioo, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioo {a b x : α} (h : a < b) : x ∈ Ioo a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases hab : ¬a < b, { exfalso; exact hab h }, { refine ⟨(b-x) / (b-a), (x-a) / (b-a), _⟩, refine ⟨div_pos (by linarith) (by linarith), div_pos (by linarith) (by linarith),_,_⟩; { field_simp [show b - a ≠ 0, by linarith], ring } } }, { rw [mem_Ioo], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If x is in an Ioc, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ioc {a b x : α} (h : a < b) : x ∈ Ioc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 < x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = b, { exact ⟨0, 1, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨h_ax, lt_of_le_of_ne h_bx h_x⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, by linarith, Ioo_case.2⟩ } }, { rw [mem_Ioc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If x is in an Ico, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Ico {a b x : α} (h : a < b) : x ∈ Ico a b ↔ ∃ (x_a x_b : α), 0 < x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { rintros ⟨h_ax, h_bx⟩, by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioo h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Ico], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end /-- If x is in an Icc, it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Icc {a b x : α} (h : a ≤ b): x ∈ Icc a b ↔ ∃ (x_a x_b : α), 0 ≤ x_a ∧ 0 ≤ x_b ∧ x_a + x_b = 1 ∧ x_a * a + x_b * b = x := begin split, { intro x_in_I, rw [Icc, mem_set_of_eq] at x_in_I, rcases x_in_I with ⟨h_ax, h_bx⟩, by_cases hab' : a = b, { exact ⟨0, 1, le_refl 0, by linarith, by ring, by linarith⟩ }, change a ≠ b at hab', replace h : a < b, exact lt_of_le_of_ne h hab', by_cases h_x : x = a, { exact ⟨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}⟩ }, { rcases (convex.mem_Ioc h).mp ⟨lt_of_le_of_ne h_ax (ne.symm h_x), h_bx⟩ with ⟨x_a, x_b, Ioo_case⟩, exact ⟨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2⟩ } }, { rw [mem_Icc], rintros ⟨xa, xb, ⟨hxa, hxb, hxaxb, h₂⟩⟩, rw [←h₂], exact ⟨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]⟩ } end section submodule open submodule lemma submodule.convex (K : submodule ℝ E) : convex (↑K : set E) := by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption } lemma subspace.convex (K : subspace ℝ E) : convex (↑K : set E) := K.convex end submodule end sets section functions variables {β : Type*} [ordered_add_comm_monoid β] [semimodule ℝ β] local notation `[`x `, ` y `]` := segment x y /-! ### Convex functions -/ /-- Convexity of functions -/ def convex_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y /-- Concavity of functions -/ def concave_on (s : set E) (f : E → β) : Prop := convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y) /-- A function f is concave iff -f is convex -/ @[simp] lemma neg_convex_on_iff {γ : Type*} [ordered_add_comm_group γ] [semimodule ℝ γ] (s : set E) (f : E → γ) : convex_on s (-f) ↔ concave_on s f := begin split, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm] at h, exact h }, { rintros ⟨hconv, h⟩, refine ⟨hconv, _⟩, intros x y xs ys a b ha hb hab, specialize h xs ys ha hb hab, simp [neg_apply, neg_le, add_comm, h] } end /-- A function f is concave iff -f is convex -/ @[simp] lemma neg_concave_on_iff {γ : Type*} [ordered_add_comm_group γ] [semimodule ℝ γ] (s : set E) (f : E → γ) : concave_on s (-f) ↔ convex_on s f:= by rw [← neg_convex_on_iff s (-f), neg_neg f] lemma convex_on_id {s : set ℝ} (hs : convex s) : convex_on s id := ⟨hs, by { intros, refl }⟩ lemma concave_on_id {s : set ℝ} (hs : convex s) : concave_on s id := ⟨hs, by { intros, refl }⟩ lemma convex_on_const (c : β) (hs : convex s) : convex_on s (λ x:E, c) := ⟨hs, by { intros, simp only [← add_smul, *, one_smul] }⟩ lemma concave_on_const (c : β) (hs : convex s) : concave_on s (λ x:E, c) := @convex_on_const _ _ _ _ (order_dual β) _ _ c hs variables {t : set E} lemma convex_on_iff_div {f : E → β} : convex_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) • f x + (b/(a+b)) • f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha $ le_of_lt hab) (div_nonneg hb $ le_of_lt hab), rw [←add_div], exact div_self (ne_of_gt hab) end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ lemma concave_on_iff_div {f : E → β} : concave_on s f ↔ convex s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : ℝ⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • f x + (b/(a+b)) • f y ≤ f ((a/(a+b)) • x + (b/(a+b)) • y) := @convex_on_iff_div _ _ _ _ (order_dual β) _ _ _ /-- For a function on a convex set in a linear ordered space, in order to prove that it is convex it suffices to verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y) : convex_on s f := begin use hs, intros x y hx hy a b ha hb hab, wlog hxy : x<=y using [x y a b, y x b a], { exact le_total _ _ }, { cases eq_or_lt_of_le hxy with hxy hxy, by { subst y, rw [← add_smul, ← add_smul, hab, one_smul, one_smul] }, cases eq_or_lt_of_le ha with ha ha, by { subst a, rw [zero_add] at hab, subst b, simp }, cases eq_or_lt_of_le hb with hb hb, by { subst b, rw [add_zero] at hab, subst a, simp }, exact hf hx hy hxy ha hb hab } end /-- For a function on a convex set in a linear ordered space, in order to prove that it is concave it suffices to verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` only for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.concave_on_of_lt {f : E → β} [linear_order E] (hs : convex s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : ℝ⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y)) : concave_on s f := @linear_order.convex_on_of_lt _ _ _ _ (order_dual β) _ _ f _ hs hf /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity of a function is used in the proof of convexity of a function with a monotone derivative. -/ lemma convex_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) : convex_on s f := linear_order.convex_on_of_lt hs begin assume x z hx hz hxz a b ha hb hab, let y := a * x + b * z, have hxy : x < y, { rw [← one_mul x, ← hab, add_mul], exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ }, have hyz : y < z, { rw [← one_mul z, ← hab, add_mul], exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ }, have : (f y - f x) * (z - y) ≤ (f z - f y) * (y - x), from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz), have A : z - y + (y - x) = z - x, by abel, have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz), rw [sub_mul, sub_mul, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le, ← mul_add, A, ← le_div_iff B, add_div, mul_div_assoc, mul_div_assoc, mul_comm (f x), mul_comm (f z)] at this, rw [eq_comm, ← sub_eq_iff_eq_add] at hab; subst a, convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is convex on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : convex_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f y - f x) / (y - x) ≤ (f z - f y) / (z - y) := begin have h₁ : 0 < y - x := by linarith, have h₂ : 0 < z - y := by linarith, have h₃ : 0 < z - x := by linarith, suffices : f y / (y - x) + f y / (z - y) ≤ f x / (y - x) + f z / (z - y), by { ring at this ⊢, linarith }, set a := (z - y) / (z - x), set b := (y - x) / (z - x), have heqz : a • x + b • z = y, by { field_simp, rw div_eq_iff; [ring, linarith], }, have key, from hf.2 hx hz (show 0 ≤ a, by apply div_nonneg; linarith) (show 0 ≤ b, by apply div_nonneg; linarith) (show a + b = 1, by { field_simp, rw div_eq_iff; [ring, linarith], }), rw heqz at key, replace key := mul_le_mul_of_nonneg_left key (le_of_lt h₃), field_simp [ne_of_gt h₁, ne_of_gt h₂, ne_of_gt h₃, mul_comm (z - x) _] at key ⊢, rw div_le_div_right, { linarith, }, { nlinarith, }, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is convex on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma convex_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : convex_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f y - f x) / (y - x) ≤ (f z - f y) / (z - y)) := ⟨convex_on.slope_mono_adjacent, convex_on_real_of_slope_mono_adjacent hs⟩ /-- For a function `f` defined on a convex subset `D` of `ℝ`, if for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`, then `f` is concave on `D`. -/ lemma concave_on_real_of_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} (hf : ∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) : concave_on s f := begin rw [←neg_convex_on_iff], apply convex_on_real_of_slope_mono_adjacent hs, intros x y z xs zs xy yz, rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], simp only [hf xs zs xy yz, neg_sub_neg, pi.neg_apply], end /-- For a function `f` defined on a subset `D` of `ℝ`, if `f` is concave on `D`, then for any three points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on.slope_mono_adjacent {s : set ℝ} {f : ℝ → ℝ} (hf : concave_on s f) {x y z : ℝ} (hx : x ∈ s) (hz : z ∈ s) (hxy : x < y) (hyz : y < z) : (f z - f y) / (z - y) ≤ (f y - f x) / (y - x) := begin rw [←neg_le_neg_iff, ←neg_div, ←neg_div, neg_sub, neg_sub], rw [←neg_sub_neg (f y), ←neg_sub_neg (f z)], simp_rw [←pi.neg_apply], rw [←neg_convex_on_iff] at hf, apply convex_on.slope_mono_adjacent hf; assumption, end /-- For a function `f` defined on a convex subset `D` of `ℝ`, `f` is concave on `D` iff for any three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope of the secant line of `f` on `[x, z]`. -/ lemma concave_on_real_iff_slope_mono_adjacent {s : set ℝ} (hs : convex s) {f : ℝ → ℝ} : concave_on s f ↔ (∀ {x y z : ℝ}, x ∈ s → z ∈ s → x < y → y < z → (f z - f y) / (z - y) ≤ (f y - f x) / (y - x)) := ⟨concave_on.slope_mono_adjacent, concave_on_real_of_slope_mono_adjacent hs⟩ lemma convex_on.subset {f : E → β} (h_convex_on : convex_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : convex_on s f := begin apply and.intro h_convex, intros x y hx hy, exact h_convex_on.2 (h_subset hx) (h_subset hy), end lemma concave_on.subset {f : E → β} (h_concave_on : concave_on t f) (h_subset : s ⊆ t) (h_convex : convex s) : concave_on s f := @convex_on.subset _ _ _ _ (order_dual β) _ _ t f h_concave_on h_subset h_convex lemma convex_on.add {f g : E → β} (hf : convex_on s f) (hg : convex_on s g) : convex_on s (λx, f x + g x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) ≤ (a • f x + b • f y) + (a • g x + b • g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a • f x + a • g x + b • f y + b • g y : by abel ... = a • (f x + g x) + b • (f y + g y) : by simp [smul_add, add_assoc] end lemma concave_on.add {f g : E → β} (hf : concave_on s f) (hg : concave_on s g) : concave_on s (λx, f x + g x) := @convex_on.add _ _ _ _ (order_dual β) _ _ f g hf hg lemma convex_on.smul [ordered_semimodule ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : convex_on s f) : convex_on s (λx, c • f x) := begin apply and.intro hf.1, intros x y hx hy a b ha hb hab, calc c • f (a • x + b • y) ≤ c • (a • f x + b • f y) : smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc ... = a • (c • f x) + b • (c • f y) : by simp only [smul_add, smul_comm c] end lemma concave_on.smul [ordered_semimodule ℝ β] {f : E → β} {c : ℝ} (hc : 0 ≤ c) (hf : concave_on s f) : concave_on s (λx, c • f x) := @convex_on.smul _ _ _ _ (order_dual β) _ _ _ f c hc hf /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment' {γ : Type*} [linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} {x y : E} {a b : ℝ} (hf : convex_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • max (f x) (f y) + b • max (f x) (f y) : add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha) (smul_le_smul_of_nonneg (le_max_right _ _) hb) ... ≤ max (f x) (f y) : by rw [←add_smul, hab, one_smul] /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment' {γ : Type*} [linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} {x y : E} {a b : ℝ} (hf : concave_on s f) (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : min (f x) (f y) ≤ f (a • x + b • y) := @convex_on.le_on_segment' _ _ _ _ (order_dual γ) _ _ _ f x y a b hf hx hy ha hb hab /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment {γ : Type*} [linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : convex_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : f z ≤ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.le_on_segment {γ : Type*} [linear_ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : concave_on s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x, y]) : min (f x) (f y) ≤ f z := @convex_on.le_on_segment _ _ _ _ (order_dual γ) _ _ _ f hf x y z hx hy hz lemma convex_on.convex_le [ordered_semimodule ℝ β] {f : E → β} (hf : convex_on s f) (r : β) : convex {x ∈ s | f x ≤ r} := convex_iff_segment_subset.2 $ λ x y hx hy z hz, begin refine ⟨hf.1.segment_subset hx.1 hy.1 hz,_⟩, rcases hz with ⟨za,zb,hza,hzb,hzazb,H⟩, rw ←H, calc f (za • x + zb • y) ≤ za • (f x) + zb • (f y) : hf.2 hx.1 hy.1 hza hzb hzazb ... ≤ za • r + zb • r : add_le_add (smul_le_smul_of_nonneg hx.2 hza) (smul_le_smul_of_nonneg hy.2 hzb) ... ≤ r : by simp [←add_smul, hzazb] end lemma concave_on.concave_le [ordered_semimodule ℝ β] {f : E → β} (hf : concave_on s f) (r : β) : convex {x ∈ s | r ≤ f x} := @convex_on.convex_le _ _ _ _ (order_dual β) _ _ _ f hf r lemma convex_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : convex_on s f) (r : γ) : convex {x ∈ s | f x < r} := begin intros a b as bs xa xb hxa hxb hxaxb, refine ⟨hf.1 as.1 bs.1 hxa hxb hxaxb,_⟩, dsimp, by_cases H : xa = 0, { have H' : xb = 1 := by rwa [H, zero_add] at hxaxb, rw [H, H', zero_smul, one_smul, zero_add], exact bs.2 }, { calc f (xa • a + xb • b) ≤ xa • (f a) + xb • (f b) : hf.2 as.1 bs.1 hxa hxb hxaxb ... < xa • r + xb • (f b) : (add_lt_add_iff_right (xb • (f b))).mpr (smul_lt_smul_of_pos as.2 (lt_of_le_of_ne hxa (ne.symm H))) ... ≤ xa • r + xb • r : (add_le_add_iff_left (xa • r)).mpr (smul_le_smul_of_nonneg (le_of_lt bs.2) hxb) ... = r : by simp only [←add_smul, hxaxb, one_smul] } end lemma concave_on.convex_lt {γ : Type*} [ordered_cancel_add_comm_monoid γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : concave_on s f) (r : γ) : convex {x ∈ s | r < f x} := @convex_on.convex_lt _ _ _ _ (order_dual γ) _ _ _ f hf r lemma convex_on.convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : convex_on s f) : convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin rintros ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • r + b • t : add_le_add (smul_le_smul_of_nonneg hr ha) (smul_le_smul_of_nonneg ht hb) end lemma concave_on.convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} (hf : concave_on s f) : convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on.convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f hf lemma convex_on_iff_convex_epigraph {γ : Type*} [ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} : convex_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin refine ⟨convex_on.convex_epigraph, λ h, ⟨_, _⟩⟩, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).1 }, { assume x y hx hy a b ha hb hab, exact (@h (x, f x) (y, f y) ⟨hx, le_refl _⟩ ⟨hy, le_refl _⟩ a b ha hb hab).2 } end lemma concave_on_iff_convex_hypograph {γ : Type*} [ordered_add_comm_group γ] [semimodule ℝ γ] [ordered_semimodule ℝ γ] {f : E → γ} : concave_on s f ↔ convex {p : E × γ | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on_iff_convex_epigraph _ _ _ _ (order_dual γ) _ _ _ f /-- If a function is convex on s, it remains convex when precomposed by an affine map -/ lemma convex_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F} (hf : convex_on s f) : convex_on (g ⁻¹' s) (f ∘ g) := begin refine ⟨hf.1.affine_preimage _,_⟩, intros x y xs ys a b ha hb hab, calc (f ∘ g) (a • x + b • y) = f (g (a • x + b • y)) : rfl ... = f (a • (g x) + b • (g y)) : by rw [convex.combo_affine_apply hab] ... ≤ a • f (g x) + b • f (g y) : hf.2 xs ys ha hb hab ... = a • (f ∘ g) x + b • (f ∘ g) y : rfl end /-- If a function is concave on s, it remains concave when precomposed by an affine map -/ lemma concave_on.comp_affine_map {f : F → β} (g : E →ᵃ[ℝ] F) {s : set F} (hf : concave_on s f) : concave_on (g ⁻¹' s) (f ∘ g) := @convex_on.comp_affine_map _ _ _ _ _ _ (order_dual β) _ _ f g s hf /-- If g is convex on s, so is (g ∘ f) on f ⁻¹' s for a linear f. -/ lemma convex_on.comp_linear_map {g : F → β} {s : set F} (hg : convex_on s g) (f : E →ₗ[ℝ] F) : convex_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If g is concave on s, so is (g ∘ f) on f ⁻¹' s for a linear f. -/ lemma concave_on.comp_linear_map {g : F → β} {s : set F} (hg : concave_on s g) (f : E →ₗ[ℝ] F) : concave_on (f ⁻¹' s) (g ∘ f) := hg.comp_affine_map f.to_affine_map /-- If a function is convex on s, it remains convex after a translation. -/ lemma convex_on.translate_right {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is concave on s, it remains concave after a translation. -/ lemma concave_on.translate_right {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, a + z)) := hf.comp_affine_map $ affine_map.const ℝ E a +ᵥ affine_map.id ℝ E /-- If a function is convex on s, it remains convex after a translation. -/ lemma convex_on.translate_left {f : E → β} {s : set E} {a : E} (hf : convex_on s f) : convex_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right /-- If a function is concave on s, it remains concave after a translation. -/ lemma concave_on.translate_left {f : E → β} {s : set E} {a : E} (hf : concave_on s f) : concave_on ((λ z, a + z) ⁻¹' s) (f ∘ (λ z, z + a)) := by simpa only [add_comm] using hf.translate_right end functions section center_mass /-- Center mass of a finite collection of points with prescribed weights. Note that we require neither `0 ≤ w i` nor `∑ w = 1`. -/ noncomputable def finset.center_mass (t : finset ι) (w : ι → ℝ) (z : ι → E) : E := (∑ i in t, w i)⁻¹ • (∑ i in t, w i • z i) variables (i j : ι) (c : ℝ) (t : finset ι) (w : ι → ℝ) (z : ι → E) open finset lemma finset.center_mass_empty : (∅ : finset ι).center_mass w z = 0 := by simp only [center_mass, sum_empty, smul_zero] lemma finset.center_mass_pair (hne : i ≠ j) : ({i, j} : finset ι).center_mass w z = (w i / (w i + w j)) • z i + (w j / (w i + w j)) • z j := by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul] variable {w} lemma finset.center_mass_insert (ha : i ∉ t) (hw : ∑ j in t, w j ≠ 0) : (insert i t).center_mass w z = (w i / (w i + ∑ j in t, w j)) • z i + ((∑ j in t, w j) / (w i + ∑ j in t, w j)) • t.center_mass w z := begin simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm, ← div_eq_inv_mul], congr' 2, rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div] end lemma finset.center_mass_singleton (hw : w i ≠ 0) : ({i} : finset ι).center_mass w z = z i := by rw [center_mass, sum_singleton, sum_singleton, ← mul_smul, inv_mul_cancel hw, one_smul] lemma finset.center_mass_eq_of_sum_1 (hw : ∑ i in t, w i = 1) : t.center_mass w z = ∑ i in t, w i • z i := by simp only [finset.center_mass, hw, inv_one, one_smul] lemma finset.center_mass_smul : t.center_mass w (λ i, c • z i) = c • t.center_mass w z := by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc] /-- A convex combination of two centers of mass is a center of mass as well. This version deals with two different index types. -/ lemma finset.center_mass_segment' (s : finset ι) (t : finset ι') (ws : ι → ℝ) (zs : ι → E) (wt : ι' → ℝ) (zt : ι' → E) (hws : ∑ i in s, ws i = 1) (hwt : ∑ i in t, wt i = 1) (a b : ℝ) (hab : a + b = 1): a • s.center_mass ws zs + b • t.center_mass wt zt = (s.image sum.inl ∪ t.image sum.inr).center_mass (sum.elim (λ i, a * ws i) (λ j, b * wt j)) (sum.elim zs zt) := begin rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt, smul_sum, smul_sum, ← finset.sum_sum_elim, finset.center_mass_eq_of_sum_1], { congr' with ⟨⟩; simp only [sum.elim_inl, sum.elim_inr, mul_smul] }, { rw [sum_sum_elim, ← mul_sum, ← mul_sum, hws, hwt, mul_one, mul_one, hab] } end /-- A convex combination of two centers of mass is a center of mass as well. This version works if two centers of mass share the set of original points. -/ lemma finset.center_mass_segment (s : finset ι) (w₁ w₂ : ι → ℝ) (z : ι → E) (hw₁ : ∑ i in s, w₁ i = 1) (hw₂ : ∑ i in s, w₂ i = 1) (a b : ℝ) (hab : a + b = 1): a • s.center_mass w₁ z + b • s.center_mass w₂ z = s.center_mass (λ i, a * w₁ i + b * w₂ i) z := have hw : ∑ i in s, (a * w₁ i + b * w₂ i) = 1, by simp only [mul_sum.symm, sum_add_distrib, mul_one, *], by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *] lemma finset.center_mass_ite_eq (hi : i ∈ t) : t.center_mass (λ j, if (i = j) then 1 else 0) z = z i := begin rw [finset.center_mass_eq_of_sum_1], transitivity ∑ j in t, if (i = j) then z i else 0, { congr' with i, split_ifs, exacts [h ▸ one_smul _ _, zero_smul _ _] }, { rw [sum_ite_eq, if_pos hi] }, { rw [sum_ite_eq, if_pos hi] } end variables {t w} lemma finset.center_mass_subset {t' : finset ι} (ht : t ⊆ t') (h : ∀ i ∈ t', i ∉ t → w i = 0) : t.center_mass w z = t'.center_mass w z := begin rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum], apply sum_subset ht, assume i hit' hit, rw [h i hit' hit, zero_smul, smul_zero] end lemma finset.center_mass_filter_ne_zero : (t.filter (λ i, w i ≠ 0)).center_mass w z = t.center_mass w z := finset.center_mass_subset z (filter_subset _ _) $ λ i hit hit', by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit' variable {z} /-- Center mass of a finite subset of a convex set belongs to the set provided that all weights are non-negative, and the total weight is positive. -/ lemma convex.center_mass_mem (hs : convex s) : (∀ i ∈ t, 0 ≤ w i) → (0 < ∑ i in t, w i) → (∀ i ∈ t, z i ∈ s) → t.center_mass w z ∈ s := begin induction t using finset.induction with i t hi ht, { simp [lt_irrefl] }, intros h₀ hpos hmem, have zi : z i ∈ s, from hmem _ (mem_insert_self _ _), have hs₀ : ∀ j ∈ t, 0 ≤ w j, from λ j hj, h₀ j $ mem_insert_of_mem hj, rw [sum_insert hi] at hpos, by_cases hsum_t : ∑ j in t, w j = 0, { have ws : ∀ j ∈ t, w j = 0, from (sum_eq_zero_iff_of_nonneg hs₀).1 hsum_t, have wz : ∑ j in t, w j • z j = 0, from sum_eq_zero (λ i hi, by simp [ws i hi]), simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero], simp only [hsum_t, add_zero] at hpos, rw [← mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul], exact zi }, { rw [finset.center_mass_insert _ _ _ hi hsum_t], refine convex_iff_div.1 hs zi (ht hs₀ _ _) _ (sum_nonneg hs₀) hpos, { exact lt_of_le_of_ne (sum_nonneg hs₀) (ne.symm hsum_t) }, { intros j hj, exact hmem j (mem_insert_of_mem hj) }, { exact h₀ _ (mem_insert_self _ _) } } end lemma convex.sum_mem (hs : convex s) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s) : ∑ i in t, w i • z i ∈ s := by simpa only [h₁, center_mass, inv_one, one_smul] using hs.center_mass_mem h₀ (h₁.symm ▸ zero_lt_one) hz lemma convex_iff_sum_mem : convex s ↔ (∀ (t : finset E) (w : E → ℝ), (∀ i ∈ t, 0 ≤ w i) → ∑ i in t, w i = 1 → (∀ x ∈ t, x ∈ s) → ∑ x in t, w x • x ∈ s ) := begin refine ⟨λ hs t w hw₀ hw₁ hts, hs.sum_mem hw₀ hw₁ hts, _⟩, intros h x y hx hy a b ha hb hab, by_cases h_cases: x = y, { rw [h_cases, ←add_smul, hab, one_smul], exact hy }, { convert h {x, y} (λ z, if z = y then b else a) _ _ _, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] }, { simp_intros i hi, cases hi; subst i; simp [ha, hb, if_neg h_cases] }, { simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] }, { simp_intros i hi, cases hi; subst i; simp [hx, hy, if_neg h_cases] } } end /-- Jensen's inequality, `finset.center_mass` version. -/ lemma convex_on.map_center_mass_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (hpos : 0 < ∑ i in t, w i) (hmem : ∀ i ∈ t, z i ∈ s) : f (t.center_mass w z) ≤ t.center_mass w (f ∘ z) := begin have hmem' : ∀ i ∈ t, (z i, (f ∘ z) i) ∈ {p : E × ℝ | p.1 ∈ s ∧ f p.1 ≤ p.2}, from λ i hi, ⟨hmem i hi, le_refl _⟩, convert (hf.convex_epigraph.center_mass_mem h₀ hpos hmem').2; simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum] end /-- Jensen's inequality, `finset.sum` version. -/ lemma convex_on.map_sum_le {f : E → ℝ} (hf : convex_on s f) (h₀ : ∀ i ∈ t, 0 ≤ w i) (h₁ : ∑ i in t, w i = 1) (hmem : ∀ i ∈ t, z i ∈ s) : f (∑ i in t, w i • z i) ≤ ∑ i in t, w i * (f (z i)) := by simpa only [center_mass, h₁, inv_one, one_smul] using hf.map_center_mass_le h₀ (h₁.symm ▸ zero_lt_one) hmem /-- If a function `f` is convex on `s` takes value `y` at the center mass of some points `z i ∈ s`, then for some `i` we have `y ≤ f (z i)`. -/ lemma convex_on.exists_ge_of_center_mass {f : E → ℝ} (h : convex_on s f) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) (hz : ∀ i ∈ t, z i ∈ s) : ∃ i ∈ t, f (t.center_mass w z) ≤ f (z i) := begin set y := t.center_mass w z, have : f y ≤ t.center_mass w (f ∘ z) := h.map_center_mass_le hw₀ hws hz, rw ← sum_filter_ne_zero at hws, rw [← finset.center_mass_filter_ne_zero (f ∘ z), center_mass, smul_eq_mul, ← div_eq_inv_mul, le_div_iff hws, mul_sum] at this, replace : ∃ i ∈ t.filter (λ i, w i ≠ 0), f y * w i ≤ w i • (f ∘ z) i := exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this, rcases this with ⟨i, hi, H⟩, rw [mem_filter] at hi, use [i, hi.1], simp only [smul_eq_mul, mul_comm (w i)] at H, refine (mul_le_mul_right _).1 H, exact lt_of_le_of_ne (hw₀ i hi.1) hi.2.symm end end center_mass section convex_hull variable {t : set E} /-- Convex hull of a set `s` is the minimal convex set that includes `s` -/ def convex_hull (s : set E) : set E := ⋂ (t : set E) (hst : s ⊆ t) (ht : convex t), t variable (s) lemma subset_convex_hull : s ⊆ convex_hull s := set.subset_Inter $ λ t, set.subset_Inter $ λ hst, set.subset_Inter $ λ ht, hst lemma convex_convex_hull : convex (convex_hull s) := convex_Inter $ λ t, convex_Inter $ λ ht, convex_Inter id variable {s} lemma convex_hull_min (hst : s ⊆ t) (ht : convex t) : convex_hull s ⊆ t := set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht lemma convex_hull_mono (hst : s ⊆ t) : convex_hull s ⊆ convex_hull t := convex_hull_min (set.subset.trans hst $ subset_convex_hull t) (convex_convex_hull t) lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s := set.subset.antisymm (convex_hull_min (set.subset.refl _) hs) (subset_convex_hull s) @[simp] lemma convex_hull_singleton {x : E} : convex_hull ({x} : set E) = {x} := (convex_singleton x).convex_hull_eq lemma is_linear_map.image_convex_hull {f : E → F} (hf : is_linear_map ℝ f) : f '' (convex_hull s) = convex_hull (f '' s) := begin refine set.subset.antisymm _ _, { rw [set.image_subset_iff], exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s) ((convex_convex_hull (f '' s)).is_linear_preimage hf) }, { exact convex_hull_min (set.image_subset _ $ subset_convex_hull s) ((convex_convex_hull s).is_linear_image hf) } end lemma linear_map.image_convex_hull (f : E →ₗ[ℝ] F) : f '' (convex_hull s) = convex_hull (f '' s) := f.is_linear.image_convex_hull lemma finset.center_mass_mem_convex_hull (t : finset ι) {w : ι → ℝ} (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hws : 0 < ∑ i in t, w i) {z : ι → E} (hz : ∀ i ∈ t, z i ∈ s) : t.center_mass w z ∈ convex_hull s := (convex_convex_hull s).center_mass_mem hw₀ hws (λ i hi, subset_convex_hull s $ hz i hi) -- TODO : Do we need other versions of the next lemma? /-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t ⊆ s`. This version allows finsets in any type in any universe. -/ lemma convex_hull_eq (s : set E) : convex_hull s = {x : E | ∃ (ι : Type u') (t : finset ι) (w : ι → ℝ) (z : ι → E) (hw₀ : ∀ i ∈ t, 0 ≤ w i) (hw₁ : ∑ i in t, w i = 1) (hz : ∀ i ∈ t, z i ∈ s) , t.center_mass w z = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, use [punit, {punit.star}, λ _, 1, λ _, x, λ _ _, zero_le_one, finset.sum_singleton, λ _ _, hx], simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] }, { rintros x y ⟨ι, sx, wx, zx, hwx₀, hwx₁, hzx, rfl⟩ ⟨ι', sy, wy, zy, hwy₀, hwy₁, hzy, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment' _ _ _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, _, _, _, _, rfl⟩, { rintros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [mul_nonneg, hwx₀, hwy₀] }, { simp [finset.sum_sum_elim, finset.mul_sum.symm, *] }, { intros i hi, rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨j, hj, rfl⟩|⟨j, hj, rfl⟩; simp only [sum.elim_inl, sum.elim_inr]; apply_rules [hzx, hzy] } }, { rintros _ ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, exact t.center_mass_mem_convex_hull hw₀ (hw₁.symm ▸ zero_lt_one) hz } end /-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`, then `f` can't have a maximum on `convex_hull s` outside of `s`. -/ lemma convex_on.exists_ge_of_mem_convex_hull {f : E → ℝ} (hf : convex_on (convex_hull s) f) {x} (hx : x ∈ convex_hull s) : ∃ y ∈ s, f x ≤ f y := begin rw convex_hull_eq at hx, rcases hx with ⟨α, t, w, z, hw₀, hw₁, hz, rfl⟩, rcases hf.exists_ge_of_center_mass hw₀ (hw₁.symm ▸ zero_lt_one) (λ i hi, subset_convex_hull s (hz i hi)) with ⟨i, hit, Hi⟩, exact ⟨z i, hz i hit, Hi⟩ end lemma finset.convex_hull_eq (s : finset E) : convex_hull ↑s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in s, w y = 1), s.center_mass w id = x} := begin refine subset.antisymm (convex_hull_min _ _) _, { intros x hx, rw [finset.mem_coe] at hx, refine ⟨_, _, _, finset.center_mass_ite_eq _ _ _ hx⟩, { intros, split_ifs, exacts [zero_le_one, le_refl 0] }, { rw [finset.sum_ite_eq, if_pos hx] } }, { rintros x y ⟨wx, hwx₀, hwx₁, rfl⟩ ⟨wy, hwy₀, hwy₁, rfl⟩ a b ha hb hab, rw [finset.center_mass_segment _ _ _ _ hwx₁ hwy₁ _ _ hab], refine ⟨_, _, _, rfl⟩, { rintros i hi, apply_rules [add_nonneg, mul_nonneg, hwx₀, hwy₀], }, { simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } }, { rintros _ ⟨w, hw₀, hw₁, rfl⟩, exact s.center_mass_mem_convex_hull (λ x hx, hw₀ _ hx) (hw₁.symm ▸ zero_lt_one) (λ x hx, hx) } end lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) : convex_hull s = {x : E | ∃ (w : E → ℝ) (hw₀ : ∀ y ∈ s, 0 ≤ w y) (hw₁ : ∑ y in hs.to_finset, w y = 1), hs.to_finset.center_mass w id = x} := by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop] using hs.to_finset.convex_hull_eq lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) : convex_hull s = ⋃ (t : finset E) (w : ↑t ⊆ s), convex_hull ↑t := begin refine subset.antisymm _ _, { rw [convex_hull_eq.{u}], rintros x ⟨ι, t, w, z, hw₀, hw₁, hz, rfl⟩, simp only [mem_Union], refine ⟨t.image z, _, _⟩, { rw [finset.coe_image, image_subset_iff], exact hz }, { apply t.center_mass_mem_convex_hull hw₀, { simp only [hw₁, zero_lt_one] }, { exact λ i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } }, { exact Union_subset (λ i, Union_subset convex_hull_mono), }, end lemma is_linear_map.convex_hull_image {f : E → F} (hf : is_linear_map ℝ f) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $ (convex_convex_hull s).is_linear_image hf) (image_subset_iff.2 $ convex_hull_min (image_subset_iff.1 $ subset_convex_hull _) ((convex_convex_hull _).is_linear_preimage hf)) lemma linear_map.convex_hull_image (f : E →ₗ[ℝ] F) (s : set E) : convex_hull (f '' s) = f '' convex_hull s := f.is_linear.convex_hull_image s end convex_hull /-! ### Simplex -/ section simplex variables (ι) [fintype ι] {f : ι → ℝ} /-- Standard simplex in the space of functions `ι → ℝ` is the set of vectors with non-negative coordinates with total sum `1`. -/ def std_simplex (ι : Type*) [fintype ι] : set (ι → ℝ) := { f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1 } lemma std_simplex_eq_inter : std_simplex ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} := by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] } lemma convex_std_simplex : convex (std_simplex ι) := begin refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩, { apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] }, { erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2, smul_eq_mul, smul_eq_mul, mul_one, mul_one], exact hab } end variable {ι} lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:ℝ) 0) ∈ std_simplex ι := ⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)] ⟩ /-- `std_simplex ι` is the convex hull of the canonical basis in `ι → ℝ`. -/ lemma convex_hull_basis_eq_std_simplex : convex_hull (range $ λ(i j:ι), if i = j then (1:ℝ) else 0) = std_simplex ι := begin refine subset.antisymm (convex_hull_min _ (convex_std_simplex ι)) _, { rintros _ ⟨i, rfl⟩, exact ite_eq_mem_std_simplex i }, { rintros w ⟨hw₀, hw₁⟩, rw [pi_eq_sum_univ w, ← finset.univ.center_mass_eq_of_sum_1 _ hw₁], exact finset.univ.center_mass_mem_convex_hull (λ i hi, hw₀ i) (hw₁.symm ▸ zero_lt_one) (λ i hi, mem_range_self i) } end variable {ι} /-- Convex hull of a finite set is the image of the standard simplex in `s → ℝ` under the linear map sending each function `w` to `∑ x in s, w x • x`. Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`. The map is defined in terms of operations on `(s → ℝ) →ₗ[ℝ] ℝ` so that later we will not need to prove that this map is linear. -/ lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) : convex_hull s = by haveI := hs.fintype; exact (⇑(∑ x : s, (@linear_map.proj ℝ s _ (λ i, ℝ) _ _ x).smul_right x.1)) '' (std_simplex s) := begin rw [← convex_hull_basis_eq_std_simplex, ← linear_map.convex_hull_image, ← set.range_comp, (∘)], apply congr_arg, convert subtype.range_coe.symm, ext x, simp [linear_map.sum_apply, ite_smul, finset.filter_eq] end /-- All values of a function `f ∈ std_simplex ι` belong to `[0, 1]`. -/ lemma mem_Icc_of_mem_std_simplex (hf : f ∈ std_simplex ι) (x) : f x ∈ I := ⟨hf.1 x, hf.2 ▸ finset.single_le_sum (λ y hy, hf.1 y) (finset.mem_univ x)⟩ end simplex
107099ed6931be942d6023f27becf9e2787b0099
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/category-theory.lean
83b6699799b2f21a2ac52e3e85b78dbabb56867d
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
5,943
lean
import standard --import data.nat structure Category := (Obj : Type) (Hom : Obj → Obj → Type) (identity : Π A : Obj, Hom A A) (compose : Π ⦃A B C : Obj⦄, Hom A B → Hom B C → Hom A C) (left_identity : Π ⦃A B : Obj⦄ (f : Hom A B), compose (identity _) f = f) (right_identity : Π ⦃A B : Obj⦄ (f : Hom A B), compose f (identity _) = f) (associativity : Π ⦃A B C D : Obj⦄ (f : Hom A B) (g : Hom B C) (h : Hom C D), compose (compose f g) h = compose f (compose g h)) namespace Category -- Can we put this before the definition? notation f ∘ g := compose _ _ _ _ f g -- infixr `∘` := compose _ _ _ _ infixl `⟶` :25 := Hom _ --def Mor := Hom end Category /- instance ℕCategory : Category := { Category . Obj := unit, Hom := λ a b, ℕ, identity := λ a, 0, compose := λ a b c, add, left_identity := λ a b, zero_add, right_identity := λ a b, add_zero, associativity := λ a b c d, add_assoc } -- This is how Coq's program directive does it under the -- hood. Everything after the refine line should be able to be -- replaced by a single tactic (like crush). instance ℕCategory' : Category := begin refine (Category.mk unit (λ a b, ℕ) (λ a, 0) (λ a b c, add) _ _ _), intros A B, exact zero_add, intros A B, exact add_zero, intros A B C D, exact add_assoc end -/ open Category print Category -- This needs to use typeclasses; still trying to figure that out class Functor (source target : Category) := (onObjects : Obj source → Obj target) (onMorphisms : Π ⦃a b : Obj source⦄, Hom _ a b → Hom _ (onObjects a) (onObjects b)) -- -- (identities : Π (a : Obj source), onMorphisms (Id _ a) = Id _ (onObjects a)) -- (functoriality : Π ⦃a b c : Obj source⦄ (f : Hom _ a b) (g : Hom _ b c), -- onMorphisms (f ∘ g) = onMorphisms f ∘ onMorphisms g) --namespace Functor -- infix `<$>`:50 := λ {C D : Category} (F : Functor C D) (a : Obj C), onObjects F a -- infix `<$>m`:50 := λ {C D : Category} (F : Functor C D) {a b : Obj C} -- (f : Hom _ a b), onMorphisms F f --end Functor -- --open function -- This clearly shouldn't be here. In Lean 2, this could be done by blast theorem double_order (n m p q : ℕ) : n + m + (p + q) = n + p + (m + q) := calc n + m + (p + q) = n + (m + (p + q)) : add_assoc n m (p + q) ... = n + (m + p + q) : eq.symm (congr_arg (add n) (add_assoc m p q)) ... = n + (p + m + q) : congr_arg (add n) (congr_arg (λ n, n + q) (add_comm m p)) ... = n + (p + (m + q)) : congr_arg (add n) (add_assoc p m q) ... = n + p + (m + q) : eq.symm (add_assoc n p (m + q)) --@[reducible] --def DoublingAsFunctor : Functor ℕCategory ℕCategory := -- { Functor . -- onObj := id, -- onMor := λ a b (n : ℕ), n + n, -- -- respect_Id := λ a, rfl, -- respect_comp := begin -- intros, -- exact double_order f g f g -- end } -- This was a part of the standard library in Lean 2. Let's put it in -- until they add it again. theorem pair_eq {A B : Type} {a₁ a₂ : A} {b₁ b₂ : B} : a₁ = a₂ → b₁ = b₂ → (a₁, b₁) = (a₂, b₂) := assume H1 H2, H1 ▸ H2 ▸ rfl open prod -- Needs to use typeclasses again. --instance ProductCategory (C D : Category) [Category] [Category] : Category := -- { Category . -- Obj := Obj C × Obj D, -- Hom := λ a b, Hom C (fst a) (fst b) × Hom D (snd a) (snd b), -- -- identity := λ a, (identity C (fst a), identity D (snd a)), -- compose := λ a b c f g, (fst f ∘ fst g, snd f ∘ snd g), -- -- left_identities := λ a b c d, pair_eq (left_identity C _) (left_identity D _) , -- right_identities := λ a b c d, pair_eq (right_identity C _) (right_identity D _), -- associativity := begin -- intros, -- exact pair_eq (assoc C _ _ _ _ _) (assoc D _ _ _ _ _) -- end } -- --namespace ProductCategory -- notation C `×c` D := ProductCategory C D --end ProductCategory -- --open Functor --open ProductCategory -- --structure LaxMonoidalCategory := -- (carrier : Category) -- (tensor : Functor (carrier ×c carrier) carrier) -- (unit : let obj := Obj carrier in obj) -- -- (associator : Π (a b c : Obj carrier), -- Hom _ (tensor <$> (tensor <$> (a,b), c)) -- (tensor <$> (a, tensor <$> (b,c)))) -- --(pentagon : Π (a b c d : Obj carrier), -- -- associator (tensor <$> (a,b)) c d ∘c associator a b (tensor <$> (c,d)) = -- ----attribute [coercion] LaxMonoidalCategory.carrier ---- --namespace LaxMonoidalCategory -- infix `⊗`:70 := λ {C : LaxMonoidalCategory} (a b : Obj C), tensor C <$> (a,b) -- infix `⊗m`:70 := λ {C : LaxMonoidalCategory} {a b c d : Obj C} -- (f : Hom a b) (g : Hom c d), tensor C <$> (f,g) --end LaxMonoidalCategory --@[reducible] --def ℕTensorProduct : Functor (ℕCategory ×c ℕCategory) ℕCategory := -- { Functor . -- onObj := fst, -- onMor := λ a b n, fst n + snd n, -- -- respect_Id := λ a, rfl, -- respect_comp := begin -- intros, -- refine (double_order f g f g) -- end } --def ℕTensorProduct' : Functor (ℕCategory ×c ℕCategory) ℕCategory := -- Functor.mk pr1 (λ a b (f : ℕ × ℕ), pr1 f + pr2 f) _ _ _ --begin -- refine Functor.mk (pr1) (λ (a b : unit), λ (f : ℕ × ℕ), pr1 f + pr2 f) _ _, --end -- --def ℕLaxMonoidalCategory : LaxMonoidalCategory := -- ⦃ LaxMonoidalCategory, -- carrier := ℕCategory, -- tensor := ℕTensorProduct, -- unit := unit.star, -- -- associator := λ a b c, Id _ _ ⦄ -- --open LaxMonoidalCategory --check (2 : Hom ℕLaxMonoidalCategory unit.star unit.star)
aae2634dd0be4c86a041edf5ef3f4b7f5acba4ce
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/data/buffer.lean
40b481575fb19cecffa67844de522001c6c66149
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,115
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 -/ universes u w def buffer (α : Type u) := Σ n, array α n def mk_buffer {α : Type u} : buffer α := ⟨0, {data := λ i, fin.elim0 i}⟩ def array.to_buffer {α : Type u} {n : nat} (a : array α n) : buffer α := ⟨n, a⟩ namespace buffer variables {α : Type u} {β : Type w} def nil : buffer α := mk_buffer def size (b : buffer α) : nat := b.1 def to_array (b : buffer α) : array α (b.size) := b.2 def push_back : buffer α → α → buffer α | ⟨n, a⟩ v := ⟨n+1, a.push_back v⟩ def pop_back : buffer α → buffer α | ⟨0, a⟩ := ⟨0, a⟩ | ⟨n+1, a⟩ := ⟨n, a.pop_back⟩ def read : Π (b : buffer α), fin b.size → α | ⟨n, a⟩ i := a.read i def write : Π (b : buffer α), fin b.size → α → buffer α | ⟨n, a⟩ i v := ⟨n, a.write i v⟩ def read' [inhabited α] : buffer α → nat → α | ⟨n, a⟩ i := a.read' i def write' : buffer α → nat → α → buffer α | ⟨n, a⟩ i v := ⟨n, a.write' i v⟩ lemma read_eq_read' [inhabited α] (b : buffer α) (i : nat) (h : i < b.size) : read b ⟨i, h⟩ = read' b i := by cases b; unfold read read'; simp [array.read_eq_read'] lemma write_eq_write' (b : buffer α) (i : nat) (h : i < b.size) (v : α) : write b ⟨i, h⟩ v = write' b i v := by cases b; unfold write write'; simp [array.write_eq_write'] def to_list (b : buffer α) : list α := b.to_array.to_list protected def to_string (b : buffer α) : list α := b.to_array.to_list.reverse def append_list {α : Type u} : buffer α → list α → buffer α | b [] := b | b (v::vs) := append_list (b.push_back v) vs def append_string (b : buffer char) (s : string) : buffer char := b.append_list s.reverse def append_array {α : Type u} {n : nat} (nz : n > 0) : buffer α → array α n → ∀ i : nat, i < n → buffer α | ⟨m, b⟩ a 0 _ := let i : fin n := ⟨n - 1, array.lt_aux_2 nz⟩ in ⟨m+1, b.push_back (a.read i)⟩ | ⟨m, b⟩ a (j+1) h := let i : fin n := ⟨n - 2 - j, array.lt_aux_3 h⟩ in append_array ⟨m+1, b.push_back (a.read i)⟩ a j (array.lt_aux_1 h) protected def append {α : Type u} : buffer α → buffer α → buffer α | b ⟨0, a⟩ := b | b ⟨n+1, a⟩ := append_array (nat.zero_lt_succ _) b a n (nat.lt_succ_self _) def iterate : Π b : buffer α, β → (fin b.size → α → β → β) → β | ⟨_, a⟩ b f := a.iterate b f def foreach : Π b : buffer α, (fin b.size → α → α) → buffer α | ⟨n, a⟩ f := ⟨n, a.foreach f⟩ def map (f : α → α) : buffer α → buffer α | ⟨n, a⟩ := ⟨n, a.map f⟩ def foldl : buffer α → β → (α → β → β) → β | ⟨_, a⟩ b f := a.foldl b f def rev_iterate : Π (b : buffer α), β → (fin b.size → α → β → β) → β | ⟨_, a⟩ b f := a.rev_iterate b f def taken (b : buffer α) (n : nat) : buffer α := if h : n ≤ b.size then ⟨n, b.to_array.taken n h⟩ else b def taken_right (b : buffer α) (n : nat) : buffer α := if h : n ≤ b.size then ⟨n, b.to_array.taken_right n h⟩ else b def dropn (b : buffer α) (n : nat) : buffer α := if h : n ≤ b.size then ⟨_, b.to_array.dropn n h⟩ else b def reverse (b : buffer α) : buffer α := ⟨b.size, b.to_array.reverse⟩ instance : has_append (buffer α) := ⟨buffer.append⟩ instance [has_to_string α] : has_to_string (buffer α) := ⟨to_string ∘ to_list⟩ meta instance [has_to_format α] : has_to_format (buffer α) := ⟨to_fmt ∘ to_list⟩ meta instance [has_to_tactic_format α] : has_to_tactic_format (buffer α) := ⟨tactic.pp ∘ to_list⟩ end buffer def list.to_buffer {α : Type u} (l : list α) : buffer α := mk_buffer.append_list l @[reducible] def char_buffer := buffer char /-- Convert a format object into a character buffer with the provided formatting options. -/ meta constant format.to_buffer : format → options → buffer char def string.to_char_buffer (s : string) : char_buffer := buffer.nil.append_string s
5ce458e49a98c5b1e34e1833fc792bf2380a92f1
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/archive/miu_language/decision_suf.lean
797067d871fa5010fb080d7c6a79825619826964
[ "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
14,333
lean
/- Copyright (c) 2020 Gihan Marasingha. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gihan Marasingha -/ import .decision_nec import tactic.linarith /-! # Decision procedure - sufficient condition and decidability We give a sufficient condition for a string to be derivable in the MIU language. Together with the necessary condition, we use this to prove that `derivable` is an instance of `decidable_pred`. Let `count I st` and `count U st` denote the number of `I`s (respectively `U`s) in `st : miustr`. We'll show that `st` is derivable if it has the form `M::x` where `x` is a string of `I`s and `U`s for which `count I x` is congruent to 1 or 2 modulo 3. To prove this, it suffices to show `derivable M::y` where `y` is any `miustr` consisting only of `I`s such that the number of `I`s in `y` is `a+3b`, where `a = count I x` and `b = count U x`. This suffices because Rule 3 permits us to change any string of three consecutive `I`s into a `U`. As `count I y = (count I x) + 3*(count U x) ≡ (count I x) [MOD 3]`, it suffices to show `derivable M::z` where `z` is an `miustr` of `I`s such that `count I z` is congruent to 1 or 2 modulo 3. Let `z` be such an `miustr` and let `c` denote `count I z`, so `c ≡ 1 or 2 [MOD 3]`. To derive such an `miustr`, it suffices to derive an `miustr` `M::w`, where again w is an `miustr` of only `I`s with the additional conditions that `count I w` is a power of 2, that `count I w ≥ c` and that `count I w ≡ c [MOD 3]`. To see that this suffices, note that we can remove triples of `I`s from the end of `M::w`, creating `U`s as we go along. Once the number of `I`s equals `m`, we remove `U`s two at a time until we have no `U`s. The only issue is that we may begin the removal process with an odd number of `U`s. Writing `d = count I w`, we see that this happens if and only if `(d-c)/3` is odd. In this case, we must apply Rule 1 to `z`, prior to removing triples of `I`s. We thereby introduce an additional `U` and ensure that the final number of `U`s will be even. ## Tags miu, decision procedure, decidability, decidable_pred, decidable -/ namespace miu open miu_atom list nat /-- We start by showing that an `miustr` `M::w` can be derived, where `w` consists only of `I`s and where `count I w` is a power of 2. -/ private lemma der_cons_repeat (n : ℕ) : derivable (M::(repeat I (2^n))) := begin induction n with k hk, { constructor, }, -- base case { rw [succ_eq_add_one, pow_add, pow_one 2, mul_two,repeat_add], -- inductive step exact derivable.r2 hk, }, end /-! ## Converting `I`s to `U`s For any given natural number `c ≡ 1 or 2 [MOD 3]`, we need to show that can derive an `miustr` `M::w` where `w` consists only of `I`s, where `d = count I w` is a power of 2, where `d ≥ c` and where `d ≡ c [MOD 3]`. Given the above lemmas, the desired result reduces to an arithmetic result, given in the file `arithmetic.lean`. We'll use this result to show we can derive an `miustr` of the form `M::z` where `z` is an string consisting only of `I`s such that `count I z ≡ 1 or 2 [MOD 3]`. As an intermediate step, we show that derive `z` from `zt`, where `t` is aN `miustr` consisting of an even number of `U`s and `z` is any `miustr`. -/ /-- Any number of successive occurrences of `"UU"` can be removed from the end of a `derivable` `miustr` to produce another `derivable` `miustr`. -/ lemma der_of_der_append_repeat_U_even {z : miustr} {m : ℕ} (h : derivable (z ++ repeat U (m*2))) : derivable z := begin induction m with k hk, { revert h, simp only [list.repeat, zero_mul, append_nil, imp_self], }, { apply hk, simp only [succ_mul, repeat_add] at h, change repeat U 2 with [U,U] at h, rw ←(append_nil (z ++ repeat U (k*2) )), apply derivable.r4, simp only [append_nil, append_assoc,h], }, end /-! In fine-tuning my application of `simp`, I issued the following commend to determine which lemmas `simp` uses. `set_option trace.simplify.rewrite true` -/ /-- We may replace several consecutive occurrences of `"III"` with the same number of `"U"`s. In application of the following lemma, `xs` will either be `[]` or `[U]`. -/ lemma der_cons_repeat_I_repeat_U_append_of_der_cons_repeat_I_append (c k : ℕ) (hc : c % 3 = 1 ∨ c % 3 = 2) (xs : miustr) (hder : derivable (M ::(repeat I (c+3*k)) ++ xs)) : derivable (M::(repeat I c ++ repeat U k) ++ xs) := begin revert xs, induction k with a ha, { simp only [list.repeat, mul_zero, add_zero, append_nil, forall_true_iff, imp_self],}, { intro xs, specialize ha (U::xs), intro h₂, simp only [succ_eq_add_one, repeat_add], -- We massage the goal rw [←append_assoc, ←cons_append], -- into a form amenable change repeat U 1 with [U], -- to the application of rw [append_assoc, singleton_append], -- ha. apply ha, apply derivable.r3, change [I,I,I] with repeat I 3, simp only [cons_append, ←repeat_add], convert h₂, }, end /-! ### Arithmetic We collect purely arithmetic lemmas: `add_mod2` is used to ensure we have an even number of `U`s while `le_pow2_and_pow2_eq_mod3` treats the congruence condition modulo 3. -/ section arithmetic /-- For every `a`, the number `a + a % 2` is even. -/ lemma add_mod2 (a : ℕ) : ∃ t, a + a % 2 = t*2 := begin simp only [mul_comm _ 2], -- write `t*2` as `2*t` apply dvd_of_mod_eq_zero, -- it suffices to prove `(a + a % 2) % 2 = 0` rw [add_mod, mod_mod, ←two_mul, mul_mod_right], end private lemma le_pow2_and_pow2_eq_mod3' (c : ℕ) (x : ℕ) (h : c = 1 ∨ c = 2) : ∃ m : ℕ, c + 3*x ≤ 2^m ∧ 2^m % 3 = c % 3 := begin induction x with k hk, { use (c+1), cases h with hc hc; { rw hc, norm_num }, }, rcases hk with ⟨g, hkg, hgmod⟩, by_cases hp : (c + 3*(k+1) ≤ 2 ^g), { use g, exact ⟨hp, hgmod⟩ }, refine ⟨g + 2, _, _⟩, { rw [mul_succ, ←add_assoc, pow_add], change 2^2 with (1+3), rw [mul_add (2^g) 1 3, mul_one], linarith [hkg, one_le_two_pow g], }, { rw [pow_add, ←mul_one c], exact modeq.mul hgmod rfl } end /-- If `a` is 1 or 2 modulo 3, then exists `k` a power of 2 for which `a ≤ k` and `a ≡ k [MOD 3]`. -/ lemma le_pow2_and_pow2_eq_mod3 (a : ℕ) (h : a % 3 = 1 ∨ a % 3 = 2) : ∃ m : ℕ, a ≤ 2^m ∧ 2^m % 3 = a % 3:= begin cases le_pow2_and_pow2_eq_mod3' (a%3) (a/3) h with m hm, use m, split, { convert hm.1, exact (mod_add_div a 3).symm, }, { rw [hm.2, mod_mod _ 3], }, end end arithmetic lemma repeat_pow_minus_append {m : ℕ} : M :: repeat I (2^m - 1) ++ [I] = M::(repeat I (2^m)) := begin change [I] with repeat I 1, rw [cons_append, ←repeat_add, nat.sub_add_cancel (one_le_pow' m 1)], end /-- `der_repeat_I_of_mod3` states that `M::y` is `derivable` if `y` is any `miustr` consisiting just of `I`s, where `count I y` is 1 or 2 modulo 3. -/ lemma der_repeat_I_of_mod3 (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2): derivable (M::(repeat I c)) := begin -- From `der_cons_repeat`, we can derive the `miustr` `M::w` described in the introduction. cases (le_pow2_and_pow2_eq_mod3 c h) with m hm, -- `2^m` will be the number of `I`s in `M::w` have hw₂ : derivable (M::(repeat I (2^m)) ++ repeat U ((2^m -c)/3 % 2)), { cases mod_two_eq_zero_or_one ((2^m -c)/3) with h_zero h_one, { simp only [der_cons_repeat m, append_nil,list.repeat, h_zero], }, -- `(2^m - c)/3 ≡ 0 [MOD 2]` { rw [h_one, ←repeat_pow_minus_append, append_assoc], -- case `(2^m - c)/3 ≡ 1 [MOD 2]` apply derivable.r1, rw repeat_pow_minus_append, exact (der_cons_repeat m), }, }, have hw₃ : derivable (M::(repeat I c) ++ repeat U ((2^m-c)/3) ++ repeat U ((2^m-c)/3 % 2)), { apply der_cons_repeat_I_repeat_U_append_of_der_cons_repeat_I_append c ((2^m-c)/3) h, convert hw₂, -- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m` rw nat.mul_div_cancel', { exact nat.add_sub_of_le hm.1 }, { exact (modeq_iff_dvd' hm.1).mp hm.2.symm } }, rw [append_assoc, ←repeat_add _ _] at hw₃, cases add_mod2 ((2^m-c)/3) with t ht, rw ht at hw₃, exact der_of_der_append_repeat_U_even hw₃, end example (c : ℕ) (h : c % 3 = 1 ∨ c % 3 = 2): derivable (M::(repeat I c)) := begin -- From `der_cons_repeat`, we can derive the `miustr` `M::w` described in the introduction. cases (le_pow2_and_pow2_eq_mod3 c h) with m hm, -- `2^m` will be the number of `I`s in `M::w` have hw₂ : derivable (M::(repeat I (2^m)) ++ repeat U ((2^m -c)/3 % 2)), { cases mod_two_eq_zero_or_one ((2^m -c)/3) with h_zero h_one, { simp only [der_cons_repeat m, append_nil, list.repeat,h_zero], }, -- `(2^m - c)/3 ≡ 0 [MOD 2]` { rw [h_one, ←repeat_pow_minus_append, append_assoc], -- case `(2^m - c)/3 ≡ 1 [MOD 2]` apply derivable.r1, rw repeat_pow_minus_append, exact (der_cons_repeat m), }, }, have hw₃ : derivable (M::(repeat I c) ++ repeat U ((2^m-c)/3) ++ repeat U ((2^m-c)/3 % 2)), { apply der_cons_repeat_I_repeat_U_append_of_der_cons_repeat_I_append c ((2^m-c)/3) h, convert hw₂, -- now we must show `c + 3 * ((2 ^ m - c) / 3) = 2 ^ m` rw nat.mul_div_cancel', { exact nat.add_sub_of_le hm.1 }, { exact (modeq_iff_dvd' hm.1).mp hm.2.symm } }, rw [append_assoc, ←repeat_add _ _] at hw₃, cases add_mod2 ((2^m-c)/3) with t ht, rw ht at hw₃, exact der_of_der_append_repeat_U_even hw₃, end /-! ### `decstr` is a sufficient condition The remainder of this file sets up the proof that `dectstr en` is sufficent to ensure `derivable en`. Decidability of `derivable en` is an easy consequence. The proof proceeds by induction on the `count U` of `en`. We tackle first the base case of the induction. This requires auxiliary results giving conditions under which `count I ys = length ys`. -/ /-- If an `miustr` has a zero `count U` and contains no `M`, then its `count I` is its length. -/ lemma count_I_eq_length_of_count_U_zero_and_neg_mem {ys : miustr} (hu : count U ys = 0) (hm : M ∉ ys) : count I ys = length ys := begin induction ys with x xs hxs, { refl, }, { cases x, { exfalso, exact hm (mem_cons_self M xs), }, -- case `x = M` gives a contradiction. { rw [count_cons, if_pos (rfl), length, succ_eq_add_one, succ_inj'], -- case `x = I` apply hxs, { simpa only [count], }, { simp only [mem_cons_iff,false_or] at hm, exact hm, }, }, { exfalso, simp only [count, countp_cons_of_pos] at hu, -- case `x = U` gives a contradiction. exact succ_ne_zero _ hu, }, }, end /-- `base_case_suf` is the base case of the sufficiency result. -/ lemma base_case_suf (en : miustr) (h : decstr en) (hu : count U en = 0) : derivable en := begin rcases h with ⟨⟨mhead, nmtail⟩, hi ⟩, have : en ≠ nil, { intro k, simp only [k, count, countp, if_false, zero_mod, zero_ne_one, false_or] at hi, contradiction, }, rcases (exists_cons_of_ne_nil this) with ⟨y,ys,rfl⟩, rw head at mhead, rw mhead at *, suffices : ∃ c, repeat I c = ys ∧ (c % 3 = 1 ∨ c % 3 = 2), { rcases this with ⟨c, hysr, hc⟩, rw ←hysr, exact der_repeat_I_of_mod3 c hc, }, { simp only [count] at *, use (count I ys), refine and.intro _ hi, apply repeat_count_eq_of_count_eq_length, exact count_I_eq_length_of_count_U_zero_and_neg_mem hu nmtail, }, end /-! Before continuing to the proof of the induction step, we need other auxiliary results that relate to `count U`. -/ lemma mem_of_count_U_eq_succ {xs : miustr} {k : ℕ} (h : count U xs = succ k) : U ∈ xs := begin induction xs with z zs hzs, { exfalso, rw count at h, contradiction, }, { simp only [mem_cons_iff], cases z, repeat -- cases `z = M` and `z=I` { right, apply hzs, simp only [count, countp, if_false] at h, rw ←h, refl, }, { left, refl, }, }, -- case `z = U` end lemma eq_append_cons_U_of_count_U_pos {k : ℕ} {zs : miustr} (h : count U zs = succ k) : ∃ (as bs : miustr), (zs = as ++ U :: bs) := mem_split (mem_of_count_U_eq_succ h) /-- `ind_hyp_suf` is the inductive step of the sufficiency result. -/ lemma ind_hyp_suf (k : ℕ) (ys : miustr) (hu : count U ys = succ k) (hdec : decstr ys) : ∃ (as bs : miustr), (ys = M::as ++ U:: bs) ∧ (count U (M::as ++ [I,I,I] ++ bs) = k) ∧ decstr (M::as ++ [I,I,I] ++ bs) := begin rcases hdec with ⟨⟨mhead,nmtail⟩, hic⟩, have : ys ≠ nil, { intro k, simp only [k ,count, countp, zero_mod, false_or, zero_ne_one] at hic, contradiction, }, rcases (exists_cons_of_ne_nil this) with ⟨z,zs,rfl⟩, rw head at mhead, rw mhead at *, simp only [count, countp, cons_append, if_false, countp_append] at *, rcases (eq_append_cons_U_of_count_U_pos hu) with ⟨as,bs,hab⟩, rw hab at *, simp only [countp, cons_append, if_pos, if_false, countp_append] at *, use [as,bs], apply and.intro rfl (and.intro (succ.inj hu) _), split, { apply and.intro rfl, simp only [tail, mem_append, mem_cons_iff, false_or, not_mem_nil, or_false] at *, exact nmtail, }, { simp only [count, countp, cons_append, if_false, countp_append, if_pos], rw [add_right_comm, add_mod_right], exact hic, }, end /-- `der_of_decstr` states that `derivable en` follows from `decstr en`. -/ theorem der_of_decstr {en : miustr} (h : decstr en) : derivable en := begin /- The next three lines have the effect of introducing `count U en` as a variable that can be used for induction -/ have hu : ∃ n, count U en = n := exists_eq', cases hu with n hu, revert en, /- Crucially, we need the induction hypothesis to quantify over `en` -/ induction n with k hk, { exact base_case_suf, }, { intros ys hdec hus, rcases ind_hyp_suf k ys hus hdec with ⟨as, bs, hyab, habuc, hdecab⟩, have h₂ : derivable (M::as ++ [I,I,I] ++ bs) := hk hdecab habuc, rw hyab, exact derivable.r3 h₂, }, end /-! ### Decidability of `derivable` -/ /-- Finally, we have the main result, namely that `derivable` is a decidable predicate. -/ instance : decidable_pred derivable := λ en, decidable_of_iff _ ⟨der_of_decstr, decstr_of_der⟩ /-! By decidability, we can automatically determine whether any given `miustr` is `derivable`. -/ example : ¬(derivable "MU") := dec_trivial example : derivable "MUIUIUIIIIIUUUIUII" := dec_trivial end miu
71ff796e73aff3ffc96e1fb9cdd95c97219dec01
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
/Project/mergesort.lean
7f6bd4f1738b260d0100aceefa94831c14b818d3
[]
no_license
KjellZijlemaker/Logical_Verification_VU
ced0ba95316a30e3c94ba8eebd58ea004fa6f53b
4578b93bf1615466996157bb333c84122b201d99
refs/heads/master
1,585,966,086,108
1,549,187,704,000
1,549,187,704,000
155,690,284
0
0
null
null
null
null
UTF-8
Lean
false
false
3,215
lean
def new_list_sizeof : has_sizeof (list ℕ) := ⟨list.length⟩ local attribute [instance, priority 100000] new_list_sizeof -- Creating definitions for the mergesort def fhalf {α: Type} (xs: list α): list α := list.take (list.length xs/2) xs def sndhalf {α: Type} (xs: list α): list α := list.drop (list.length xs/2) xs #reduce fhalf [1,2,3,4,5,6] --Expecting [1, 2, 3] #reduce sndhalf [1,2,3,4,5,6] --Expecting [4, 5, 6] -- Definition of the merge (merging two lists with the smallest first) def merge : list ℕ → list ℕ → list ℕ | xs [] := xs | [] ys := ys | (x :: xs) (y :: ys) := if x < y then x :: merge xs (y :: ys) else y :: merge (x :: xs) ys -- Standard definitions for proving with merge later def reverse {α : Type} : list α → list α | [] := [] | (x :: xs) := reverse xs ++ [x] -- Testing the merge #reduce merge [8, 2, 1] [2,1,4] --Expecting: [2, 1, 4, 8, 2, 1] #reduce merge [2,3,4] [2,3,7] --Expecting: [2, 2, 3, 3, 4, 7] #reduce reverse(reverse(merge [2,3,7] [2,3,4])) lemma test : 1 < 1 + 1 := by exact dec_trivial def mergesort : list ℕ → list ℕ | [] := [] | [a] := [a] | (x::xs) := have list.sizeof (fhalf xs) < x + (1 + list.sizeof xs), from begin induction x, simp, simp[fhalf], cases xs, simp, simp[list.sizeof], simp[test],simp[list.sizeof], exact dec_trivial end, have list.sizeof (sndhalf xs) < x + (1 + list.sizeof xs), from sorry, merge (mergesort (fhalf xs)) (mergesort (sndhalf xs)) -- #reduce mergesort [10,2,1,2,3] -- Proving the merge definition instead of the mergesort as it includes the merge defenition. -- Proving the reverse definitions which will also partially be applied to the merge definition lemma reverse_append {α : Type} : ∀xs ys : list α, reverse (xs ++ ys) = reverse ys ++ reverse xs | [] ys := by simp[reverse] | (x :: xs) ys := begin simp[reverse, reverse_append] end lemma reverse_append_nil : ∀{α:Type} (xs:list α) (x:α), reverse (x::xs) = reverse xs ++ ( x :: list.nil) | xs [] := by simp[reverse] | xs (x :: xss) := begin intro xsss, simp[reverse] end lemma reverse_reverse {α : Type} : ∀xs : list α, reverse (reverse xs) = xs | [] := by simp[reverse] | (x :: xs) := begin simp[reverse], simp[reverse_append], rw[reverse_reverse], rw[reverse], rw[reverse], refl end -- Proving merge properties lemma merge_nil: ∀(n : list ℕ), merge ([] : list ℕ) n = n | [] := by refl | (x :: xs) := by simp[merge] lemma nil_merge: ∀(n : list ℕ), merge n ([] : list ℕ) = n | [] := by refl | (x :: xs) := by simp[merge] lemma merge_reverse_reverse : ∀(n m: list ℕ), reverse(reverse(merge n m)) = merge n m | [] m := by simp[reverse_reverse] | (x :: xs) m := by simp[reverse_reverse] -- Seems obvious, but can't seem to prove the ite.. lemma merge_cons: ∀(xs xss : list ℕ), ∀(x: ℕ), merge xs (x::xss) = merge (x::xss) xs | [] xss := by simp[merge] | (x :: xs) [] := begin intro x2, simp[merge], simp[merge_cons], sorry end | (x :: xs) (xx :: xss) := begin intro x2, simp[merge], sorry end lemma comm_merge : ∀(n m: list ℕ), merge m n = merge n m | [] xs := by simp[nil_merge, merge_nil] | (x :: xs) xss := by simp[merge_cons]
024c49bd2410999222dd0a532d047e8b51d24d73
4fa161becb8ce7378a709f5992a594764699e268
/src/data/real/ennreal.lean
96474f3ba24a001d0123392ff4320555eef8045c
[ "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
45,686
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Yury Kudryashov Extended non-negative reals -/ import data.real.nnreal import data.set.intervals noncomputable theory open classical set open_locale classical big_operators variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered] def ennreal := with_top nnreal localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ennreal} {r p q : nnreal} instance : inhabited ennreal := ⟨0⟩ instance : has_coe nnreal ennreal := ⟨ option.some ⟩ instance : can_lift ennreal nnreal := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ennreal) = (⊤ : ennreal) := rfl @[simp] lemma some_eq_coe (a : nnreal) : (some a : ennreal) = (↑a : ennreal) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ennreal → nnreal | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ennreal) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ennreal := coe (nnreal.of_real r) @[simp, norm_cast] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ennreal}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ennreal} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : real} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma coe_to_nnreal_le_self : ∀{a:ennreal}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : nnreal) : (r : ennreal) = ennreal.of_real r := by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : real} (h : 0 ≤ x) : ennreal.of_real x = @coe nnreal ennreal _ (⟨x, h⟩ : nnreal) := by { rw [coe_nnreal_eq], refl } @[simp, norm_cast] lemma coe_zero : ↑(0 : nnreal) = (0 : ennreal) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : nnreal) = (1 : ennreal) := rfl @[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma one_to_real : (1 : ennreal).to_real = 1 := rfl @[simp] lemma one_to_nnreal : (1 : ennreal).to_nnreal = 1 := rfl @[simp] lemma coe_to_real (r : nnreal) : (r : ennreal).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ennreal) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ennreal} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ennreal → Prop} : (∀a, p a) ↔ (∀r:nnreal, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ⊤ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:nnreal) = (0:ennreal) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 ↔ x = 0 ∨ x = ⊤ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ennreal) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ennreal) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, norm_cast] lemma coe_eq_coe : (↑r : ennreal) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, norm_cast] lemma coe_le_coe : (↑r : ennreal) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, norm_cast] lemma coe_lt_coe : (↑r : ennreal) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : nnreal → ennreal) := λ _ _, coe_le_coe.2 @[simp, norm_cast] lemma coe_eq_zero : (↑r : ennreal) = 0 ↔ r = 0 := coe_eq_coe @[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ennreal) ↔ 0 = r := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one : (↑r : ennreal) = 1 ↔ r = 1 := coe_eq_coe @[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ennreal) ↔ 1 = r := coe_eq_coe @[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ennreal) ↔ 0 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_pos : 0 < (↑r : ennreal) ↔ 0 < r := coe_lt_coe @[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ennreal) := with_top.coe_add @[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ennreal) := with_top.coe_mul @[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ennreal) = bit0 r := coe_add @[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ennreal) = bit1 r := by simp [bit1] lemma coe_two : ((2:nnreal) : ennreal) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ennreal) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1:ennreal) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast one_lt_two @[simp] lemma two_pos : (0:ennreal) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ennreal) ≠ 0 := ne_of_gt two_pos lemma two_ne_top : (2:ennreal) ≠ ∞ := coe_two ▸ coe_ne_top @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add /-- Coercion `ℝ≥0 → ennreal` as a `ring_hom`. -/ def of_nnreal_hom : nnreal →+* ennreal := ⟨coe, coe_one, λ _ _, coe_mul, coe_zero, λ _ _, coe_add⟩ @[simp] lemma coe_of_nnreal_hom : ⇑of_nnreal_hom = coe := rfl @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ennreal) = r^n := of_nnreal_hom.map_pow r n lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top _ _ lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top _ _ lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ⊤) (h₂ : r₂ < ⊤) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ennreal _ _ ⊤, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top {a b : ennreal} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_ne_top {a b : ennreal} : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simp [(≠), mul_eq_top] {contextual := tt} lemma mul_lt_top {a b : ennreal} : a < ⊤ → b < ⊤ → a * b < ⊤ := by simpa only [ennreal.lt_top_iff_ne_top] using mul_ne_top lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → nnreal} : ↑(∑ a in s, f a) = (∑ a in s, f a : ennreal) := of_nnreal_hom.map_sum f s @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → nnreal} : ↑(∏ a in s, f a) = ((∏ a in s, f a) : ennreal) := of_nnreal_hom.map_prod f s section order @[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ (⊤:ennreal) ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ennreal) ↔ 0 < p := coe_lt_coe @[simp, norm_cast] lemma one_le_coe_iff : (1:ennreal) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ennreal) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ennreal) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ennreal) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] lemma coe_nat (n : nat) : ((n : nnreal) : ennreal) = n := with_top.coe_nat n @[simp] lemma nat_ne_top (n : nat) : (n : ennreal) ≠ ⊤ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : nat) : (⊤ : ennreal) ≠ n := with_top.top_ne_nat n lemma le_coe_iff : a ≤ ↑r ↔ (∃p:nnreal, a = p ∧ p ≤ r) := with_top.le_coe_iff r a lemma coe_le_iff : ↑r ≤ a ↔ (∀p:nnreal, a = p → r ≤ p) := with_top.coe_le_iff r a lemma lt_iff_exists_coe : a < b ↔ (∃p:nnreal, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe a b lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := begin cases a, { cases m, { rw eq_bot_iff.mpr h, exact le_refl _ }, { rw [none_eq_top, top_pow (nat.succ_pos m)], exact le_top } }, { rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe], exact pow_le_pow (by simpa using ha) h } end @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [le_zero_iff_eq.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [zero_lt_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ⊤ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ⊤ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ⊤) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_epsilon_le : ∀{a b : ennreal}, (∀ε:nnreal, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have (⊤:ennreal) ≤ ↑a + ↑(1:nnreal), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_epsilon_le h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ennreal) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases dense h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ennreal) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:nnreal, a < r ∧ (r : ennreal) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : nnreal, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : nnreal := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : nnreal.of_real c = d, by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ennreal) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ennreal) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ennreal) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ennreal) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ennreal) := λ _ _, coe_nat_lt_coe_nat.2 @[norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ennreal) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ennreal := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ennreal} (h : r ≠ ⊤) : ∃n:ℕ, r < n := begin rcases lt_iff_exists_coe.1 (lt_top_iff_ne_top.2 h) with ⟨r, rfl, hb⟩, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin rcases dense ac with ⟨a', aa', a'c⟩, rcases lt_iff_exists_coe.1 aa' with ⟨aR, rfl, _⟩, rcases lt_iff_exists_coe.1 a'c with ⟨a'R, rfl, _⟩, rcases dense bd with ⟨b', bb', b'd⟩, rcases lt_iff_exists_coe.1 bb' with ⟨bR, rfl, _⟩, rcases lt_iff_exists_coe.1 b'd with ⟨b'R, rfl, _⟩, have I : ↑aR + ↑bR < ↑a'R + ↑b'R := begin rw [← coe_add, ← coe_add, coe_lt_coe], apply add_lt_add (coe_lt_coe.1 aa') (coe_lt_coe.1 bb') end, have J : ↑a'R + ↑b'R ≤ c + d := add_le_add' (le_of_lt a'c) (le_of_lt b'd), apply lt_of_lt_of_le I J end @[norm_cast] lemma coe_min : ((min r p:nnreal):ennreal) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:nnreal):ennreal) = max r p := coe_mono.map_max end order section complete_lattice lemma coe_Sup {s : set nnreal} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set nnreal} : s.nonempty → (↑(Inf s) : ennreal) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ennreal} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set nnreal} : ↑r ∈ upper_bounds ((coe : nnreal → ennreal) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨅n, f n) = (⨅n:nnreal, f n) ⊓ f ⊤ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) end complete_lattice section mul lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (zero_lt_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left lemma mul_eq_zero {a b : ennreal} : a * b = 0 ↔ a = 0 ∨ b = 0 := canonically_ordered_comm_semiring.mul_eq_zero_iff _ _ end mul section sub instance : has_sub ennreal := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ennreal) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ennreal) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le _) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add' (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_right_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_left_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_right_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right' h) (assume h : a ≤ c + b, calc a - b ≤ (c + b) - b : sub_le_sub h (le_refl _) ... ≤ c : Inf_le (le_refl (c + b))) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_sub_self : a ≠ ⊤ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, zero_lt_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact zero_lt_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ennreal) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_of_nonneg_right' $ zero_le _ @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left' le_sub_add_self ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_left_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_right_inj {a b c : ennreal} (ha : a < ⊤) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- A sum of finite numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ennreal} : (∀a∈s, f a < ⊤) → ∑ a in s, f a < ⊤ := with_top.sum_lt_top /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ennreal} : ∑ a in s, f a < ⊤ ↔ (∀a∈s, f a < ⊤) := with_top.sum_lt_top_iff /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff {s : finset α} {f : α → ennreal} : (∑ x in s, f x) = ⊤ ↔ (∃a∈s, f a = ⊤) := with_top.sum_eq_top_iff /-- seeing `ennreal` as `nnreal` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ⊤) : ennreal.to_nnreal (∑ a in s, f a) = ∑ a in s, ennreal.to_nnreal (f a) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, rw coe_to_nnreal, rw ← ennreal.lt_top_iff_ne_top, exact hf x hx }, { rw ← ennreal.lt_top_iff_ne_top, exact sum_lt_top hf } end /-- seeing `ennreal` as `real` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ⊤) : ennreal.to_real (∑ a in s, f a) = ∑ a in s, ennreal.to_real (f a) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } end sum section interval variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ⊤ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ⊤ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_sub_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_left_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : has_div ennreal := ⟨λa b, a * b⁻¹⟩ lemma div_def : a / b = a * b⁻¹ := rfl lemma mul_div_assoc : (a * b) / c = a * (b / c) := mul_assoc _ _ _ @[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ := show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : (∞ : ennreal)⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ennreal) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, nnreal.mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ennreal) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, nnreal.inv_zero, inv_zero, coe_zero, zero_le] else by simp only [coe_inv hr, le_refl] @[norm_cast] lemma coe_inv_two : ((2⁻¹:nnreal):ennreal) = 2⁻¹ := by rw [coe_inv (ne_of_gt zero_lt_two), coe_two] @[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ennreal) = p / r := show ↑(p * r⁻¹) = ↑p * (↑r)⁻¹, by rw [coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ennreal)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 nnreal.inv_one @[simp] lemma div_one {a : ennreal} : a / 1 = a := by simp [ennreal.div_def] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv, nnreal.inv_pow, coe_pow], rw [← ne.def] at h, rw [← zero_lt_iff_ne_zero] at *, apply pow_pos h end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ennreal, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ennreal, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := zero_lt_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [zero_lt_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [div_def, top_mul, *] @[simp] lemma div_top : a / ∞ = 0 := by simp only [div_def, inv_top, mul_zero] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ⊤ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ⊤ ∧ b ≠ ⊤) := by simp [ennreal.div_def, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ⊤ ∨ c ≠ ⊤) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ⊤ = ⊤, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ennreal) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_def, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, nnreal.mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ⊤, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ⊤) (hbt : b ≠ ⊤ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_def], apply (le_div_iff_mul_le _ _).symm, simpa [inv_ne_zero] using hbt, simpa [inv_ne_zero] using hb0 end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ⊤, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end protected lemma div_lt_iff (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ⊤ ∨ c ≠ ⊤) : c / b < a ↔ c < a * b := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le h0 ht lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ⊤ → a ≠ 0) → (a = ⊤ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_def, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ⊤) : a * a⁻¹ = 1 := begin lift a to nnreal using ht, norm_cast at h0, norm_cast, exact nnreal.mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ennreal} (hr₀ : r ≠ 0) (hr₁ : r ≠ ⊤) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_lt_one_mul_lt : ∀{x y : ennreal}, (∀a<1, a * x ≤ y) → x ≤ y := forall_ennreal.2 $ and.intro (assume r, forall_ennreal.2 $ and.intro (assume q h, coe_le_coe.2 $ nnreal.le_of_forall_lt_one_mul_lt $ assume a ha, begin rw [← coe_le_coe, coe_mul], exact h _ (coe_lt_coe.2 ha) end) (assume h, le_top)) (assume r hr, have ((1 / 2 : nnreal) : ennreal) * ⊤ ≤ r := hr _ (coe_lt_coe.2 ((@nnreal.coe_lt_coe (1/2) 1).1 one_half_lt_one)), have ne : ((1 / 2 : nnreal) : ennreal) ≠ 0, begin rw [(≠), coe_eq_zero], refine zero_lt_iff_ne_zero.1 _, show 0 < (1 / 2 : ℝ), exact div_pos zero_lt_one _root_.two_pos end, by rwa [mul_top, if_neg ne] at this) lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_def, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma inv_two_add_inv_two : (2:ennreal)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_def, div_self two_ne_zero two_ne_top] lemma add_halves (a : ennreal) : a / 2 + a / 2 = a := by rw [div_def, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff {a b : ennreal} : a / b = 0 ↔ a = 0 ∨ b = ⊤ := by simp [div_def, mul_eq_zero] @[simp] lemma div_pos_iff {a b : ennreal} : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ⊤ := by simp [zero_lt_iff_ne_zero, not_or_distrib] lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ennreal) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ⊤) : a / 2 < a := begin lift a to nnreal using ht, have h : (2 : ennreal) = ((2 : nnreal) : ennreal), from rfl, have h' : (2 : nnreal) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to nnreal using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ennreal) - 2⁻¹ = 2⁻¹ := by simpa only [div_def, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) : ∃n:ℕ, (n:ennreal)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] lemma exists_nat_mul_gt (ha : a ≠ 0) (hb : b ≠ ⊤) : ∃ n : ℕ, b < n * a := begin have : b / a ≠ ⊤, from mul_ne_top hb (inv_ne_top.2 ha), refine (ennreal.exists_nat_gt this).imp (λ n hn, _), rwa [← ennreal.div_lt_iff (or.inl ha) (or.inr hb)] end end inv section real lemma to_real_add (ha : a ≠ ⊤) (hb : b ≠ ⊤) : (a+b).to_real = a.to_real + b.to_real := begin lift a to nnreal using ha, lift b to nnreal using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ⊤ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ⊤ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] @[simp] lemma to_real_le_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to nnreal using ha, lift b to nnreal using hb, norm_cast end @[simp] lemma to_real_lt_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real < b.to_real ↔ a < b := begin lift a to nnreal using ha, lift b to nnreal using hb, norm_cast end lemma to_real_max (hr : a ≠ ⊤) (hp : b ≠ ⊤) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ennreal} (hb : b ≠ ⊤) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to nnreal using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ennreal} (ha : 0 ≤ a) (hb : b ≠ ⊤) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to nnreal using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ennreal} {b : ℝ} (ha : a ≠ ⊤) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to nnreal using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ennreal} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ⊤, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ennreal} {b : ℝ} (ha : a ≠ ⊤) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to nnreal using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp } lemma to_real_of_real_mul (c : ℝ) (a : ennreal) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply nnreal.coe_of_real, exact h } end @[simp] lemma to_real_mul_top (a : ennreal) : ennreal.to_real (a * ⊤) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_real] }, { rw [mul_top, if_neg h, top_to_real] } end @[simp] lemma to_real_top_mul (a : ennreal) : ennreal.to_real (⊤ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real {a b : ennreal} (ha : a < ⊤) (hb : b < ⊤) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin rw ennreal.lt_top_iff_ne_top at *, split, { assume h, apply le_antisymm, rw ← to_real_le_to_real ha hb, exact le_of_eq h, rw ← to_real_le_to_real hb ha, exact le_of_eq h.symm }, { assume h, rw h } end lemma to_real_mul_to_real {a b : ennreal} : (ennreal.to_real a) * (ennreal.to_real b) = ennreal.to_real (a * b) := begin by_cases ha : a = ⊤, { rw ha, simp }, by_cases hb : b = ⊤, { rw hb, simp }, have ha : ennreal.of_real (ennreal.to_real a) = a := of_real_to_real ha, have hb : ennreal.of_real (ennreal.to_real b) = b := of_real_to_real hb, conv_rhs { rw [← ha, ← hb, ← of_real_mul to_real_nonneg] }, rw [to_real_of_real (mul_nonneg to_real_nonneg to_real_nonneg)] end end real section infi variables {ι : Sort*} {f g : ι → ennreal} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add' (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add' (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, ∑ a in s, f i a) = ∑ a in s, ⨅i, f i a := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + ∑ b in s, f k b ≤ f i a + ∑ b in s, f j b, from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add' (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] end infi section supr lemma supr_coe_nat : (⨆n:ℕ, (n : ennreal)) = ⊤ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr end ennreal
9af588bf0d8e8b20733d52c7f19664d2f6fba5cd
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/normed_space/lattice_ordered_group.lean
737aa3b69e7c15ed1b39271800ba34724daf85f0
[ "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
8,225
lean
/- Copyright (c) 2021 Christopher Hoskin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christopher Hoskin -/ import topology.order.lattice import analysis.normed.group.basic import algebra.order.lattice_group /-! # Normed lattice ordered groups Motivated by the theory of Banach Lattices, we then define `normed_lattice_add_comm_group` as a lattice with a covariant normed group addition satisfying the solid axiom. ## Main statements We show that a normed lattice ordered group is a topological lattice with respect to the norm topology. ## References * [Meyer-Nieberg, Banach lattices][MeyerNieberg1991] ## Tags normed, lattice, ordered, group -/ /-! ### Normed lattice orderd groups Motivated by the theory of Banach Lattices, this section introduces normed lattice ordered groups. -/ local notation `|`a`|` := abs a /-- Let `α` be a normed commutative group equipped with a partial order covariant with addition, with respect which `α` forms a lattice. Suppose that `α` is *solid*, that is to say, for `a` and `b` in `α`, with absolute values `|a|` and `|b|` respectively, `|a| ≤ |b|` implies `∥a∥ ≤ ∥b∥`. Then `α` is said to be a normed lattice ordered group. -/ class normed_lattice_add_comm_group (α : Type*) extends normed_add_comm_group α, lattice α := (add_le_add_left : ∀ a b : α, a ≤ b → ∀ c : α, c + a ≤ c + b) (solid : ∀ a b : α, |a| ≤ |b| → ∥a∥ ≤ ∥b∥) lemma solid {α : Type*} [normed_lattice_add_comm_group α] {a b : α} (h : |a| ≤ |b|) : ∥a∥ ≤ ∥b∥ := normed_lattice_add_comm_group.solid a b h noncomputable instance : normed_lattice_add_comm_group ℝ := { add_le_add_left := λ _ _ h _, add_le_add le_rfl h, solid := λ _ _, id, } /-- A normed lattice ordered group is an ordered additive commutative group -/ @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_to_ordered_add_comm_group {α : Type*} [h : normed_lattice_add_comm_group α] : ordered_add_comm_group α := { ..h } /-- Let `α` be a normed group with a partial order. Then the order dual is also a normed group. -/ @[priority 100] -- see Note [lower instance priority] instance {α : Type*} : Π [normed_add_comm_group α], normed_add_comm_group αᵒᵈ := id variables {α : Type*} [normed_lattice_add_comm_group α] open lattice_ordered_comm_group lemma dual_solid (a b : α) (h: b⊓-b ≤ a⊓-a) : ∥a∥ ≤ ∥b∥ := begin apply solid, rw abs_eq_sup_neg, nth_rewrite 0 ← neg_neg a, rw ← neg_inf_eq_sup_neg, rw abs_eq_sup_neg, nth_rewrite 0 ← neg_neg b, rwa [← neg_inf_eq_sup_neg, neg_le_neg_iff, @inf_comm _ _ _ b, @inf_comm _ _ _ a], end /-- Let `α` be a normed lattice ordered group, then the order dual is also a normed lattice ordered group. -/ @[priority 100] -- see Note [lower instance priority] instance : normed_lattice_add_comm_group αᵒᵈ := { add_le_add_left := λ a b, add_le_add_left, solid := dual_solid } lemma norm_abs_eq_norm (a : α) : ∥|a|∥ = ∥a∥ := (solid (abs_abs a).le).antisymm (solid (abs_abs a).symm.le) lemma norm_inf_sub_inf_le_add_norm (a b c d : α) : ∥a ⊓ b - c ⊓ d∥ ≤ ∥a - c∥ + ∥b - d∥ := begin rw [← norm_abs_eq_norm (a - c), ← norm_abs_eq_norm (b - d)], refine le_trans (solid _) (norm_add_le (|a - c|) (|b - d|)), rw abs_of_nonneg (|a - c| + |b - d|) (add_nonneg (abs_nonneg (a - c)) (abs_nonneg (b - d))), calc |a ⊓ b - c ⊓ d| = |a ⊓ b - c ⊓ b + (c ⊓ b - c ⊓ d)| : by rw sub_add_sub_cancel ... ≤ |a ⊓ b - c ⊓ b| + |c ⊓ b - c ⊓ d| : abs_add_le _ _ ... ≤ |a -c| + |b - d| : by { apply add_le_add, { exact abs_inf_sub_inf_le_abs _ _ _, }, { rw [@inf_comm _ _ c, @inf_comm _ _ c], exact abs_inf_sub_inf_le_abs _ _ _, } }, end lemma norm_sup_sub_sup_le_add_norm (a b c d : α) : ∥a ⊔ b - (c ⊔ d)∥ ≤ ∥a - c∥ + ∥b - d∥ := begin rw [← norm_abs_eq_norm (a - c), ← norm_abs_eq_norm (b - d)], refine le_trans (solid _) (norm_add_le (|a - c|) (|b - d|)), rw abs_of_nonneg (|a - c| + |b - d|) (add_nonneg (abs_nonneg (a - c)) (abs_nonneg (b - d))), calc |a ⊔ b - (c ⊔ d)| = |a ⊔ b - (c ⊔ b) + (c ⊔ b - (c ⊔ d))| : by rw sub_add_sub_cancel ... ≤ |a ⊔ b - (c ⊔ b)| + |c ⊔ b - (c ⊔ d)| : abs_add_le _ _ ... ≤ |a -c| + |b - d| : by { apply add_le_add, { exact abs_sup_sub_sup_le_abs _ _ _, }, { rw [@sup_comm _ _ c, @sup_comm _ _ c], exact abs_sup_sub_sup_le_abs _ _ _, } }, end lemma norm_inf_le_add (x y : α) : ∥x ⊓ y∥ ≤ ∥x∥ + ∥y∥ := begin have h : ∥x ⊓ y - 0 ⊓ 0∥ ≤ ∥x - 0∥ + ∥y - 0∥ := norm_inf_sub_inf_le_add_norm x y 0 0, simpa only [inf_idem, sub_zero] using h, end lemma norm_sup_le_add (x y : α) : ∥x ⊔ y∥ ≤ ∥x∥ + ∥y∥ := begin have h : ∥x ⊔ y - 0 ⊔ 0∥ ≤ ∥x - 0∥ + ∥y - 0∥ := norm_sup_sub_sup_le_add_norm x y 0 0, simpa only [sup_idem, sub_zero] using h, end /-- Let `α` be a normed lattice ordered group. Then the infimum is jointly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_has_continuous_inf : has_continuous_inf α := begin refine ⟨continuous_iff_continuous_at.2 $ λ q, tendsto_iff_norm_tendsto_zero.2 $ _⟩, have : ∀ p : α × α, ∥p.1 ⊓ p.2 - q.1 ⊓ q.2∥ ≤ ∥p.1 - q.1∥ + ∥p.2 - q.2∥, from λ _, norm_inf_sub_inf_le_add_norm _ _ _ _, refine squeeze_zero (λ e, norm_nonneg _) this _, convert (((continuous_fst.tendsto q).sub tendsto_const_nhds).norm).add (((continuous_snd.tendsto q).sub tendsto_const_nhds).norm), simp, end @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_has_continuous_sup {α : Type*} [normed_lattice_add_comm_group α] : has_continuous_sup α := order_dual.has_continuous_sup αᵒᵈ /-- Let `α` be a normed lattice ordered group. Then `α` is a topological lattice in the norm topology. -/ @[priority 100] -- see Note [lower instance priority] instance normed_lattice_add_comm_group_topological_lattice : topological_lattice α := topological_lattice.mk lemma norm_abs_sub_abs (a b : α) : ∥ |a| - |b| ∥ ≤ ∥a-b∥ := solid (lattice_ordered_comm_group.abs_abs_sub_abs_le _ _) lemma norm_sup_sub_sup_le_norm (x y z : α) : ∥x ⊔ z - (y ⊔ z)∥ ≤ ∥x - y∥ := solid (abs_sup_sub_sup_le_abs x y z) lemma norm_inf_sub_inf_le_norm (x y z : α) : ∥x ⊓ z - (y ⊓ z)∥ ≤ ∥x - y∥ := solid (abs_inf_sub_inf_le_abs x y z) lemma lipschitz_with_sup_right (z : α) : lipschitz_with 1 (λ x, x ⊔ z) := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [nonneg.coe_one, one_mul, dist_eq_norm, dist_eq_norm], exact norm_sup_sub_sup_le_norm x y z, } lemma lipschitz_with_pos : lipschitz_with 1 (has_pos_part.pos : α → α) := lipschitz_with_sup_right 0 lemma continuous_pos : continuous (has_pos_part.pos : α → α) := lipschitz_with.continuous lipschitz_with_pos lemma continuous_neg' : continuous (has_neg_part.neg : α → α) := continuous_pos.comp continuous_neg lemma is_closed_nonneg {E} [normed_lattice_add_comm_group E] : is_closed {x : E | 0 ≤ x} := begin suffices : {x : E | 0 ≤ x} = has_neg_part.neg ⁻¹' {(0 : E)}, by { rw this, exact is_closed.preimage continuous_neg' is_closed_singleton, }, ext1 x, simp only [set.mem_preimage, set.mem_singleton_iff, set.mem_set_of_eq, neg_eq_zero_iff], end lemma is_closed_le_of_is_closed_nonneg {G} [ordered_add_comm_group G] [topological_space G] [has_continuous_sub G] (h : is_closed {x : G | 0 ≤ x}) : is_closed {p : G × G | p.fst ≤ p.snd} := begin have : {p : G × G | p.fst ≤ p.snd} = (λ p : G × G, p.snd - p.fst) ⁻¹' {x : G | 0 ≤ x}, by { ext1 p, simp only [sub_nonneg, set.preimage_set_of_eq], }, rw this, exact is_closed.preimage (continuous_snd.sub continuous_fst) h, end @[priority 100] -- See note [lower instance priority] instance normed_lattice_add_comm_group.order_closed_topology {E} [normed_lattice_add_comm_group E] : order_closed_topology E := ⟨is_closed_le_of_is_closed_nonneg is_closed_nonneg⟩
dd720539968f38621763908b908682215a8386b1
66a6486e19b71391cc438afee5f081a4257564ec
/homotopy/pushout.hlean
0d354770ed97a1d3798e4f428ef0921a2fe6993f
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
37,028
hlean
import ..algebra.exactness homotopy.cofiber homotopy.wedge homotopy.smash open eq function is_trunc sigma prod lift is_equiv equiv pointed sum unit bool cofiber namespace pushout section variables {TL BL TR : Type*} {f : TL →* BL} {g : TL →* TR} {TL' BL' TR' : Type*} {f' : TL' →* BL'} {g' : TL' →* TR'} (tl : TL ≃ TL') (bl : BL ≃* BL') (tr : TR ≃ TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) definition ppushout_functor [constructor] (tl : TL → TL') (bl : BL →* BL') (tr : TR → TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) : ppushout f g →* ppushout f' g' := begin fconstructor, { exact pushout.functor tl bl tr fh gh }, { exact ap inl (respect_pt bl) }, end definition ppushout_pequiv (tl : TL ≃ TL') (bl : BL ≃* BL') (tr : TR ≃ TR') (fh : bl ∘ f ~ f' ∘ tl) (gh : tr ∘ g ~ g' ∘ tl) : ppushout f g ≃* ppushout f' g' := pequiv_of_equiv (pushout.equiv _ _ _ _ tl bl tr fh gh) (ap inl (respect_pt bl)) end /- WIP: proving that satisfying the universal property of the pushout is equivalent to being equivalent to the pushout -/ universe variables u₁ u₂ u₃ u₄ variables {A : Type.{u₁}} {B : Type.{u₂}} {C : Type.{u₃}} {D D' : Type.{u₄}} {f : A → B} {g : A → C} {h : B → D} {k : C → D} (p : h ∘ f ~ k ∘ g) {h' : B → D'} {k' : C → D'} (p' : h' ∘ f ~ k' ∘ g) -- (f : A → B) (g : A → C) (h : B → D) (k : C → D) include p definition is_pushout : Type := Π⦃X : Type.{max u₁ u₂ u₃ u₄}⦄ (h' : B → X) (k' : C → X) (p' : h' ∘ f ~ k' ∘ g), is_contr (Σ(l : D → X) (v : l ∘ h ~ h' × l ∘ k ~ k'), Πa, square (prod.pr1 v (f a)) (prod.pr2 v (g a)) (ap l (p a)) (p' a)) definition cocone [reducible] (X : Type) : Type := Σ(v : (B → X) × (C → X)), prod.pr1 v ∘ f ~ prod.pr2 v ∘ g definition cocone_of_map [constructor] (X : Type) (l : D → X) : cocone p X := ⟨(l ∘ h, l ∘ k), λa, ap l (p a)⟩ -- definition cocone_of_map (X : Type) (l : D → X) : Σ(h' : B → X) (k' : C → X), -- h' ∘ f ~ k' ∘ g := -- ⟨l ∘ h, l ∘ k, λa, ap l (p a)⟩ omit p definition is_pushout2 [reducible] : Type := Π(X : Type.{max u₁ u₂ u₃ u₄}), is_equiv (cocone_of_map p X) section open sigma.ops protected definition inv_left (H : is_pushout2 p) {X : Type} (v : cocone p X) : (cocone_of_map p X)⁻¹ᶠ v ∘ h ~ prod.pr1 v.1 := ap10 (ap prod.pr1 (right_inv (cocone_of_map p X) v)..1) protected definition inv_right (H : is_pushout2 p) {X : Type} (v : cocone p X) : (cocone_of_map p X)⁻¹ᶠ v ∘ k ~ prod.pr2 v.1 := ap10 (ap prod.pr2 (right_inv (cocone_of_map p X) v)..1) end section local attribute is_pushout [reducible] definition is_prop_is_pushout : is_prop (is_pushout p) := _ local attribute is_pushout2 [reducible] definition is_prop_is_pushout2 : is_prop (is_pushout2 p) := _ end definition ap_eq_apd10_ap {A B : Type} {C : B → Type} (f : A → Πb, C b) {a a' : A} (p : a = a') (b : B) : ap (λa, f a b) p = apd10 (ap f p) b := by induction p; reflexivity variables (f g) definition is_pushout2_pushout : @is_pushout2 _ _ _ _ f g inl inr glue := λX, to_is_equiv (pushout_arrow_equiv f g X ⬝e assoc_equiv_prod _) definition is_equiv_of_is_pushout2_simple [constructor] {A B C D : Type.{u₁}} {f : A → B} {g : A → C} {h : B → D} {k : C → D} (p : h ∘ f ~ k ∘ g) {h' : B → D'} {k' : C → D'} (p' : h' ∘ f ~ k' ∘ g) (H : is_pushout2 p) : D ≃ pushout f g := begin fapply equiv.MK, { exact (cocone_of_map p _)⁻¹ᶠ ⟨(inl, inr), glue⟩ }, { exact pushout.elim h k p }, { intro x, exact sorry }, { apply ap10, apply eq_of_fn_eq_fn (equiv.mk _ (H D)), fapply sigma_eq, { esimp, fapply prod_eq, apply eq_of_homotopy, intro b, exact ap (pushout.elim h k p) (pushout.inv_left p H ⟨(inl, inr), glue⟩ b), apply eq_of_homotopy, intro c, exact ap (pushout.elim h k p) (pushout.inv_right p H ⟨(inl, inr), glue⟩ c) }, { apply pi.pi_pathover_constant, intro a, apply eq_pathover, refine !ap_eq_apd10_ap ⬝ph _ ⬝hp !ap_eq_apd10_ap⁻¹, refine ap (λx, apd10 x _) (ap_compose (λx, x ∘ f) pr1 _ ⬝ ap02 _ !prod_eq_pr1) ⬝ph _ ⬝hp ap (λx, apd10 x _) (ap_compose (λx, x ∘ g) pr2 _ ⬝ ap02 _ !prod_eq_pr2)⁻¹, refine apd10 !apd10_ap_precompose_dependent a ⬝ph _ ⬝hp apd10 !apd10_ap_precompose_dependent⁻¹ a, refine apd10 !apd10_eq_of_homotopy (f a) ⬝ph _ ⬝hp apd10 !apd10_eq_of_homotopy⁻¹ (g a), refine ap_compose (pushout.elim h k p) _ _ ⬝pv _, refine aps (pushout.elim h k p) _ ⬝vp (!elim_glue ⬝ !ap_id⁻¹), esimp, exact sorry }, } end -- definition is_equiv_of_is_pushout2 [constructor] (H : is_pushout2 p) : D ≃ pushout f g := -- begin -- fapply equiv.MK, -- { exact down.{_ u₄} ∘ (cocone_of_map p _)⁻¹ᶠ ⟨(up ∘ inl, up ∘ inr), λa, ap up (glue a)⟩ }, -- { exact pushout.elim h k p }, -- { intro x, exact sorry -- }, -- { intro d, apply eq_of_fn_eq_fn (equiv_lift D), esimp, revert d, -- apply ap10, -- apply eq_of_fn_eq_fn (equiv.mk _ (H (lift.{_ (max u₁ u₂ u₃)} D))), -- fapply sigma_eq, -- { esimp, fapply prod_eq, -- apply eq_of_homotopy, intro b, apply ap up, esimp, -- exact ap (pushout.elim h k p ∘ down.{_ u₄}) -- (pushout.inv_left p H ⟨(up ∘ inl, up ∘ inr), λa, ap up (glue a)⟩ b), -- exact sorry }, -- { exact sorry }, -- -- note q := @eq_of_is_contr _ H'' -- -- ⟨up ∘ pushout.elim h k p ∘ down ∘ (center' H').1, -- -- (λb, ap (up ∘ pushout.elim h k p ∘ down) (prod.pr1 (center' H').2 b), -- -- λc, ap (up ∘ pushout.elim h k p ∘ down) (prod.pr2 (center' H').2 c))⟩ -- -- ⟨up, (λx, idp, λx, idp)⟩, -- -- exact ap down (ap10 q..1 d) -- } -- end /- composing pushouts -/ definition pushout_vcompose_to [unfold 8] {A B C D : Type} {f : A → B} {g : A → C} {h : B → D} (x : pushout h (@inl _ _ _ f g)) : pushout (h ∘ f) g := begin induction x with d y b, { exact inl d }, { induction y with b c a, { exact inl (h b) }, { exact inr c }, { exact glue a }}, { reflexivity } end definition pushout_vcompose_from [unfold 8] {A B C D : Type} {f : A → B} {g : A → C} {h : B → D} (x : pushout (h ∘ f) g) : pushout h (@inl _ _ _ f g) := begin induction x with d c a, { exact inl d }, { exact inr (inr c) }, { exact glue (f a) ⬝ ap inr (glue a) } end definition pushout_vcompose [constructor] {A B C D : Type} (f : A → B) (g : A → C) (h : B → D) : pushout h (@inl _ _ _ f g) ≃ pushout (h ∘ f) g := begin fapply equiv.MK, { exact pushout_vcompose_to }, { exact pushout_vcompose_from }, { intro x, induction x with d c a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_vcompose_to _ _ ⬝ ap02 _ !elim_glue ⬝ _, refine !ap_con ⬝ !elim_glue ◾ !ap_compose'⁻¹ ⬝ !idp_con ⬝ _, esimp, apply elim_glue }}, { intro x, induction x with d y b, { reflexivity }, { induction y with b c a, { exact glue b }, { reflexivity }, { apply eq_pathover, refine ap_compose pushout_vcompose_from _ _ ⬝ph _, esimp, refine ap02 _ !elim_glue ⬝ !elim_glue ⬝ph _, apply square_of_eq, reflexivity }}, { apply eq_pathover_id_right, esimp, refine ap_compose pushout_vcompose_from _ _ ⬝ ap02 _ !elim_glue ⬝ph _, apply square_of_eq, reflexivity }} end definition pushout_hcompose {A B C D : Type} (f : A → B) (g : A → C) (h : C → D) : pushout (@inr _ _ _ f g) h ≃ pushout f (h ∘ g) := calc pushout (@inr _ _ _ f g) h ≃ pushout h (@inr _ _ _ f g) : pushout.symm ... ≃ pushout h (@inl _ _ _ g f) : pushout.equiv _ _ _ _ erfl erfl (pushout.symm f g) (λa, idp) (λa, idp) ... ≃ pushout (h ∘ g) f : pushout_vcompose ... ≃ pushout f (h ∘ g) : pushout.symm definition pushout_vcompose_equiv {A B C D E : Type} (f : A → B) {g : A → C} {h : B → D} {hf : A → D} {k : B → E} (e : E ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inl) (q : h ∘ f ~ hf) : pushout h k ≃ pushout hf g := begin refine _ ⬝e pushout_vcompose f g h ⬝e _, { fapply pushout.equiv, reflexivity, reflexivity, exact e, reflexivity, exact homotopy_of_homotopy_inv_post e _ _ p }, { fapply pushout.equiv, reflexivity, reflexivity, reflexivity, exact q, reflexivity }, end definition pushout_hcompose_equiv {A B C D E : Type} {f : A → B} (g : A → C) {h : C → E} {hg : A → E} {k : C → D} (e : D ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inr) (q : h ∘ g ~ hg) : pushout k h ≃ pushout f hg := calc pushout k h ≃ pushout h k : pushout.symm ... ≃ pushout hg f : by exact pushout_vcompose_equiv _ (e ⬝e pushout.symm f g) p q ... ≃ pushout f hg : pushout.symm definition pushout_of_equiv_left_to [unfold 6] {A B C : Type} {f : A ≃ B} {g : A → C} (x : pushout f g) : C := begin induction x with b c a, { exact g (f⁻¹ b) }, { exact c }, { exact ap g (left_inv f a) } end definition pushout_of_equiv_left [constructor] {A B C : Type} (f : A ≃ B) (g : A → C) : pushout f g ≃ C := begin fapply equiv.MK, { exact pushout_of_equiv_left_to }, { exact inr }, { intro c, reflexivity }, { intro x, induction x with b c a, { exact (glue (f⁻¹ b))⁻¹ ⬝ ap inl (right_inv f b) }, { reflexivity }, { apply eq_pathover_id_right, refine ap_compose inr _ _ ⬝ ap02 _ !elim_glue ⬝ph _, apply move_top_of_left, apply move_left_of_bot, refine ap02 _ (adj f _) ⬝ !ap_compose⁻¹ ⬝pv _ ⬝vp !ap_compose, apply natural_square_tr }} end definition pushout_of_equiv_right [constructor] {A B C : Type} (f : A → B) (g : A ≃ C) : pushout f g ≃ B := calc pushout f g ≃ pushout g f : pushout.symm f g ... ≃ B : pushout_of_equiv_left g f -- todo: define pushout.equiv (renamed to pushout_equiv_pushout) using this variables {A₁ B₁ C₁ A₂ B₂ C₂ A₃ B₃ C₃ : Type} {f₁ : A₁ → B₁} {g₁ : A₁ → C₁} {f₂ : A₂ → B₂} {g₂ : A₂ → C₂} {f₃ : A₃ → B₃} {g₃ : A₃ → C₃} {h₂ : A₂ → A₃} {h₁ : A₁ → A₂} {i₂ : B₂ → B₃} {i₁ : B₁ → B₂} {j₂ : C₂ → C₃} {j₁ : C₁ → C₂} (p₂ : i₂ ∘ f₂ ~ f₃ ∘ h₂) (q₂ : j₂ ∘ g₂ ~ g₃ ∘ h₂) (p₁ : i₁ ∘ f₁ ~ f₂ ∘ h₁) (q₁ : j₁ ∘ g₁ ~ g₂ ∘ h₁) definition pushout_functor_compose : pushout.functor (h₂ ∘ h₁) (i₂ ∘ i₁) (j₂ ∘ j₁) (p₁ ⬝htyv p₂) (q₁ ⬝htyv q₂) ~ pushout.functor h₂ i₂ j₂ p₂ q₂ ∘ pushout.functor h₁ i₁ j₁ p₁ q₁ := begin intro x, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, esimp, refine !elim_glue ⬝ whisker_right _ (!ap_con ⬝ !ap_compose'⁻¹ ◾ idp) ◾ (ap02 _ !con_inv ⬝ !ap_con ⬝ whisker_left _ (ap02 _ !ap_inv⁻¹ ⬝ !ap_compose'⁻¹)) ⬝ _ ⬝ (ap_compose (pushout.functor h₂ i₂ j₂ p₂ q₂) _ _ ⬝ ap02 _ !elim_glue)⁻¹, refine _ ⬝ (!ap_con ⬝ (!ap_con ⬝ !ap_compose'⁻¹ ◾ !elim_glue) ◾ !ap_compose'⁻¹)⁻¹ᵖ, refine !con.assoc⁻¹ ⬝ whisker_right _ _, exact whisker_right _ !con.assoc ⬝ !con.assoc } end variables {p₁ q₁} definition pushout_functor_homotopy_constant {p₁' : i₁ ∘ f₁ ~ f₂ ∘ h₁} {q₁' : j₁ ∘ g₁ ~ g₂ ∘ h₁} (p : p₁ ~ p₁') (q : q₁ ~ q₁') : pushout.functor h₁ i₁ j₁ p₁ q₁ ~ pushout.functor h₁ i₁ j₁ p₁' q₁' := begin induction p, induction q, reflexivity end definition pushout_functor_homotopy {h₁ h₂ : A₁ → A₂} {i₁ i₂ : B₁ → B₂} {j₁ j₂ : C₁ → C₂} {p₁ : i₁ ∘ f₁ ~ f₂ ∘ h₁} {q₁ : j₁ ∘ g₁ ~ g₂ ∘ h₁} {p₂ : i₂ ∘ f₁ ~ f₂ ∘ h₂} {q₂ : j₂ ∘ g₁ ~ g₂ ∘ h₂} (r : h₁ ~ h₂) (s : i₁ ~ i₂) (t : j₁ ~ j₂) (u : r ⬝htyh p₁ ~ p₂ ⬝htyh s) (v : r ⬝htyh q₁ ~ q₂ ⬝htyh t) : pushout.functor h₁ i₁ j₁ p₁ q₁ ~ pushout.functor h₂ i₂ j₂ p₂ q₂ := begin induction r, induction s, induction t, apply pushout_functor_homotopy_constant, { exact (rfl_hhconcat p₁)⁻¹ʰᵗʸ ⬝hty u ⬝hty hhconcat_rfl p₂ }, exact (rfl_hhconcat q₁)⁻¹ʰᵗʸ ⬝hty v ⬝hty hhconcat_rfl q₂ end /- pushout where one map is constant is a cofiber -/ definition pushout_const_equiv_to [unfold 6] {A B C : Type} {f : A → B} {c₀ : C} (x : pushout f (const A c₀)) : cofiber (sum_functor f (const unit c₀)) := begin induction x with b c a, { exact !cod (sum.inl b) }, { exact !cod (sum.inr c) }, { exact glue (sum.inl a) ⬝ (glue (sum.inr ⋆))⁻¹ } end definition pushout_const_equiv_from [unfold 6] {A B C : Type} {f : A → B} {c₀ : C} (x : cofiber (sum_functor f (const unit c₀))) : pushout f (const A c₀) := begin induction x with v v, { induction v with b c, exact inl b, exact inr c }, { exact inr c₀ }, { induction v with a u, exact glue a, reflexivity } end definition pushout_const_equiv [constructor] {A B C : Type} (f : A → B) (c₀ : C) : pushout f (const A c₀) ≃ cofiber (sum_functor f (const unit c₀)) := begin fapply equiv.MK, { exact pushout_const_equiv_to }, { exact pushout_const_equiv_from }, { intro x, induction x with v v, { induction v with b c, reflexivity, reflexivity }, { exact glue (sum.inr ⋆) }, { apply eq_pathover_id_right, refine ap_compose pushout_const_equiv_to _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction v with a u, { refine !elim_glue ⬝ph _, apply whisker_bl, exact hrfl }, { induction u, exact square_of_eq idp }}}, { intro x, induction x with c b a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_const_equiv_from _ _ ⬝ ap02 _ !elim_glue ⬝ _, refine !ap_con ⬝ !elim_glue ◾ (!ap_inv ⬝ !elim_glue⁻²) }} end /- wedge is the cofiber of the map 2 -> A + B -/ -- move to sum definition sum_of_bool [unfold 3] (A B : Type*) (b : bool) : A + B := by induction b; exact sum.inl pt; exact sum.inr pt definition psum_of_pbool [constructor] (A B : Type*) : pbool →* (A +* B) := pmap.mk (sum_of_bool A B) idp -- move to wedge definition wedge_equiv_pushout_sum [constructor] (A B : Type*) : wedge A B ≃ cofiber (sum_of_bool A B) := begin refine pushout_const_equiv _ _ ⬝e _, fapply pushout.equiv, exact bool_equiv_unit_sum_unit⁻¹ᵉ, reflexivity, reflexivity, intro x, induction x: reflexivity, intro x, induction x with u u: induction u; reflexivity end section open prod.ops /- products preserve pushouts -/ definition pushout_prod_equiv_to [unfold 7] {A B C D : Type} {f : A → B} {g : A → C} (xd : pushout f g × D) : pushout (prod_functor f (@id D)) (prod_functor g id) := begin induction xd with x d, induction x with b c a, { exact inl (b, d) }, { exact inr (c, d) }, { exact glue (a, d) } end definition pushout_prod_equiv_from [unfold 7] {A B C D : Type} {f : A → B} {g : A → C} (x : pushout (prod_functor f (@id D)) (prod_functor g id)) : pushout f g × D := begin induction x with bd cd ad, { exact (inl bd.1, bd.2) }, { exact (inr cd.1, cd.2) }, { exact prod_eq (glue ad.1) idp } end definition pushout_prod_equiv {A B C D : Type} (f : A → B) (g : A → C) : pushout f g × D ≃ pushout (prod_functor f (@id D)) (prod_functor g id) := begin fapply equiv.MK, { exact pushout_prod_equiv_to }, { exact pushout_prod_equiv_from }, { intro x, induction x with bd cd ad, { induction bd, reflexivity }, { induction cd, reflexivity }, { induction ad with a d, apply eq_pathover_id_right, apply hdeg_square, refine ap_compose pushout_prod_equiv_to _ _ ⬝ ap02 _ !elim_glue ⬝ _, esimp, exact !ap_prod_elim ⬝ !idp_con ⬝ !elim_glue }}, { intro xd, induction xd with x d, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, refine ap_compose (pushout_prod_equiv_from ∘ pushout_prod_equiv_to) _ _ ⬝ _, refine ap02 _ !ap_prod_mk_left ⬝ !ap_compose ⬝ _, refine ap02 _ (!ap_prod_elim ⬝ !idp_con ⬝ !elim_glue) ⬝ _, refine !elim_glue ⬝ !ap_prod_mk_left⁻¹ }} end end /- interaction of pushout and sums -/ definition pushout_to_sum [unfold 8] {A B C : Type} {f : A → B} {g : A → C} (D : Type) (c₀ : C) (x : pushout f g) : pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀)) := begin induction x with b c a, { exact inl (sum.inl b) }, { exact inr c }, { exact glue (sum.inl a) } end definition pushout_from_sum [unfold 8] {A B C : Type} {f : A → B} {g : A → C} (D : Type) (c₀ : C) (x : pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀))) : pushout f g := begin induction x with x c x, { induction x with b d, exact inl b, exact inr c₀ }, { exact inr c }, { induction x with a d, exact glue a, reflexivity } end /- The pushout of B <-- A --> C is the same as the pushout of B + D <-- A + D --> C -/ definition pushout_sum_cancel_equiv [constructor] {A B C : Type} (f : A → B) (g : A → C) (D : Type) (c₀ : C) : pushout f g ≃ pushout (sum_functor f (@id D)) (sum.rec g (λd, c₀)) := begin fapply equiv.MK, { exact pushout_to_sum D c₀ }, { exact pushout_from_sum D c₀ }, { intro x, induction x with x c x, { induction x with b d, reflexivity, esimp, exact (glue (sum.inr d))⁻¹ }, { reflexivity }, { apply eq_pathover_id_right, refine ap_compose (pushout_to_sum D c₀) _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction x with a d: esimp, { exact hdeg_square !elim_glue }, { exact square_of_eq !con.left_inv }}}, { intro x, induction x with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose (pushout_from_sum D c₀) _ _ ⬝ ap02 _ !elim_glue ⬝ !elim_glue }} end end pushout namespace pushout variables {A A' B B' C C' : Type} {f : A → B} {g : A → C} {f' : A' → B'} {g' : A' → C'} definition sum_pushout_of_pushout_sum [unfold 11] (x : pushout (sum_functor f f') (sum_functor g g')) : pushout f g ⊎ pushout f' g' := begin induction x with b c a, { exact sum_functor inl inl b }, { exact sum_functor inr inr c }, { induction a with a a', exact ap sum.inl (glue a), exact ap sum.inr (glue a') } end definition pushout_sum_of_sum_pushout [unfold 11] (x : pushout f g ⊎ pushout f' g') : pushout (sum_functor f f') (sum_functor g g') := begin induction x with x x, { exact pushout.functor sum.inl sum.inl sum.inl homotopy.rfl homotopy.rfl x }, { exact pushout.functor sum.inr sum.inr sum.inr homotopy.rfl homotopy.rfl x } end variables (f g f' g') /- do we want to define this in terms of sigma_pushout? One possible disadvantage is that the computation on glue is less convenient -/ definition pushout_sum_equiv_sum_pushout [constructor] : pushout (sum_functor f f') (sum_functor g g') ≃ pushout f g ⊎ pushout f' g' := equiv.MK sum_pushout_of_pushout_sum pushout_sum_of_sum_pushout abstract begin intro x, induction x with x x, { induction x, { reflexivity }, { reflexivity }, apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sum_pushout_of_pushout_sum _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue }, { induction x, { reflexivity }, { reflexivity }, apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sum_pushout_of_pushout_sum _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue }, end end abstract begin intro x, induction x with b c a, { induction b: reflexivity }, { induction c: reflexivity }, { apply eq_pathover_id_right, refine ap_compose pushout_sum_of_sum_pushout _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a': (apply hdeg_square; refine !ap_compose'⁻¹ ⬝ !elim_glue ⬝ !con_idp ⬝ !idp_con) } end end variables {f g f' g'} variables {D E F D' E' F' : Type} {h : D → E} {i : D → F} {h' : D' → E'} {i' : D' → F'} {j : A → D} {k : B → E} {l : C → F} {j' : A' → D'} {k' : B' → E'} {l' : C' → F'} {j₂ : A' → D} {k₂ : B' → E} {l₂ : C' → F} (s : hsquare f h j k) (t : hsquare g i j l) (s' : hsquare f' h' j' k') (t' : hsquare g' i' j' l') (s₂ : hsquare f' h j₂ k₂) (t₂ : hsquare g' i j₂ l₂) definition sum_rec_pushout_sum_equiv_sum_pushout : sum.rec (pushout.functor j k l s t) (pushout.functor j₂ k₂ l₂ s₂ t₂) ∘ pushout_sum_equiv_sum_pushout f g f' g' ~ pushout.functor (sum.rec j j₂) (sum.rec k k₂) (sum.rec l l₂) (sum_rec_hsquare s s₂) (sum_rec_hsquare t t₂) := begin intro x, induction x with b c a, { induction b with b b': reflexivity }, { induction c with c c': reflexivity }, { exact abstract begin apply eq_pathover, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a': exact hdeg_square (!ap_compose'⁻¹ ⬝ !elim_glue ⬝ !elim_glue⁻¹) end end } end definition pushout_sum_equiv_sum_pushout_natural : hsquare (pushout.functor (j +→ j') (k +→ k') (l +→ l') (sum_functor_hsquare s s') (sum_functor_hsquare t t')) (pushout.functor j k l s t +→ pushout.functor j' k' l' s' t') (pushout_sum_equiv_sum_pushout f g f' g') (pushout_sum_equiv_sum_pushout h i h' i') := begin intro x, induction x with b c a, { induction b with b b': reflexivity }, { induction c with c c': reflexivity }, { exact abstract begin apply eq_pathover, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ph _ ⬝hp (!ap_compose ⬝ ap02 _ !elim_glue)⁻¹, refine !ap_con ⬝ (!ap_con ⬝ !ap_compose'⁻¹ ◾ !elim_glue) ◾ (!ap_compose'⁻¹ ⬝ !ap_inv) ⬝ph _, induction a with a a', { apply hdeg_square, refine !ap_compose'⁻¹ ◾ idp ◾ !ap_compose'⁻¹⁻² ⬝ _ ⬝ !ap_compose', refine _ ⬝ (ap_compose sum.inl _ _ ⬝ ap02 _ !elim_glue)⁻¹, exact (ap_compose sum.inl _ _ ◾ idp ⬝ !ap_con⁻¹) ◾ (!ap_inv⁻¹ ⬝ ap_compose sum.inl _ _) ⬝ !ap_con⁻¹ }, { apply hdeg_square, refine !ap_compose'⁻¹ ◾ idp ◾ !ap_compose'⁻¹⁻² ⬝ _ ⬝ !ap_compose', refine _ ⬝ (ap_compose sum.inr _ _ ⬝ ap02 _ !elim_glue)⁻¹, exact (ap_compose sum.inr _ _ ◾ idp ⬝ !ap_con⁻¹) ◾ (!ap_inv⁻¹ ⬝ ap_compose sum.inr _ _) ⬝ !ap_con⁻¹ } end end } end end pushout namespace pushout open sigma sigma.ops variables {X : Type} {A B C : X → Type} {f : Πx, A x → B x} {g : Πx, A x → C x} definition sigma_pushout_of_pushout_sigma [unfold 7] (x : pushout (total f) (total g)) : Σx, pushout (f x) (g x) := begin induction x with b c a, { exact total (λx, inl) b }, { exact total (λx, inr) c }, { exact sigma_eq_right (glue a.2) } end definition pushout_sigma_of_sigma_pushout [unfold 7] (x : Σx, pushout (f x) (g x)) : pushout (total f) (total g) := pushout.functor (dpair x.1) (dpair x.1) (dpair x.1) homotopy.rfl homotopy.rfl x.2 variables (f g) definition pushout_sigma_equiv_sigma_pushout [constructor] : pushout (total f) (total g) ≃ Σx, pushout (f x) (g x) := equiv.MK sigma_pushout_of_pushout_sigma pushout_sigma_of_sigma_pushout abstract begin intro x, induction x with x y, induction y with b c a, { reflexivity }, { reflexivity }, { apply eq_pathover, apply hdeg_square, esimp, exact ap_compose sigma_pushout_of_pushout_sigma _ _ ⬝ ap02 _ (!elim_glue ⬝ !con_idp ⬝ !idp_con) ⬝ !elim_glue } end end abstract begin intro x, induction x with b c a, { induction b, reflexivity }, { induction c, reflexivity }, { apply eq_pathover_id_right, refine ap_compose pushout_sigma_of_sigma_pushout _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction a with a a', apply hdeg_square, refine !ap_compose'⁻¹ ⬝ !elim_glue ⬝ !con_idp ⬝ !idp_con } end end variables {f g} variables {X' : Type} {A' B' C' : X' → Type} {f' : Πx, A' x → B' x} {g' : Πx, A' x → C' x} {s : X → X'} {h₁ : Πx, A x → A' (s x)} {h₂ : Πx, B x → B' (s x)} {h₃ : Πx, C x → C' (s x)} (p : Πx, h₂ x ∘ f x ~ f' (s x) ∘ h₁ x) (q : Πx, h₃ x ∘ g x ~ g' (s x) ∘ h₁ x) definition pushout_sigma_equiv_sigma_pushout_natural : hsquare (pushout.functor (sigma_functor s h₁) (sigma_functor s h₂) (sigma_functor s h₃) (λa, sigma_eq_right (p a.1 a.2)) (λa, sigma_eq_right (q a.1 a.2))) (sigma_functor s (λx, pushout.functor (h₁ x) (h₂ x) (h₃ x) (p x) (q x))) (pushout_sigma_equiv_sigma_pushout f g) (pushout_sigma_equiv_sigma_pushout f' g') := begin intro x, induction x with b c a, { reflexivity }, { reflexivity }, { exact abstract begin apply eq_pathover, apply hdeg_square, refine !ap_compose ⬝ ap02 _ !elim_glue ⬝ !ap_con ⬝ (!ap_con ⬝ (!ap_compose'⁻¹ ⬝ !ap_compose'⁻¹) ◾ !elim_glue) ◾ (!ap_compose'⁻¹ ⬝ ap02 _ !ap_inv⁻¹ ⬝ !ap_compose'⁻¹) ⬝ _, exact (ap_compose (sigma_functor s (λ x, pushout.functor (h₁ x) (h₂ x) (h₃ x) (p x) (q x))) _ _ ⬝ ap02 _ !elim_glue ⬝ !ap_compose'⁻¹ ⬝ ap_compose (dpair _) _ _ ⬝ ap02 _ !elim_glue ⬝ !ap_con ⬝ (!ap_con ⬝ !ap_compose'⁻¹ ◾ idp) ◾ !ap_compose'⁻¹)⁻¹ end end } end /- an induction principle for the cofiber of f : A → B if A is a pushout where the second map has a section. The Pgluer is modified to get the right coherence See https://github.com/HoTT/HoTT-Agda/blob/master/theorems/homotopy/elims/CofPushoutSection.agda -/ open sigma.ops definition cofiber_pushout_helper' {A : Type} {B : A → Type} {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₀₂} {b₂₂ b₂₂' : B a₂₂} {q₁₀ : b₀₀ =[p₁₀] b₂₀} {q₀₁ : b₀₀ =[p₀₁] b₀₂} {q₂₁ : b₂₀ =[p₂₁] b₂₂'} {q₁₂ : b₀₂ =[p₁₂] b₂₂} : Σ(r : b₂₂' = b₂₂), squareover B s q₀₁ (r ▸ q₂₁) q₁₀ q₁₂ := begin induction s, induction q₀₁ using idp_rec_on, induction q₂₁ using idp_rec_on, induction q₁₀ using idp_rec_on, induction q₁₂ using idp_rec_on, exact ⟨idp, idso⟩ end definition cofiber_pushout_helper {A B C D : Type} {f : A → B} {g : A → C} {h : pushout f g → D} {P : cofiber h → Type} {Pcod : Πd, P (cofiber.cod h d)} {Pbase : P (cofiber.base h)} (Pgluel : Π(b : B), Pcod (h (inl b)) =[cofiber.glue (inl b)] Pbase) (Pgluer : Π(c : C), Pcod (h (inr c)) =[cofiber.glue (inr c)] Pbase) (a : A) : Σ(p : Pbase = Pbase), squareover P (natural_square cofiber.glue (glue a)) (Pgluel (f a)) (p ▸ Pgluer (g a)) (pathover_ap P (λa, cofiber.cod h (h a)) (apd (λa, Pcod (h a)) (glue a))) (pathover_ap P (λa, cofiber.base h) (apd (λa, Pbase) (glue a))) := !cofiber_pushout_helper' definition cofiber_pushout_rec {A B C D : Type} {f : A → B} {g : A → C} {h : pushout f g → D} {P : cofiber h → Type} (Pcod : Πd, P (cofiber.cod h d)) (Pbase : P (cofiber.base h)) (Pgluel : Π(b : B), Pcod (h (inl b)) =[cofiber.glue (inl b)] Pbase) (Pgluer : Π(c : C), Pcod (h (inr c)) =[cofiber.glue (inr c)] Pbase) (r : C → A) (p : Πa, r (g a) = a) (x : cofiber h) : P x := begin induction x with d x, { exact Pcod d }, { exact Pbase }, { induction x with b c a, { exact Pgluel b }, { exact (cofiber_pushout_helper Pgluel Pgluer (r c)).1 ▸ Pgluer c }, { apply pathover_pathover, rewrite [p a], exact (cofiber_pushout_helper Pgluel Pgluer a).2 }} end /- universal property of cofiber -/ definition cofiber_exact_1 {X Y Z : Type*} (f : X →* Y) (g : pcofiber f →* Z) : (g ∘* pcod f) ∘* f ~* pconst X Z := !passoc ⬝* pwhisker_left _ !pcod_pcompose ⬝* !pcompose_pconst protected definition pcofiber.elim [constructor] {X Y Z : Type*} {f : X →* Y} (g : Y →* Z) (p : g ∘* f ~* pconst X Z) : pcofiber f →* Z := begin fapply pmap.mk, { intro w, induction w with y x, exact g y, exact pt, exact p x }, { reflexivity } end protected definition pcofiber.elim_pcod {X Y Z : Type*} {f : X →* Y} {g : Y →* Z} (p : g ∘* f ~* pconst X Z) : pcofiber.elim g p ∘* pcod f ~* g := begin fapply phomotopy.mk, { intro y, reflexivity }, { esimp, refine !idp_con ⬝ _, refine _ ⬝ (!ap_con ⬝ (!ap_compose'⁻¹ ⬝ !ap_inv) ◾ !elim_glue)⁻¹, apply eq_inv_con_of_con_eq, exact (to_homotopy_pt p)⁻¹ } end /- The maps Z^{C_f} --> Z^Y --> Z^X are exact at Z^Y. Here Y^X means pointed maps from X to Y and C_f is the cofiber of f. The maps are given by precomposing with (pcod f) and f. -/ definition cofiber_exact {X Y Z : Type*} (f : X →* Y) : is_exact_t (@ppcompose_right _ _ Z (pcod f)) (ppcompose_right f) := begin constructor, { intro g, apply eq_of_phomotopy, apply cofiber_exact_1 }, { intro g p, note q := phomotopy_of_eq p, exact fiber.mk (pcofiber.elim g q) (eq_of_phomotopy (pcofiber.elim_pcod q)) } end /- cofiber of pcod is suspension -/ definition pcofiber_pcod {A B : Type*} (f : A →* B) : pcofiber (pcod f) ≃* susp A := begin fapply pequiv_of_equiv, { refine !pushout.symm ⬝e _, exact pushout_vcompose_equiv f equiv.rfl homotopy.rfl homotopy.rfl }, reflexivity end -- definition pushout_vcompose [constructor] {A B C D : Type} (f : A → B) (g : A → C) (h : B → D) : -- pushout h (@inl _ _ _ f g) ≃ pushout (h ∘ f) g := -- definition pushout_hcompose {A B C D : Type} (f : A → B) (g : A → C) (h : C → D) : -- pushout (@inr _ _ _ f g) h ≃ pushout f (h ∘ g) := -- definition pushout_vcompose_equiv {A B C D E : Type} (f : A → B) {g : A → C} {h : B → D} -- {hf : A → D} {k : B → E} (e : E ≃ pushout f g) (p : k ~ e⁻¹ᵉ ∘ inl) (q : h ∘ f ~ hf) : -- pushout h k ≃ pushout hf g := end pushout namespace pushout /- define the quotient using pushout -/ section open quotient sigma.ops variables {A B : Type} (R : A → A → Type) {Q : B → B → Type} (f : A → B) (k : Πa a' : A, R a a' → Q (f a) (f a')) definition pushout_quotient {A : Type} (R : A → A → Type) : Type := @pushout ((Σa a', R a a') ⊎ (Σa a', R a a')) A (Σa a', R a a') (sum.rec pr1 (λx, x.2.1)) (sum.rec id id) variable {R} definition pushout_quotient_of_quotient [unfold 3] (x : quotient R) : pushout_quotient R := begin induction x with a a a' r, { exact inl a }, { exact glue (sum.inl ⟨a, a', r⟩) ⬝ (glue (sum.inr ⟨a, a', r⟩))⁻¹ } end definition quotient_of_pushout_quotient [unfold 3] (x : pushout_quotient R) : quotient R := begin induction x with a x x, { exact class_of R a }, { exact class_of R x.2.1 }, { induction x with x x, exact eq_of_rel R x.2.2, reflexivity } end variable (R) definition quotient_equiv_pushout [constructor] : quotient R ≃ pushout_quotient R := equiv.MK pushout_quotient_of_quotient quotient_of_pushout_quotient abstract begin intro x, induction x with a x x, { reflexivity }, { exact glue (sum.inr x) }, { apply eq_pathover_id_right, refine ap_compose pushout_quotient_of_quotient _ _ ⬝ ap02 _ !elim_glue ⬝ph _, induction x with x x, { refine !elim_eq_of_rel ⬝ph _, induction x with a x, induction x with a' r, exact whisker_bl _ hrfl }, { exact square_of_eq idp }} end end abstract begin intro x, induction x, { reflexivity }, { apply eq_pathover_id_right, apply hdeg_square, refine ap_compose quotient_of_pushout_quotient _ _ ⬝ ap02 _ !elim_eq_of_rel ⬝ _, exact !ap_con ⬝ !elim_glue ◾ (!ap_inv ⬝ !elim_glue⁻²) } end end variable {R} definition sigma_functor2 [unfold 7] : (Σ a a', R a a') → (Σ b b', Q b b') := sigma_functor f (λa, sigma_functor f (k a)) definition pushout_quotient_functor [unfold 7] : pushout_quotient R → pushout_quotient Q := let tf := sigma_functor2 f k in pushout.functor (sum_functor tf tf) f tf begin intro x, induction x: reflexivity end begin intro x, induction x: reflexivity end definition quotient_equiv_pushout_natural : hsquare (quotient.functor _ _ f k) (pushout_quotient_functor f k) (quotient_equiv_pushout R) (quotient_equiv_pushout Q) := begin intro x, induction x with a a a' r, { reflexivity }, { apply eq_pathover, apply hdeg_square, refine ap_compose pushout_quotient_of_quotient _ _ ⬝ _ ⬝ (ap_compose (pushout.functor _ _ _ _ _) _ _)⁻¹, refine ap02 _ !elim_eq_of_rel ⬝ _ ⬝ (ap02 _ !elim_eq_of_rel)⁻¹, refine !elim_eq_of_rel ⬝ _, exact (!ap_con ⬝ (!pushout.elim_glue ⬝ !con_idp ⬝ !idp_con) ◾ (!ap_inv ⬝ (!pushout.elim_glue ⬝ !con_idp ⬝ !idp_con)⁻²))⁻¹ } end end variables {A B : Type*} open smash definition prod_of_wedge [unfold 3] (v : wedge A B) : A × B := begin induction v with a b , { exact (a, pt) }, { exact (pt, b) }, { reflexivity } end definition wedge_of_sum [unfold 3] (v : A + B) : wedge A B := begin induction v with a b, { exact pushout.inl a }, { exact pushout.inr b } end definition prod_of_wedge_of_sum [unfold 3] (v : A + B) : prod_of_wedge (wedge_of_sum v) = prod_of_sum v := begin induction v with a b, { reflexivity }, { reflexivity } end definition eq_inl_pushout_wedge_of_sum [unfold 3] (v : wedge A B) : inl pt = inl v :> pushout wedge_of_sum bool_of_sum := begin induction v with a b, { exact glue (sum.inl pt) ⬝ (glue (sum.inl a))⁻¹, }, { exact ap inl (glue ⋆) ⬝ glue (sum.inr pt) ⬝ (glue (sum.inr b))⁻¹, }, { apply eq_pathover_constant_left, refine !con.right_inv ⬝pv _ ⬝vp !con_inv_cancel_right⁻¹, exact square_of_eq idp } end variables (A B) definition eq_inr_pushout_wedge_of_sum [unfold 3] (b : bool) : inl pt = inr b :> pushout (@wedge_of_sum A B) bool_of_sum := begin induction b, { exact glue (sum.inl pt) }, { exact ap inl (glue ⋆) ⬝ glue (sum.inr pt) } end definition is_contr_pushout_wedge_of_sum : is_contr (pushout (@wedge_of_sum A B) bool_of_sum) := begin apply is_contr.mk (pushout.inl pt), intro x, induction x with v b w, { apply eq_inl_pushout_wedge_of_sum }, { apply eq_inr_pushout_wedge_of_sum }, { apply eq_pathover_constant_left_id_right, induction w with a b, { apply whisker_rt, exact vrfl }, { apply whisker_rt, exact vrfl }} end definition bool_of_sum_of_bool {A B : Type*} (b : bool) : bool_of_sum (sum_of_bool A B b) = b := by induction b: reflexivity /- a different proof, using pushout lemmas, and the fact that the wedge is the pushout of A + B <-- 2 --> 1 -/ definition pushout_wedge_of_sum_equiv_unit : pushout (@wedge_of_sum A B) bool_of_sum ≃ unit := begin refine pushout_hcompose_equiv (sum_of_bool A B) (wedge_equiv_pushout_sum A B ⬝e !pushout.symm) _ _ ⬝e _, exact erfl, intro x, induction x, reflexivity, reflexivity, exact bool_of_sum_of_bool, apply pushout_of_equiv_right end end pushout
69574ab40ef5ae7cc5433908e9f9a473e75d60fd
c777c32c8e484e195053731103c5e52af26a25d1
/src/order/interval.lean
ece0f3aee0dea9eea18c7e5dc978bdf501df8cc2
[ "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
18,446
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.set.intervals.basic import data.set.lattice import data.set_like.basic /-! # Order intervals This file defines (nonempty) closed intervals in an order (see `set.Icc`). This is a prototype for interval arithmetic. ## Main declarations * `nonempty_interval`: Nonempty intervals. Pairs where the second element is greater than the first. * `interval`: Intervals. Either `∅` or a nonempty interval. -/ open function order_dual set variables {α β γ δ : Type*} {ι : Sort*} {κ : ι → Sort*} /-- The nonempty closed intervals in an order. We define intervals by the pair of endpoints `fst`, `snd`. To convert intervals to the set of elements between these endpoints, use the coercion `nonempty_interval α → set α`. -/ @[ext] structure nonempty_interval (α : Type*) [has_le α] extends α × α := (fst_le_snd : fst ≤ snd) namespace nonempty_interval section has_le variables [has_le α] {s t : nonempty_interval α} lemma to_prod_injective : injective (to_prod : nonempty_interval α → α × α) := λ s t, (ext_iff _ _).2 /-- The injection that induces the order on intervals. -/ def to_dual_prod : nonempty_interval α → αᵒᵈ × α := to_prod @[simp] lemma to_dual_prod_apply (s : nonempty_interval α) : s.to_dual_prod = (to_dual s.fst, s.snd) := prod.mk.eta.symm lemma to_dual_prod_injective : injective (to_dual_prod : nonempty_interval α → αᵒᵈ × α) := to_prod_injective instance [is_empty α] : is_empty (nonempty_interval α) := ⟨λ s, is_empty_elim s.fst⟩ instance [subsingleton α] : subsingleton (nonempty_interval α) := to_dual_prod_injective.subsingleton instance : has_le (nonempty_interval α) := ⟨λ s t, t.fst ≤ s.fst ∧ s.snd ≤ t.snd⟩ lemma le_def : s ≤ t ↔ t.fst ≤ s.fst ∧ s.snd ≤ t.snd := iff.rfl /-- `to_dual_prod` as an order embedding. -/ @[simps] def to_dual_prod_hom : nonempty_interval α ↪o αᵒᵈ × α := { to_fun := to_dual_prod, inj' := to_dual_prod_injective, map_rel_iff' := λ _ _, iff.rfl } /-- Turn an interval into an interval in the dual order. -/ def dual : nonempty_interval α ≃ nonempty_interval αᵒᵈ := { to_fun := λ s, ⟨s.to_prod.swap, s.fst_le_snd⟩, inv_fun := λ s, ⟨s.to_prod.swap, s.fst_le_snd⟩, left_inv := λ s, ext _ _ $ prod.swap_swap _, right_inv := λ s, ext _ _ $ prod.swap_swap _ } @[simp] lemma fst_dual (s : nonempty_interval α) : s.dual.fst = to_dual s.snd := rfl @[simp] lemma snd_dual (s : nonempty_interval α) : s.dual.snd = to_dual s.fst := rfl end has_le section preorder variables [preorder α] [preorder β] [preorder γ] [preorder δ] {s : nonempty_interval α} {x : α × α} {a : α} instance : preorder (nonempty_interval α) := preorder.lift to_dual_prod instance : has_coe_t (nonempty_interval α) (set α) := ⟨λ s, Icc s.fst s.snd⟩ @[priority 100] instance : has_mem α (nonempty_interval α) := ⟨λ a s, a ∈ (s : set α)⟩ @[simp] lemma mem_mk {hx : x.1 ≤ x.2} : a ∈ mk x hx ↔ x.1 ≤ a ∧ a ≤ x.2 := iff.rfl lemma mem_def : a ∈ s ↔ s.fst ≤ a ∧ a ≤ s.snd := iff.rfl @[simp] lemma coe_nonempty (s : nonempty_interval α) : (s : set α).nonempty := nonempty_Icc.2 s.fst_le_snd /-- `{a}` as an interval. -/ @[simps] def pure (a : α) : nonempty_interval α := ⟨⟨a, a⟩, le_rfl⟩ lemma mem_pure_self (a : α) : a ∈ pure a := ⟨le_rfl, le_rfl⟩ lemma pure_injective : injective (pure : α → nonempty_interval α) := λ s t, congr_arg $ prod.fst ∘ to_prod @[simp] lemma dual_pure (a : α) : (pure a).dual = pure (to_dual a) := rfl instance [inhabited α] : inhabited (nonempty_interval α) := ⟨pure default⟩ instance : ∀ [nonempty α], nonempty (nonempty_interval α) := nonempty.map pure instance [nontrivial α] : nontrivial (nonempty_interval α) := pure_injective.nontrivial /-- Pushforward of nonempty intervals. -/ @[simps] def map (f : α →o β) (a : nonempty_interval α) : nonempty_interval β := ⟨a.to_prod.map f f, f.mono a.fst_le_snd⟩ @[simp] lemma map_pure (f : α →o β) (a : α) : (pure a).map f = pure (f a) := rfl @[simp] lemma map_map (g : β →o γ) (f : α →o β) (a : nonempty_interval α) : (a.map f).map g = a.map (g.comp f) := rfl @[simp] lemma dual_map (f : α →o β) (a : nonempty_interval α) : (a.map f).dual = a.dual.map f.dual := rfl /-- Binary pushforward of nonempty intervals. -/ @[simps] def map₂ (f : α → β → γ) (h₀ : ∀ b, monotone (λ a, f a b)) (h₁ : ∀ a, monotone (f a)) : nonempty_interval α → nonempty_interval β → nonempty_interval γ := λ s t, ⟨(f s.fst t.fst, f s.snd t.snd), (h₀ _ s.fst_le_snd).trans $ h₁ _ t.fst_le_snd⟩ @[simp] lemma map₂_pure (f : α → β → γ) (h₀ h₁) (a : α) (b : β) : map₂ f h₀ h₁ (pure a) (pure b) = pure (f a b) := rfl @[simp] lemma dual_map₂ (f : α → β → γ) (h₀ h₁ s t) : (map₂ f h₀ h₁ s t).dual = map₂ (λ a b, to_dual $ f (of_dual a) $ of_dual b) (λ _, (h₀ _).dual) (λ _, (h₁ _).dual) s.dual t.dual := rfl variables [bounded_order α] instance : order_top (nonempty_interval α) := { top := ⟨⟨⊥, ⊤⟩, bot_le⟩, le_top := λ a, ⟨bot_le, le_top⟩ } @[simp] lemma dual_top : (⊤ : nonempty_interval α).dual = ⊤ := rfl end preorder section partial_order variables [partial_order α] [partial_order β] {s t : nonempty_interval α} {x : α × α} {a b : α} instance : partial_order (nonempty_interval α) := partial_order.lift _ to_dual_prod_injective /-- Consider a nonempty interval `[a, b]` as the set `[a, b]`. -/ def coe_hom : nonempty_interval α ↪o set α := order_embedding.of_map_le_iff (λ s, Icc s.fst s.snd) (λ s t, Icc_subset_Icc_iff s.fst_le_snd) instance : set_like (nonempty_interval α) α := { coe := λ s, Icc s.fst s.snd, coe_injective' := coe_hom.injective } @[simp, norm_cast] lemma coe_subset_coe : (s : set α) ⊆ t ↔ s ≤ t := (@coe_hom α _).le_iff_le @[simp, norm_cast] lemma coe_ssubset_coe : (s : set α) ⊂ t ↔ s < t := (@coe_hom α _).lt_iff_lt @[simp] lemma coe_coe_hom : (coe_hom : nonempty_interval α → set α) = coe := rfl @[simp, norm_cast] lemma coe_pure (a : α) : (pure a : set α) = {a} := Icc_self _ @[simp] lemma mem_pure : b ∈ pure a ↔ b = a := by rw [←set_like.mem_coe, coe_pure, mem_singleton_iff] @[simp, norm_cast] lemma coe_top [bounded_order α] : ((⊤ : nonempty_interval α) : set α) = univ := Icc_bot_top @[simp, norm_cast] lemma coe_dual (s : nonempty_interval α) : (s.dual : set αᵒᵈ) = of_dual ⁻¹' s := dual_Icc lemma subset_coe_map (f : α →o β) (s : nonempty_interval α) : f '' s ⊆ s.map f := image_subset_iff.2 $ λ a ha, ⟨f.mono ha.1, f.mono ha.2⟩ end partial_order section lattice variables [lattice α] instance : has_sup (nonempty_interval α) := ⟨λ s t, ⟨⟨s.fst ⊓ t.fst, s.snd ⊔ t.snd⟩, inf_le_left.trans $ s.fst_le_snd.trans le_sup_left⟩⟩ instance : semilattice_sup (nonempty_interval α) := to_dual_prod_injective.semilattice_sup _ $ λ _ _, rfl @[simp] lemma fst_sup (s t : nonempty_interval α) : (s ⊔ t).fst = s.fst ⊓ t.fst := rfl @[simp] lemma snd_sup (s t : nonempty_interval α) : (s ⊔ t).snd = s.snd ⊔ t.snd := rfl end lattice end nonempty_interval /-- The closed intervals in an order. We represent intervals either as `⊥` or a nonempty interval given by its endpoints `fst`, `snd`. To convert intervals to the set of elements between these endpoints, use the coercion `interval α → set α`. -/ @[derive [inhabited, has_le, order_bot]] def interval (α : Type*) [has_le α] := with_bot (nonempty_interval α) namespace interval section has_le variables [has_le α] {s t : interval α} instance : has_coe_t (nonempty_interval α) (interval α) := with_bot.has_coe_t instance can_lift : can_lift (interval α) (nonempty_interval α) coe (λ r, r ≠ ⊥) := with_bot.can_lift lemma coe_injective : injective (coe : nonempty_interval α → interval α) := with_bot.coe_injective @[simp, norm_cast] lemma coe_inj {s t : nonempty_interval α} : (s : interval α) = t ↔ s = t := with_bot.coe_inj @[protected] lemma «forall» {p : interval α → Prop} : (∀ s, p s) ↔ p ⊥ ∧ ∀ s : nonempty_interval α, p s := option.forall @[protected] lemma «exists» {p : interval α → Prop} : (∃ s, p s) ↔ p ⊥ ∨ ∃ s : nonempty_interval α, p s := option.exists instance [is_empty α] : unique (interval α) := option.unique /-- Turn an interval into an interval in the dual order. -/ def dual : interval α ≃ interval αᵒᵈ := nonempty_interval.dual.option_congr end has_le section preorder variables [preorder α] [preorder β] [preorder γ] instance : preorder (interval α) := with_bot.preorder /-- `{a}` as an interval. -/ def pure (a : α) : interval α := nonempty_interval.pure a lemma pure_injective : injective (pure : α → interval α) := coe_injective.comp nonempty_interval.pure_injective @[simp] lemma dual_pure (a : α) : (pure a).dual = pure (to_dual a) := rfl @[simp] lemma dual_bot : (⊥ : interval α).dual = ⊥ := rfl @[simp] lemma pure_ne_bot {a : α} : pure a ≠ ⊥ := with_bot.coe_ne_bot @[simp] lemma bot_ne_pure {a : α} : ⊥ ≠ pure a := with_bot.bot_ne_coe instance [nonempty α] : nontrivial (interval α) := option.nontrivial /-- Pushforward of intervals. -/ def map (f : α →o β) : interval α → interval β := with_bot.map (nonempty_interval.map f) @[simp] lemma map_pure (f : α →o β) (a : α) : (pure a).map f = pure (f a) := rfl @[simp] lemma map_map (g : β →o γ) (f : α →o β) (s : interval α) : (s.map f).map g = s.map (g.comp f) := option.map_map _ _ _ @[simp] lemma dual_map (f : α →o β) (s : interval α) : (s.map f).dual = s.dual.map f.dual := by { cases s, { refl }, { exact with_bot.map_comm rfl _ } } variables [bounded_order α] instance : bounded_order (interval α) := with_bot.bounded_order @[simp] lemma dual_top : (⊤ : interval α).dual = ⊤ := rfl end preorder section partial_order variables [partial_order α] [partial_order β] {s t : interval α} {a b : α} instance : partial_order (interval α) := with_bot.partial_order /-- Consider a interval `[a, b]` as the set `[a, b]`. -/ def coe_hom : interval α ↪o set α := order_embedding.of_map_le_iff (λ s, match s with | ⊥ := ∅ | some s := s end) (λ s t, match s, t with | ⊥, t := iff_of_true bot_le bot_le | some s, ⊥ := iff_of_false (λ h, s.coe_nonempty.ne_empty $ le_bot_iff.1 h) (with_bot.not_coe_le_bot _) | some s, some t := (@nonempty_interval.coe_hom α _).le_iff_le.trans with_bot.some_le_some.symm end) instance : set_like (interval α) α := { coe := coe_hom, coe_injective' := coe_hom.injective } @[simp, norm_cast] lemma coe_subset_coe : (s : set α) ⊆ t ↔ s ≤ t := (@coe_hom α _).le_iff_le @[simp, norm_cast] lemma coe_ssubset_coe : (s : set α) ⊂ t ↔ s < t := (@coe_hom α _).lt_iff_lt @[simp, norm_cast] lemma coe_pure (a : α) : (pure a : set α) = {a} := Icc_self _ @[simp, norm_cast] lemma coe_coe (s : nonempty_interval α) : ((s : interval α) : set α) = s := rfl @[simp, norm_cast] lemma coe_bot : ((⊥ : interval α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_top [bounded_order α] : ((⊤ : interval α) : set α) = univ := Icc_bot_top @[simp, norm_cast] lemma coe_dual (s : interval α) : (s.dual : set αᵒᵈ) = of_dual ⁻¹' s := by { cases s, { refl }, exact s.coe_dual } lemma subset_coe_map (f : α →o β) : ∀ s : interval α, f '' s ⊆ s.map f | ⊥ := by simp | (s : nonempty_interval α) := s.subset_coe_map _ @[simp] lemma mem_pure : b ∈ pure a ↔ b = a := by rw [←set_like.mem_coe, coe_pure, mem_singleton_iff] lemma mem_pure_self (a : α) : a ∈ pure a := mem_pure.2 rfl end partial_order section lattice variables [lattice α] instance : semilattice_sup (interval α) := with_bot.semilattice_sup section decidable variables [@decidable_rel α (≤)] instance : lattice (interval α) := { inf := λ s t, match s, t with | ⊥, t := ⊥ | s, ⊥ := ⊥ | some s, some t := if h : s.fst ≤ t.snd ∧ t.fst ≤ s.snd then some ⟨⟨s.fst ⊔ t.fst, s.snd ⊓ t.snd⟩, sup_le (le_inf s.fst_le_snd h.1) $ le_inf h.2 t.fst_le_snd⟩ else ⊥ end, inf_le_left := λ s t, match s, t with | ⊥, ⊥ := bot_le | ⊥, some t := bot_le | some s, ⊥ := bot_le | some s, some t := begin change dite _ _ _ ≤ _, split_ifs, { exact with_bot.some_le_some.2 ⟨le_sup_left, inf_le_left⟩ }, { exact bot_le } end end, inf_le_right := λ s t, match s, t with | ⊥, ⊥ := bot_le | ⊥, some t := bot_le | some s, ⊥ := bot_le | some s, some t := begin change dite _ _ _ ≤ _, split_ifs, { exact with_bot.some_le_some.2 ⟨le_sup_right, inf_le_right⟩ }, { exact bot_le } end end, le_inf := λ s t c, match s, t, c with | ⊥, t, c := λ _ _, bot_le | some s, t, c := λ hb hc, begin lift t to nonempty_interval α using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hb, lift c to nonempty_interval α using ne_bot_of_le_ne_bot with_bot.coe_ne_bot hc, change _ ≤ dite _ _ _, simp only [with_bot.some_eq_coe, with_bot.coe_le_coe] at ⊢ hb hc, rw [dif_pos, with_bot.coe_le_coe], exact ⟨sup_le hb.1 hc.1, le_inf hb.2 hc.2⟩, exact ⟨hb.1.trans $ s.fst_le_snd.trans hc.2, hc.1.trans $ s.fst_le_snd.trans hb.2⟩, end end, ..interval.semilattice_sup } @[simp, norm_cast] lemma coe_inf (s t : interval α) : (↑(s ⊓ t) : set α) = s ∩ t := begin cases s, { rw [with_bot.none_eq_bot, bot_inf_eq], exact (empty_inter _).symm }, cases t, { rw [with_bot.none_eq_bot, inf_bot_eq], exact (inter_empty _).symm }, refine (_ : coe (dite _ _ _) = _).trans Icc_inter_Icc.symm, split_ifs, { refl }, { exact (Icc_eq_empty $ λ H, h ⟨le_sup_left.trans $ H.trans inf_le_right, le_sup_right.trans $ H.trans inf_le_left⟩).symm } end end decidable @[simp, norm_cast] lemma disjoint_coe (s t : interval α) : disjoint (s : set α) t ↔ disjoint s t := begin classical, rw [disjoint_iff_inf_le, disjoint_iff_inf_le, le_eq_subset, ←coe_subset_coe, coe_inf], refl end end lattice end interval namespace nonempty_interval section preorder variables [preorder α] {s : nonempty_interval α} {a : α} @[simp, norm_cast] lemma coe_pure_interval (a : α) : (pure a : interval α) = interval.pure a := rfl @[simp, norm_cast] lemma coe_eq_pure : (s : interval α) = interval.pure a ↔ s = pure a := by rw [←interval.coe_inj, coe_pure_interval] @[simp, norm_cast] lemma coe_top_interval [bounded_order α] : ((⊤ : nonempty_interval α) : interval α) = ⊤ := rfl end preorder @[simp, norm_cast] lemma mem_coe_interval [partial_order α] {s : nonempty_interval α} {x : α} : x ∈ (s : interval α) ↔ x ∈ s := iff.rfl @[simp, norm_cast] lemma coe_sup_interval [lattice α] (s t : nonempty_interval α) : (↑(s ⊔ t) : interval α) = s ⊔ t := rfl end nonempty_interval namespace interval section complete_lattice variables [complete_lattice α] noncomputable instance [@decidable_rel α (≤)] : complete_lattice (interval α) := by classical; exact { Sup := λ S, if h : S ⊆ {⊥} then ⊥ else some ⟨⟨⨅ (s : nonempty_interval α) (h : ↑s ∈ S), s.fst, ⨆ (s : nonempty_interval α) (h : ↑s ∈ S), s.snd⟩, begin obtain ⟨s, hs, ha⟩ := not_subset.1 h, lift s to nonempty_interval α using ha, exact infi₂_le_of_le s hs (le_supr₂_of_le s hs s.fst_le_snd) end⟩, le_Sup := λ s s ha, begin split_ifs, { exact (h ha).le }, cases s, { exact bot_le }, { exact with_bot.some_le_some.2 ⟨infi₂_le _ ha, le_supr₂_of_le _ ha le_rfl⟩ } end, Sup_le := λ s s ha, begin split_ifs, { exact bot_le }, obtain ⟨b, hs, hb⟩ := not_subset.1 h, lift s to nonempty_interval α using ne_bot_of_le_ne_bot hb (ha _ hs), exact with_bot.coe_le_coe.2 ⟨le_infi₂ $ λ c hc, (with_bot.coe_le_coe.1 $ ha _ hc).1, supr₂_le $ λ c hc, (with_bot.coe_le_coe.1 $ ha _ hc).2⟩, end, Inf := λ S, if h : ⊥ ∉ S ∧ ∀ ⦃s : nonempty_interval α⦄, ↑s ∈ S → ∀ ⦃t : nonempty_interval α⦄, ↑t ∈ S → s.fst ≤ t.snd then some ⟨⟨⨆ (s : nonempty_interval α) (h : ↑s ∈ S), s.fst, ⨅ (s : nonempty_interval α) (h : ↑s ∈ S), s.snd⟩, supr₂_le $ λ s hs, le_infi₂ $ h.2 hs⟩ else ⊥, Inf_le := λ s s ha, begin split_ifs, { lift s to nonempty_interval α using ne_of_mem_of_not_mem ha h.1, exact with_bot.coe_le_coe.2 ⟨le_supr₂ s ha, infi₂_le s ha⟩ }, { exact bot_le } end, le_Inf := λ S s ha, begin cases s, { exact bot_le }, split_ifs, { exact with_bot.some_le_some.2 ⟨supr₂_le $ λ t hb, (with_bot.coe_le_coe.1 $ ha _ hb).1, le_infi₂ $ λ t hb, (with_bot.coe_le_coe.1 $ ha _ hb).2⟩ }, rw [not_and_distrib, not_not] at h, cases h, { exact ha _ h }, cases h (λ t hb c hc, (with_bot.coe_le_coe.1 $ ha _ hb).1.trans $ s.fst_le_snd.trans (with_bot.coe_le_coe.1 $ ha _ hc).2), end, ..interval.lattice, ..interval.bounded_order } @[simp, norm_cast] lemma coe_Inf [@decidable_rel α (≤)] (S : set (interval α)) : ↑(Inf S) = ⋂ s ∈ S, (s : set α) := begin change coe (dite _ _ _) = _, split_ifs, { ext, simp [with_bot.some_eq_coe, interval.forall, h.1, ←forall_and_distrib, ←nonempty_interval.mem_def] }, simp_rw [not_and_distrib, not_not] at h, cases h, { refine (eq_empty_of_subset_empty _).symm, exact Inter₂_subset_of_subset _ h subset.rfl }, { refine (not_nonempty_iff_eq_empty.1 _).symm, rintro ⟨x, hx⟩, rw mem_Inter₂ at hx, exact h (λ s ha t hb, (hx _ ha).1.trans (hx _ hb).2) } end @[simp, norm_cast] lemma coe_infi [@decidable_rel α (≤)] (f : ι → interval α) : ↑(⨅ i, f i) = ⋂ i, (f i : set α) := by simp [infi] @[simp, norm_cast] lemma coe_infi₂ [@decidable_rel α (≤)] (f : Π i, κ i → interval α) : ↑(⨅ i j, f i j) = ⋂ i j, (f i j : set α) := by simp_rw [coe_infi] end complete_lattice end interval
1e589b19695d8ff1f2f0ba3d0a04722a53b1a911
96e44fc78cabfc9d646dc37d0e756189b6b79181
/library/init/algebra/functions.lean
7b0f436ee083fa0cd405941cdc127129e7c0232e
[ "Apache-2.0" ]
permissive
TwoFX/lean
23c73c10a340f5a381f6abf27a27f53f1fb7e2e3
7e3f336714055869690b7309b6bb651fbc67e76e
refs/heads/master
1,612,504,908,183
1,594,641,622,000
1,594,641,622,000
243,750,847
0
0
Apache-2.0
1,582,890,661,000
1,582,890,661,000
null
UTF-8
Lean
false
false
4,455
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura -/ prelude import init.algebra.order init.meta universe u definition min {α : Type u} [decidable_linear_order α] (a b : α) : α := if a ≤ b then a else b definition max {α : Type u} [decidable_linear_order α] (a b : α) : α := if a ≤ b then b else a section open decidable tactic variables {α : Type u} [decidable_linear_order α] private meta def min_tac_step : tactic unit := solve1 $ intros >> `[unfold min max] >> try `[simp [*, if_pos, if_neg]] >> try `[apply le_refl] >> try `[apply le_of_not_le, assumption] meta def tactic.interactive.min_tac (a b : interactive.parse lean.parser.pexpr) : tactic unit := interactive.by_cases (none, ``(%%a ≤ %%b)); min_tac_step lemma min_le_left (a b : α) : min a b ≤ a := by min_tac a b lemma min_le_right (a b : α) : min a b ≤ b := by min_tac a b lemma le_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) : c ≤ min a b := by min_tac a b lemma le_max_left (a b : α) : a ≤ max a b := by min_tac a b lemma le_max_right (a b : α) : b ≤ max a b := by min_tac a b lemma max_le {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) : max a b ≤ c := by min_tac a b lemma eq_min {a b c : α} (h₁ : c ≤ a) (h₂ : c ≤ b) (h₃ : ∀{d}, d ≤ a → d ≤ b → d ≤ c) : c = min a b := le_antisymm (le_min h₁ h₂) (h₃ (min_le_left a b) (min_le_right a b)) lemma min_comm (a b : α) : min a b = min b a := eq_min (min_le_right a b) (min_le_left a b) (λ c h₁ h₂, le_min h₂ h₁) lemma min_assoc (a b c : α) : min (min a b) c = min a (min b c) := begin apply eq_min, { apply le_trans, apply min_le_left, apply min_le_left }, { apply le_min, apply le_trans, apply min_le_left, apply min_le_right, apply min_le_right }, { intros d h₁ h₂, apply le_min, apply le_min h₁, apply le_trans h₂, apply min_le_left, apply le_trans h₂, apply min_le_right } end lemma min_left_comm : ∀ (a b c : α), min a (min b c) = min b (min a c) := left_comm (@min α _) (@min_comm α _) (@min_assoc α _) @[simp] lemma min_self (a : α) : min a a = a := by min_tac a a @[ematch] lemma min_eq_left {a b : α} (h : a ≤ b) : min a b = a := begin apply eq.symm, apply eq_min (le_refl _) h, intros, assumption end @[ematch] lemma min_eq_right {a b : α} (h : b ≤ a) : min a b = b := eq.subst (min_comm b a) (min_eq_left h) lemma eq_max {a b c : α} (h₁ : a ≤ c) (h₂ : b ≤ c) (h₃ : ∀{d}, a ≤ d → b ≤ d → c ≤ d) : c = max a b := le_antisymm (h₃ (le_max_left a b) (le_max_right a b)) (max_le h₁ h₂) lemma max_comm (a b : α) : max a b = max b a := eq_max (le_max_right a b) (le_max_left a b) (λ c h₁ h₂, max_le h₂ h₁) lemma max_assoc (a b c : α) : max (max a b) c = max a (max b c) := begin apply eq_max, { apply le_trans, apply le_max_left a b, apply le_max_left }, { apply max_le, apply le_trans, apply le_max_right a b, apply le_max_left, apply le_max_right }, { intros d h₁ h₂, apply max_le, apply max_le h₁, apply le_trans (le_max_left _ _) h₂, apply le_trans (le_max_right _ _) h₂} end lemma max_left_comm : ∀ (a b c : α), max a (max b c) = max b (max a c) := left_comm (@max α _) (@max_comm α _) (@max_assoc α _) @[simp] lemma max_self (a : α) : max a a = a := by min_tac a a lemma max_eq_left {a b : α} (h : b ≤ a) : max a b = a := begin apply eq.symm, apply eq_max (le_refl _) h, intros, assumption end lemma max_eq_right {a b : α} (h : a ≤ b) : max a b = b := eq.subst (max_comm b a) (max_eq_left h) /- these rely on lt_of_lt -/ lemma min_eq_left_of_lt {a b : α} (h : a < b) : min a b = a := min_eq_left (le_of_lt h) lemma min_eq_right_of_lt {a b : α} (h : b < a) : min a b = b := min_eq_right (le_of_lt h) lemma max_eq_left_of_lt {a b : α} (h : b < a) : max a b = a := max_eq_left (le_of_lt h) lemma max_eq_right_of_lt {a b : α} (h : a < b) : max a b = b := max_eq_right (le_of_lt h) /- these use the fact that it is a linear ordering -/ lemma lt_min {a b c : α} (h₁ : a < b) (h₂ : a < c) : a < min b c := or.elim (le_or_gt b c) (assume h : b ≤ c, by min_tac b c) (assume h : b > c, by min_tac b c) lemma max_lt {a b c : α} (h₁ : a < c) (h₂ : b < c) : max a b < c := or.elim (le_or_gt a b) (assume h : a ≤ b, by min_tac a b) (assume h : a > b, by min_tac a b) end
e877da19b760318159c914f0d6573460482d044a
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/data/num/basic.lean
fc9e2bdbcc2dd2b3c01d81fdbc64760f5ebe0273
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
11,430
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro Binary representation of integers using inductive types. Note: Unlike in Coq, where this representation is preferred because of the reliance on kernel reduction, in Lean this representation is discouraged in favor of the "Peano" natural numbers `nat`, and the purpose of this collection of theorems is to show the equivalence of the different approaches. -/ import data.pnat data.bool data.vector data.bitvec universe u inductive pos_num : Type | one : pos_num | bit1 : pos_num → pos_num | bit0 : pos_num → pos_num instance : has_one pos_num := ⟨pos_num.one⟩ instance : decidable_eq pos_num := by tactic.mk_dec_eq_instance inductive num : Type | zero : num | pos : pos_num → num instance : has_zero num := ⟨num.zero⟩ instance : has_one num := ⟨num.pos 1⟩ instance : has_coe pos_num num := ⟨num.pos⟩ instance : decidable_eq num := by tactic.mk_dec_eq_instance -- Representation of integers using trichotomy around zero inductive znum : Type | zero : znum | pos : pos_num → znum | neg : pos_num → znum instance : has_zero znum := ⟨znum.zero⟩ instance : has_one znum := ⟨znum.pos 1⟩ instance : has_coe pos_num znum := ⟨znum.pos⟩ instance : decidable_eq znum := by tactic.mk_dec_eq_instance -- Alternative representation of integers using a sign bit at the end inductive nzsnum : Type | one : bool → nzsnum | bit : bool → nzsnum → nzsnum inductive snum : Type | zero : bool → snum | nz : nzsnum → snum instance : has_coe nzsnum snum := ⟨snum.nz⟩ instance : has_zero snum := ⟨snum.zero ff⟩ instance : has_one nzsnum := ⟨nzsnum.one tt⟩ instance : has_one snum := ⟨snum.nz 1⟩ instance : decidable_eq nzsnum := by tactic.mk_dec_eq_instance instance : decidable_eq snum := by tactic.mk_dec_eq_instance namespace pos_num def bit (b : bool) : pos_num → pos_num := cond b bit1 bit0 def succ : pos_num → pos_num | 1 := bit0 one | (bit1 n) := bit0 (succ n) | (bit0 n) := bit1 n def is_one : pos_num → bool | 1 := tt | _ := ff protected def add : pos_num → pos_num → pos_num | 1 b := succ b | a 1 := succ a | (bit0 a) (bit0 b) := bit0 (add a b) | (bit1 a) (bit1 b) := bit0 (succ (add a b)) | (bit0 a) (bit1 b) := bit1 (add a b) | (bit1 a) (bit0 b) := bit1 (add a b) instance : has_add pos_num := ⟨pos_num.add⟩ def pred' : pos_num → option pos_num | 1 := none | (bit0 n) := some (option.cases_on (pred' n) 1 bit1) | (bit1 n) := bit0 n def pred (a : pos_num) : pos_num := (pred' a).get_or_else 1 def size : pos_num → pos_num | 1 := 1 | (bit0 n) := succ (size n) | (bit1 n) := succ (size n) protected def mul (a : pos_num) : pos_num → pos_num | 1 := a | (bit0 b) := bit0 (mul b) | (bit1 b) := bit0 (mul b) + a instance : has_mul pos_num := ⟨pos_num.mul⟩ def of_nat_succ : ℕ → pos_num | 0 := 1 | (nat.succ n) := succ (of_nat_succ n) def of_nat (n : ℕ) : pos_num := of_nat_succ (nat.pred n) open ordering def cmp : pos_num → pos_num → ordering | 1 1 := eq | _ 1 := gt | 1 _ := lt | (bit0 a) (bit0 b) := cmp a b | (bit0 a) (bit1 b) := ordering.cases_on (cmp a b) lt lt gt | (bit1 a) (bit0 b) := ordering.cases_on (cmp a b) lt gt gt | (bit1 a) (bit1 b) := cmp a b instance : has_ordering pos_num := ⟨cmp⟩ def psub : pos_num → pos_num → option pos_num | 1 b := none | a 1 := pred' a | (bit0 a) (bit0 b) := bit0 <$> psub a b | (bit0 a) (bit1 b) := bit1 <$> psub a b | (bit1 a) (bit0 b) := bit1 <$> psub a b | (bit1 a) (bit1 b) := bit0 <$> psub a b protected def sub (a b : pos_num) : pos_num := (psub a b).get_or_else 1 instance : has_sub pos_num := ⟨pos_num.sub⟩ end pos_num section variables {α : Type u} [has_zero α] [has_one α] [has_add α] def cast_pos_num : pos_num → α | 1 := 1 | (pos_num.bit0 a) := bit0 (cast_pos_num a) | (pos_num.bit1 a) := bit1 (cast_pos_num a) def cast_num : num → α | 0 := 0 | (num.pos p) := cast_pos_num p @[priority 0] instance pos_num_coe : has_coe pos_num α := ⟨cast_pos_num⟩ @[priority 0] instance num_nat_coe : has_coe num α := ⟨cast_num⟩ end namespace nat def of_pos_num : pos_num → nat := cast_pos_num def of_num : num → nat := cast_num end nat instance : has_lt pos_num := ⟨λa b, (a : ℕ) < b⟩ instance : has_le pos_num := ⟨λa b, (a : ℕ) ≤ b⟩ instance : has_lt num := ⟨λa b, (a : ℕ) < b⟩ instance : has_le num := ⟨λa b, (a : ℕ) ≤ b⟩ namespace num open pos_num def succ' : num → pos_num | 0 := 1 | (pos p) := succ p def succ (n : num) : num := pos (succ' n) def of_nat : nat → num | 0 := 0 | (nat.succ n) := succ (of_nat n) instance nat_num_coe : has_coe nat num := ⟨of_nat⟩ protected def add : num → num → num | 0 a := a | b 0 := b | (pos a) (pos b) := pos (a + b) instance : has_add num := ⟨num.add⟩ def pred : num → num | 0 := 0 | (pos p) := option.cases_on (pred' p) 0 pos protected def bit0 : num → num | 0 := 0 | (pos n) := pos (pos_num.bit0 n) protected def bit1 : num → num | 0 := 1 | (pos n) := pos (pos_num.bit1 n) def bit (b : bool) : num → num := cond b num.bit1 num.bit0 def size : num → num | 0 := 0 | (pos n) := pos (pos_num.size n) protected def mul : num → num → num | 0 _ := 0 | _ 0 := 0 | (pos a) (pos b) := pos (a * b) instance : has_mul num := ⟨num.mul⟩ open ordering def cmp : num → num → ordering | 0 0 := eq | _ 0 := gt | 0 _ := lt | (pos a) (pos b) := pos_num.cmp a b instance : has_ordering num := ⟨cmp⟩ protected def sub : num → num → num | a 0 := a | 0 b := b | (pos a) (pos b) := option.cases_on (psub a b) 0 pos instance : has_sub num := ⟨num.sub⟩ def to_znum : num → znum | 0 := 0 | (pos a) := znum.pos a instance coe_znum : has_coe num znum := ⟨to_znum⟩ end num namespace znum open pos_num def succ : znum → znum | 0 := 1 | (pos a) := pos (pos_num.succ a) | (neg a) := option.cases_on (pos_num.pred' a) 0 neg def pred : znum → znum | 0 := neg 1 | (pos a) := option.cases_on (pos_num.pred' a) 0 pos | (neg a) := neg (pos_num.succ a) def zneg : znum → znum | 0 := 0 | (pos a) := neg a | (neg a) := pos a instance : has_neg znum := ⟨zneg⟩ protected def add : znum → znum → znum | 0 a := a | b 0 := b | (pos a) (pos b) := pos (a + b) | (pos a) (neg b) := option.cases_on (psub a b) (option.cases_on (psub b a) 0 neg) pos | (neg a) (pos b) := option.cases_on (psub a b) (option.cases_on (psub b a) 0 pos) neg | (neg a) (neg b) := neg (a + b) instance : has_add znum := ⟨znum.add⟩ protected def sub (a b : znum) : znum := a + zneg b instance : has_sub znum := ⟨znum.sub⟩ protected def mul : znum → znum → znum | 0 a := 0 | b 0 := 0 | (pos a) (pos b) := pos (a * b) | (pos a) (neg b) := neg (a * b) | (neg a) (pos b) := neg (a * b) | (neg a) (neg b) := pos (a * b) instance : has_mul znum := ⟨znum.mul⟩ end znum namespace int def of_znum : znum → ℤ | 0 := 0 | (znum.pos a) := a | (znum.neg a) := -[1+ option.cases_on (pos_num.pred' a) 0 nat.of_pos_num] instance znum_coe : has_coe znum ℤ := ⟨of_znum⟩ end int instance : has_lt znum := ⟨λa b, (a : ℤ) < b⟩ instance : has_le znum := ⟨λa b, (a : ℤ) ≤ b⟩ /- The snum representation uses a bit string, essentially a list of 0 (ff) and 1 (tt) bits, and the negation of the MSB is sign-extended to all higher bits. -/ namespace nzsnum notation a :: b := bit a b def sign : nzsnum → bool | (one b) := bnot b | (b :: p) := sign p @[pattern] def not : nzsnum → nzsnum | (one b) := one (bnot b) | (b :: p) := bnot b :: not p prefix ~ := not def bit0 : nzsnum → nzsnum := bit ff def bit1 : nzsnum → nzsnum := bit tt def head : nzsnum → bool | (one b) := b | (b :: p) := b def tail : nzsnum → snum | (one b) := snum.zero (bnot b) | (b :: p) := p end nzsnum namespace snum open nzsnum def sign : snum → bool | (zero z) := z | (nz p) := p.sign @[pattern] def not : snum → snum | (zero z) := zero (bnot z) | (nz p) := ~p prefix ~ := not @[pattern] def bit : bool → snum → snum | b (zero z) := if b = z then zero b else one b | b (nz p) := p.bit b notation a :: b := bit a b def bit0 : snum → snum := bit ff def bit1 : snum → snum := bit tt theorem bit_zero (b) : b :: zero b = zero b := by cases b; refl theorem bit_one (b) : b :: zero (bnot b) = one b := by cases b; refl end snum namespace nzsnum open snum def drec' {C : snum → Sort u} (z : Π b, C (snum.zero b)) (s : Π b p, C p → C (b :: p)) : Π p : nzsnum, C p | (one b) := by rw ←bit_one; exact s b (snum.zero (bnot b)) (z (bnot b)) | (bit b p) := s b p (drec' p) end nzsnum namespace snum open nzsnum def head : snum → bool | (zero z) := z | (nz p) := p.head def tail : snum → snum | (zero z) := zero z | (nz p) := p.tail def drec' {C : snum → Sort u} (z : Π b, C (snum.zero b)) (s : Π b p, C p → C (b :: p)) : Π p, C p | (zero b) := z b | (nz p) := p.drec' z s def rec' {α} (z : bool → α) (s : bool → snum → α → α) : snum → α := drec' z s def bits : snum → Π n, vector bool n | p 0 := [] | p (n+1) := head p :: bits (tail p) n def test_bit : nat → snum → bool | 0 p := head p | (n+1) p := test_bit n (tail p) def succ : snum → snum := rec' (λ b, cond b 0 1) (λb p succp, cond b (ff :: succp) (tt :: p)) def pred : snum → snum := rec' (λ b, cond b (~1) ~0) (λb p predp, cond b (ff :: p) (tt :: predp)) protected def neg (n : snum) : snum := succ ~n instance : has_neg snum := ⟨snum.neg⟩ -- First bit is 0 or 1 (tt), second bit is 0 or -1 (tt) def czadd : bool → bool → snum → snum | ff ff p := p | ff tt p := pred p | tt ff p := succ p | tt tt p := p def cadd : snum → snum → bool → snum := rec' (λ a p c, czadd c a p) $ λa p IH, rec' (λb c, czadd c b (a :: p)) $ λb q _ c, bitvec.xor3 a b c :: IH q (bitvec.carry a b c) protected def add (a b : snum) : snum := cadd a b ff instance : has_add snum := ⟨snum.add⟩ protected def sub (a b : snum) : snum := a + -b instance : has_sub snum := ⟨snum.sub⟩ protected def mul (a : snum) : snum → snum := rec' (λ b, cond b (-a) 0) $ λb q IH, cond b (bit0 IH + a) (bit0 IH) instance : has_mul snum := ⟨snum.mul⟩ end snum namespace int def of_snum : snum → ℤ := snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH)) instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩ end int instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩ instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
e3bfd8abe4e97def8c872999d3163d0ce833e13a
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/linear_algebra/exterior_algebra.lean
9a2d91e069f8452269be06f18453f6c01a473686
[ "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
5,407
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhangir Azerbayev, Adam Topaz, Eric Wieser. -/ import algebra.ring_quot import linear_algebra.tensor_algebra import group_theory.perm.sign /-! # Exterior Algebras We construct the exterior algebra of a semimodule `M` over a commutative semiring `R`. ## Notation The exterior algebra of the `R`-semimodule `M` is denoted as `exterior_algebra R M`. It is endowed with the structure of an `R`-algebra. Given a linear morphism `f : M → A` from a semimodule `M` to another `R`-algebra `A`, such that `cond : ∀ m : M, f m * f m = 0`, there is a (unique) lift of `f` to an `R`-algebra morphism, which is denoted `exterior_algebra.lift R f cond`. The canonical linear map `M → exterior_algebra R M` is denoted `exterior_algebra.ι R`. ## Theorems The main theorems proved ensure that `exterior_algebra R M` satisfies the universal property of the exterior algebra. 1. `ι_comp_lift` is fact that the composition of `ι R` with `lift R f cond` agrees with `f`. 2. `lift_unique` ensures the uniqueness of `lift R f cond` with respect to 1. ## Implementation details The exterior algebra of `M` is constructed as a quotient of the tensor algebra, as follows. 1. We define a relation `exterior_algebra.rel R M` on `tensor_algebra R M`. This is the smallest relation which identifies squares of elements of `M` with `0`. 2. The exterior algebra is the quotient of the tensor algebra by this relation. -/ variables (R : Type*) [comm_semiring R] variables (M : Type*) [add_comm_monoid M] [semimodule R M] namespace exterior_algebra open tensor_algebra /-- `rel` relates each `ι m * ι m`, for `m : M`, with `0`. The exterior algebra of `M` is defined as the quotient modulo this relation. -/ inductive rel : tensor_algebra R M → tensor_algebra R M → Prop | of (m : M) : rel ((ι R m) * (ι R m)) 0 end exterior_algebra /-- The exterior algebra of an `R`-semimodule `M`. -/ @[derive [inhabited, semiring, algebra R]] def exterior_algebra := ring_quot (exterior_algebra.rel R M) namespace exterior_algebra variables {M} -- typeclass resolution times out here, so we give it a hand instance {S : Type*} [comm_ring S] [semimodule S M] : ring (exterior_algebra S M) := let i : ring (tensor_algebra S M) := infer_instance in @ring_quot.ring (tensor_algebra S M) i (exterior_algebra.rel S M) /-- The canonical linear map `M →ₗ[R] exterior_algebra R M`. -/ def ι : M →ₗ[R] exterior_algebra R M := (ring_quot.mk_alg_hom R _).to_linear_map.comp (tensor_algebra.ι R) variables {R} /-- As well as being linear, `ι m` squares to zero -/ @[simp] theorem ι_square_zero (m : M) : (ι R m) * (ι R m) = 0 := begin erw [←alg_hom.map_mul, ring_quot.mk_alg_hom_rel R (rel.of m), alg_hom.map_zero _], end variables {A : Type*} [semiring A] [algebra R A] @[simp] theorem comp_ι_square_zero (g : exterior_algebra R M →ₐ[R] A) (m : M) : g (ι R m) * g (ι R m) = 0 := by rw [←alg_hom.map_mul, ι_square_zero, alg_hom.map_zero] variables (R) /-- Given a linear map `f : M →ₗ[R] A` into an `R`-algebra `A`, which satisfies the condition: `cond : ∀ m : M, f m * f m = 0`, this is the canonical lift of `f` to a morphism of `R`-algebras from `exterior_algebra R M` to `A`. -/ @[simps symm_apply] def lift : {f : M →ₗ[R] A // ∀ m, f m * f m = 0} ≃ (exterior_algebra R M →ₐ[R] A) := { to_fun := λ f, ring_quot.lift_alg_hom R ⟨tensor_algebra.lift R (f : M →ₗ[R] A), λ x y (h : rel R M x y), by { induction h, rw [alg_hom.map_zero, alg_hom.map_mul, tensor_algebra.lift_ι_apply, f.prop] }⟩, inv_fun := λ F, ⟨F.to_linear_map.comp (ι R), λ m, by rw [ linear_map.comp_apply, alg_hom.to_linear_map_apply, comp_ι_square_zero]⟩, left_inv := λ f, by { ext, simp [ι] }, right_inv := λ F, by { ext, simp [ι] } } @[simp] theorem ι_comp_lift (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) : (lift R ⟨f, cond⟩).to_linear_map.comp (ι R) = f := (subtype.mk_eq_mk.mp $ (lift R).symm_apply_apply ⟨f, cond⟩) @[simp] theorem lift_ι_apply (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) (x) : lift R ⟨f, cond⟩ (ι R x) = f x := (linear_map.ext_iff.mp $ ι_comp_lift R f cond) x @[simp] theorem lift_unique (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) (g : exterior_algebra R M →ₐ[R] A) : g.to_linear_map.comp (ι R) = f ↔ g = lift R ⟨f, cond⟩ := begin convert (lift R).symm_apply_eq, rw lift_symm_apply, simp only, end attribute [irreducible] ι lift -- Marking `exterior_algebra` irreducible makes our `ring` instances inaccessible. -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241 -- For now, we avoid this by not marking it irreducible. variables {R M} @[simp] theorem lift_comp_ι (g : exterior_algebra R M →ₐ[R] A) : lift R ⟨g.to_linear_map.comp (ι R), comp_ι_square_zero _⟩ = g := begin convert (lift R).apply_symm_apply g, rw lift_symm_apply, refl, end @[ext] theorem hom_ext {f g : exterior_algebra R M →ₐ[R] A} (h : f.to_linear_map.comp (ι R) = g.to_linear_map.comp (ι R)) : f = g := begin apply (lift R).symm.injective, rw [lift_symm_apply, lift_symm_apply], simp only [h], end end exterior_algebra
1f0fa59dcddb037c3dd0c77dfd8a5923809b9f86
4727251e0cd73359b15b664c3170e5d754078599
/src/data/set/functor.lean
99ed7e314045fa54779d6cdc03edf871bcd1220f
[ "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
1,583
lean
/- Copyright (c) 2016 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import data.set.lattice /-! # Functoriality of `set` This file defines the functor structure of `set`. -/ universes u open function namespace set variables {α β : Type u} {s : set α} {f : α → set β} {g : set (α → β)} instance : monad.{u} set := { pure := λ α a, {a}, bind := λ α β s f, ⋃ i ∈ s, f i, seq := λ α β, set.seq, map := λ α β, set.image } @[simp] lemma bind_def : s >>= f = ⋃ i ∈ s, f i := rfl @[simp] lemma fmap_eq_image (f : α → β) : f <$> s = f '' s := rfl @[simp] lemma seq_eq_set_seq (s : set (α → β)) (t : set α) : s <*> t = s.seq t := rfl @[simp] lemma pure_def (a : α) : (pure a : set α) = {a} := rfl instance : is_lawful_monad set := { pure_bind := λ α β x f, by simp, bind_assoc := λ α β γ s f g, set.ext $ λ a, by simp [exists_and_distrib_right.symm, -exists_and_distrib_right, exists_and_distrib_left.symm, -exists_and_distrib_left, and_assoc]; exact exists_swap, id_map := λ α, id_map, bind_pure_comp_eq_map := λ α β f s, set.ext $ by simp [set.image, eq_comm], bind_map_eq_seq := λ α β s t, by simp [seq_def] } instance : is_comm_applicative (set : Type u → Type u) := ⟨ λ α β s t, prod_image_seq_comm s t ⟩ instance : alternative set := { orelse := λ α, (∪), failure := λ α, ∅, .. set.monad } end set
c691b92aa1fea8d902ebb47755ad69cd0b7392f4
63abd62053d479eae5abf4951554e1064a4c45b4
/test/monotonicity.lean
2e92bcd4c32e1574aa596e197f636c11248dfbf0
[ "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
8,229
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import tactic.monotonicity import tactic.norm_num import algebra.ordered_ring import data.list.defs open list tactic tactic.interactive example (h : 3 + 6 ≤ 4 + 5) : 1 + 3 + 2 + 6 ≤ 4 + 2 + 1 + 5 := begin ac_mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin ac_mono, mono, end example (h : 3 ≤ (4 : ℤ)) (h' : 5 ≤ (6 : ℤ)) : (1 + 3 + 2) - 6 ≤ (4 + 2 + 1 : ℤ) - 5 := begin transitivity (1 + 3 + 2 - 5 : ℤ), { ac_mono }, { ac_mono }, end example (x y z k : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (k + 3 + x) - y ≤ (k + 4 + x) - z := begin mono, norm_num end example (x y z a b : ℤ) (h : a ≤ (b : ℤ)) (h' : z ≤ y) : (1 + a + x) - y ≤ (1 + b + x) - z := begin transitivity (1 + a + x - z), { mono, }, { mono, mono, mono }, end example (x y z : ℤ) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin transitivity (1 + 3 + x - z), { mono }, { mono, mono, norm_num }, end example (x y z : ℤ) (h : 3 ≤ (4 : ℤ)) (h' : z ≤ y) : (1 + 3 + x) - y ≤ (1 + 4 + x) - z := begin ac_mono, mono* end @[simp] def list.le' {α : Type*} [has_le α] : list α → list α → Prop | (x::xs) (y::ys) := x ≤ y ∧ list.le' xs ys | [] [] := true | _ _ := false @[simp] instance list_has_le {α : Type*} [has_le α] : has_le (list α) := ⟨ list.le' ⟩ lemma list.le_refl {α : Type*} [preorder α] {xs : list α} : xs ≤ xs := begin induction xs with x xs, { trivial }, { simp [has_le.le,list.le], split, apply le_refl, apply xs_ih } end -- @[trans] lemma list.le_trans {α : Type*} [preorder α] {xs zs : list α} (ys : list α) (h : xs ≤ ys) (h' : ys ≤ zs) : xs ≤ zs := begin revert ys zs, induction xs with x xs ; intros ys zs h h' ; cases ys with y ys ; cases zs with z zs ; try { cases h ; cases h' ; done }, { apply list.le_refl }, { simp [has_le.le,list.le], split, apply le_trans h.left h'.left, apply xs_ih _ h.right h'.right, } end @[mono] lemma list_le_mono_left {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : xs ++ zs ≤ ys ++ zs := begin revert ys, induction xs with x xs ; intros ys h, { cases ys, apply list.le_refl, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, revert h, apply and.imp_right, apply xs_ih } end @[mono] lemma list_le_mono_right {α : Type*} [preorder α] {xs ys zs : list α} (h : xs ≤ ys) : zs ++ xs ≤ zs ++ ys := begin revert ys zs, induction xs with x xs ; intros ys zs h, { cases ys, { simp, apply list.le_refl }, cases h }, { cases ys with y ys, cases h, simp [has_le.le,list.le] at *, suffices : list.le' ((zs ++ [x]) ++ xs) ((zs ++ [y]) ++ ys), { refine cast _ this, simp, }, apply list.le_trans (zs ++ [y] ++ xs), { apply list_le_mono_left, induction zs with z zs, { simp [has_le.le,list.le], apply h.left }, { simp [has_le.le,list.le], split, apply le_refl, apply zs_ih, } }, { apply xs_ih h.right, } } end lemma bar_bar' (h : [] ++ [3] ++ [2] ≤ [1] ++ [5] ++ [4]) : [] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end lemma bar_bar'' (h : [3] ++ [2] ++ [2] ≤ [5] ++ [4] ++ []) : [1] ++ ([3] ++ [2]) ++ [2] ≤ [1] ++ [5] ++ ([4] ++ []) := begin ac_mono, end lemma bar_bar (h : [3] ++ [2] ≤ [5] ++ [4]) : [1] ++ [3] ++ [2] ++ [2] ≤ [1] ++ [5] ++ ([4] ++ [2]) := begin ac_mono, end def P (x : ℕ) := 7 ≤ x def Q (x : ℕ) := x ≤ 7 @[mono] lemma P_mono {x y : ℕ} (h : x ≤ y) : P x → P y := by { intro h', apply le_trans h' h } @[mono] lemma Q_mono {x y : ℕ} (h : y ≤ x) : Q x → Q y := by apply le_trans h example (x y z : ℕ) (h : x ≤ y) : P (x + z) → P (z + y) := begin ac_mono, ac_mono, end example (x y z : ℕ) (h : y ≤ x) : Q (x + z) → Q (z + y) := begin ac_mono, ac_mono, end example (x y z k m n : ℤ) (h₀ : z ≤ 0) (h₁ : y ≤ x) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, ac_mono, ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono, -- ⊢ (m + x + n) * z ≤ z * (y + n + m) ac_mono, -- ⊢ m + x + n ≤ y + n + m ac_mono, end example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : x ≤ y) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : m + x + n ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := by { ac_mono* := h₁ } example (x y z k m n : ℕ) (h₀ : z ≥ 0) (h₁ : n + x + m ≤ y + n + m) : (m + x + n) * z + k ≤ z * (y + n + m) + k := begin ac_mono* : m + x + n ≤ y + n + m, transitivity ; [ skip , apply h₁ ], apply le_of_eq, ac_refl, end example (x y z k m n : ℤ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, success_if_fail { ac_mono }, admit }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono*, change 0 ≤ z, apply nat.zero_le, }, trivial end example (x y z k m n : ℕ) (h₁ : x ≤ y) : true := begin have : (m + x + n) * z + k ≤ z * (y + n + m) + k, { ac_mono, change (m + x + n) * z ≤ z * (y + n + m), admit }, trivial, end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono^3, cc end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : z * (x + i + n + m) + k = z * (y + j + n + m) + k := begin congr, simp [h₁], end example (x y z k m n i j : ℕ) (h₁ : x + i = y + j) : (m + x + n + i) * z + k = z * (j + n + m + y) + k := begin ac_mono*, cc, end example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 1, end example {x y z : ℕ} : true := begin have : y + x ≤ y + z, { mono, guard_target' x ≤ z, admit }, trivial end example {x y z : ℕ} : true := begin suffices : x + y ≤ z + y, trivial, mono, guard_target' x ≤ z, admit, end example {x y z w : ℕ} : true := begin have : x + y ≤ z + w, { mono, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : ℕ} : true := begin have : x * y ≤ z * w, { mono with [0 ≤ z,0 ≤ y], { guard_target 0 ≤ z, admit }, { guard_target 0 ≤ y, admit }, guard_target' x ≤ z, admit, guard_target' y ≤ w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∧ y → z ∧ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : Prop} : true := begin have : x ∨ y → z ∨ w, { mono, guard_target' x → z, admit, guard_target' y → w, admit }, trivial end example {x y z w : ℤ} : true := begin suffices : x + y < w + z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, end example {x y z w : ℤ} : true := begin suffices : x * y < w * z, trivial, have : x < w, admit, have : y ≤ z, admit, mono right, { guard_target' 0 < y, admit }, { guard_target' 0 ≤ w, admit }, end open tactic example (x y : ℕ) (h : x ≤ y) : true := begin (do v ← mk_mvar, p ← to_expr ```(%%v + x ≤ y + %%v), assert `h' p), ac_mono := h, trivial, exact 3 end example {α} [linear_order α] (a b c d e : α) : max a b ≤ e → b ≤ e := by { mono, apply le_max_right } example (a b c d e : Prop) (h : d → a) (h' : c → e) : (a ∧ b → c) ∨ d → (d ∧ b → e) ∨ a := begin mono, mono, mono, end
5c4ac0d1bc40a2697a3019c55b5aa4a420bc9a67
abbfc359cee49d3c5258b2bbedc2b4d306ec3bdf
/src/category/monad_trans.lean
a30efdd328507f5ed68807cdedf65194e040f917
[]
no_license
cipher1024/serialean
565b17241ba7edc4ee564bf0ae175dd15b06a28c
47881e4a6bc0a62cd68520564610b75f8a4fef2c
refs/heads/master
1,585,117,575,599
1,535,783,976,000
1,535,783,976,000
143,501,396
0
0
null
null
null
null
UTF-8
Lean
false
false
2,107
lean
import tactic universes u v w class is_lawful_monad_lift (m : Type u → Type v) (n : Type u → Type w) [has_monad_lift m n] [monad m] [monad n] := (monad_lift_pure : ∀ {α} (x : α), has_monad_lift.monad_lift (pure x : m α) = (pure x : n α)) (monad_lift_bind : ∀ {α β} (x : m α) (f : α → m β), (has_monad_lift.monad_lift $ x >>= f : n β) = has_monad_lift.monad_lift x >>= has_monad_lift.monad_lift ∘ f ) class is_lawful_monad_lift_t (m : Type u → Type v) (n : Type u → Type w) [has_monad_lift_t m n] [monad m] [monad n] := (monad_lift_pure : ∀ {α} (x : α), has_monad_lift_t.monad_lift (pure x : m α) = (pure x : n α)) (monad_lift_bind : ∀ {α β} (x : m α) (f : α → m β), (has_monad_lift_t.monad_lift $ x >>= f : n β) = has_monad_lift_t.monad_lift x >>= has_monad_lift_t.monad_lift ∘ f ) export is_lawful_monad_lift_t (monad_lift_pure monad_lift_bind) instance has_lawful_monad_lift_t_trans (m n o) [monad m] [monad n] [monad o] [has_monad_lift n o] [has_monad_lift_t m n] [is_lawful_monad_lift n o] [is_lawful_monad_lift_t m n] : is_lawful_monad_lift_t m o := by constructor; intros; simp [monad_lift]; [ simp [monad_lift_pure m n,is_lawful_monad_lift.monad_lift_pure n o], simp [monad_lift_bind n,is_lawful_monad_lift.monad_lift_bind o] ] instance has_lawful_monad_lift_t_refl (m) [monad m] : is_lawful_monad_lift_t m m := by constructor; intros; simp [monad_lift] class is_lawful_monad_state (σ : out_param (Type u)) (m : Type u → Type v) [monad m] [monad_state σ m] := (lift_pure {} : ∀ {α} (x : α), monad_state.lift (pure x : state σ α) = (pure x : m α)) (lift_bind {} : ∀ {α β} (x : state σ α) (f : α → state σ β), (monad_state.lift $ x >>= f : m β) = monad_state.lift x >>= monad_state.lift ∘ f ) instance (σ : (Type u)) (m : Type u → Type v) [monad m] [is_lawful_monad m] : is_lawful_monad_state σ (state_t σ m) := by { constructor; intros, { refl }, { simp [(>>=),state_t.bind,monad_state.lift,id_bind], congr, ext z, cases x.run z, refl } } -- class is_lawful_monad_state
c81d8bc6a633243ad33419660fb89a5d43016deb
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/exists7.lean
116678c3b457fd283dc6532fed8df32842a248ab
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
304
lean
set_option pp::colors false variable N : Type variables a b c : N variables P : N -> N -> N -> Bool set_opaque exists false. set_opaque not false. theorem T1 (f : N -> N) (H : P (f a) b (f (f c))) : exists x y z, P x y z := exists_intro _ (exists_intro _ (exists_intro _ H)) print environment 1.
57dcf6443a4bcf0f6aa35d09398b38f81da12147
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/continuous_affine_map.lean
37500de93756f73ba2f79baed3c83d1e741f142a
[ "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,459
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import linear_algebra.affine_space.affine_map import topology.continuous_function.basic import topology.algebra.module.basic /-! # Continuous affine maps. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines a type of bundled continuous affine maps. Note that the definition and basic properties established here require minimal assumptions, and do not even assume compatibility between the topological and algebraic structures. Of course it is necessary to assume some compatibility in order to obtain a useful theory. Such a theory is developed elsewhere for affine spaces modelled on _normed_ vector spaces, but not yet for general topological affine spaces (since we have not defined these yet). ## Main definitions: * `continuous_affine_map` ## Notation: We introduce the notation `P →A[R] Q` for `continuous_affine_map R P Q`. Note that this is parallel to the notation `E →L[R] F` for `continuous_linear_map R E F`. -/ /-- A continuous map of affine spaces. -/ structure continuous_affine_map (R : Type*) {V W : Type*} (P Q : Type*) [ring R] [add_comm_group V] [module R V] [topological_space P] [add_torsor V P] [add_comm_group W] [module R W] [topological_space Q] [add_torsor W Q] extends P →ᵃ[R] Q := (cont : continuous to_fun) notation P ` →A[`:25 R `] ` Q := continuous_affine_map R P Q namespace continuous_affine_map variables {R V W P Q : Type*} [ring R] variables [add_comm_group V] [module R V] [topological_space P] [add_torsor V P] variables [add_comm_group W] [module R W] [topological_space Q] [add_torsor W Q] include V W instance : has_coe (P →A[R] Q) (P →ᵃ[R] Q) := ⟨to_affine_map⟩ lemma to_affine_map_injective {f g : P →A[R] Q} (h : (f : P →ᵃ[R] Q) = (g : P →ᵃ[R] Q)) : f = g := by { cases f, cases g, congr' } instance : continuous_map_class (P →A[R] Q) P Q := { coe := λ f, f.to_affine_map, coe_injective' := λ f g h, to_affine_map_injective $ fun_like.coe_injective h, map_continuous := cont } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (P →A[R] Q) (λ _, P → Q) := fun_like.has_coe_to_fun lemma to_fun_eq_coe (f : P →A[R] Q) : f.to_fun = ⇑f := rfl lemma coe_injective : @function.injective (P →A[R] Q) (P → Q) coe_fn := fun_like.coe_injective @[ext] lemma ext {f g : P →A[R] Q} (h : ∀ x, f x = g x) : f = g := fun_like.ext _ _ h lemma ext_iff {f g : P →A[R] Q} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff lemma congr_fun {f g : P →A[R] Q} (h : f = g) (x : P) : f x = g x := fun_like.congr_fun h _ /-- Forgetting its algebraic properties, a continuous affine map is a continuous map. -/ def to_continuous_map (f : P →A[R] Q) : C(P, Q) := ⟨f, f.cont⟩ instance : has_coe (P →A[R] Q) (C(P, Q)) := ⟨to_continuous_map⟩ @[simp] lemma to_affine_map_eq_coe (f : P →A[R] Q) : f.to_affine_map = ↑f := rfl @[simp] lemma to_continuous_map_coe (f : P →A[R] Q) : f.to_continuous_map = ↑f := rfl @[simp, norm_cast] lemma coe_to_affine_map (f : P →A[R] Q) : ((f : P →ᵃ[R] Q) : P → Q) = f := rfl @[simp, norm_cast] lemma coe_to_continuous_map (f : P →A[R] Q) : ((f : C(P, Q)) : P → Q) = f := rfl lemma to_continuous_map_injective {f g : P →A[R] Q} (h : (f : C(P, Q)) = (g : C(P, Q))) : f = g := by { ext a, exact continuous_map.congr_fun h a, } @[norm_cast] lemma coe_affine_map_mk (f : P →ᵃ[R] Q) (h) : ((⟨f, h⟩ : P →A[R] Q) : P →ᵃ[R] Q) = f := rfl @[norm_cast] lemma coe_continuous_map_mk (f : P →ᵃ[R] Q) (h) : ((⟨f, h⟩ : P →A[R] Q) : C(P, Q)) = ⟨f, h⟩ := rfl @[simp] lemma coe_mk (f : P →ᵃ[R] Q) (h) : ((⟨f, h⟩ : P →A[R] Q) : P → Q) = f := rfl @[simp] lemma mk_coe (f : P →A[R] Q) (h) : (⟨(f : P →ᵃ[R] Q), h⟩ : P →A[R] Q) = f := by { ext, refl, } @[continuity] protected lemma continuous (f : P →A[R] Q) : continuous f := f.2 variables (R P) /-- The constant map is a continuous affine map. -/ def const (q : Q) : P →A[R] Q := { to_fun := affine_map.const R P q, cont := continuous_const, .. affine_map.const R P q, } @[simp] lemma coe_const (q : Q) : (const R P q : P → Q) = function.const P q := rfl noncomputable instance : inhabited (P →A[R] Q) := ⟨const R P $ nonempty.some (by apply_instance : nonempty Q)⟩ variables {R P} {W₂ Q₂ : Type*} variables [add_comm_group W₂] [module R W₂] [topological_space Q₂] [add_torsor W₂ Q₂] include W₂ /-- The composition of morphisms is a morphism. -/ def comp (f : Q →A[R] Q₂) (g : P →A[R] Q) : P →A[R] Q₂ := { cont := f.cont.comp g.cont, .. (f : Q →ᵃ[R] Q₂).comp (g : P →ᵃ[R] Q), } @[simp, norm_cast] lemma coe_comp (f : Q →A[R] Q₂) (g : P →A[R] Q) : (f.comp g : P → Q₂) = (f : Q → Q₂) ∘ (g : P → Q) := rfl lemma comp_apply (f : Q →A[R] Q₂) (g : P →A[R] Q) (x : P) : f.comp g x = f (g x) := rfl omit W₂ section module_valued_maps variables {S : Type*} variables [topological_space W] instance : has_zero (P →A[R] W) := ⟨continuous_affine_map.const R P 0⟩ @[norm_cast, simp] lemma coe_zero : ((0 : P →A[R] W) : P → W) = 0 := rfl lemma zero_apply (x : P) : (0 : P →A[R] W) x = 0 := rfl section mul_action variables [monoid S] [distrib_mul_action S W] [smul_comm_class R S W] variables [has_continuous_const_smul S W] instance : has_smul S (P →A[R] W) := { smul := λ t f, { cont := f.continuous.const_smul t, .. (t • (f : P →ᵃ[R] W)) } } @[norm_cast, simp] lemma coe_smul (t : S) (f : P →A[R] W) : ⇑(t • f) = t • f := rfl lemma smul_apply (t : S) (f : P →A[R] W) (x : P) : (t • f) x = t • (f x) := rfl instance [distrib_mul_action Sᵐᵒᵖ W] [is_central_scalar S W] : is_central_scalar S (P →A[R] W) := { op_smul_eq_smul := λ t f, ext $ λ _, op_smul_eq_smul _ _ } instance : mul_action S (P →A[R] W) := function.injective.mul_action _ coe_injective coe_smul end mul_action variables [topological_add_group W] instance : has_add (P →A[R] W) := { add := λ f g, { cont := f.continuous.add g.continuous, .. ((f : P →ᵃ[R] W) + (g : P →ᵃ[R] W)) }, } @[norm_cast, simp] lemma coe_add (f g : P →A[R] W) : ⇑(f + g) = f + g := rfl lemma add_apply (f g : P →A[R] W) (x : P) : (f + g) x = f x + g x := rfl instance : has_sub (P →A[R] W) := { sub := λ f g, { cont := f.continuous.sub g.continuous, .. ((f : P →ᵃ[R] W) - (g : P →ᵃ[R] W)) }, } @[norm_cast, simp] lemma coe_sub (f g : P →A[R] W) : ⇑(f - g) = f - g := rfl lemma sub_apply (f g : P →A[R] W) (x : P) : (f - g) x = f x - g x := rfl instance : has_neg (P →A[R] W) := { neg := λ f, { cont := f.continuous.neg, .. (-(f : P →ᵃ[R] W)) }, } @[norm_cast, simp] lemma coe_neg (f : P →A[R] W) : ⇑(-f) = -f := rfl lemma neg_apply (f : P →A[R] W) (x : P) : (-f) x = -(f x) := rfl instance : add_comm_group (P →A[R] W) := coe_injective.add_comm_group _ coe_zero coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _) instance [monoid S] [distrib_mul_action S W] [smul_comm_class R S W] [has_continuous_const_smul S W] : distrib_mul_action S (P →A[R] W) := function.injective.distrib_mul_action ⟨λ f, f.to_affine_map.to_fun, rfl, coe_add⟩ coe_injective coe_smul instance [semiring S] [module S W] [smul_comm_class R S W] [has_continuous_const_smul S W] : module S (P →A[R] W) := function.injective.module S ⟨λ f, f.to_affine_map.to_fun, rfl, coe_add⟩ coe_injective coe_smul end module_valued_maps end continuous_affine_map namespace continuous_linear_map variables {R V W : Type*} [ring R] variables [add_comm_group V] [module R V] [topological_space V] variables [add_comm_group W] [module R W] [topological_space W] /-- A continuous linear map can be regarded as a continuous affine map. -/ def to_continuous_affine_map (f : V →L[R] W) : V →A[R] W := { to_fun := f, linear := f, map_vadd' := by simp, cont := f.cont, } @[simp] lemma coe_to_continuous_affine_map (f : V →L[R] W) : ⇑f.to_continuous_affine_map = f := rfl @[simp] lemma to_continuous_affine_map_map_zero (f : V →L[R] W) : f.to_continuous_affine_map 0 = 0 := by simp end continuous_linear_map
68d72c947be8e01b8baa0964809eadbf9d14f238
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/ns1.lean
b684ae620e664856a947a87987c8bf8bb5ae35e0
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
265
lean
import Int. namespace foo. variable a : Nat. definition b := a. theorem T : a = b := refl a. axiom H : b >= a. namespace bla. variables a c d : Int. check a + b + c. end. end. check foo::T. check foo::H. check foo::a. check foo::bla::a. end
02eccf9de290f44447c1891b5761f4619ccdfc23
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/csimpAttr.lean
1a27ed0a585b24a29c6ea738b17e892023fcc05a
[ "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
339
lean
def foo (x : Nat) := 2*x def boo (x : Nat) := x + x @[csimp] theorem foo_eq_boo1 (x : Nat) : foo x = boo x := by -- Error simp [foo, boo, Nat.mul_comm] show (x * 1) + x = x + x simp @[csimp] theorem foo_eq_boo2 : foo = boo := funext foo_eq_boo1 set_option trace.compiler.ir.init true def f (x : Nat) : Nat := foo (foo x)
55a46df65deec72dd05be1d99b86dc158523c1dd
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/pattern_pp.lean
7a4a5211601299e6bcf5c5c613e65d85ce0c8444
[ "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
462
lean
definition Sum : nat → (nat → nat) → nat := sorry definition Sum_weird [forward] (f g h : nat → nat) (n : nat) : (Sum n (λ x, f (g (h x)))) = 1 := sorry print Sum_weird /- definition Sum_weird [forward] : ∀ (f g h : nat → nat) (n : nat), eq (Sum n (λ (x : nat), f (g (h x)))) 1 := λ (f g h : nat → nat) (n : nat), sorry (multi-)patterns: ?M_1 : nat → nat, ?M_2 : nat → nat, ?M_3 : nat → nat, ?M_4 : nat {Sum ?M_4 (λ (x : nat), ?M_1)} -/
75ce504a206f075e4513a0437fe75fd1476cba9a
d757fb8bb0d538df3510904d3c09a0da191d06b9
/sf_colors.lean
9bf23b858e187d9dd683e837a1548639c5e4d16c
[]
no_license
happy-bracket/lean_playground
188f64c2a431dec5617c75e33c7a75e475b9c23d
137b76966001091c445f6f472d27bbe5a8cf5d49
refs/heads/master
1,600,889,668,807
1,575,375,570,000
1,575,375,570,000
225,569,694
2
0
null
null
null
null
UTF-8
Lean
false
false
256
lean
inductive rgb : Type | red | green | blue open rgb inductive color : Type | black | white | other : rgb → color open color def mono : color -> bool | black := tt | white := tt | (other _) := ff def is_red : color -> bool | (other red) := tt | _ := ff
b687725b713ab4cf6ef4ab896b7604ca890bc978
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/bitwise.lean
f50ad67677d0bf40193fbb534e3aeb3ead3730cb
[]
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
4,453
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.linarith.default import Mathlib.PostPort namespace Mathlib /-! # Bitwise operations on natural numbers In the first half of this file, we provide theorems for reasoning about natural numbers from their bitwise properties. In the second half of this file, we show properties of the bitwise operations `lor`, `land` and `lxor`, which are defined in core. ## Main results * `eq_of_test_bit_eq`: two natural numbers are equal if they have equal bits at every position. * `exists_most_significant_bit`: if `n ≠ 0`, then there is some position `i` that contains the most significant `1`-bit of `n`. * `lt_of_test_bit`: if `n` and `m` are numbers and `i` is a position such that the `i`-th bit of of `n` is zero, the `i`-th bit of `m` is one, and all more significant bits are equal, then `n < m`. ## Future work There is another way to express bitwise properties of natural number: `digits 2`. The two ways should be connected. ## Keywords bitwise, and, or, xor -/ namespace nat @[simp] theorem bit_ff : bit false = bit0 := rfl @[simp] theorem bit_tt : bit tt = bit1 := rfl @[simp] theorem bit_eq_zero {n : ℕ} {b : Bool} : bit b n = 0 ↔ n = 0 ∧ b = false := sorry theorem zero_of_test_bit_eq_ff {n : ℕ} (h : ∀ (i : ℕ), test_bit n i = false) : n = 0 := sorry @[simp] theorem zero_test_bit (i : ℕ) : test_bit 0 i = false := sorry /-- Bitwise extensionality: Two numbers agree if they agree at every bit position. -/ theorem eq_of_test_bit_eq {n : ℕ} {m : ℕ} (h : ∀ (i : ℕ), test_bit n i = test_bit m i) : n = m := sorry theorem exists_most_significant_bit {n : ℕ} (h : n ≠ 0) : ∃ (i : ℕ), test_bit n i = tt ∧ ∀ (j : ℕ), i < j → test_bit n j = false := sorry theorem lt_of_test_bit {n : ℕ} {m : ℕ} (i : ℕ) (hn : test_bit n i = false) (hm : test_bit m i = tt) (hnm : ∀ (j : ℕ), i < j → test_bit n j = test_bit m j) : n < m := sorry /-- If `f` is a commutative operation on bools such that `f ff ff = ff`, then `bitwise f` is also commutative. -/ theorem bitwise_comm {f : Bool → Bool → Bool} (hf : ∀ (b b' : Bool), f b b' = f b' b) (hf' : f false false = false) (n : ℕ) (m : ℕ) : bitwise f n m = bitwise f m n := sorry theorem lor_comm (n : ℕ) (m : ℕ) : lor n m = lor m n := bitwise_comm bool.bor_comm rfl n m theorem land_comm (n : ℕ) (m : ℕ) : land n m = land m n := bitwise_comm bool.band_comm rfl n m theorem lxor_comm (n : ℕ) (m : ℕ) : lxor n m = lxor m n := bitwise_comm bool.bxor_comm rfl n m @[simp] theorem zero_lxor (n : ℕ) : lxor 0 n = n := rfl @[simp] theorem lxor_zero (n : ℕ) : lxor n 0 = n := lxor_comm 0 n ▸ rfl @[simp] theorem zero_land (n : ℕ) : land 0 n = 0 := rfl @[simp] theorem land_zero (n : ℕ) : land n 0 = 0 := land_comm 0 n ▸ rfl @[simp] theorem zero_lor (n : ℕ) : lor 0 n = n := rfl @[simp] theorem lor_zero (n : ℕ) : lor n 0 = n := lor_comm 0 n ▸ rfl /-- Proving associativity of bitwise operations in general essentially boils down to a huge case distinction, so it is shorter to use this tactic instead of proving it in the general case. -/ theorem lxor_assoc (n : ℕ) (m : ℕ) (k : ℕ) : lxor (lxor n m) k = lxor n (lxor m k) := sorry theorem land_assoc (n : ℕ) (m : ℕ) (k : ℕ) : land (land n m) k = land n (land m k) := sorry theorem lor_assoc (n : ℕ) (m : ℕ) (k : ℕ) : lor (lor n m) k = lor n (lor m k) := sorry @[simp] theorem lxor_self (n : ℕ) : lxor n n = 0 := sorry theorem lxor_right_inj {n : ℕ} {m : ℕ} {m' : ℕ} (h : lxor n m = lxor n m') : m = m' := sorry theorem lxor_left_inj {n : ℕ} {n' : ℕ} {m : ℕ} (h : lxor n m = lxor n' m) : n = n' := lxor_right_inj (eq.mp (Eq._oldrec (Eq.refl (lxor m n = lxor n' m)) (lxor_comm n' m)) (eq.mp (Eq._oldrec (Eq.refl (lxor n m = lxor n' m)) (lxor_comm n m)) h)) theorem lxor_eq_zero {n : ℕ} {m : ℕ} : lxor n m = 0 ↔ n = m := { mp := eq.mpr (id (Eq._oldrec (Eq.refl (lxor n m = 0 → n = m)) (Eq.symm (lxor_self m)))) lxor_left_inj, mpr := fun (ᾰ : n = m) => Eq._oldrec (lxor_self n) ᾰ } theorem lxor_trichotomy {a : ℕ} {b : ℕ} {c : ℕ} (h : lxor a (lxor b c) ≠ 0) : lxor b c < a ∨ lxor a c < b ∨ lxor a b < c := sorry
984cbe3cebf3867b67d5ed7eac90746e2db2dcaa
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/order/filter/filter_product.lean
97bcd5f38a271d3bfe8a1896f3276c11fa1ab320
[ "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
20,359
lean
/- Copyright (c) 2019 Abhimanyu Pallavi Sudhir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abhimanyu Pallavi Sudhir "Filterproducts" (ultraproducts on general filters), ultraproducts. -/ import order.filter.basic import algebra.pi_instances universes u v variables {α : Type u} (β : Type v) (φ : filter α) local attribute [instance] classical.prop_decidable namespace filter /-- Two sequences are bigly equal iff the kernel of their difference is in φ -/ def bigly_equal : setoid (α → β) := ⟨ λ a b, {n | a n = b n} ∈ φ, λ a, by simp only [eq_self_iff_true, (set.univ_def).symm, univ_sets], λ a b ab, by simpa only [eq_comm], λ a b c ab bc, sets_of_superset φ (inter_sets φ ab bc) (λ n r, eq.trans r.1 r.2)⟩ /-- Ultraproduct, but on a general filter -/ def filterprod := quotient (bigly_equal β φ) local notation `β*` := filterprod β φ namespace filter_product variables {α β φ} include φ def of_seq : (α → β) → β* := @quotient.mk' (α → β) (bigly_equal β φ) /-- Equivalence class containing the constant sequence of a term in β -/ def of (b : β) : β* := of_seq (function.const α b) /-- Lift function to filter product -/ def lift (f : β → β) : β* → β* := λ x, quotient.lift_on' x (λ a, (of_seq $ λ n, f (a n) : β*)) $ λ a b h, quotient.sound' $ show _ ∈ _, by filter_upwards [h] λ i hi, congr_arg _ hi /-- Lift binary operation to filter product -/ def lift₂ (f : β → β → β) : β* → β* → β* := λ x y, quotient.lift_on₂' x y (λ a b, (of_seq $ λ n, f (a n) (b n) : β*)) $ λ a₁ a₂ b₁ b₂ h1 h2, quotient.sound' $ show _ ∈ _, by filter_upwards [h1, h2] λ i hi1 hi2, congr (congr_arg _ hi1) hi2 /-- Lift properties to filter product -/ def lift_rel (R : β → Prop) : β* → Prop := λ x, quotient.lift_on' x (λ a, {i : α | R (a i)} ∈ φ) $ λ a b h, propext ⟨ λ ha, by filter_upwards [h, ha] λ i hi hia, by simpa [hi.symm], λ hb, by filter_upwards [h, hb] λ i hi hib, by simpa [hi.symm.symm] ⟩ /-- Lift binary relations to filter product -/ def lift_rel₂ (R : β → β → Prop) : β* → β* → Prop := λ x y, quotient.lift_on₂' x y (λ a b, {i : α | R (a i) (b i)} ∈ φ) $ λ a₁ a₂ b₁ b₂ h₁ h₂, propext ⟨ λ ha, by filter_upwards [h₁, h₂, ha] λ i hi1 hi2 hia, by simpa [hi1.symm, hi2.symm], λ hb, by filter_upwards [h₁, h₂, hb] λ i hi1 hi2 hib, by simpa [hi1.symm.symm, hi2.symm.symm] ⟩ instance coe_filterprod : has_coe β β* := ⟨ of ⟩ instance [has_add β] : has_add β* := { add := lift₂ has_add.add } instance [has_zero β] : has_zero β* := { zero := of 0 } instance [has_neg β] : has_neg β* := { neg := lift has_neg.neg } instance [add_semigroup β] : add_semigroup β* := { add_assoc := λ x y z, quotient.induction_on₃' x y z $ λ a b c, quotient.sound' $ show {n | _ + _ + _ = _ + (_ + _)} ∈ _, by simp only [add_assoc, eq_self_iff_true]; exact φ.univ_sets, ..filter_product.has_add } instance [add_left_cancel_semigroup β] : add_left_cancel_semigroup β* := { add_left_cancel := λ x y z, quotient.induction_on₃' x y z $ λ a b c h, have h' : _ := quotient.exact' h, quotient.sound' $ by filter_upwards [h'] λ i, add_left_cancel, ..filter_product.add_semigroup } instance [add_right_cancel_semigroup β] : add_right_cancel_semigroup β* := { add_right_cancel := λ x y z, quotient.induction_on₃' x y z $ λ a b c h, have h' : _ := quotient.exact' h, quotient.sound' $ by filter_upwards [h'] λ i, add_right_cancel, ..filter_product.add_semigroup } instance [add_monoid β] : add_monoid β* := { zero_add := λ x, quotient.induction_on' x (λ a, quotient.sound'(by simp only [zero_add]; apply (setoid.iseqv _).1)), add_zero := λ x, quotient.induction_on' x (λ a, quotient.sound'(by simp only [add_zero]; apply (setoid.iseqv _).1)), ..filter_product.add_semigroup, ..filter_product.has_zero } instance [add_comm_semigroup β] : add_comm_semigroup β* := { add_comm := λ x y, quotient.induction_on₂' x y (λ a b, quotient.sound' (by simp only [add_comm]; apply (setoid.iseqv _).1)), ..filter_product.add_semigroup } instance [add_comm_monoid β] : add_comm_monoid β* := { ..filter_product.add_comm_semigroup, ..filter_product.add_monoid } instance [add_group β] : add_group β* := { add_left_neg := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [add_left_neg]; apply (setoid.iseqv _).1)), ..filter_product.add_monoid, ..filter_product.has_neg } instance [add_comm_group β] : add_comm_group β* := { ..filter_product.add_comm_monoid, ..filter_product.add_group } instance [has_mul β] : has_mul β* := { mul := lift₂ has_mul.mul } instance [has_one β] : has_one β* := { one := of 1 } instance [has_inv β] : has_inv β* := { inv := lift has_inv.inv } instance [semigroup β] : semigroup β* := { mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ a b c, quotient.sound' $ show {n | _ * _ * _ = _ * (_ * _)} ∈ _, by simp only [mul_assoc, eq_self_iff_true]; exact φ.univ_sets, ..filter_product.has_mul } instance [monoid β] : monoid β* := { one_mul := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [one_mul]; apply (setoid.iseqv _).1)), mul_one := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_one]; apply (setoid.iseqv _).1)), ..filter_product.semigroup, ..filter_product.has_one } instance [comm_semigroup β] : comm_semigroup β* := { mul_comm := λ x y, quotient.induction_on₂' x y (λ a b, quotient.sound' (by simp only [mul_comm]; apply (setoid.iseqv _).1)), ..filter_product.semigroup } instance [comm_monoid β] : comm_monoid β* := { ..filter_product.comm_semigroup, ..filter_product.monoid } instance [group β] : group β* := { mul_left_inv := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_left_inv]; apply (setoid.iseqv _).1)), ..filter_product.monoid, ..filter_product.has_inv } instance [comm_group β] : comm_group β* := { ..filter_product.comm_monoid, ..filter_product.group } instance [distrib β] : distrib β* := { left_distrib := λ x y z, quotient.induction_on₃' x y z (λ x y z, quotient.sound' (by simp only [left_distrib]; apply (setoid.iseqv _).1)), right_distrib := λ x y z, quotient.induction_on₃' x y z (λ x y z, quotient.sound' (by simp only [right_distrib]; apply (setoid.iseqv _).1)), ..filter_product.has_add, ..filter_product.has_mul } instance [mul_zero_class β] : mul_zero_class β* := { zero_mul := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [zero_mul]; apply (setoid.iseqv _).1)), mul_zero := λ x, quotient.induction_on' x (λ a, quotient.sound' (by simp only [mul_zero]; apply (setoid.iseqv _).1)), ..filter_product.has_mul, ..filter_product.has_zero } instance [semiring β] : semiring β* := { ..filter_product.add_comm_monoid, ..filter_product.monoid, ..filter_product.distrib, ..filter_product.mul_zero_class } instance [ring β] : ring β* := { ..filter_product.add_comm_group, ..filter_product.monoid, ..filter_product.distrib } instance [comm_semiring β] : comm_semiring β* := { ..filter_product.semiring, ..filter_product.comm_monoid } instance [comm_ring β] : comm_ring β* := { ..filter_product.ring, ..filter_product.comm_semigroup } instance [zero_ne_one_class β] (NT : φ ≠ ⊥) : zero_ne_one_class β* := { zero_ne_one := λ c, have c' : _ := quotient.exact' c, by { change _ ∈ _ at c', simp only [set.set_of_false, zero_ne_one, empty_in_sets_eq_bot] at c', exact NT c' }, ..filter_product.has_zero, ..filter_product.has_one } instance [division_ring β] (U : is_ultrafilter φ) : division_ring β* := { mul_inv_cancel := λ x, quotient.induction_on' x $ λ a hx, quotient.sound' $ have hx1 : _ := (not_imp_not.mpr quotient.eq'.mpr) hx, have hx2 : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hx1, have h : {n : α | ¬a n = 0} ⊆ {n : α | a n * (a n)⁻¹ = 1} := by rw [set.set_of_subset_set_of]; exact λ n, division_ring.mul_inv_cancel, mem_sets_of_superset hx2 h, inv_mul_cancel := λ x, quotient.induction_on' x $ λ a hx, quotient.sound' $ have hx1 : _ := (not_imp_not.mpr quotient.eq'.mpr) hx, have hx2 : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hx1, have h : {n : α | ¬a n = 0} ⊆ {n : α | (a n)⁻¹ * a n = 1} := by rw [set.set_of_subset_set_of]; exact λ n, division_ring.inv_mul_cancel, mem_sets_of_superset hx2 h, ..filter_product.ring, ..filter_product.has_inv, ..filter_product.zero_ne_one_class U.1 } instance [field β] (U : is_ultrafilter φ) : field β* := { ..filter_product.comm_ring, ..filter_product.division_ring U } noncomputable instance [discrete_field β] (U : is_ultrafilter φ) : discrete_field β* := { inv_zero := quotient.sound' $ by show _ ∈ _; simp only [inv_zero, eq_self_iff_true, (set.univ_def).symm, univ_sets], has_decidable_eq := by apply_instance, ..filter_product.field U } instance [has_le β] : has_le β* := { le := lift_rel₂ has_le.le } instance [preorder β] : preorder β* := { le_refl := λ x, quotient.induction_on' x $ λ a, show _ ∈ _, by simp only [le_refl, (set.univ_def).symm, univ_sets], le_trans := λ x y z, quotient.induction_on₃' x y z $ λ a b c hab hbc, by filter_upwards [hab, hbc] λ i, le_trans, ..filter_product.has_le} instance [partial_order β] : partial_order β* := { le_antisymm := λ x y, quotient.induction_on₂' x y $ λ a b hab hba, quotient.sound' $ have hI : {n | a n = b n} = _ ∩ _ := set.ext (λ n, le_antisymm_iff), show _ ∈ _, by rw hI; exact inter_sets _ hab hba ..filter_product.preorder } instance [linear_order β] (U : is_ultrafilter φ) : linear_order β* := { le_total := λ x y, quotient.induction_on₂' x y $ λ a b, have hS : _ ⊆ {i | b i ≤ a i} := λ i, le_of_not_le, or.cases_on (mem_or_compl_mem_of_ultrafilter U {i | a i ≤ b i}) (λ h, or.inl h) (λ h, or.inr (sets_of_superset _ h hS)) ..filter_product.partial_order } theorem of_inj (NT : φ ≠ ⊥) : function.injective (@of _ β φ) := begin intros r s rs, by_contra N, rw [of, of, of_seq, quotient.eq', bigly_equal] at rs, simp only [N, set.set_of_false, empty_in_sets_eq_bot] at rs, exact NT rs end theorem of_seq_fun (f g : α → β) (h : β → β) (H : {n : α | f n = h (g n) } ∈ φ) : of_seq f = (lift h) (@of_seq _ _ φ g) := quotient.sound' H theorem of_seq_fun₂ (f g₁ g₂ : α → β) (h : β → β → β) (H : {n : α | f n = h (g₁ n) (g₂ n) } ∈ φ) : of_seq f = (lift₂ h) (@of_seq _ _ φ g₁) (@of_seq _ _ φ g₂) := quotient.sound' H @[simp] lemma of_seq_zero [has_zero β] (f : α → β) : of_seq 0 = (0 : β*) := rfl @[simp] lemma of_seq_add [has_add β] (f g : α → β) : of_seq (f + g) = of_seq f + (of_seq g : β*) := rfl @[simp] lemma of_seq_neg [has_neg β] (f : α → β) : of_seq (-f) = - (of_seq f : β*) := rfl @[simp] lemma of_seq_one [has_one β] (f : α → β) : of_seq 1 = (1 : β*) := rfl @[simp] lemma of_seq_mul [has_mul β] (f g : α → β) : of_seq (f * g) = of_seq f * (of_seq g : β*) := rfl @[simp] lemma of_seq_inv [has_inv β] (f : α → β) : of_seq (f⁻¹) = (of_seq f : β*)⁻¹ := rfl @[simp] lemma of_eq_coe (x : β) : of x = (x : β*) := rfl lemma of_eq (x y : β) (NT : φ ≠ ⊥) : x = y ↔ of x = (of y : β*) := ⟨ λ h, by rw h, by apply of_inj NT ⟩ lemma of_ne (x y : β) (NT : φ ≠ ⊥) : x ≠ y ↔ of x ≠ (of y : β*) := by show ¬ x = y ↔ of x ≠ of y; rwa [of_eq] lemma of_eq_zero [has_zero β] (NT : φ ≠ ⊥) (x : β) : x = 0 ↔ of x = (0 : β*) := of_eq _ _ NT lemma of_ne_zero [has_zero β] (NT : φ ≠ ⊥) (x : β) : x ≠ 0 ↔ of x ≠ (0 : β*) := of_ne _ _ NT @[simp] lemma of_zero [has_zero β] : of 0 = (0 : β*) := rfl @[simp] lemma of_add [has_add β] (x y : β) : of (x + y) = of x + (of y : β*) := rfl @[simp] lemma of_neg [has_neg β] (x : β) : of (- x) = - (of x : β*) := rfl @[simp] lemma of_sub [add_group β] (x y : β) : of (x - y) = of x - (of y : β*) := rfl @[simp] lemma of_one [has_one β] : of 1 = (1 : β*) := rfl @[simp] lemma of_mul [has_mul β] (x y : β) : of (x * y) = of x * (of y : β*) := rfl @[simp] lemma of_inv [has_inv β] (x : β) : of (x⁻¹) = (of x : β*)⁻¹ := rfl @[simp] lemma of_div [division_ring β] (U : is_ultrafilter φ) (x y : β) : of (x / y) = @has_div.div _ (@has_div_of_division_ring _ (filter_product.division_ring U)) (of x) (of y) := rfl lemma of_rel_of_rel {R : β → Prop} {x : β} : R x → (lift_rel R) (of x : β*) := λ hx, by show {i | R x} ∈ _; simp only [hx]; exact univ_mem_sets lemma of_rel {R : β → Prop} {x : β} (NT: φ ≠ ⊥) : R x ↔ (lift_rel R) (of x : β*) := ⟨ of_rel_of_rel, λ hxy, by change {i | R x} ∈ _ at hxy; by_contra h; simp only [h, set.set_of_false, empty_in_sets_eq_bot] at hxy; exact NT hxy ⟩ lemma of_rel_of_rel₂ {R : β → β → Prop} {x y : β} : R x y → (lift_rel₂ R) (of x) (of y : β*) := λ hxy, by show {i | R x y} ∈ _; simp only [hxy]; exact univ_mem_sets lemma of_rel₂ {R : β → β → Prop} {x y : β} (NT: φ ≠ ⊥) : R x y ↔ (lift_rel₂ R) (of x) (of y : β*) := ⟨ of_rel_of_rel₂, λ hxy, by change {i | R x y} ∈ _ at hxy; by_contra h; simp only [h, set.set_of_false, empty_in_sets_eq_bot] at hxy; exact NT hxy ⟩ lemma of_le_of_le [has_le β] {x y : β} : x ≤ y → of x ≤ (of y : β*) := of_rel_of_rel₂ lemma of_le [has_le β] {x y : β} (NT: φ ≠ ⊥) : x ≤ y ↔ of x ≤ (of y : β*) := of_rel₂ NT lemma lt_def [K : preorder β] (U : is_ultrafilter φ) {x y : β*} : (x < y) ↔ @lift_rel₂ _ _ φ K.lt x y := ⟨ quotient.induction_on₂' x y $ λ a b ⟨hxy, hyx⟩, have hyx' : _ := (ultrafilter_iff_compl_mem_iff_not_mem.mp U _).mpr hyx, by filter_upwards [hxy, hyx'] λ i hi1 hi2, lt_iff_le_not_le.mpr ⟨hi1, hi2⟩, quotient.induction_on₂' x y $ λ a b hab, ⟨ by filter_upwards [hab] λ i, le_of_lt, λ hba, have hc : ∀ i : α, a i < b i ∧ b i ≤ a i → false := λ i ⟨h1, h2⟩, not_lt_of_le h2 h1, have h0 : ∅ = {i : α | a i < b i} ∩ {i : α | b i ≤ a i} := by simp only [set.inter_def, hc, set.set_of_false, eq_self_iff_true, set.mem_set_of_eq], U.1 $ empty_in_sets_eq_bot.mp $ by rw [h0]; exact inter_sets _ hab hba ⟩ ⟩ lemma lt_def' [K : preorder β] (U : is_ultrafilter φ) : filter_product.preorder.lt = @lift_rel₂ _ _ φ K.lt := by ext x y; exact lt_def U lemma of_lt_of_lt [preorder β] (U : is_ultrafilter φ) {x y : β} : x < y → of x < (of y : β*) := by rw lt_def U; apply of_rel_of_rel₂ lemma of_lt [preorder β] {x y : β} (U : is_ultrafilter φ) : x < y ↔ of x < (of y : β*) := by rw lt_def U; exact of_rel₂ U.1 lemma lift_id : lift id = (id : β* → β*) := funext $ λ x, quotient.induction_on' x $ by apply λ a, quotient.sound (setoid.refl _) instance [ordered_comm_group β] (U : is_ultrafilter φ) : ordered_comm_group β* := { add_le_add_left := λ x y hxy z, by revert hxy; exact quotient.induction_on₃' x y z (λ a b c hab, by filter_upwards [hab] λ i hi, by simpa), add_lt_add_left := λ x y hxy z, by revert hxy; exact quotient.induction_on₃' x y z (λ a b c hab, by rw lt_def U at hab ⊢; filter_upwards [hab] λ i hi, add_lt_add_left hi (c i)), ..filter_product.partial_order, ..filter_product.add_comm_group } instance [ordered_ring β] (U : is_ultrafilter φ) : ordered_ring β* := { mul_nonneg := λ x y, quotient.induction_on₂' x y $ λ a b ha hb, by filter_upwards [ha, hb] λ i, by simp only [set.mem_set_of_eq]; exact mul_nonneg, mul_pos := λ x y, quotient.induction_on₂' x y $ λ a b ha hb, by rw lt_def U at ha hb ⊢; filter_upwards [ha, hb] λ i, mul_pos, ..filter_product.ring, ..filter_product.ordered_comm_group U, ..filter_product.zero_ne_one_class U.1 } instance [linear_ordered_ring β] (U : is_ultrafilter φ) : linear_ordered_ring β* := { zero_lt_one := by rw lt_def U; show {i | (0 : β) < 1} ∈ _; simp only [zero_lt_one, (set.univ_def).symm, univ_sets], ..filter_product.ordered_ring U, ..filter_product.linear_order U } instance [linear_ordered_field β] (U : is_ultrafilter φ) : linear_ordered_field β* := { ..filter_product.linear_ordered_ring U, ..filter_product.field U } instance [linear_ordered_comm_ring β] (U : is_ultrafilter φ) : linear_ordered_comm_ring β* := { ..filter_product.linear_ordered_ring U, ..filter_product.comm_monoid } noncomputable instance [decidable_linear_order β] (U : is_ultrafilter φ) : decidable_linear_order β* := { decidable_le := by apply_instance, ..filter_product.linear_order U } noncomputable instance [decidable_linear_ordered_comm_group β] (U : is_ultrafilter φ) : decidable_linear_ordered_comm_group β* := { ..filter_product.ordered_comm_group U, ..filter_product.decidable_linear_order U } noncomputable instance [decidable_linear_ordered_comm_ring β] (U : is_ultrafilter φ) : decidable_linear_ordered_comm_ring β* := { ..filter_product.linear_ordered_comm_ring U, ..filter_product.decidable_linear_ordered_comm_group U } noncomputable instance [discrete_linear_ordered_field β] (U : is_ultrafilter φ) : discrete_linear_ordered_field β* := { ..filter_product.linear_ordered_field U, ..filter_product.decidable_linear_ordered_comm_ring U, ..filter_product.discrete_field U } instance [ordered_cancel_comm_monoid β] : ordered_cancel_comm_monoid β* := { add_le_add_left := λ x y hxy z, by revert hxy; exact quotient.induction_on₃' x y z (λ a b c hab, by filter_upwards [hab] λ i hi, by simpa), le_of_add_le_add_left := λ x y z, quotient.induction_on₃' x y z $ λ x y z h, by filter_upwards [h] λ i, le_of_add_le_add_left, ..filter_product.add_comm_monoid, ..filter_product.add_left_cancel_semigroup, ..filter_product.add_right_cancel_semigroup, ..filter_product.partial_order } lemma max_def [K : decidable_linear_order β] (U : is_ultrafilter φ) (x y : β*) : @max β* (filter_product.decidable_linear_order U) x y = (lift₂ max) x y := quotient.induction_on₂' x y $ λ a b, by unfold max; begin split_ifs, exact quotient.sound'(by filter_upwards [h] λ i hi, (max_eq_right hi).symm), exact quotient.sound'(by filter_upwards [@le_of_not_le _ (filter_product.linear_order U) _ _ h] λ i hi, (max_eq_left hi).symm), end lemma min_def [K : decidable_linear_order β] (U : is_ultrafilter φ) (x y : β*) : @min β* (filter_product.decidable_linear_order U) x y = (lift₂ min) x y := quotient.induction_on₂' x y $ λ a b, by unfold min; begin split_ifs, exact quotient.sound'(by filter_upwards [h] λ i hi, (min_eq_left hi).symm), exact quotient.sound'(by filter_upwards [@le_of_not_le _ (filter_product.linear_order U) _ _ h] λ i hi, (min_eq_right hi).symm), end lemma abs_def [decidable_linear_ordered_comm_group β] (U : is_ultrafilter φ) (x y : β*) : @abs _ (filter_product.decidable_linear_ordered_comm_group U) x = (lift abs) x := quotient.induction_on' x $ λ a, by unfold abs; rw max_def; exact quotient.sound' (by show {i | abs _ = _} ∈ _; simp only [eq_self_iff_true, set.univ_def.symm]; exact univ_mem_sets) @[simp] lemma of_max [decidable_linear_order β] (U : is_ultrafilter φ) (x y : β) : (of (max x y) : β*) = @max _ (filter_product.decidable_linear_order U) (of x) (of y) := begin unfold max, split_ifs, { refl }, { exact false.elim (h_1 (of_le_of_le h)) }, { exact false.elim (h ((of_le U.1).mpr h_1)) }, { refl } end @[simp] lemma of_min [decidable_linear_order β] (U : is_ultrafilter φ) (x y : β) : (of (min x y) : β*) = @min _ (filter_product.decidable_linear_order U) (of x) (of y) := begin unfold min, split_ifs, { refl }, { exact false.elim (h_1 (of_le_of_le h)) }, { exact false.elim (h ((of_le U.1).mpr h_1)) }, { refl } end @[simp] lemma of_abs [decidable_linear_ordered_comm_group β] (U : is_ultrafilter φ) (x : β) : (of (abs x) : β*) = @abs _ (filter_product.decidable_linear_ordered_comm_group U) (of x) := of_max U x (-x) end filter_product end filter
a9841c45c88abe816a64747b6fce7e913b41ba79
fe84e287c662151bb313504482b218a503b972f3
/src/combinatorics/fiber.lean
107bc160bcd32d8f7bee3f96144e621ffcd43708
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
2,620
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland -/ import data.fintype.basic import data.fintype.card import algebra.big_operators.basic import algebra.big_operators.order import tactic.squeeze namespace combinatorics universes u v variables {α : Type u} {β : Type v} (p : α → β) variables [fintype α] [fintype β] [decidable_eq α] [decidable_eq β] def fiber (b : β) : Type* := { a : α // p a = b } instance (b : β) : fintype (fiber p b) := by { dsimp[fiber], apply_instance } def fiber' (b : β) : finset α := finset.univ.filter (λ a, p a = b) lemma mem_fiber' (b : β) (a : α) : a ∈ fiber' p b ↔ p a = b := ⟨λ h,(finset.mem_filter.mp h).right, λ h,finset.mem_filter.mpr ⟨finset.mem_univ a,h⟩⟩ lemma card_fiber (b : β) : fintype.card (fiber p b) = (fiber' p b).card := fintype.subtype_card (fiber' p b) (mem_fiber' p b) def equiv_fibre_sigma : α ≃ Σ (b : β), (fiber p b) := { to_fun := λ a, ⟨p a,⟨a,rfl⟩⟩, inv_fun := λ x, x.2.val, left_inv := λ a, by { refl }, right_inv := by { rintro ⟨b,⟨a,⟨e⟩⟩⟩, simp only[heq_iff_eq], split; refl } } lemma card_eq_fiber_sum : fintype.card α = finset.univ.sum (λ b, fintype.card (fiber p b)) := (fintype.card_congr (equiv_fibre_sigma p)).trans (fintype.card_sigma (fiber p)) lemma card_eq_fiber_sum' : fintype.card α = finset.univ.sum (λ b, finset.card (fiber' p b)) := begin let e0 := card_eq_fiber_sum p, let e1 : ∀ b : β, b ∈ finset.univ → fintype.card (fiber p b) = finset.card (fiber' p b) := λ b _, card_fiber p b, let e2 := @finset.sum_congr ℕ β finset.univ _ _ _ _ rfl e1, exact e0.trans e2 end variable {p} lemma fiber_nonempty_of_surjective (p_surj : function.surjective p) (b : β) : nonempty (fiber p b) := begin rcases p_surj b with ⟨a,e⟩, exact ⟨⟨a,e⟩⟩, end lemma card_le_of_surjective : function.surjective p → (fintype.card β) ≤ (fintype.card α) := begin intro p_surj, have h0 : ∀ b, b ∈ finset.univ → 1 ≤ fintype.card (fiber p b) := λ b _, fintype.card_pos_iff.mpr (fiber_nonempty_of_surjective p_surj b), let h1 := @finset.sum_le_sum β ℕ _ _ _ finset.univ h0, let h2 := calc finset.sum finset.univ (λ b : β, 1) = add_monoid.nsmul finset.univ.card 1 : @finset.sum_const ℕ β finset.univ _ 1 ... = ↑finset.univ.card : nsmul_one _ ... = finset.univ.card : nat.cast_id _ ... = fintype.card β : rfl, rw[h2,← card_eq_fiber_sum p] at h1, exact h1 end end combinatorics
247a75637424f098ec6034a3297e74ae7fbcb256
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/list/zip.lean
bc4e1499aff5f9b5d92ccac7d480667a918bac71
[ "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
7,220
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau -/ import data.list.basic universes u v w z variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type z} open nat namespace list /- zip & unzip -/ @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := by cases l; refl @[simp] theorem zip_swap : ∀ (l₁ : list α) (l₂ : list β), (zip l₁ l₂).map prod.swap = zip l₂ l₁ | [] l₂ := (zip_nil_right _).symm | l₁ [] := by rw zip_nil_right; refl | (a::l₁) (b::l₂) := by simp only [zip_cons_cons, map_cons, zip_swap l₁ l₂, prod.swap_prod_mk]; split; refl @[simp] theorem length_zip : ∀ (l₁ : list α) (l₂ : list β), length (zip l₁ l₂) = min (length l₁) (length l₂) | [] l₂ := rfl | l₁ [] := by simp only [length, zip_nil_right, min_zero] | (a::l₁) (b::l₂) := by by simp only [length, zip_cons_cons, length_zip l₁ l₂, min_add_add_right] theorem zip_append : ∀ {l₁ l₂ r₁ r₂ : list α} (h : length l₁ = length l₂), zip (l₁ ++ r₁) (l₂ ++ r₂) = zip l₁ l₂ ++ zip r₁ r₂ | [] l₂ r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h.symm]; refl | l₁ [] r₁ r₂ h := by simp only [eq_nil_of_length_eq_zero h]; refl | (a::l₁) (b::l₂) r₁ r₂ h := by simp only [cons_append, zip_cons_cons, zip_append (succ.inj h)]; split; refl theorem zip_map (f : α → γ) (g : β → δ) : ∀ (l₁ : list α) (l₂ : list β), zip (l₁.map f) (l₂.map g) = (zip l₁ l₂).map (prod.map f g) | [] l₂ := rfl | l₁ [] := by simp only [map, zip_nil_right] | (a::l₁) (b::l₂) := by simp only [map, zip_cons_cons, zip_map l₁ l₂, prod.map]; split; refl theorem zip_map_left (f : α → γ) (l₁ : list α) (l₂ : list β) : zip (l₁.map f) l₂ = (zip l₁ l₂).map (prod.map f id) := by rw [← zip_map, map_id] theorem zip_map_right (f : β → γ) (l₁ : list α) (l₂ : list β) : zip l₁ (l₂.map f) = (zip l₁ l₂).map (prod.map id f) := by rw [← zip_map, map_id] theorem zip_map' (f : α → β) (g : α → γ) : ∀ (l : list α), zip (l.map f) (l.map g) = l.map (λ a, (f a, g a)) | [] := rfl | (a::l) := by simp only [map, zip_cons_cons, zip_map' l]; split; refl theorem mem_zip {a b} : ∀ {l₁ : list α} {l₂ : list β}, (a, b) ∈ zip l₁ l₂ → a ∈ l₁ ∧ b ∈ l₂ | (_::l₁) (_::l₂) (or.inl rfl) := ⟨or.inl rfl, or.inl rfl⟩ | (a'::l₁) (b'::l₂) (or.inr h) := by split; simp only [mem_cons_iff, or_true, mem_zip h] theorem map_fst_zip : ∀ (l₁ : list α) (l₂ : list β), l₁.length ≤ l₂.length → map prod.fst (zip l₁ l₂) = l₁ | [] bs _ := rfl | (a :: as) (b :: bs) h := by { simp at h, simp! * } | (a :: as) [] h := by { simp at h, contradiction } theorem map_snd_zip : ∀ (l₁ : list α) (l₂ : list β), l₂.length ≤ l₁.length → map prod.snd (zip l₁ l₂) = l₂ | _ [] _ := by { rw zip_nil_right, refl } | [] (b :: bs) h := by { simp at h, contradiction } | (a :: as) (b :: bs) h := by { simp at h, simp! * } @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem unzip_eq_map : ∀ (l : list (α × β)), unzip l = (l.map prod.fst, l.map prod.snd) | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, map_cons, unzip_eq_map l] theorem unzip_left (l : list (α × β)) : (unzip l).1 = l.map prod.fst := by simp only [unzip_eq_map] theorem unzip_right (l : list (α × β)) : (unzip l).2 = l.map prod.snd := by simp only [unzip_eq_map] theorem unzip_swap (l : list (α × β)) : unzip (l.map prod.swap) = (unzip l).swap := by simp only [unzip_eq_map, map_map]; split; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp only [unzip_cons, zip_cons_cons, zip_unzip l]; split; refl theorem unzip_zip_left : ∀ {l₁ : list α} {l₂ : list β}, length l₁ ≤ length l₂ → (unzip (zip l₁ l₂)).1 = l₁ | [] l₂ h := rfl | l₁ [] h := by rw eq_nil_of_length_eq_zero (eq_zero_of_le_zero h); refl | (a::l₁) (b::l₂) h := by simp only [zip_cons_cons, unzip_cons, unzip_zip_left (le_of_succ_le_succ h)]; split; refl theorem unzip_zip_right {l₁ : list α} {l₂ : list β} (h : length l₂ ≤ length l₁) : (unzip (zip l₁ l₂)).2 = l₂ := by rw [← zip_swap, unzip_swap]; exact unzip_zip_left h theorem unzip_zip {l₁ : list α} {l₂ : list β} (h : length l₁ = length l₂) : unzip (zip l₁ l₂) = (l₁, l₂) := by rw [← @prod.mk.eta _ _ (unzip (zip l₁ l₂)), unzip_zip_left (le_of_eq h), unzip_zip_right (ge_of_eq h)] @[simp] theorem length_revzip (l : list α) : length (revzip l) = length l := by simp only [revzip, length_zip, length_reverse, min_self] @[simp] theorem unzip_revzip (l : list α) : (revzip l).unzip = (l, l.reverse) := unzip_zip (length_reverse l).symm @[simp] theorem revzip_map_fst (l : list α) : (revzip l).map prod.fst = l := by rw [← unzip_left, unzip_revzip] @[simp] theorem revzip_map_snd (l : list α) : (revzip l).map prod.snd = l.reverse := by rw [← unzip_right, unzip_revzip] theorem reverse_revzip (l : list α) : reverse l.revzip = revzip l.reverse := by rw [← zip_unzip.{u u} (revzip l).reverse, unzip_eq_map]; simp; simp [revzip] theorem revzip_swap (l : list α) : (revzip l).map prod.swap = revzip l.reverse := by simp [revzip] lemma nth_zip_with {α β γ} (f : α → β → γ) (l₁ : list α) (l₂ : list β) (i : ℕ) : (zip_with f l₁ l₂).nth i = f <$> l₁.nth i <*> l₂.nth i := begin induction l₁ generalizing l₂ i, { simp [zip_with, (<*>)] }, { cases l₂; simp only [zip_with, has_seq.seq, functor.map, nth, option.map_none'], { cases ((l₁_hd :: l₁_tl).nth i); refl }, { cases i; simp only [option.map_some', nth, option.some_bind', *], refl } }, end lemma nth_zip_with_eq_some {α β γ} (f : α → β → γ) (l₁ : list α) (l₂ : list β) (z : γ) (i : ℕ) : (zip_with f l₁ l₂).nth i = some z ↔ ∃ x y, l₁.nth i = some x ∧ l₂.nth i = some y ∧ f x y = z := begin induction l₁ generalizing l₂ i, { simp [zip_with] }, { cases l₂; simp only [zip_with, nth, exists_false, and_false, false_and], cases i; simp *, }, end lemma nth_zip_eq_some (l₁ : list α) (l₂ : list β) (z : α × β) (i : ℕ) : (zip l₁ l₂).nth i = some z ↔ l₁.nth i = some z.1 ∧ l₂.nth i = some z.2 := begin cases z, rw [zip, nth_zip_with_eq_some], split, { rintro ⟨x, y, h₀, h₁, h₂⟩, cc }, { rintro ⟨h₀, h₁⟩, exact ⟨_,_,h₀,h₁,rfl⟩ } end end list
564a85cc496a40a9a2f9c3f4945ea54edb77606d
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/logic/function.lean
60de24f1d22b7d469ff5d2a352e2b82cb9e328fc
[ "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
10,211
lean
/- Copyright (c) 2016 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Miscellaneous function constructions and lemmas. -/ import logic.basic data.option.defs universes u v w namespace function section variables {α : Sort u} {β : Sort v} {f : α → β} lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a} (hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' := begin subst hα, have : ∀a, f a == f' a, { intro a, exact h a a (heq.refl a) }, have : β = β', { funext a, exact type_eq_of_heq (this a) }, subst this, apply heq_of_eq, funext a, exact eq_of_heq (this a) end lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) := iff.intro (assume h a, h ▸ rfl) funext lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl @[simp] theorem injective.eq_iff (I : injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ lemma injective.ne (hf : function.injective f) {a₁ a₂ : α} : a₁ ≠ a₂ → f a₁ ≠ f a₂ := mt (assume h, hf h) def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α | a b := decidable_of_iff _ I.eq_iff instance decidable_eq_pfun (p : Prop) [decidable p] (α : p → Type*) [Π hp, decidable_eq (α hp)] : decidable_eq (Π hp, α hp) | f g := decidable_of_iff (∀ hp, f hp = g hp) funext_iff.symm theorem cantor_surjective {α} (f : α → α → Prop) : ¬ function.surjective f | h := let ⟨D, e⟩ := h (λ a, ¬ f a a) in (iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D) theorem cantor_injective {α : Type*} (f : (α → Prop) → α) : ¬ function.injective f | i := cantor_surjective (λ a b, ∀ U, a = f U → U b) $ surjective_of_has_right_inverse ⟨f, λ U, funext $ λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩⟩ /-- `g` is a partial inverse to `f` (an injective but not necessarily surjective function) if `g y = some x` implies `f x = y`, and `g y = none` implies that `y` is not in the range of `f`. -/ def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop := ∀ x y, g y = some x ↔ f x = y theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x := (H _ _).2 rfl theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f := λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl) theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g) (x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y := ((H _ _).1 h₁).symm.trans ((H _ _).1 h₂) theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id := funext h theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id := funext h theorem left_inverse.comp {γ} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a] theorem right_inverse.comp {γ} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) := left_inverse.comp hh hf local attribute [instance] classical.prop_decidable /-- We can use choice to construct explicitly a partial inverse for a given injective function `f`. -/ noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α := if h : ∃ a, f a = b then some (classical.some h) else none theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) : is_partial_inv f (partial_inv f) | a b := ⟨λ h, if h' : ∃ a, f a = b then begin rw [partial_inv, dif_pos h'] at h, injection h with h, subst h, apply classical.some_spec h' end else by rw [partial_inv, dif_neg h'] at h; contradiction, λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩, (dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩ theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x := is_partial_inv_left (partial_inv_of_injective I) end section inv_fun variables {α : Type u} [inhabited α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β} local attribute [instance] classical.prop_decidable /-- Construct the inverse for a function `f` on domain `s`. -/ noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else default α theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_eq' (h : ∀ x y ∈ s, f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a := have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h _ _ (inv_fun_on_mem this) ha (inv_fun_on_eq this) theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = default α := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] /-- The inverse of a function (which is a left inverse if `f` is injective and a right inverse if `f` is surjective). -/ noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b := inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩ lemma inv_fun_neg (h : ¬ ∃ a, f a = b) : inv_fun f b = default α := by refine inv_fun_on_neg (mt _ h); exact assume ⟨a, _, ha⟩, ⟨a, ha⟩ theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g := funext $ assume b, hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f := assume b, inv_fun_eq $ hf b lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f := assume b, have f (inv_fun f (f b)) = f b, from inv_fun_eq ⟨b, rfl⟩, hf this lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) := surjective_of_has_right_inverse ⟨_, left_inverse_inv_fun hf⟩ lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f := ⟨inv_fun f, left_inverse_inv_fun hf⟩ lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f := ⟨injective.has_left_inverse, injective_of_has_left_inverse⟩ end inv_fun section surj_inv variables {α : Sort u} {β : Sort v} {f : α → β} /-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require `α` to be inhabited.) -/ noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b) lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b) lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f := surj_inv_eq hf lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f := right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2) lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f := ⟨_, right_inverse_surj_inv hf⟩ lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f := ⟨surjective.has_right_inverse, surjective_of_has_right_inverse⟩ lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f := ⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩, λ ⟨g, gl, gr⟩, ⟨injective_of_left_inverse gl, surjective_of_has_right_inverse ⟨_, gr⟩⟩⟩ lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) := injective_of_has_left_inverse ⟨f, right_inverse_surj_inv h⟩ end surj_inv section update variables {α : Sort u} {β : α → Sort v} [decidable_eq α] def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a := if h : a = a' then eq.rec v h.symm else f a @[simp] lemma update_same {a : α} {v : β a} {f : Πa, β a} : update f a v a = v := dif_pos rfl @[simp] lemma update_noteq {a a' : α} {v : β a'} {f : Πa, β a} (h : a ≠ a') : update f a' v a = f a := dif_neg h end update lemma uncurry_def {α β γ} (f : α → β → γ) : uncurry f = (λp, f p.1 p.2) := funext $ assume ⟨a, b⟩, rfl -- `uncurry'` is the version of `uncurry` with correct definitional reductions def uncurry' {α β γ} (f : α → β → γ) := λ p : α × β, f p.1 p.2 @[simp] lemma curry_uncurry' {α : Type*} {β : Type*} {γ : Type*} (f : α → β → γ) : curry (uncurry' f) = f := by funext ; refl @[simp] lemma uncurry'_curry {α : Type*} {β : Type*} {γ : Type*} (f : α × β → γ) : uncurry' (curry f) = f := by { funext, simp [curry, uncurry', prod.mk.eta] } def restrict {α β} (f : α → β) (s : set α) : subtype s → β := λ x, f x.val theorem restrict_eq {α β} (f : α → β) (s : set α) : function.restrict f s = f ∘ (@subtype.val _ s) := rfl section bicomp variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ε : Type*} def bicompl (f : γ → δ → ε) (g : α → γ) (h : β → δ) (a b) := f (g a) (h b) def bicompr (f : γ → δ) (g : α → β → γ) (a b) := f (g a b) -- Suggested local notation: local notation f `∘₂` g := bicompr f g lemma uncurry_bicompr (f : α → β → γ) (g : γ → δ) : uncurry (g ∘₂ f) = (g ∘ uncurry f) := funext $ λ ⟨p, q⟩, rfl lemma uncurry'_bicompr (f : α → β → γ) (g : γ → δ) : uncurry' (g ∘₂ f) = (g ∘ uncurry' f) := rfl end bicomp end function
5f28666994aef5df16b4b35dcfe8f6b5d85ed16f
e5c11e5a7d990ce404047c2bd848eeafac3c0a85
/src/fractional_ideal.lean
7125ebec3e6235f052b0679e00e7e341fb7a4f23
[ "LPPL-1.3c" ]
permissive
lean-forward/class-number
9ec63c24845e46efc8fa8b15324d0815918292c7
4fccf36d5e0e16accae84c16df77a3839ad964e4
refs/heads/main
1,686,927,014,542
1,624,886,724,000
1,624,886,724,000
327,319,245
2
0
null
null
null
null
UTF-8
Lean
false
false
42,561
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.localization import ring_theory.noetherian import ring_theory.principal_ideal_domain import tactic.field_simp /-! # Fractional ideals This file defines fractional ideals of an integral domain and proves basic facts about them. ## Main definitions Let `S` be a submonoid of an integral domain `R`, `P` the localization of `R` at `S`, and `f` the natural ring hom from `R` to `P`. * `is_fractional` defines which `R`-submodules of `P` are fractional ideals * `fractional_ideal f` is the type of fractional ideals in `P` * `has_coe (ideal R) (fractional_ideal f)` instance * `comm_semiring (fractional_ideal f)` instance: the typical ideal operations generalized to fractional ideals * `lattice (fractional_ideal f)` instance * `map` is the pushforward of a fractional ideal along an algebra morphism Let `K` be the localization of `R` at `R \ {0}` and `g` the natural ring hom from `R` to `K`. * `has_div (fractional_ideal g)` instance: the ideal quotient `I / J` (typically written $I : J$, but a `:` operator cannot be defined) ## Main statements * `mul_left_mono` and `mul_right_mono` state that ideal multiplication is monotone * `prod_one_self_div_eq` states that `1 / I` is the inverse of `I` if one exists * `is_noetherian` states that very fractional ideal of a noetherian integral domain is noetherian ## Implementation notes Fractional ideals are considered equal when they contain the same elements, independent of the denominator `a : R` such that `a I ⊆ R`. Thus, we define `fractional_ideal` to be the subtype of the predicate `is_fractional`, instead of having `fractional_ideal` be a structure of which `a` is a field. Most definitions in this file specialize operations from submodules to fractional ideals, proving that the result of this operation is fractional if the input is fractional. Exceptions to this rule are defining `(+) := (⊔)` and `⊥ := 0`, in order to re-use their respective proof terms. We can still use `simp` to show `I.1 + J.1 = (I + J).1` and `⊥.1 = 0.1`. In `ring_theory.localization`, we define a copy of the localization map `f`'s codomain `P` (`f.codomain`) so that the `R`-algebra instance on `P` can 'know' the map needed to induce the `R`-algebra structure. We don't assume that the localization is a field until we need it to define ideal quotients. When this assumption is needed, we replace `S` with `non_zero_divisors R`, making the localization a field. ## References * https://en.wikipedia.org/wiki/Fractional_ideal ## Tags fractional ideal, fractional ideals, invertible ideal -/ open localization_map namespace ring section defs variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P] (f : localization_map S P) /-- A submodule `I` is a fractional ideal if `a I ⊆ R` for some `a ≠ 0`. -/ def is_fractional (I : submodule R f.codomain) := ∃ a ∈ S, ∀ b ∈ I, f.is_integer (f.to_map a * b) /-- The fractional ideals of a domain `R` are ideals of `R` divided by some `a ∈ R`. More precisely, let `P` be a localization of `R` at some submonoid `S`, then a fractional ideal `I ⊆ P` is an `R`-submodule of `P`, such that there is a nonzero `a : R` with `a I ⊆ R`. -/ def fractional_ideal := {I : submodule R f.codomain // is_fractional f I} end defs namespace fractional_ideal open set open submodule variables {R : Type*} [comm_ring R] {S : submonoid R} {P : Type*} [comm_ring P] {f : localization_map S P} instance : has_coe (fractional_ideal f) (submodule R f.codomain) := ⟨λ I, I.val⟩ @[simp] lemma val_eq_coe (I : fractional_ideal f) : I.val = I := rfl @[simp, norm_cast] lemma coe_mk (I : submodule R f.codomain) (hI : is_fractional f I) : (subtype.mk I hI : submodule R f.codomain) = I := rfl instance : has_mem P (fractional_ideal f) := ⟨λ x I, x ∈ (I : submodule R f.codomain)⟩ lemma mem_coe {x : f.codomain} {I : fractional_ideal f} : x ∈ (I : submodule R f.codomain) ↔ x ∈ I := iff.rfl /-- Fractional ideals are equal if their submodules are equal. Combined with `submodule.ext` this gives that fractional ideals are equal if they have the same elements. -/ @[ext] lemma ext {I J : fractional_ideal f} : (I : submodule R f.codomain) = J → I = J := subtype.ext_iff_val.mpr lemma ext_iff {I J : fractional_ideal f} : (∀ x, (x ∈ I ↔ x ∈ J)) ↔ I = J := ⟨ λ h, ext (submodule.ext h), λ h x, h ▸ iff.rfl ⟩ lemma fractional_of_subset_one (I : submodule R f.codomain) (h : I ≤ (submodule.span R {1})) : is_fractional f I := begin use [1, S.one_mem], intros b hb, rw [f.to_map.map_one, one_mul], rw ←submodule.one_eq_span at h, obtain ⟨b', b'_mem, b'_eq_b⟩ := h hb, rw (show b = f.to_map b', from b'_eq_b.symm), exact set.mem_range_self b', end lemma is_fractional_of_le {I : submodule R f.codomain} {J : fractional_ideal f} (hIJ : I ≤ J) : is_fractional f I := begin obtain ⟨a, a_mem, ha⟩ := J.2, use [a, a_mem], intros b b_mem, exact ha b (hIJ b_mem) end instance coe_to_fractional_ideal : has_coe (ideal R) (fractional_ideal f) := ⟨ λ I, ⟨f.coe_submodule I, fractional_of_subset_one _ $ λ x ⟨y, hy, h⟩, submodule.mem_span_singleton.2 ⟨y, by rw ←h; exact mul_one _⟩⟩ ⟩ @[simp, norm_cast] lemma coe_coe_ideal (I : ideal R) : ((I : fractional_ideal f) : submodule R f.codomain) = f.coe_submodule I := rfl @[simp] lemma mem_coe_ideal {x : f.codomain} {I : ideal R} : x ∈ (I : fractional_ideal f) ↔ ∃ (x' ∈ I), f.to_map x' = x := ⟨ λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩, λ ⟨x', hx', hx⟩, ⟨x', hx', hx⟩ ⟩ instance : has_zero (fractional_ideal f) := ⟨(0 : ideal R)⟩ @[simp] lemma mem_zero_iff {x : P} : x ∈ (0 : fractional_ideal f) ↔ x = 0 := ⟨ (λ ⟨x', x'_mem_zero, x'_eq_x⟩, have x'_eq_zero : x' = 0 := x'_mem_zero, by simp [x'_eq_x.symm, x'_eq_zero]), (λ hx, ⟨0, rfl, by simp [hx]⟩) ⟩ @[simp, norm_cast] lemma coe_zero : ↑(0 : fractional_ideal f) = (⊥ : submodule R f.codomain) := submodule.ext $ λ _, mem_zero_iff @[simp, norm_cast] lemma coe_to_fractional_ideal_bot : ((⊥ : ideal R) : fractional_ideal f) = 0 := rfl @[simp] lemma exists_mem_to_map_eq {x : R} {I : ideal R} (h : S ≤ non_zero_divisors R) : (∃ x', x' ∈ I ∧ f.to_map x' = f.to_map x) ↔ x ∈ I := ⟨λ ⟨x', hx', eq⟩, f.injective h eq ▸ hx', λ h, ⟨x, h, rfl⟩⟩ lemma coe_to_fractional_ideal_injective (h : S ≤ non_zero_divisors R) : function.injective (coe : ideal R → fractional_ideal f) := λ I J heq, have ∀ (x : R), f.to_map x ∈ (I : fractional_ideal f) ↔ f.to_map x ∈ (J : fractional_ideal f) := λ x, heq ▸ iff.rfl, ideal.ext (by { simpa only [mem_coe_ideal, exists_prop, exists_mem_to_map_eq h] using this }) lemma coe_to_fractional_ideal_eq_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) : (I : fractional_ideal f) = 0 ↔ I = (⊥ : ideal R) := ⟨λ h, coe_to_fractional_ideal_injective hS h, λ h, by rw [h, coe_to_fractional_ideal_bot]⟩ lemma coe_to_fractional_ideal_ne_zero {I : ideal R} (hS : S ≤ non_zero_divisors R) : (I : fractional_ideal f) ≠ 0 ↔ I ≠ (⊥ : ideal R) := not_iff_not.mpr (coe_to_fractional_ideal_eq_zero hS) lemma coe_to_submodule_eq_bot {I : fractional_ideal f} : (I : submodule R f.codomain) = ⊥ ↔ I = 0 := ⟨λ h, ext (by simp [h]), λ h, by simp [h] ⟩ lemma coe_to_submodule_ne_bot {I : fractional_ideal f} : ↑I ≠ (⊥ : submodule R f.codomain) ↔ I ≠ 0 := not_iff_not.mpr coe_to_submodule_eq_bot instance : inhabited (fractional_ideal f) := ⟨0⟩ instance : has_one (fractional_ideal f) := ⟨(1 : ideal R)⟩ lemma mem_one_iff {x : P} : x ∈ (1 : fractional_ideal f) ↔ ∃ x' : R, f.to_map x' = x := iff.intro (λ ⟨x', _, h⟩, ⟨x', h⟩) (λ ⟨x', h⟩, ⟨x', ⟨x', set.mem_univ _, rfl⟩, h⟩) lemma coe_mem_one (x : R) : f.to_map x ∈ (1 : fractional_ideal f) := mem_one_iff.mpr ⟨x, rfl⟩ lemma one_mem_one : (1 : P) ∈ (1 : fractional_ideal f) := mem_one_iff.mpr ⟨1, f.to_map.map_one⟩ /-- `(1 : fractional_ideal f)` is defined as the R-submodule `f(R) ≤ K`. However, this is not definitionally equal to `1 : submodule R K`, which is proved in the actual `simp` lemma `coe_one`. -/ lemma coe_one_eq_coe_submodule_one : ↑(1 : fractional_ideal f) = f.coe_submodule (1 : ideal R) := rfl @[simp, norm_cast] lemma coe_one : (↑(1 : fractional_ideal f) : submodule R f.codomain) = 1 := begin simp only [coe_one_eq_coe_submodule_one, ideal.one_eq_top], convert (submodule.one_eq_map_top).symm, end section lattice /-! ### `lattice` section Defines the order on fractional ideals as inclusion of their underlying sets, and ports the lattice structure on submodules to fractional ideals. -/ instance : partial_order (fractional_ideal f) := { le := λ I J, I.1 ≤ J.1, le_refl := λ I, le_refl I.1, le_antisymm := λ ⟨I, hI⟩ ⟨J, hJ⟩ hIJ hJI, by { congr, exact le_antisymm hIJ hJI }, le_trans := λ _ _ _ hIJ hJK, le_trans hIJ hJK } lemma le_iff_mem {I J : fractional_ideal f} : I ≤ J ↔ (∀ x ∈ I, x ∈ J) := iff.rfl @[simp] lemma coe_le_coe {I J : fractional_ideal f} : (I : submodule R f.codomain) ≤ (J : submodule R f.codomain) ↔ I ≤ J := iff.rfl lemma zero_le (I : fractional_ideal f) : 0 ≤ I := begin intros x hx, convert submodule.zero_mem _, simpa using hx end instance order_bot : order_bot (fractional_ideal f) := { bot := 0, bot_le := zero_le, ..fractional_ideal.partial_order } @[simp] lemma bot_eq_zero : (⊥ : fractional_ideal f) = 0 := rfl @[simp] lemma le_zero_iff {I : fractional_ideal f} : I ≤ 0 ↔ I = 0 := le_bot_iff lemma eq_zero_iff {I : fractional_ideal f} : I = 0 ↔ (∀ x ∈ I, x = (0 : P)) := ⟨ (λ h x hx, by simpa [h, mem_zero_iff] using hx), (λ h, le_bot_iff.mp (λ x hx, mem_zero_iff.mpr (h x hx))) ⟩ lemma fractional_sup (I J : fractional_ideal f) : is_fractional f (I.1 ⊔ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, rcases J.2 with ⟨aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, rcases mem_sup.mp hb with ⟨bI, hbI, bJ, hbJ, hbIJ⟩, rw [←hbIJ, mul_add], apply is_integer_add, { rw [mul_comm aI, f.to_map.map_mul, mul_assoc], apply is_integer_smul (hI bI hbI), }, { rw [f.to_map.map_mul, mul_assoc], apply is_integer_smul (hJ bJ hbJ) } end lemma fractional_inf (I J : fractional_ideal f) : is_fractional f (I.1 ⊓ J.1) := begin rcases I.2 with ⟨aI, haI, hI⟩, use aI, use haI, intros b hb, rcases mem_inf.mp hb with ⟨hbI, hbJ⟩, exact (hI b hbI) end instance lattice : lattice (fractional_ideal f) := { inf := λ I J, ⟨I.1 ⊓ J.1, fractional_inf I J⟩, sup := λ I J, ⟨I.1 ⊔ J.1, fractional_sup I J⟩, inf_le_left := λ I J, show I.1 ⊓ J.1 ≤ I.1, from inf_le_left, inf_le_right := λ I J, show I.1 ⊓ J.1 ≤ J.1, from inf_le_right, le_inf := λ I J K hIJ hIK, show I.1 ≤ (J.1 ⊓ K.1), from le_inf hIJ hIK, le_sup_left := λ I J, show I.1 ≤ I.1 ⊔ J.1, from le_sup_left, le_sup_right := λ I J, show J.1 ≤ I.1 ⊔ J.1, from le_sup_right, sup_le := λ I J K hIK hJK, show (I.1 ⊔ J.1) ≤ K.1, from sup_le hIK hJK, ..fractional_ideal.partial_order } instance : semilattice_sup_bot (fractional_ideal f) := { ..fractional_ideal.order_bot, ..fractional_ideal.lattice } @[simp] lemma coe_ideal_le {I : ideal R} {J : fractional_ideal f} : ↑I ≤ J ↔ ∀ x ∈ I, f.to_map x ∈ J := ⟨λ h x hx, h ⟨x, hx, rfl⟩, λ h x hx, let ⟨x', hx', eq_x⟩ := fractional_ideal.mem_coe_ideal.mp hx in eq_x ▸ h x' hx'⟩ end lattice section semiring instance : has_add (fractional_ideal f) := ⟨(⊔)⟩ @[simp] lemma sup_eq_add (I J : fractional_ideal f) : I ⊔ J = I + J := rfl @[simp, norm_cast] lemma coe_add (I J : fractional_ideal f) : (↑(I + J) : submodule R f.codomain) = I + J := rfl lemma fractional_mul (I J : fractional_ideal f) : is_fractional f (I.1 * J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨I, aJ, haJ, hJ⟩, use aI * aJ, use S.mul_mem haI haJ, intros b hb, apply submodule.mul_induction_on hb, { intros m hm n hn, obtain ⟨n', hn'⟩ := hJ n hn, rw [f.to_map.map_mul, mul_comm m, ←mul_assoc, mul_assoc _ _ n], erw ←hn', rw mul_assoc, apply hI, exact submodule.smul_mem _ _ hm }, { rw [mul_zero], exact ⟨0, f.to_map.map_zero⟩ }, { intros x y hx hy, rw [mul_add], apply is_integer_add hx hy }, { intros r x hx, show f.is_integer (_ * (f.to_map r * x)), rw [←mul_assoc, ←f.to_map.map_mul, mul_comm _ r, f.to_map.map_mul, mul_assoc], apply is_integer_smul hx }, end /-- `fractional_ideal.mul` is the product of two fractional ideals, used to define the `has_mul` instance. This is only an auxiliary definition: the preferred way of writing `I.mul J` is `I * J`. Elaborated terms involving `fractional_ideal` tend to grow quite large, so by making definitions irreducible, we hope to avoid deep unfolds. -/ @[irreducible] def mul (I J : fractional_ideal f) : fractional_ideal f := ⟨I.1 * J.1, fractional_mul I J⟩ local attribute [semireducible] mul instance : has_mul (fractional_ideal f) := ⟨λ I J, mul I J⟩ @[simp] lemma mul_eq_mul (I J : fractional_ideal f) : mul I J = I * J := rfl @[simp, norm_cast] lemma coe_mul (I J : fractional_ideal f) : (↑(I * J) : submodule R f.codomain) = I * J := rfl lemma mul_left_mono (I : fractional_ideal f) : monotone ((*) I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul hx (h hy)) lemma mul_right_mono (I : fractional_ideal f) : monotone (λ J, J * I) := λ J J' h, mul_le.mpr (λ x hx y hy, mul_mem_mul (h hx) hy) lemma mul_mem_mul {I J : fractional_ideal f} {i j : f.codomain} (hi : i ∈ I) (hj : j ∈ J) : i * j ∈ I * J := submodule.mul_mem_mul hi hj lemma mul_le {I J K : fractional_ideal f} : I * J ≤ K ↔ (∀ (i ∈ I) (j ∈ J), i * j ∈ K) := submodule.mul_le @[elab_as_eliminator] protected theorem mul_induction_on {I J : fractional_ideal f} {C : f.codomain → Prop} {r : f.codomain} (hr : r ∈ I * J) (hm : ∀ (i ∈ I) (j ∈ J), C (i * j)) (h0 : C 0) (ha : ∀ x y, C x → C y → C (x + y)) (hs : ∀ (r : R) x, C x → C (r • x)) : C r := submodule.mul_induction_on hr hm h0 ha hs @[simp, norm_cast] lemma coe_ideal_mul (I J : ideal R) : (↑(I * J) : fractional_ideal f) = I * J := begin apply le_antisymm, { rw fractional_ideal.coe_ideal_le, intros x hx, refine submodule.mul_induction_on hx (λ x hx y hy, _) _ (λ x y hx hy, _) (λ r x hx, _), { rw f.to_map.map_mul, apply fractional_ideal.mul_mem_mul; rw fractional_ideal.mem_coe_ideal, { exact ⟨x, hx, rfl⟩ }, { exact ⟨y, hy, rfl⟩ } }, { rw f.to_map.map_zero, exact submodule.zero_mem _ }, { rw f.to_map.map_add, exact submodule.add_mem _ hx hy }, { rw [smul_eq_mul, f.to_map.map_mul], exact submodule.smul_mem _ _ hx } }, { rw fractional_ideal.mul_le, intros x hx y hy, obtain ⟨x', hx', rfl⟩ := fractional_ideal.mem_coe_ideal.mp hx, obtain ⟨y', hy', rfl⟩ := fractional_ideal.mem_coe_ideal.mp hy, rw fractional_ideal.mem_coe_ideal, exact ⟨x' * y', ideal.mul_mem_mul hx' hy', f.to_map.map_mul _ _⟩ }, end instance comm_semiring : comm_semiring (fractional_ideal f) := { add_assoc := λ I J K, sup_assoc, add_comm := λ I J, sup_comm, add_zero := λ I, sup_bot_eq, zero_add := λ I, bot_sup_eq, mul_assoc := λ I J K, ext (submodule.mul_assoc _ _ _), mul_comm := λ I J, ext (submodule.mul_comm _ _), mul_one := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x hx y ⟨y', y'_mem_R, y'_eq_y⟩, rw [←y'_eq_y, mul_comm], exact submodule.smul_mem _ _ hx }, { have : x * 1 ∈ (I * 1) := mul_mem_mul h one_mem_one, rwa [mul_one] at this } end, one_mul := λ I, begin ext, split; intro h, { apply mul_le.mpr _ h, rintros x ⟨x', x'_mem_R, x'_eq_x⟩ y hy, rw ←x'_eq_x, exact submodule.smul_mem _ _ hy }, { have : 1 * x ∈ (1 * I) := mul_mem_mul one_mem_one h, rwa [one_mul] at this } end, mul_zero := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hy]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), zero_mul := λ I, eq_zero_iff.mpr (λ x hx, submodule.mul_induction_on hx (λ x hx y hy, by simp [mem_zero_iff.mp hx]) rfl (λ x y hx hy, by simp [hx, hy]) (λ r x hx, by simp [hx])), left_distrib := λ I J K, ext (mul_add _ _ _), right_distrib := λ I J K, ext (add_mul _ _ _), ..fractional_ideal.has_zero, ..fractional_ideal.has_add, ..fractional_ideal.has_one, ..fractional_ideal.has_mul } section order lemma add_le_add_left {I J : fractional_ideal f} (hIJ : I ≤ J) (J' : fractional_ideal f) : J' + I ≤ J' + J := sup_le_sup_left hIJ J' lemma mul_le_mul_left {I J : fractional_ideal f} (hIJ : I ≤ J) (J' : fractional_ideal f) : J' * I ≤ J' * J := mul_le.mpr (λ k hk j hj, mul_mem_mul hk (hIJ hj)) lemma le_self_mul_self {I : fractional_ideal f} (hI: 1 ≤ I) : I ≤ I * I := begin convert mul_left_mono I hI, exact (mul_one I).symm end lemma mul_self_le_self {I : fractional_ideal f} (hI: I ≤ 1) : I * I ≤ I := begin convert mul_left_mono I hI, exact (mul_one I).symm end lemma coe_ideal_le_one {I : ideal R} : (I : fractional_ideal f) ≤ 1 := λ x hx, let ⟨y, _, hy⟩ := fractional_ideal.mem_coe_ideal.mp hx in fractional_ideal.mem_one_iff.mpr ⟨y, hy⟩ lemma le_one_iff_exists_coe_ideal {J : fractional_ideal f} : J ≤ (1 : fractional_ideal f) ↔ ∃ (I : ideal R), ↑I = J := begin split, { intro hJ, refine ⟨⟨{x : R | f.to_map x ∈ J}, _, _, _⟩, _⟩, { rw [mem_set_of_eq, ring_hom.map_zero], exact J.val.zero_mem }, { intros a b ha hb, rw [mem_set_of_eq, ring_hom.map_add], exact J.val.add_mem ha hb }, { intros c x hx, rw [smul_eq_mul, mem_set_of_eq, ring_hom.map_mul], exact J.val.smul_mem c hx }, { ext x, split, { rintros ⟨y, hy, eq_y⟩, rwa ← eq_y }, { intro hx, obtain ⟨y, eq_x⟩ := fractional_ideal.mem_one_iff.mp (hJ hx), rw ← eq_x at *, exact ⟨y, hx, rfl⟩ } } }, { rintro ⟨I, hI⟩, rw ← hI, apply coe_ideal_le_one }, end end order variables {P' : Type*} [comm_ring P'] {f' : localization_map S P'} variables {P'' : Type*} [comm_ring P''] {f'' : localization_map S P''} lemma fractional_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) : is_fractional f' (submodule.map g.to_linear_map I.1) := begin rcases I with ⟨I, a, a_nonzero, hI⟩, use [a, a_nonzero], intros b hb, obtain ⟨b', b'_mem, hb'⟩ := submodule.mem_map.mp hb, obtain ⟨x, hx⟩ := hI b' b'_mem, use x, erw [←g.commutes, hx, g.map_smul, hb'], refl end /-- `I.map g` is the pushforward of the fractional ideal `I` along the algebra morphism `g` -/ def map (g : f.codomain →ₐ[R] f'.codomain) : fractional_ideal f → fractional_ideal f' := λ I, ⟨submodule.map g.to_linear_map I.1, fractional_map g I⟩ @[simp, norm_cast] lemma coe_map (g : f.codomain →ₐ[R] f'.codomain) (I : fractional_ideal f) : ↑(map g I) = submodule.map g.to_linear_map I := rfl @[simp] lemma mem_map {I : fractional_ideal f} {g : f.codomain →ₐ[R] f'.codomain} {y : f'.codomain} : y ∈ I.map g ↔ ∃ x, x ∈ I ∧ g x = y := submodule.mem_map variables (I J : fractional_ideal f) (g : f.codomain →ₐ[R] f'.codomain) @[simp] lemma map_id : I.map (alg_hom.id _ _) = I := ext (submodule.map_id I.1) @[simp] lemma map_comp (g' : f'.codomain →ₐ[R] f''.codomain) : I.map (g'.comp g) = (I.map g).map g' := ext (submodule.map_comp g.to_linear_map g'.to_linear_map I.1) @[simp, norm_cast] lemma map_coe_ideal (I : ideal R) : (I : fractional_ideal f).map g = I := begin ext x, simp only [coe_coe_ideal, mem_coe_submodule], split, { rintro ⟨_, ⟨y, hy, rfl⟩, rfl⟩, exact ⟨y, hy, (g.commutes y).symm⟩ }, { rintro ⟨y, hy, rfl⟩, exact ⟨_, ⟨y, hy, rfl⟩, g.commutes y⟩ }, end @[simp] lemma map_one : (1 : fractional_ideal f).map g = 1 := map_coe_ideal g 1 @[simp] lemma map_zero : (0 : fractional_ideal f).map g = 0 := map_coe_ideal g 0 @[simp] lemma map_add : (I + J).map g = I.map g + J.map g := ext (submodule.map_sup _ _ _) @[simp] lemma map_mul : (I * J).map g = I.map g * J.map g := ext (submodule.map_mul _ _ _) @[simp] lemma map_map_symm (g : f.codomain ≃ₐ[R] f'.codomain) : (I.map (g : f.codomain →ₐ[R] f'.codomain)).map (g.symm : f'.codomain →ₐ[R] f.codomain) = I := by rw [←map_comp, g.symm_comp, map_id] @[simp] lemma map_symm_map (I : fractional_ideal f') (g : f.codomain ≃ₐ[R] f'.codomain) : (I.map (g.symm : f'.codomain →ₐ[R] f.codomain)).map (g : f.codomain →ₐ[R] f'.codomain) = I := by rw [←map_comp, g.comp_symm, map_id] /-- If `g` is an equivalence, `map g` is an isomorphism -/ def map_equiv (g : f.codomain ≃ₐ[R] f'.codomain) : fractional_ideal f ≃+* fractional_ideal f' := { to_fun := map g, inv_fun := map g.symm, map_add' := λ I J, map_add I J _, map_mul' := λ I J, map_mul I J _, left_inv := λ I, by { rw [←map_comp, alg_equiv.symm_comp, map_id] }, right_inv := λ I, by { rw [←map_comp, alg_equiv.comp_symm, map_id] } } @[simp] lemma coe_fun_map_equiv (g : f.codomain ≃ₐ[R] f'.codomain) : ⇑(map_equiv g) = map g := rfl @[simp] lemma map_equiv_apply (g : f.codomain ≃ₐ[R] f'.codomain) (I : fractional_ideal f) : map_equiv g I = map ↑g I := rfl @[simp] lemma map_equiv_symm (g : f.codomain ≃ₐ[R] f'.codomain) : (map_equiv g).symm = map_equiv g.symm := rfl @[simp] lemma map_equiv_refl : map_equiv alg_equiv.refl = ring_equiv.refl (fractional_ideal f) := ring_equiv.ext (λ x, by simp) lemma is_fractional_span_iff {s : set f.codomain} : is_fractional f (span R s) ↔ ∃ a ∈ S, ∀ (b : P), b ∈ s → f.is_integer (f.to_map a * b) := ⟨ λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, h b (subset_span hb)⟩, λ ⟨a, a_mem, h⟩, ⟨a, a_mem, λ b hb, span_induction hb h (by { rw mul_zero, exact f.is_integer_zero }) (λ x y hx hy, by { rw mul_add, exact is_integer_add hx hy }) (λ s x hx, by { rw algebra.mul_smul_comm, exact is_integer_smul hx }) ⟩ ⟩ lemma is_fractional_of_fg {I : submodule R f.codomain} (hI : I.fg) : is_fractional f I := begin rcases hI with ⟨I, rfl⟩, rcases localization_map.exist_integer_multiples_of_finset f I with ⟨⟨s, hs1⟩, hs⟩, rw is_fractional_span_iff, exact ⟨s, hs1, hs⟩, end /-- `canonical_equiv f f'` is the canonical equivalence between the fractional ideals in `f.codomain` and in `f'.codomain` -/ @[irreducible] noncomputable def canonical_equiv (f : localization_map S P) (f' : localization_map S P') : fractional_ideal f ≃+* fractional_ideal f' := map_equiv { commutes' := λ r, ring_equiv_of_ring_equiv_eq _ _ _, ..ring_equiv_of_ring_equiv f f' (ring_equiv.refl R) (by rw [ring_equiv.to_monoid_hom_refl, submonoid.map_id]) } @[simp] lemma mem_canonical_equiv_apply {I : fractional_ideal f} {x : f'.codomain} : x ∈ canonical_equiv f f' I ↔ ∃ y ∈ I, @localization_map.map _ _ _ _ _ _ _ f (ring_hom.id _) _ (λ ⟨y, hy⟩, hy) _ _ f' y = x := begin rw [canonical_equiv, map_equiv_apply, mem_map], exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ end @[simp] lemma canonical_equiv_symm (f : localization_map S P) (f' : localization_map S P') : (canonical_equiv f f').symm = canonical_equiv f' f := ring_equiv.ext $ λ I, fractional_ideal.ext_iff.mp $ λ x, by { erw [mem_canonical_equiv_apply, canonical_equiv, map_equiv_symm, map_equiv, mem_map], exact ⟨λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩, λ ⟨y, mem, eq⟩, ⟨y, mem, eq⟩⟩ } @[simp] lemma canonical_equiv_flip (f : localization_map S P) (f' : localization_map S P') (I) : canonical_equiv f f' (canonical_equiv f' f I) = I := by rw [←canonical_equiv_symm, ring_equiv.symm_apply_apply] end semiring section fraction_map /-! ### `fraction_map` section This section concerns fractional ideals in the field of fractions, i.e. the type `fractional_ideal g` when `g` is a `fraction_map R K`. -/ variables {K K' : Type*} [field K] [field K'] {g : fraction_map R K} {g' : fraction_map R K'} variables {I J : fractional_ideal g} (h : g.codomain →ₐ[R] g'.codomain) /-- Nonzero fractional ideals contain a nonzero integer. -/ lemma exists_ne_zero_mem_is_integer [nontrivial R] (hI : I ≠ 0) : ∃ x ≠ (0 : R), g.to_map x ∈ I := begin obtain ⟨y, y_mem, y_not_mem⟩ := submodule.exists_of_lt (bot_lt_iff_ne_bot.mpr hI), have y_ne_zero : y ≠ 0 := by simpa using y_not_mem, obtain ⟨z, ⟨x, hx⟩⟩ := g.exists_integer_multiple y, refine ⟨x, _, _⟩, { rw [ne.def, ← g.to_map_eq_zero_iff, hx], exact mul_ne_zero (g.to_map_ne_zero_of_mem_non_zero_divisors _) y_ne_zero }, { rw hx, exact smul_mem _ _ y_mem } end lemma map_ne_zero [nontrivial R] (hI : I ≠ 0) : I.map h ≠ 0 := begin obtain ⟨x, x_ne_zero, hx⟩ := exists_ne_zero_mem_is_integer hI, contrapose! x_ne_zero with map_eq_zero, refine g'.to_map_eq_zero_iff.mp (eq_zero_iff.mp map_eq_zero _ (mem_map.mpr _)), exact ⟨g.to_map x, hx, h.commutes x⟩, end @[simp] lemma map_eq_zero_iff [nontrivial R] : I.map h = 0 ↔ I = 0 := ⟨imp_of_not_imp_not _ _ (map_ne_zero _), λ hI, hI.symm ▸ map_zero h⟩ @[simp, norm_cast] lemma coe_ideal_le_coe_ideal {I J : ideal R} : (I : fractional_ideal g) ≤ (J : fractional_ideal g) ↔ I ≤ J := begin split, { intros h x hI, rw le_iff_mem at h, specialize h (g.to_map x), simp only [mem_coe_ideal, exists_prop, exists_mem_to_map_eq] at h, exact h hI }, { rintros h x hx, simp only [val_eq_coe, coe_coe_ideal, localization_map.mem_coe_submodule] at hx ⊢, obtain ⟨y, hy, y_eq⟩ := hx, exact ⟨y, h hy, y_eq⟩ }, end end fraction_map section quotient /-! ### `quotient` section This section defines the ideal quotient of fractional ideals. In this section we need that each non-zero `y : R` has an inverse in the localization, i.e. that the localization is a field. We satisfy this assumption by taking `S = non_zero_divisors R`, `R`'s localization at which is a field because `R` is a domain. -/ open_locale classical variables {R₁ : Type*} [integral_domain R₁] {K : Type*} [field K] {g : fraction_map R₁ K} instance : nontrivial (fractional_ideal g) := ⟨⟨0, 1, λ h, have this : (1 : K) ∈ (0 : fractional_ideal g) := by rw ←g.to_map.map_one; convert coe_mem_one _, one_ne_zero (mem_zero_iff.mp this) ⟩⟩ lemma fractional_div_of_nonzero {I J : fractional_ideal g} (h : J ≠ 0) : is_fractional g (I.1 / J.1) := begin rcases I with ⟨I, aI, haI, hI⟩, rcases J with ⟨J, aJ, haJ, hJ⟩, obtain ⟨y, mem_J, not_mem_zero⟩ := exists_of_lt (bot_lt_iff_ne_bot.mpr h), obtain ⟨y', hy'⟩ := hJ y mem_J, use (aI * y'), split, { apply (non_zero_divisors R₁).mul_mem haI (mem_non_zero_divisors_iff_ne_zero.mpr _), intro y'_eq_zero, have : g.to_map aJ * y = 0 := by rw [←hy', y'_eq_zero, g.to_map.map_zero], obtain aJ_zero | y_zero := mul_eq_zero.mp this, { have : aJ = 0 := g.to_map.injective_iff.1 g.injective _ aJ_zero, have : aJ ≠ 0 := mem_non_zero_divisors_iff_ne_zero.mp haJ, contradiction }, { exact not_mem_zero (mem_zero_iff.mpr y_zero) } }, intros b hb, rw [g.to_map.map_mul, mul_assoc, mul_comm _ b, hy'], exact hI _ (hb _ (submodule.smul_mem _ aJ mem_J)), end noncomputable instance fractional_ideal_has_div : has_div (fractional_ideal g) := ⟨ λ I J, if h : J = 0 then 0 else ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ ⟩ variables {I J : fractional_ideal g} [ J ≠ 0 ] @[simp] lemma div_zero {I : fractional_ideal g} : I / 0 = 0 := dif_pos rfl lemma div_nonzero {I J : fractional_ideal g} (h : J ≠ 0) : (I / J) = ⟨I.1 / J.1, fractional_div_of_nonzero h⟩ := dif_neg h @[simp] lemma coe_div {I J : fractional_ideal g} (hJ : J ≠ 0) : (↑(I / J) : submodule R₁ g.codomain) = ↑I / (↑J : submodule R₁ g.codomain) := begin unfold has_div.div, simp only [dif_neg hJ, coe_mk, val_eq_coe], end lemma mem_div_iff_of_nonzero {I J : fractional_ideal g} (h : J ≠ 0) {x} : x ∈ I / J ↔ ∀ y ∈ J, x * y ∈ I := by { rw div_nonzero h, exact submodule.mem_div_iff_forall_mul_mem } lemma mul_one_div_le_one {I : fractional_ideal g} : I * (1 / I) ≤ 1 := begin by_cases hI : I = 0, { rw [hI, div_zero, mul_zero], exact zero_le 1 }, { rw [← coe_le_coe, coe_mul, coe_div hI, coe_one], apply submodule.mul_one_div_le_one }, end lemma le_self_mul_one_div {I : fractional_ideal g} (hI : I ≤ (1 : fractional_ideal g)) : I ≤ I * (1 / I) := begin by_cases hI_nz : I = 0, { rw [hI_nz, div_zero, mul_zero], exact zero_le 0 }, { rw [← coe_le_coe, coe_mul, coe_div hI_nz, coe_one], rw [← coe_le_coe, coe_one] at hI, exact submodule.le_self_mul_one_div hI }, end lemma le_div_iff_of_nonzero {I J J' : fractional_ideal g} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ ∀ (x ∈ I) (y ∈ J'), x * y ∈ J := ⟨ λ h x hx, (mem_div_iff_of_nonzero hJ').mp (h hx), λ h x hx, (mem_div_iff_of_nonzero hJ').mpr (h x hx) ⟩ lemma le_div_iff_mul_le {I J J' : fractional_ideal g} (hJ' : J' ≠ 0) : I ≤ J / J' ↔ I * J' ≤ J := begin rw div_nonzero hJ', convert submodule.le_div_iff_mul_le using 1, rw [val_eq_coe, val_eq_coe, ←coe_mul], refl, end lemma mul_one_div_le_div {I J : fractional_ideal g} : I * (1 / J) ≤ I / J := if hJ : J = 0 then by simp [hJ] else (le_div_iff_mul_le hJ).mpr $ calc I * (1 / J) * J = I * (J * (1 / J)) : by rw [mul_assoc, mul_comm (1 / J)] ... ≤ I * 1 : mul_left_mono _ mul_one_div_le_one ... = I : mul_one _ @[simp] lemma div_one {I : fractional_ideal g} : I / 1 = I := begin rw [div_nonzero (@one_ne_zero (fractional_ideal g) _ _)], ext, split; intro h, { convert mem_div_iff_forall_mul_mem.mp h 1 (g.to_map.map_one ▸ coe_mem_one 1), simp }, { apply mem_div_iff_forall_mul_mem.mpr, rintros y ⟨y', _, y_eq_y'⟩, rw mul_comm, convert submodule.smul_mem _ y' h, rw ←y_eq_y', refl } end lemma ne_zero_of_mul_eq_one (I J : fractional_ideal g) (h : I * J = 1) : I ≠ 0 := λ hI, @zero_ne_one (fractional_ideal g) _ _ (by { convert h, simp [hI], }) theorem eq_one_div_of_mul_eq_one (I J : fractional_ideal g) (h : I * J = 1) : J = 1 / I := begin have hI : I ≠ 0 := ne_zero_of_mul_eq_one I J h, suffices h' : I * (1 / I) = 1, { exact (congr_arg units.inv $ @units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) }, apply le_antisymm, { apply mul_le.mpr _, intros x hx y hy, rw mul_comm, exact (mem_div_iff_of_nonzero hI).mp hy x hx }, rw ← h, apply mul_left_mono I, apply (le_div_iff_of_nonzero hI).mpr _, intros y hy x hx, rw mul_comm, exact mul_mem_mul hx hy, end theorem mul_div_self_cancel_iff {I : fractional_ideal g} : I * (1 / I) = 1 ↔ ∃ J, I * J = 1 := ⟨λ h, ⟨(1 / I), h⟩, λ ⟨J, hJ⟩, by rwa [← eq_one_div_of_mul_eq_one I J hJ]⟩ variables {K' : Type*} [field K'] {g' : fraction_map R₁ K'} @[simp] lemma map_div (I J : fractional_ideal g) (h : g.codomain ≃ₐ[R₁] g'.codomain) : (I / J).map (h : g.codomain →ₐ[R₁] g'.codomain) = I.map h / J.map h := begin by_cases H : J = 0, { rw [H, div_zero, map_zero, div_zero] }, { ext x, simp [div_nonzero H, div_nonzero (map_ne_zero _ H), submodule.map_div] } end @[simp] lemma map_one_div (I : fractional_ideal g) (h : g.codomain ≃ₐ[R₁] g'.codomain) : (1 / I).map (h : g.codomain →ₐ[R₁] g'.codomain) = 1 / I.map h := by rw [map_div, map_one] end quotient section principal_ideal_ring variables {R₁ : Type*} [integral_domain R₁] {K : Type*} [field K] {g : fraction_map R₁ K} open_locale classical open submodule submodule.is_principal lemma is_fractional_span_singleton (x : f.codomain) : is_fractional f (span R {x}) := let ⟨a, ha⟩ := f.exists_integer_multiple x in is_fractional_span_iff.mpr ⟨ a.1, a.2, λ x hx, (mem_singleton_iff.mp hx).symm ▸ ha⟩ /-- `span_singleton x` is the fractional ideal generated by `x` if `0 ∉ S` -/ @[irreducible] def span_singleton (x : f.codomain) : fractional_ideal f := ⟨span R {x}, is_fractional_span_singleton x⟩ local attribute [semireducible] span_singleton @[simp] lemma coe_span_singleton (x : f.codomain) : (span_singleton x : submodule R f.codomain) = span R {x} := rfl @[simp] lemma mem_span_singleton {x y : f.codomain} : x ∈ span_singleton y ↔ ∃ (z : R), z • y = x := submodule.mem_span_singleton lemma mem_span_singleton_self (x : f.codomain) : x ∈ span_singleton x := mem_span_singleton.mpr ⟨1, one_smul _ _⟩ lemma eq_span_singleton_of_principal (I : fractional_ideal f) [is_principal (I : submodule R f.codomain)] : I = span_singleton (generator (I : submodule R f.codomain)) := ext (span_singleton_generator I.1).symm lemma is_principal_iff (I : fractional_ideal f) : is_principal (I : submodule R f.codomain) ↔ ∃ x, I = span_singleton x := ⟨λ h, ⟨@generator _ _ _ _ _ I.1 h, @eq_span_singleton_of_principal _ _ _ _ _ _ I h⟩, λ ⟨x, hx⟩, { principal := ⟨x, trans (congr_arg _ hx) (coe_span_singleton x)⟩ } ⟩ @[simp] lemma span_singleton_zero : span_singleton (0 : f.codomain) = 0 := by { ext, simp [submodule.mem_span_singleton, eq_comm] } lemma span_singleton_eq_zero_iff {y : f.codomain} : span_singleton y = 0 ↔ y = 0 := ⟨λ h, span_eq_bot.mp (by simpa using congr_arg subtype.val h : span R {y} = ⊥) y (mem_singleton y), λ h, by simp [h] ⟩ lemma span_singleton_ne_zero_iff {y : f.codomain} : span_singleton y ≠ 0 ↔ y ≠ 0 := not_congr span_singleton_eq_zero_iff @[simp] lemma span_singleton_one : span_singleton (1 : f.codomain) = 1 := begin ext, refine mem_span_singleton.trans ((exists_congr _).trans mem_one_iff.symm), intro x', refine eq.congr (mul_one _) rfl, end @[simp] lemma span_singleton_mul_span_singleton (x y : f.codomain) : span_singleton x * span_singleton y = span_singleton (x * y) := begin ext, simp_rw [coe_mul, coe_span_singleton, span_mul_span, singleton.is_mul_hom.map_mul] end @[simp] lemma coe_ideal_span_singleton (x : R) : (↑(span R {x} : ideal R) : fractional_ideal f) = span_singleton (f.to_map x) := begin ext y, refine mem_coe_ideal.trans (iff.trans _ mem_span_singleton.symm), split, { rintros ⟨y', hy', rfl⟩, obtain ⟨x', rfl⟩ := submodule.mem_span_singleton.mp hy', use x', rw [smul_eq_mul, f.to_map.map_mul], refl }, { rintros ⟨y', rfl⟩, exact ⟨y' * x, submodule.mem_span_singleton.mpr ⟨y', rfl⟩, f.to_map.map_mul _ _⟩ } end @[simp] lemma canonical_equiv_span_singleton (f : localization_map S P) {P'} [comm_ring P'] (f' : localization_map S P') (x : f.codomain) : canonical_equiv f f' (span_singleton x) = span_singleton (f.map (show ∀ (y : S), ring_hom.id _ y.1 ∈ S, from λ y, y.2) f' x) := begin apply ext_iff.mp, intro y, split; intro h, { apply mem_span_singleton.mpr, obtain ⟨x', hx', rfl⟩ := mem_canonical_equiv_apply.mp h, obtain ⟨z, rfl⟩ := mem_span_singleton.mp hx', use z, rw localization_map.map_smul, refl }, { apply mem_canonical_equiv_apply.mpr, obtain ⟨z, rfl⟩ := mem_span_singleton.mp h, use f.to_map z * x, use mem_span_singleton.mpr ⟨z, rfl⟩, rw [ring_hom.map_mul, localization_map.map_eq], refl } end lemma mem_singleton_mul {x y : f.codomain} {I : fractional_ideal f} : y ∈ span_singleton x * I ↔ ∃ y' ∈ I, y = x * y' := begin split, { intro h, apply fractional_ideal.mul_induction_on h, { intros x' hx' y' hy', obtain ⟨a, ha⟩ := mem_span_singleton.mp hx', use [a • y', I.1.smul_mem a hy'], rw [←ha, algebra.mul_smul_comm, algebra.smul_mul_assoc] }, { exact ⟨0, I.1.zero_mem, (mul_zero x).symm⟩ }, { rintros _ _ ⟨y, hy, rfl⟩ ⟨y', hy', rfl⟩, exact ⟨y + y', I.1.add_mem hy hy', (mul_add _ _ _).symm⟩ }, { rintros r _ ⟨y', hy', rfl⟩, exact ⟨r • y', I.1.smul_mem r hy', (algebra.mul_smul_comm _ _ _).symm ⟩ } }, { rintros ⟨y', hy', rfl⟩, exact mul_mem_mul (mem_span_singleton.mpr ⟨1, one_smul _ _⟩) hy' } end lemma one_div_span_singleton (x : g.codomain) : 1 / span_singleton x = span_singleton (x⁻¹) := if h : x = 0 then by simp [h] else (eq_one_div_of_mul_eq_one _ _ (by simp [h])).symm @[simp] lemma div_span_singleton (J : fractional_ideal g) (d : g.codomain) : J / span_singleton d = span_singleton (d⁻¹) * J := begin rw ← one_div_span_singleton, by_cases hd : d = 0, { simp only [hd, span_singleton_zero, div_zero, zero_mul] }, have h_spand : span_singleton d ≠ 0 := mt span_singleton_eq_zero_iff.mp hd, apply le_antisymm, { intros x hx, rw [val_eq_coe, coe_div h_spand, submodule.mem_div_iff_forall_mul_mem] at hx, specialize hx d (mem_span_singleton_self d), have h_xd : x = d⁻¹ * (x * d), { field_simp }, rw [val_eq_coe, coe_mul, one_div_span_singleton, h_xd], exact submodule.mul_mem_mul (mem_span_singleton_self _) hx }, { rw [le_div_iff_mul_le h_spand, mul_assoc, mul_left_comm, one_div_span_singleton, span_singleton_mul_span_singleton, inv_mul_cancel hd, span_singleton_one, mul_one], exact le_refl J }, end lemma exists_eq_span_singleton_mul (I : fractional_ideal g) : ∃ (a : R₁) (aI : ideal R₁), a ≠ 0 ∧ I = span_singleton (g.to_map a)⁻¹ * aI := begin obtain ⟨a_inv, nonzero, ha⟩ := I.2, have nonzero := mem_non_zero_divisors_iff_ne_zero.mp nonzero, have map_a_nonzero := mt g.to_map_eq_zero_iff.mp nonzero, use a_inv, use (span_singleton (g.to_map a_inv) * I).1.comap g.lin_coe, split, exact nonzero, ext, refine iff.trans _ mem_singleton_mul.symm, split, { intro hx, obtain ⟨x', hx'⟩ := ha x hx, refine ⟨g.to_map x', mem_coe_ideal.mpr ⟨x', (mem_singleton_mul.mpr ⟨x, hx, hx'⟩), rfl⟩, _⟩, erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul] }, { rintros ⟨y, hy, rfl⟩, obtain ⟨x', hx', rfl⟩ := mem_coe_ideal.mp hy, obtain ⟨y', hy', hx'⟩ := mem_singleton_mul.mp hx', rw lin_coe_apply at hx', erw [hx', ←mul_assoc, inv_mul_cancel map_a_nonzero, one_mul], exact hy' } end instance is_principal {R} [integral_domain R] [is_principal_ideal_ring R] {f : fraction_map R K} (I : fractional_ideal f) : (I : submodule R f.codomain).is_principal := begin obtain ⟨a, aI, -, ha⟩ := exists_eq_span_singleton_mul I, use (f.to_map a)⁻¹ * f.to_map (generator aI), suffices : I = span_singleton ((f.to_map a)⁻¹ * f.to_map (generator aI)), { exact congr_arg subtype.val this }, conv_lhs { rw [ha, ←span_singleton_generator aI] }, rw [coe_ideal_span_singleton (generator aI), span_singleton_mul_span_singleton] end end principal_ideal_ring variables {R₁ : Type*} [integral_domain R₁] variables {K : Type*} [field K] {g : fraction_map R₁ K} local attribute [instance] classical.prop_decidable lemma is_noetherian_zero : is_noetherian R₁ (0 : fractional_ideal g) := is_noetherian_submodule.mpr (λ I (hI : I ≤ (0 : fractional_ideal g)), by { rw coe_zero at hI, rw le_bot_iff.mp hI, exact fg_bot }) lemma is_noetherian_iff {I : fractional_ideal g} : is_noetherian R₁ I ↔ ∀ J ≤ I, (J : submodule R₁ g.codomain).fg := is_noetherian_submodule.trans ⟨λ h J hJ, h _ hJ, λ h J hJ, h ⟨J, is_fractional_of_le hJ⟩ hJ⟩ lemma is_noetherian_coe_to_fractional_ideal [is_noetherian_ring R₁] (I : ideal R₁) : is_noetherian R₁ (I : fractional_ideal g) := begin rw is_noetherian_iff, intros J hJ, obtain ⟨J, rfl⟩ := le_one_iff_exists_coe_ideal.mp (le_trans hJ coe_ideal_le_one), exact fg_map (is_noetherian.noetherian J), end lemma is_noetherian_span_singleton_inv_to_map_mul (x : R₁) {I : fractional_ideal g} (hI : is_noetherian R₁ I) : is_noetherian R₁ (span_singleton (g.to_map x)⁻¹ * I : fractional_ideal g) := begin by_cases hx : x = 0, { rw [hx, g.to_map.map_zero, _root_.inv_zero, span_singleton_zero, zero_mul], exact is_noetherian_zero }, have h_gx : g.to_map x ≠ 0, from mt (g.to_map.injective_iff.mp (fraction_map.injective g) x) hx, have h_spanx : span_singleton (g.to_map x) ≠ (0 : fractional_ideal g), from span_singleton_ne_zero_iff.mpr h_gx, rw is_noetherian_iff at ⊢ hI, intros J hJ, rw [← div_span_singleton, le_div_iff_mul_le h_spanx] at hJ, obtain ⟨s, hs⟩ := hI _ hJ, use s * {(g.to_map x)⁻¹}, rw [finset.coe_mul, finset.coe_singleton, ← span_mul_span, hs, ← coe_span_singleton, ← coe_mul, mul_assoc, span_singleton_mul_span_singleton, mul_inv_cancel h_gx, span_singleton_one, mul_one], end /-- Every fractional ideal of a noetherian integral domain is noetherian. -/ theorem is_noetherian [is_noetherian_ring R₁] (I : fractional_ideal g) : is_noetherian R₁ I := begin obtain ⟨d, J, h_nzd, rfl⟩ := exists_eq_span_singleton_mul I, apply is_noetherian_span_singleton_inv_to_map_mul, apply is_noetherian_coe_to_fractional_ideal, end section field lemma eq_zero_or_one {K L : Type*} [field K] [field L] {f : fraction_map K L} (I : fractional_ideal f) : I = 0 ∨ I = 1 := begin rw or_iff_not_imp_left, intro hI, simp only [← fractional_ideal.ext_iff, fractional_ideal.mem_one_iff], intro x, split, { intro x_mem, obtain ⟨n, d, rfl⟩ := f.mk'_surjective x, refine ⟨n / d, _⟩, rw [ring_hom.map_div, f.mk'_eq_div] }, { rintro ⟨x, rfl⟩, obtain ⟨y, y_ne, y_mem⟩ := fractional_ideal.exists_ne_zero_mem_is_integer hI, rw [← div_mul_cancel x y_ne, ring_hom.map_mul], exact submodule.smul_mem I _ y_mem } end lemma eq_zero_or_one_of_is_field (hF : is_field R₁) (I : fractional_ideal g) : I = 0 ∨ I = 1 := by { letI : field R₁ := hF.to_field R₁, exact eq_zero_or_one I } end field end fractional_ideal end ring
9064e6f65f5edf594073c13cf8c4d54b67255f22
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/ring_theory/localization/basic.lean
1283dd6e3a0f71cf49d228e026108cccd3de22c4
[ "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
45,197
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johan Commelin, Amelia Livingston, Anne Baanen -/ import algebra.algebra.basic import algebra.ring.equiv import group_theory.monoid_localization import ring_theory.ideal.basic import ring_theory.non_zero_divisors import tactic.ring_exp /-! # Localizations of commutative rings We characterize the localization of a commutative ring `R` at a submonoid `M` up to isomorphism; that is, a commutative ring `S` is the localization of `R` at `M` iff we can find a ring homomorphism `f : R →+* S` satisfying 3 properties: 1. For all `y ∈ M`, `f y` is a unit; 2. For all `z : S`, there exists `(x, y) : R × M` such that `z * f y = f x`; 3. For all `x, y : R`, `f x = f y` iff there exists `c ∈ M` such that `x * c = y * c`. In the following, let `R, P` be commutative rings, `S, Q` be `R`- and `P`-algebras and `M, T` be submonoids of `R` and `P` respectively, e.g.: ``` variables (R S P Q : Type*) [comm_ring R] [comm_ring S] [comm_ring P] [comm_ring Q] variables [algebra R S] [algebra P Q] (M : submonoid R) (T : submonoid P) ``` ## Main definitions * `is_localization (M : submonoid R) (S : Type*)` is a typeclass expressing that `S` is a localization of `R` at `M`, i.e. the canonical map `algebra_map R S : R →+* S` is a localization map (satisfying the above properties). * `is_localization.mk' S` is a surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹` * `is_localization.lift` is the ring homomorphism from `S` induced by a homomorphism from `R` which maps elements of `M` to invertible elements of the codomain. * `is_localization.map S Q` is the ring homomorphism from `S` to `Q` which maps elements of `M` to elements of `T` * `is_localization.ring_equiv_of_ring_equiv`: if `R` and `P` are isomorphic by an isomorphism sending `M` to `T`, then `S` and `Q` are isomorphic * `is_localization.alg_equiv`: if `Q` is another localization of `R` at `M`, then `S` and `Q` are isomorphic as `R`-algebras ## Main results * `localization M S`, a construction of the localization as a quotient type, defined in `group_theory.monoid_localization`, has `comm_ring`, `algebra R` and `is_localization M` instances if `R` is a ring. `localization.away`, `localization.at_prime` and `fraction_ring` are abbreviations for `localization`s and have their corresponding `is_localization` instances ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. A previous version of this file used a fully bundled type of ring localization maps, then used a type synonym `f.codomain` for `f : localization_map M S` to instantiate the `R`-algebra structure on `S`. This results in defining ad-hoc copies for everything already defined on `S`. By making `is_localization` a predicate on the `algebra_map R S`, we can ensure the localization map commutes nicely with other `algebra_map`s. To prove most lemmas about a localization map `algebra_map R S` in this file we invoke the corresponding proof for the underlying `comm_monoid` localization map `is_localization.to_localization_map M S`, which can be found in `group_theory.monoid_localization` and the namespace `submonoid.localization_map`. To reason about the localization as a quotient type, use `mk_eq_of_mk'` and associated lemmas. These show the quotient map `mk : R → M → localization M` equals the surjection `localization_map.mk'` induced by the map `algebra_map : R →+* localization M`. The lemma `mk_eq_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. The proof that "a `comm_ring` `K` which is the localization of an integral domain `R` at `R \ {0}` is a field" is a `def` rather than an `instance`, so if you want to reason about a field of fractions `K`, assume `[field K]` instead of just `[comm_ring K]`. ## Tags localization, ring localization, commutative ring localization, characteristic predicate, commutative ring, field of fractions -/ open function open_locale big_operators section comm_semiring variables {R : Type*} [comm_semiring R] (M : submonoid R) (S : Type*) [comm_semiring S] variables [algebra R S] {P : Type*} [comm_semiring P] /-- The typeclass `is_localization (M : submodule R) S` where `S` is an `R`-algebra expresses that `S` is isomorphic to the localization of `R` at `M`. -/ class is_localization : Prop := (map_units [] : ∀ y : M, is_unit (algebra_map R S y)) (surj [] : ∀ z : S, ∃ x : R × M, z * algebra_map R S x.2 = algebra_map R S x.1) (eq_iff_exists [] : ∀ {x y}, algebra_map R S x = algebra_map R S y ↔ ∃ c : M, x * c = y * c) variables {M S} namespace is_localization section is_localization variables [is_localization M S] section variables (M) lemma of_le (N : submonoid R) (h₁ : M ≤ N) (h₂ : ∀ r ∈ N, is_unit (algebra_map R S r)) : is_localization N S := { map_units := λ r, h₂ r r.2, surj := λ s, by { obtain ⟨⟨x, y, hy⟩, H⟩ := is_localization.surj M s, exact ⟨⟨x, y, h₁ hy⟩, H⟩ }, eq_iff_exists := λ x y, begin split, { rw is_localization.eq_iff_exists M, rintro ⟨c, hc⟩, exact ⟨⟨c, h₁ c.2⟩, hc⟩ }, { rintro ⟨c, h⟩, simpa only [set_like.coe_mk, map_mul, (h₂ c c.2).mul_left_inj] using congr_arg (algebra_map R S) h } end } variables (S) /-- `is_localization.to_localization_with_zero_map M S` shows `S` is the monoid localization of `R` at `M`. -/ @[simps] def to_localization_with_zero_map : submonoid.localization_with_zero_map M S := { to_fun := algebra_map R S, map_units' := is_localization.map_units _, surj' := is_localization.surj _, eq_iff_exists' := λ _ _, is_localization.eq_iff_exists _ _, .. algebra_map R S } /-- `is_localization.to_localization_map M S` shows `S` is the monoid localization of `R` at `M`. -/ abbreviation to_localization_map : submonoid.localization_map M S := (to_localization_with_zero_map M S).to_localization_map @[simp] lemma to_localization_map_to_map : (to_localization_map M S).to_map = (algebra_map R S : R →*₀ S) := rfl lemma to_localization_map_to_map_apply (x) : (to_localization_map M S).to_map x = algebra_map R S x := rfl end variables (M) /-- Given a localization map `f : M →* N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x * (f y)⁻¹ = z`. -/ noncomputable def sec (z : S) : R × M := classical.some $ is_localization.surj _ z @[simp] lemma to_localization_map_sec : (to_localization_map M S).sec = sec M := rfl /-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x` (so this lemma is true by definition). -/ lemma sec_spec (z : S) : z * algebra_map R S (is_localization.sec M z).2 = algebra_map R S (is_localization.sec M z).1 := classical.some_spec $ is_localization.surj _ z /-- Given `z : S`, `is_localization.sec M z` is defined to be a pair `(x, y) : R × M` such that `z * f y = f x`, so this lemma is just an application of `S`'s commutativity. -/ lemma sec_spec' (z : S) : algebra_map R S (is_localization.sec M z).1 = algebra_map R S (is_localization.sec M z).2 * z := by rw [mul_comm, sec_spec] variables {R M} lemma map_right_cancel {x y} {c : M} (h : algebra_map R S (c * x) = algebra_map R S (c * y)) : algebra_map R S x = algebra_map R S y := (to_localization_map M S).map_right_cancel h lemma map_left_cancel {x y} {c : M} (h : algebra_map R S (x * c) = algebra_map R S (y * c)) : algebra_map R S x = algebra_map R S y := (to_localization_map M S).map_left_cancel h lemma eq_zero_of_fst_eq_zero {z x} {y : M} (h : z * algebra_map R S y = algebra_map R S x) (hx : x = 0) : z = 0 := by { rw [hx, (algebra_map R S).map_zero] at h, exact (is_unit.mul_left_eq_zero (is_localization.map_units S y)).1 h} variables (M S) lemma map_eq_zero_iff (r : R) : algebra_map R S r = 0 ↔ ∃ m : M, r * m = 0 := begin split, intro h, { obtain ⟨m, hm⟩ := (is_localization.eq_iff_exists M S).mp ((algebra_map R S).map_zero.trans h.symm), exact ⟨m, by simpa using hm.symm⟩ }, { rintro ⟨m, hm⟩, rw [← (is_localization.map_units S m).mul_left_inj, zero_mul, ← ring_hom.map_mul, hm, ring_hom.map_zero] } end variables {M} /-- `is_localization.mk' S` is the surjection sending `(x, y) : R × M` to `f x * (f y)⁻¹`. -/ noncomputable def mk' (x : R) (y : M) : S := (to_localization_map M S).mk' x y @[simp] lemma mk'_sec (z : S) : mk' S (is_localization.sec M z).1 (is_localization.sec M z).2 = z := (to_localization_map M S).mk'_sec _ lemma mk'_mul (x₁ x₂ : R) (y₁ y₂ : M) : mk' S (x₁ * x₂) (y₁ * y₂) = mk' S x₁ y₁ * mk' S x₂ y₂ := (to_localization_map M S).mk'_mul _ _ _ _ lemma mk'_one (x) : mk' S x (1 : M) = algebra_map R S x := (to_localization_map M S).mk'_one _ @[simp] lemma mk'_spec (x) (y : M) : mk' S x y * algebra_map R S y = algebra_map R S x := (to_localization_map M S).mk'_spec _ _ @[simp] lemma mk'_spec' (x) (y : M) : algebra_map R S y * mk' S x y = algebra_map R S x := (to_localization_map M S).mk'_spec' _ _ @[simp] lemma mk'_spec_mk (x) (y : R) (hy : y ∈ M) : mk' S x ⟨y, hy⟩ * algebra_map R S y = algebra_map R S x := mk'_spec S x ⟨y, hy⟩ @[simp] lemma mk'_spec'_mk (x) (y : R) (hy : y ∈ M) : algebra_map R S y * mk' S x ⟨y, hy⟩ = algebra_map R S x := mk'_spec' S x ⟨y, hy⟩ variables {S} theorem eq_mk'_iff_mul_eq {x} {y : M} {z} : z = mk' S x y ↔ z * algebra_map R S y = algebra_map R S x := (to_localization_map M S).eq_mk'_iff_mul_eq theorem mk'_eq_iff_eq_mul {x} {y : M} {z} : mk' S x y = z ↔ algebra_map R S x = z * algebra_map R S y := (to_localization_map M S).mk'_eq_iff_eq_mul theorem mk'_add_eq_iff_add_mul_eq_mul {x} {y : M} {z₁ z₂} : mk' S x y + z₁ = z₂ ↔ algebra_map R S x + z₁ * algebra_map R S y = z₂ * algebra_map R S y := by rw [←mk'_spec S x y, ←is_unit.mul_left_inj (is_localization.map_units S y), right_distrib] variables (M) lemma mk'_surjective (z : S) : ∃ x (y : M), mk' S x y = z := let ⟨r, hr⟩ := is_localization.surj _ z in ⟨r.1, r.2, (eq_mk'_iff_mul_eq.2 hr).symm⟩ variables (S) include M /-- The localization of a `fintype` is a `fintype`. Cannot be an instance. -/ noncomputable def fintype' [fintype R] : fintype S := have _ := classical.prop_decidable, by exactI fintype.of_surjective (function.uncurry $ is_localization.mk' S) (λ a, prod.exists'.mpr $ is_localization.mk'_surjective M a) omit M variables {M S} /-- Localizing at a submonoid with 0 inside it leads to the trivial ring. -/ def unique_of_zero_mem (h : (0 : R) ∈ M) : unique S := unique_of_zero_eq_one $ by simpa using is_localization.map_units S ⟨0, h⟩ lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ algebra_map R S (x₁ * y₂) = algebra_map R S (x₂ * y₁) := (to_localization_map M S).mk'_eq_iff_eq lemma mk'_mem_iff {x} {y : M} {I : ideal S} : mk' S x y ∈ I ↔ algebra_map R S x ∈ I := begin split; intro h, { rw [← mk'_spec S x y, mul_comm], exact I.mul_mem_left ((algebra_map R S) y) h }, { rw ← mk'_spec S x y at h, obtain ⟨b, hb⟩ := is_unit_iff_exists_inv.1 (map_units S y), have := I.mul_mem_left b h, rwa [mul_comm, mul_assoc, hb, mul_one] at this } end protected lemma eq {a₁ b₁} {a₂ b₂ : M} : mk' S a₁ a₂ = mk' S b₁ b₂ ↔ ∃ c : M, a₁ * b₂ * c = b₁ * a₂ * c := (to_localization_map M S).eq lemma mk'_eq_zero_iff (x : R) (s : M) : mk' S x s = 0 ↔ ∃ (m : M), x * m = 0 := by rw [← (map_units S s).mul_left_inj, mk'_spec, zero_mul, map_eq_zero_iff M] @[simp] lemma mk'_zero (s : M) : is_localization.mk' S 0 s = 0 := by rw [eq_comm, is_localization.eq_mk'_iff_mul_eq, zero_mul, map_zero] lemma ne_zero_of_mk'_ne_zero {x : R} {y : M} (hxy : is_localization.mk' S x y ≠ 0) : x ≠ 0 := begin rintro rfl, exact hxy (is_localization.mk'_zero _) end section ext variables [algebra R P] [is_localization M P] lemma eq_iff_eq {x y} : algebra_map R S x = algebra_map R S y ↔ algebra_map R P x = algebra_map R P y := (to_localization_map M S).eq_iff_eq (to_localization_map M P) lemma mk'_eq_iff_mk'_eq {x₁ x₂} {y₁ y₂ : M} : mk' S x₁ y₁ = mk' S x₂ y₂ ↔ mk' P x₁ y₁ = mk' P x₂ y₂ := (to_localization_map M S).mk'_eq_iff_mk'_eq (to_localization_map M P) lemma mk'_eq_of_eq {a₁ b₁ : R} {a₂ b₂ : M} (H : b₁ * a₂ = a₁ * b₂) : mk' S a₁ a₂ = mk' S b₁ b₂ := (to_localization_map M S).mk'_eq_of_eq H variables (S) @[simp] lemma mk'_self {x : R} (hx : x ∈ M) : mk' S x ⟨x, hx⟩ = 1 := (to_localization_map M S).mk'_self _ hx @[simp] lemma mk'_self' {x : M} : mk' S (x : R) x = 1 := (to_localization_map M S).mk'_self' _ lemma mk'_self'' {x : M} : mk' S x.1 x = 1 := mk'_self' _ end ext lemma mul_mk'_eq_mk'_of_mul (x y : R) (z : M) : (algebra_map R S) x * mk' S y z = mk' S (x * y) z := (to_localization_map M S).mul_mk'_eq_mk'_of_mul _ _ _ lemma mk'_eq_mul_mk'_one (x : R) (y : M) : mk' S x y = (algebra_map R S) x * mk' S 1 y := ((to_localization_map M S).mul_mk'_one_eq_mk' _ _).symm @[simp] lemma mk'_mul_cancel_left (x : R) (y : M) : mk' S (y * x : R) y = (algebra_map R S) x := (to_localization_map M S).mk'_mul_cancel_left _ _ lemma mk'_mul_cancel_right (x : R) (y : M) : mk' S (x * y) y = (algebra_map R S) x := (to_localization_map M S).mk'_mul_cancel_right _ _ @[simp] lemma mk'_mul_mk'_eq_one (x y : M) : mk' S (x : R) y * mk' S (y : R) x = 1 := by rw [←mk'_mul, mul_comm]; exact mk'_self _ _ lemma mk'_mul_mk'_eq_one' (x : R) (y : M) (h : x ∈ M) : mk' S x y * mk' S (y : R) ⟨x, h⟩ = 1 := mk'_mul_mk'_eq_one ⟨x, h⟩ _ section variables (M) lemma is_unit_comp (j : S →+* P) (y : M) : is_unit (j.comp (algebra_map R S) y) := (to_localization_map M S).is_unit_comp j.to_monoid_hom _ end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →+* P` such that `g(M) ⊆ units P`, `f x = f y → g x = g y` for all `x y : R`. -/ lemma eq_of_eq {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) {x y} (h : (algebra_map R S) x = (algebra_map R S) y) : g x = g y := @submonoid.localization_map.eq_of_eq _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg _ _ h lemma mk'_add (x₁ x₂ : R) (y₁ y₂ : M) : mk' S (x₁ * y₂ + x₂ * y₁) (y₁ * y₂) = mk' S x₁ y₁ + mk' S x₂ y₂ := mk'_eq_iff_eq_mul.2 $ eq.symm begin rw [mul_comm (_ + _), mul_add, mul_mk'_eq_mk'_of_mul, mk'_add_eq_iff_add_mul_eq_mul, mul_comm (_ * _), ←mul_assoc, add_comm, ←map_mul, mul_mk'_eq_mk'_of_mul, mk'_add_eq_iff_add_mul_eq_mul], simp only [map_add, submonoid.coe_mul, map_mul], ring end lemma mul_add_inv_left {g : R →+* P} (h : ∀ y : M, is_unit (g y)) (y : M) (w z₁ z₂ : P) : w * ↑(is_unit.lift_right (g.to_monoid_hom.restrict M) h y)⁻¹ + z₁ = z₂ ↔ w + g y * z₁ = g y * z₂ := begin rw [mul_comm, ←one_mul z₁, ←units.inv_mul (is_unit.lift_right (g.to_monoid_hom.restrict M) h y), mul_assoc, ←mul_add, units.inv_mul_eq_iff_eq_mul, units.inv_mul_cancel_left, is_unit.coe_lift_right], simp only [ring_hom.to_monoid_hom_eq_coe, monoid_hom.restrict_apply, ring_hom.coe_monoid_hom] end lemma lift_spec_mul_add {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) (z w w' v) : ((to_localization_with_zero_map M S).lift g.to_monoid_with_zero_hom hg) z * w + w' = v ↔ g ((to_localization_map M S).sec z).1 * w + g ((to_localization_map M S).sec z).2 * w' = g ((to_localization_map M S).sec z).2 * v := begin show (_ * _) * _ + _ = _ ↔ _ = _, erw [mul_comm, ←mul_assoc, mul_add_inv_left hg, mul_comm], refl end /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →+* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` sending `z : S` to `g x * (g y)⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def lift {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) : S →+* P := { map_add' := begin intros x y, erw [(to_localization_map M S).lift_spec, mul_add, mul_comm, eq_comm, lift_spec_mul_add, add_comm, mul_comm,mul_assoc,mul_comm,mul_assoc, lift_spec_mul_add], simp_rw ←mul_assoc, show g _ * g _ * g _ + g _ * g _ * g _ = g _ * g _ * g _, simp_rw [←map_mul g, ←map_add g], apply @eq_of_eq _ _ _ S _ _ _ _ _ g hg, simp only [sec_spec', to_localization_map_sec, map_add, map_mul], ring end, .. @submonoid.localization_with_zero_map.lift _ _ _ _ _ _ _ (to_localization_with_zero_map M S) g.to_monoid_with_zero_hom hg } variables {g : R →+* P} (hg : ∀ y : M, is_unit (g y)) /-- Given a localization map `f : R →+* S` for a submonoid `M ⊆ R` and a map of `comm_semiring`s `g : R →* P` such that `g y` is invertible for all `y : M`, the homomorphism induced from `S` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : R, y ∈ M`. -/ lemma lift_mk' (x y) : lift hg (mk' S x y) = g x * ↑(is_unit.lift_right (g.to_monoid_hom.restrict M) hg y)⁻¹ := (to_localization_map M S).lift_mk' _ _ _ lemma lift_mk'_spec (x v) (y : M) : lift hg (mk' S x y) = v ↔ g x = g y * v := (to_localization_map M S).lift_mk'_spec _ _ _ _ @[simp] lemma lift_eq (x : R) : lift hg ((algebra_map R S) x) = g x := (to_localization_map M S).lift_eq _ _ lemma lift_eq_iff {x y : R × M} : lift hg (mk' S x.1 x.2) = lift hg (mk' S y.1 y.2) ↔ g (x.1 * y.2) = g (y.1 * x.2) := (to_localization_map M S).lift_eq_iff _ @[simp] lemma lift_comp : (lift hg).comp (algebra_map R S) = g := ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_comp _ @[simp] lemma lift_of_comp (j : S →+* P) : lift (is_unit_comp M j) = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ (to_localization_map M S).lift_of_comp j.to_monoid_hom variables (M) /-- See note [partially-applied ext lemmas] -/ lemma monoid_hom_ext ⦃j k : S →* P⦄ (h : j.comp (algebra_map R S : R →* S) = k.comp (algebra_map R S)) : j = k := submonoid.localization_map.epic_of_localization_map (to_localization_map M S) $ monoid_hom.congr_fun h /-- See note [partially-applied ext lemmas] -/ lemma ring_hom_ext ⦃j k : S →+* P⦄ (h : j.comp (algebra_map R S) = k.comp (algebra_map R S)) : j = k := ring_hom.coe_monoid_hom_injective $ monoid_hom_ext M $ monoid_hom.ext $ ring_hom.congr_fun h /- This is not an instance because the submonoid `M` would become a metavariable in typeclass search. -/ lemma alg_hom_subsingleton [algebra R P] : subsingleton (S →ₐ[R] P) := ⟨λ f g, alg_hom.coe_ring_hom_injective $ is_localization.ring_hom_ext M $ by rw [f.comp_algebra_map, g.comp_algebra_map]⟩ /-- To show `j` and `k` agree on the whole localization, it suffices to show they agree on the image of the base ring, if they preserve `1` and `*`. -/ protected lemma ext (j k : S → P) (hj1 : j 1 = 1) (hk1 : k 1 = 1) (hjm : ∀ a b, j (a * b) = j a * j b) (hkm : ∀ a b, k (a * b) = k a * k b) (h : ∀ a, j (algebra_map R S a) = k (algebra_map R S a)) : j = k := monoid_hom.mk.inj (monoid_hom_ext M $ monoid_hom.ext h : (⟨j, hj1, hjm⟩ : S →* P) = ⟨k, hk1, hkm⟩) variables {M} lemma lift_unique {j : S →+* P} (hj : ∀ x, j ((algebra_map R S) x) = g x) : lift hg = j := ring_hom.ext $ monoid_hom.ext_iff.1 $ @submonoid.localization_map.lift_unique _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom hg j.to_monoid_hom hj @[simp] lemma lift_id (x) : lift (map_units S : ∀ y : M, is_unit _) x = x := (to_localization_map M S).lift_id _ lemma lift_surjective_iff : surjective (lift hg : S → P) ↔ ∀ v : P, ∃ x : R × M, v * g x.2 = g x.1 := (to_localization_map M S).lift_surjective_iff hg lemma lift_injective_iff : injective (lift hg : S → P) ↔ ∀ x y, algebra_map R S x = algebra_map R S y ↔ g x = g y := (to_localization_map M S).lift_injective_iff hg section map variables {T : submonoid P} {Q : Type*} [comm_semiring Q] (hy : M ≤ T.comap g) variables [algebra P Q] [is_localization T Q] section variables (Q) /-- Map a homomorphism `g : R →+* P` to `S →+* Q`, where `S` and `Q` are localizations of `R` and `P` at `M` and `T` respectively, such that `g(M) ⊆ T`. We send `z : S` to `algebra_map P Q (g x) * (algebra_map P Q (g y))⁻¹`, where `(x, y) : R × M` are such that `z = f x * (f y)⁻¹`. -/ noncomputable def map (g : R →+* P) (hy : M ≤ T.comap g) : S →+* Q := @lift R _ M _ _ _ _ _ _ ((algebra_map P Q).comp g) (λ y, map_units _ ⟨g y, hy y.2⟩) end lemma map_eq (x) : map Q g hy ((algebra_map R S) x) = algebra_map P Q (g x) := lift_eq (λ y, map_units _ ⟨g y, hy y.2⟩) x @[simp] lemma map_comp : (map Q g hy).comp (algebra_map R S) = (algebra_map P Q).comp g := lift_comp $ λ y, map_units _ ⟨g y, hy y.2⟩ lemma map_mk' (x) (y : M) : map Q g hy (mk' S x y) = mk' Q (g x) ⟨g y, hy y.2⟩ := @submonoid.localization_map.map_mk' _ _ _ _ _ _ _ (to_localization_map M S) g.to_monoid_hom _ (λ y, hy y.2) _ _ (to_localization_map T Q) _ _ @[simp] lemma map_id (z : S) (h : M ≤ M.comap (ring_hom.id R) := le_refl M) : map S (ring_hom.id _) h z = z := lift_id _ lemma map_unique (j : S →+* Q) (hj : ∀ x : R, j (algebra_map R S x) = algebra_map P Q (g x)) : map Q g hy = j := lift_unique (λ y, map_units _ ⟨g y, hy y.2⟩) hj /-- If `comm_semiring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_comp_map {A : Type*} [comm_semiring A] {U : submonoid A} {W} [comm_semiring W] [algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) : (map W l hl).comp (map Q g hy : S →+* _) = map W (l.comp g) (λ x hx, hl (hy hx)) := ring_hom.ext $ λ x, @submonoid.localization_map.map_map _ _ _ _ _ P _ (to_localization_map M S) g _ _ _ _ _ _ _ _ _ _ (to_localization_map U W) l _ x /-- If `comm_semiring` homs `g : R →+* P, l : P →+* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ lemma map_map {A : Type*} [comm_semiring A] {U : submonoid A} {W} [comm_semiring W] [algebra A W] [is_localization U W] {l : P →+* A} (hl : T ≤ U.comap l) (x : S) : map W l hl (map Q g hy x) = map W (l.comp g) (λ x hx, hl (hy hx)) x := by rw ←map_comp_map hy hl; refl lemma map_smul (x : S) (z : R) : map Q g hy (z • x : S) = g z • map Q g hy x := by rw [algebra.smul_def, algebra.smul_def, ring_hom.map_mul, map_eq] section variables (S Q) /-- If `S`, `Q` are localizations of `R` and `P` at submonoids `M, T` respectively, an isomorphism `j : R ≃+* P` such that `j(M) = T` induces an isomorphism of localizations `S ≃+* Q`. -/ @[simps] noncomputable def ring_equiv_of_ring_equiv (h : R ≃+* P) (H : M.map h.to_monoid_hom = T) : S ≃+* Q := have H' : T.map h.symm.to_monoid_hom = M, by { rw [← M.map_id, ← H, submonoid.map_map], congr, ext, apply h.symm_apply_apply }, { to_fun := map Q (h : R →+* P) (M.le_comap_of_map_le (le_of_eq H)), inv_fun := map S (h.symm : P →+* R) (T.le_comap_of_map_le (le_of_eq H')), left_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply], intro x, convert congr_arg (algebra_map R S) (h.symm_apply_apply x).symm }, right_inv := λ x, by { rw [map_map, map_unique _ (ring_hom.id _), ring_hom.id_apply], intro x, convert congr_arg (algebra_map P Q) (h.apply_symm_apply x).symm }, .. map Q (h : R →+* P) _ } end lemma ring_equiv_of_ring_equiv_eq_map {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) : (ring_equiv_of_ring_equiv S Q j H : S →+* Q) = map Q (j : R →+* P) (M.le_comap_of_map_le (le_of_eq H)) := rfl @[simp] lemma ring_equiv_of_ring_equiv_eq {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x) : ring_equiv_of_ring_equiv S Q j H ((algebra_map R S) x) = algebra_map P Q (j x) := map_eq _ _ lemma ring_equiv_of_ring_equiv_mk' {j : R ≃+* P} (H : M.map j.to_monoid_hom = T) (x : R) (y : M) : ring_equiv_of_ring_equiv S Q j H (mk' S x y) = mk' Q (j x) ⟨j y, show j y ∈ T, from H ▸ set.mem_image_of_mem j y.2⟩ := map_mk' _ _ _ end map section alg_equiv variables {Q : Type*} [comm_semiring Q] [algebra R Q] [is_localization M Q] section variables (M S Q) /-- If `S`, `Q` are localizations of `R` at the submonoid `M` respectively, there is an isomorphism of localizations `S ≃ₐ[R] Q`. -/ @[simps] noncomputable def alg_equiv : S ≃ₐ[R] Q := { commutes' := ring_equiv_of_ring_equiv_eq _, .. ring_equiv_of_ring_equiv S Q (ring_equiv.refl R) M.map_id } end @[simp] lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S Q (mk' S x y) = mk' Q x y:= map_mk' _ _ _ @[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S Q).symm (mk' Q x y) = mk' S x y:= map_mk' _ _ _ end alg_equiv end is_localization section variables (M) lemma is_localization_of_alg_equiv [algebra R P] [is_localization M S] (h : S ≃ₐ[R] P) : is_localization M P := begin constructor, { intro y, convert (is_localization.map_units S y).map h.to_alg_hom.to_ring_hom.to_monoid_hom, exact (h.commutes y).symm }, { intro y, obtain ⟨⟨x, s⟩, e⟩ := is_localization.surj M (h.symm y), apply_fun h at e, simp only [h.map_mul, h.apply_symm_apply, h.commutes] at e, exact ⟨⟨x, s⟩, e⟩ }, { intros x y, rw [← h.symm.to_equiv.injective.eq_iff, ← is_localization.eq_iff_exists M S, ← h.symm.commutes, ← h.symm.commutes], refl } end lemma is_localization_iff_of_alg_equiv [algebra R P] (h : S ≃ₐ[R] P) : is_localization M S ↔ is_localization M P := ⟨λ _, by exactI is_localization_of_alg_equiv M h, λ _, by exactI is_localization_of_alg_equiv M h.symm⟩ lemma is_localization_iff_of_ring_equiv (h : S ≃+* P) : is_localization M S ↔ @@is_localization _ M P _ (h.to_ring_hom.comp $ algebra_map R S).to_algebra := begin letI := (h.to_ring_hom.comp $ algebra_map R S).to_algebra, exact is_localization_iff_of_alg_equiv M { commutes' := λ _, rfl, ..h }, end variable (S) lemma is_localization_of_base_ring_equiv [is_localization M S] (h : R ≃+* P) : @@is_localization _ (M.map h.to_monoid_hom) S _ ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra := begin constructor, { rintros ⟨_, ⟨y, hy, rfl⟩⟩, convert is_localization.map_units S ⟨y, hy⟩, dsimp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply], exact congr_arg _ (h.symm_apply_apply _) }, { intro y, obtain ⟨⟨x, s⟩, e⟩ := is_localization.surj M y, refine ⟨⟨h x, _, _, s.prop, rfl⟩, _⟩, dsimp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply] at ⊢ e, convert e; exact h.symm_apply_apply _ }, { intros x y, rw [ring_hom.algebra_map_to_algebra, ring_hom.comp_apply, ring_hom.comp_apply, is_localization.eq_iff_exists M S], simp_rw ← h.to_equiv.apply_eq_iff_eq, change (∃ (c : M), h (h.symm x * c) = h (h.symm y * c)) ↔ _, simp only [ring_equiv.apply_symm_apply, ring_equiv.map_mul], exact ⟨λ ⟨c, e⟩, ⟨⟨_, _, c.prop, rfl⟩, e⟩, λ ⟨⟨_, c, h, e₁⟩, e₂⟩, ⟨⟨_, h⟩, e₁.symm ▸ e₂⟩⟩ } end lemma is_localization_iff_of_base_ring_equiv (h : R ≃+* P) : is_localization M S ↔ @@is_localization _ (M.map h.to_monoid_hom) S _ ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra := begin refine ⟨λ _, by exactI is_localization_of_base_ring_equiv _ _ h, _⟩, letI := ((algebra_map R S).comp h.symm.to_ring_hom).to_algebra, intro H, convert @@is_localization_of_base_ring_equiv _ _ _ _ _ _ H h.symm, { erw [submonoid.map_equiv_eq_comap_symm, submonoid.comap_map_eq_of_injective], exact h.to_equiv.injective }, rw [ring_hom.algebra_map_to_algebra, ring_hom.comp_assoc], simp only [ring_hom.comp_id, ring_equiv.symm_symm, ring_equiv.symm_to_ring_hom_comp_to_ring_hom], apply algebra.algebra_ext, intro r, rw ring_hom.algebra_map_to_algebra end end variables (M S) include M lemma non_zero_divisors_le_comap [is_localization M S] : non_zero_divisors R ≤ (non_zero_divisors S).comap (algebra_map R S) := begin rintros a ha b (e : b * algebra_map R S a = 0), obtain ⟨x, s, rfl⟩ := mk'_surjective M b, rw [← @mk'_one R _ M, ← mk'_mul, ← (algebra_map R S).map_zero, ← @mk'_one R _ M, is_localization.eq] at e, obtain ⟨c, e⟩ := e, rw [zero_mul, zero_mul, submonoid.coe_one, mul_one, mul_comm x a, mul_assoc, mul_comm] at e, rw mk'_eq_zero_iff, exact ⟨c, ha _ e⟩ end lemma map_non_zero_divisors_le [is_localization M S] : (non_zero_divisors R).map (algebra_map R S) ≤ non_zero_divisors S := submonoid.map_le_iff_le_comap.mpr (non_zero_divisors_le_comap M S) end is_localization namespace localization open is_localization /-! ### Constructing a localization at a given submonoid -/ variables {M} section instance [subsingleton R] : unique (localization M) := ⟨⟨1⟩, begin intro a, induction a, induction default, congr, refl, refl end⟩ /-- Addition in a ring localization is defined as `⟨a, b⟩ + ⟨c, d⟩ = ⟨b * c + d * a, b * d⟩`. Should not be confused with `add_localization.add`, which is defined as `⟨a, b⟩ + ⟨c, d⟩ = ⟨a + c, b + d⟩`. -/ @[irreducible] protected def add (z w : localization M) : localization M := localization.lift_on₂ z w (λ a b c d, mk ((b : R) * c + d * a) (b * d)) $ λ a a' b b' c c' d d' h1 h2, mk_eq_mk_iff.2 begin rw r_eq_r' at h1 h2 ⊢, cases h1 with t₅ ht₅, cases h2 with t₆ ht₆, use t₆ * t₅, calc ((b : R) * c + d * a) * (b' * d') * (t₆ * t₅) = (c * d' * t₆) * (b * b' * t₅) + (a * b' * t₅) * (d * d' * t₆) : by ring ... = (b' * c' + d' * a') * (b * d) * (t₆ * t₅) : by rw [ht₆, ht₅]; ring end instance : has_add (localization M) := ⟨localization.add⟩ lemma add_mk (a b c d) : (mk a b : localization M) + mk c d = mk (b * c + d * a) (b * d) := by { unfold has_add.add localization.add, apply lift_on₂_mk } lemma add_mk_self (a b c) : (mk a b : localization M) + mk c b = mk (a + c) b := begin rw [add_mk, mk_eq_mk_iff, r_eq_r'], refine (r' M).symm ⟨1, _⟩, simp only [submonoid.coe_one, submonoid.coe_mul], ring end private meta def tac := `[ { intros, simp only [add_mk, localization.mk_mul, ← localization.mk_zero 1], refine mk_eq_mk_iff.mpr (r_of_eq _), simp only [submonoid.coe_mul], ring }] instance : comm_semiring (localization M) := { zero := 0, one := 1, add := (+), mul := (*), npow := localization.npow _, nsmul := (•), nsmul_zero' := λ x, localization.induction_on x (λ x, by simp only [smul_mk, zero_nsmul, mk_zero]), nsmul_succ' := λ n x, localization.induction_on x (λ x, by simp only [smul_mk, succ_nsmul, add_mk_self]), add_assoc := λ m n k, localization.induction_on₃ m n k (by tac), zero_add := λ y, localization.induction_on y (by tac), add_zero := λ y, localization.induction_on y (by tac), add_comm := λ y z, localization.induction_on₂ z y (by tac), left_distrib := λ m n k, localization.induction_on₃ m n k (by tac), right_distrib := λ m n k, localization.induction_on₃ m n k (by tac), .. localization.comm_monoid_with_zero M } /--For any given denominator `b : M`, the map `a ↦ a / b` is an `add_monoid_hom` from `R` to `localization M`-/ @[simps] def mk_add_monoid_hom (b : M) : R →+ localization M := { to_fun := λ a, mk a b, map_zero' := mk_zero _, map_add' := λ x y, (add_mk_self _ _ _).symm } lemma mk_sum {ι : Type*} (f : ι → R) (s : finset ι) (b : M) : mk (∑ i in s, f i) b = ∑ i in s, mk (f i) b := (mk_add_monoid_hom b).map_sum f s lemma mk_list_sum (l : list R) (b : M) : mk l.sum b = (l.map $ λ a, mk a b).sum := (mk_add_monoid_hom b).map_list_sum l lemma mk_multiset_sum (l : multiset R) (b : M) : mk l.sum b = (l.map $ λ a, mk a b).sum := (mk_add_monoid_hom b).map_multiset_sum l instance {S : Type*} [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] : distrib_mul_action S (localization M) := { smul_zero := λ s, by simp only [←localization.mk_zero 1, localization.smul_mk, smul_zero], smul_add := λ s x y, localization.induction_on₂ x y $ prod.rec $ by exact λ r₁ x₁, prod.rec $ by exact λ r₂ x₂, by simp only [localization.smul_mk, localization.add_mk, smul_add, mul_comm _ (s • _), mul_comm _ r₁, mul_comm _ r₂, smul_mul_assoc] } instance {S : Type*} [semiring S] [mul_semiring_action S R] [is_scalar_tower S R R] : mul_semiring_action S (localization M) := { ..localization.mul_distrib_mul_action } instance {S : Type*} [semiring S] [module S R] [is_scalar_tower S R R] : module S (localization M) := { zero_smul := localization.ind $ prod.rec $ by { intros, simp only [localization.smul_mk, zero_smul, mk_zero] }, add_smul := λ s₁ s₂, localization.ind $ prod.rec $ by { intros, simp only [localization.smul_mk, add_smul, add_mk_self] }, ..localization.distrib_mul_action } instance {S : Type*} [comm_semiring S] [algebra S R] : algebra S (localization M) := { to_ring_hom := ring_hom.comp { to_fun := (monoid_of M).to_map, map_zero' := by rw [← mk_zero (1 : M), mk_one_eq_monoid_of_mk], map_add' := λ x y, by simp only [← mk_one_eq_monoid_of_mk, add_mk, submonoid.coe_one, one_mul, add_comm], .. localization.monoid_of M } (algebra_map S R), smul_def' := λ s, localization.ind $ prod.rec $ begin intros r x, dsimp, simp only [←mk_one_eq_monoid_of_mk, mk_mul, localization.smul_mk, one_mul, algebra.smul_def], end, commutes' := λ s, localization.ind $ prod.rec $ begin intros r x, dsimp, simp only [←mk_one_eq_monoid_of_mk, mk_mul, localization.smul_mk, one_mul, mul_one, algebra.commutes], end } instance : is_localization M (localization M) := { map_units := (localization.monoid_of M).map_units, surj := (localization.monoid_of M).surj, eq_iff_exists := λ _ _, (localization.monoid_of M).eq_iff_exists } end @[simp] lemma to_localization_map_eq_monoid_of : to_localization_map M (localization M) = monoid_of M := rfl lemma monoid_of_eq_algebra_map (x) : (monoid_of M).to_map x = algebra_map R (localization M) x := rfl lemma mk_one_eq_algebra_map (x) : mk x 1 = algebra_map R (localization M) x := rfl lemma mk_eq_mk'_apply (x y) : mk x y = is_localization.mk' (localization M) x y := by rw [mk_eq_monoid_of_mk'_apply, mk', to_localization_map_eq_monoid_of] @[simp] lemma mk_eq_mk' : (mk : R → M → localization M) = is_localization.mk' (localization M) := mk_eq_monoid_of_mk' lemma mk_algebra_map {A : Type*} [comm_semiring A] [algebra A R] (m : A) : mk (algebra_map A R m) 1 = algebra_map A (localization M) m := by rw [mk_eq_mk', mk'_eq_iff_eq_mul, submonoid.coe_one, map_one, mul_one]; refl lemma mk_nat_cast (m : ℕ) : (mk m 1 : localization M) = m := by simpa using @mk_algebra_map R _ M ℕ _ _ m variables [is_localization M S] section variables (M S) /-- The localization of `R` at `M` as a quotient type is isomorphic to any other localization. -/ @[simps] noncomputable def alg_equiv : localization M ≃ₐ[R] S := is_localization.alg_equiv M _ _ /-- The localization of a singleton is a singleton. Cannot be an instance due to metavariables. -/ noncomputable def _root_.is_localization.unique (R Rₘ) [comm_semiring R] [comm_semiring Rₘ] (M : submonoid R) [subsingleton R] [algebra R Rₘ] [is_localization M Rₘ] : unique Rₘ := have inhabited Rₘ := ⟨1⟩, by exactI (alg_equiv M Rₘ).symm.injective.unique end @[simp] lemma alg_equiv_mk' (x : R) (y : M) : alg_equiv M S (mk' (localization M) x y) = mk' S x y := alg_equiv_mk' _ _ @[simp] lemma alg_equiv_symm_mk' (x : R) (y : M) : (alg_equiv M S).symm (mk' S x y) = mk' (localization M) x y := alg_equiv_symm_mk' _ _ lemma alg_equiv_mk (x y) : alg_equiv M S (mk x y) = mk' S x y := by rw [mk_eq_mk', alg_equiv_mk'] lemma alg_equiv_symm_mk (x : R) (y : M) : (alg_equiv M S).symm (mk' S x y) = mk x y := by rw [mk_eq_mk', alg_equiv_symm_mk'] end localization end comm_semiring section comm_ring variables {R : Type*} [comm_ring R] {M : submonoid R} (S : Type*) [comm_ring S] variables [algebra R S] {P : Type*} [comm_ring P] namespace localization /-- Negation in a ring localization is defined as `-⟨a, b⟩ = ⟨-a, b⟩`. -/ @[irreducible] protected def neg (z : localization M) : localization M := localization.lift_on z (λ a b, mk (-a) b) $ λ a b c d h, mk_eq_mk_iff.2 begin rw r_eq_r' at h ⊢, cases h with t ht, use t, rw [neg_mul, neg_mul, ht], ring_nf, end instance : has_neg (localization M) := ⟨localization.neg⟩ lemma neg_mk (a b) : -(mk a b : localization M) = mk (-a) b := by { unfold has_neg.neg localization.neg, apply lift_on_mk } instance : comm_ring (localization M) := { zsmul := (•), zsmul_zero' := λ x, localization.induction_on x (λ x, by simp only [smul_mk, zero_zsmul, mk_zero]), zsmul_succ' := λ n x, localization.induction_on x (λ x, by simp [smul_mk, add_mk_self, -mk_eq_monoid_of_mk', add_comm (n : ℤ) 1, add_smul]), zsmul_neg' := λ n x, localization.induction_on x (λ x, by { rw [smul_mk, smul_mk, neg_mk, ← neg_smul], refl }), neg := has_neg.neg, sub := λ x y, x + -y, sub_eq_add_neg := λ x y, rfl, add_left_neg := λ y, by exact localization.induction_on y begin intros, simp only [add_mk, localization.mk_mul, neg_mk, ← mk_zero 1], refine mk_eq_mk_iff.mpr (r_of_eq _), simp only [submonoid.coe_mul], ring end, .. localization.comm_semiring } lemma sub_mk (a c) (b d) : (mk a b : localization M) - mk c d = mk (d * a - b * c) (b * d) := calc mk a b - mk c d = mk a b + (- mk c d) : sub_eq_add_neg _ _ ... = mk a b + (mk (-c) d) : by rw neg_mk ... = mk (b * (-c) + d * a) (b * d) : add_mk _ _ _ _ ... = mk (d * a - b * c) (b * d) : by congr'; ring lemma mk_int_cast (m : ℤ) : (mk m 1 : localization M) = m := by simpa using @mk_algebra_map R _ M ℤ _ _ m end localization namespace is_localization variables {R M} (S) {K : Type*} [is_localization M S] lemma to_map_eq_zero_iff {x : R} (hM : M ≤ non_zero_divisors R) : algebra_map R S x = 0 ↔ x = 0 := begin rw ← (algebra_map R S).map_zero, split; intro h, { cases (eq_iff_exists M S).mp h with c hc, rw zero_mul at hc, exact hM c.2 x hc }, { rw h }, end protected lemma injective (hM : M ≤ non_zero_divisors R) : injective (algebra_map R S) := begin rw injective_iff_map_eq_zero (algebra_map R S), intros a ha, rwa to_map_eq_zero_iff S hM at ha end protected lemma to_map_ne_zero_of_mem_non_zero_divisors [nontrivial R] (hM : M ≤ non_zero_divisors R) {x : R} (hx : x ∈ non_zero_divisors R) : algebra_map R S x ≠ 0 := show (algebra_map R S).to_monoid_with_zero_hom x ≠ 0, from map_ne_zero_of_mem_non_zero_divisors (algebra_map R S) (is_localization.injective S hM) hx variables {S} lemma sec_snd_ne_zero [nontrivial R] (hM : M ≤ non_zero_divisors R) (x : S) : ((sec M x).snd : R) ≠ 0 := non_zero_divisors.coe_ne_zero ⟨(sec M x).snd.val, hM (sec M x).snd.property⟩ lemma sec_fst_ne_zero [nontrivial R] [no_zero_divisors S] (hM : M ≤ non_zero_divisors R) {x : S} (hx : x ≠ 0) : (sec M x).fst ≠ 0 := begin have hsec := sec_spec M x, intro hfst, rw [hfst, map_zero, mul_eq_zero, _root_.map_eq_zero_iff] at hsec, { exact or.elim hsec hx (sec_snd_ne_zero hM x) }, { exact is_localization.injective S hM } end variables (S M) (Q : Type*) [comm_ring Q] {g : R →+* P} [algebra P Q] /-- Injectivity of a map descends to the map induced on localizations. -/ lemma map_injective_of_injective (hg : function.injective g) [is_localization (M.map g : submonoid P) Q] : function.injective (map Q g M.le_comap_map : S → Q) := begin rw injective_iff_map_eq_zero, intros z hz, obtain ⟨a, b, rfl⟩ := mk'_surjective M z, rw [map_mk', mk'_eq_zero_iff] at hz, obtain ⟨⟨m', hm'⟩, hm⟩ := hz, rw submonoid.mem_map at hm', obtain ⟨n, hn, hnm⟩ := hm', rw [subtype.coe_mk, ← hnm, ← map_mul, ← map_zero g] at hm, rw [mk'_eq_zero_iff], exact ⟨⟨n, hn⟩, hg hm⟩, end variables {S Q M} variables (A : Type*) [comm_ring A] [is_domain A] /-- A `comm_ring` `S` which is the localization of an integral domain `R` at a subset of non-zero elements is an integral domain. See note [reducible non-instances]. -/ @[reducible] theorem is_domain_of_le_non_zero_divisors [algebra A S] {M : submonoid A} [is_localization M S] (hM : M ≤ non_zero_divisors A) : is_domain S := { eq_zero_or_eq_zero_of_mul_eq_zero := begin intros z w h, cases surj M z with x hx, cases surj M w with y hy, have : z * w * algebra_map A S y.2 * algebra_map A S x.2 = algebra_map A S x.1 * algebra_map A S y.1, by rw [mul_assoc z, hy, ←hx]; ring, rw [h, zero_mul, zero_mul, ← (algebra_map A S).map_mul] at this, cases eq_zero_or_eq_zero_of_mul_eq_zero ((to_map_eq_zero_iff S hM).mp this.symm) with H H, { exact or.inl (eq_zero_of_fst_eq_zero hx H) }, { exact or.inr (eq_zero_of_fst_eq_zero hy H) }, end, exists_pair_ne := ⟨(algebra_map A S) 0, (algebra_map A S) 1, λ h, zero_ne_one (is_localization.injective S hM h)⟩, } variables {A} /-- The localization at of an integral domain to a set of non-zero elements is an integral domain. See note [reducible non-instances]. -/ @[reducible] theorem is_domain_localization {M : submonoid A} (hM : M ≤ non_zero_divisors A) : is_domain (localization M) := is_domain_of_le_non_zero_divisors _ hM end is_localization open is_localization /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ lemma is_field.localization_map_bijective {R Rₘ : Type*} [comm_ring R] [comm_ring Rₘ] {M : submonoid R} (hM : (0 : R) ∉ M) (hR : is_field R) [algebra R Rₘ] [is_localization M Rₘ] : function.bijective (algebra_map R Rₘ) := begin letI := hR.to_field, replace hM := le_non_zero_divisors_of_no_zero_divisors hM, refine ⟨is_localization.injective _ hM, λ x, _⟩, obtain ⟨r, ⟨m, hm⟩, rfl⟩ := mk'_surjective M x, obtain ⟨n, hn⟩ := hR.mul_inv_cancel (non_zero_divisors.ne_zero $ hM hm), exact ⟨r * n, by erw [eq_mk'_iff_mul_eq, ←map_mul, mul_assoc, mul_comm n, hn, mul_one]⟩ end /-- If `R` is a field, then localizing at a submonoid not containing `0` adds no new elements. -/ lemma field.localization_map_bijective {K Kₘ : Type*} [field K] [comm_ring Kₘ] {M : submonoid K} (hM : (0 : K) ∉ M) [algebra K Kₘ] [is_localization M Kₘ] : function.bijective (algebra_map K Kₘ) := (field.to_is_field K).localization_map_bijective hM -- this looks weird due to the `letI` inside the above lemma, but trying to do it the other -- way round causes issues with defeq of instances, so this is actually easier. section algebra variables {R S} {Rₘ Sₘ : Type*} [comm_ring Rₘ] [comm_ring Sₘ] variables [algebra R Rₘ] [is_localization M Rₘ] variables [algebra S Sₘ] [is_localization (algebra.algebra_map_submonoid S M) Sₘ] section variables (S M) /-- Definition of the natural algebra induced by the localization of an algebra. Given an algebra `R → S`, a submonoid `R` of `M`, and a localization `Rₘ` for `M`, let `Sₘ` be the localization of `S` to the image of `M` under `algebra_map R S`. Then this is the natural algebra structure on `Rₘ → Sₘ`, such that the entire square commutes, where `localization_map.map_comp` gives the commutativity of the underlying maps -/ noncomputable def localization_algebra : algebra Rₘ Sₘ := (map Sₘ (algebra_map R S) (show _ ≤ (algebra.algebra_map_submonoid S M).comap _, from M.le_comap_map) : Rₘ →+* Sₘ).to_algebra end lemma algebra_map_mk' (r : R) (m : M) : (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) (mk' Rₘ r m) = mk' Sₘ (algebra_map R S r) ⟨algebra_map R S m, algebra.mem_algebra_map_submonoid_of_mem m⟩ := map_mk' _ _ _ variables (Rₘ Sₘ) /-- Injectivity of the underlying `algebra_map` descends to the algebra induced by localization. -/ lemma localization_algebra_injective (hRS : function.injective (algebra_map R S)) : function.injective (@algebra_map Rₘ Sₘ _ _ (localization_algebra M S)) := is_localization.map_injective_of_injective M Rₘ Sₘ hRS end algebra end comm_ring
3c8eb0ca0f9e5e5549c145d38e83cddcded094f2
274261f7150b4ed5f1962f172c9357591be8a2b5
/src/Module.lean
163c269ff5a1f73a5d3584c6ae8b9c3acad1890b
[]
no_license
rspencer01/lean_representation_theory
219ea1edf4b9897b2997226b54473e44e1538b50
2eef2b4b39d99d7ce71bec7bbc3dcc2f7586fcb5
refs/heads/master
1,588,133,157,029
1,571,689,957,000
1,571,689,957,000
175,835,785
0
0
null
null
null
null
UTF-8
Lean
false
false
2,796
lean
import algebra.module import algebra.punit_instances import category_theory.types import linear_algebra.basic universe u open category_theory variables (R : Type u) [ring R] /-- An example of a module for any ring is the zero module -/ instance zero_module : module R punit := module.of_core $ by refine { smul := λ _ _, punit.star, .. punit.comm_ring, ..}; intros; exact subsingleton.elim _ _ /-- The category of R-modules and their morphisms. -/ structure Module := (carrier : Type) (prop_add_comm_group : add_comm_group carrier) (prop_module : module R carrier) lemma id_is_linear (M : Type) [add_comm_group M] [module R M] : is_linear_map R (@id M) := { add := λ x y, (by repeat {apply id.def}), smul := λ c x, (by repeat {apply id.def}), } lemma linear_maps_comp (A B C : Type) [add_comm_group A] [module R A] [add_comm_group B] [module R B] [add_comm_group C] [module R C] (f : A → B) (g : B → C) (h₁ : is_linear_map R f) (h₂ : is_linear_map R g) : is_linear_map R (g ∘ f) := { add := λ x y, (by simp; rw is_linear_map.add R f; rw is_linear_map.add R g), smul := λ c x, (by simp; rw is_linear_map.smul f c; rw is_linear_map.smul g c) } namespace Module instance : has_coe_to_sort (Module R) := { S := Type, coe := Module.carrier} end Module instance Module_add_comm_group (M: Module R) : add_comm_group M := M.prop_add_comm_group instance Module_R_module (M: Module R) : module R M := M.prop_module namespace Module def of (X : Type) [h₁ : add_comm_group X] [h₂ : module R X] : Module R := ⟨ X , h₁ , h₂⟩ instance : has_zero (Module R) := ⟨ of R punit ⟩ variables (M N U : Module R) instance : category (Module R) := { hom := λ M N, M →ₗ[R] N, id := λ M, 1 , comp := λ A B C f g, g.comp f , } @[simp] lemma module_id : linear_map.to_fun (𝟙 M) = id := rfl @[simp] lemma module_hom_comp (f : M ⟶ N) (g : N ⟶ U) : ((f ≫ g) : M → U) = g.to_fun ∘ f.to_fun := rfl instance : has_coe_to_fun (M ⟶ N) := { F := λ f, M → N, coe := λ f, (f : M → N) } @[extensionality] lemma hom_ext {f g : M ⟶ N} : (∀ x : M, f x = g x) → f = g := λ w, linear_map.ext w @[extensionality] lemma hom_ext' {f g : M ⟶ N} : (f : M → N) = g → f = g := λ w, hom_ext R M N (function.funext_iff.1 w) @[simp] lemma coe_id {M : Module R} : ((𝟙 M) : M → M) = id := rfl instance hom_is_module_hom {M₁ M₂ : Module R} (f : M₁ ⟶ M₂) : is_linear_map R (f : M₁ → M₂) := linear_map.is_linear _ end Module instance (M : Type) [add_comm_group M] [module R M] : has_coe (submodule R M) (Module R) := ⟨ λ N, Module.of R N ⟩ def are_isomorphic {R} [ring R] (M₁ M₂ : Module R) := nonempty (M₁ ≅ M₂)
199cf0859e250b7bdb26e99fba484a7e7ffe4692
71c62298fd72620ddff9e4ed896ca29a77073a7c
/thm.lean
ade2934c097b84e448dee4c89cf700d7eb2d605c
[]
no_license
BelegCuthalion/lean-exc
dcfe8e4c2293a661a830ce06f5fa032563901ec6
9143dc8b8aac62b9b2dcee85b619fe5c2e2a7144
refs/heads/master
1,688,507,036,780
1,627,883,419,000
1,627,883,419,000
335,643,688
3
2
null
null
null
null
UTF-8
Lean
false
false
1,696
lean
namespace exc theorem and_comm {P Q : Prop} : P ∧ Q → Q ∧ P := begin assume h : P ∧ Q, have hp : P, from h.left, have hq : Q, from h.right, show Q ∧ P, from and.intro hq hp end theorem and_comm_1 {P Q : Prop} : P ∧ Q → Q ∧ P := fun x : P ∧ Q , and.intro x.right x.left theorem or_comm (P Q : Prop) : P ∨ Q → Q ∨ P := begin assume h : P ∨ Q, cases h with hp hq, right, exact hp, left, exact hq end theorem or_elim_0 (p q r : Prop) : (p ∨ q) → (p → r) → (q → r) → r := begin assume poq : p ∨ q, assume par : p → r, assume qar : q → r, cases poq with hp hq, show r, from par(hp), show r, from qar(hq) end variable S : Type variable P : S -> S -> Prop example : (∃ x : S, ∀ y : S, P x y) -> (∀ x : S, ∃ y : S, P y x) := begin intro h, intro x, cases h with x0, existsi x0, exact (h_h x), end theorem contrapostition (R Q : Prop) : (R → Q) → ¬ Q → ¬ R := begin assume h0, assume h1, assume h2, exact h1(h0(h2)) end theorem id_S : S → S := fun (x : S), x theorem transitivity (P Q R : Prop) : (P → Q) → (Q → R) → P → R := begin assume pq, assume qr, assume p, exact qr (pq p) end theorem transitivity_0 (P Q R : Prop) : (P → Q) → (Q → R) → P → R := fun pq : P → Q, fun qr : Q → R, fun p : P, qr (pq p) variable R : Prop variable r : R variable Q : Prop variable q : Q example : R ∨ Q := or.inl r example : R ∨ Q := or.inr q example (P Q : Prop) : (P ∧ Q) → (P ∨ Q) := fun pq : P ∧ Q, or.inl pq.left example (P Q : Prop) : (P ∧ Q) → (P ∨ Q) := fun pq : P ∧ Q, or.inr pq.right end exc
bd7e08ecadb45fd4e61a14c2b0c56c7df4862d0a
1fd908b06e3f9c1252cb2285ada1102623a67f72
/init/meta/simp.lean
bcdbb5bbdd970f3e4cd2f85031570fde8300f126
[ "Apache-2.0" ]
permissive
avigad/hott3
609a002849182721e7c7ae536d9f1e2956d6d4d3
f64750cd2de7a81e87d4828246d1369d59f16f43
refs/heads/master
1,629,027,243,322
1,510,946,717,000
1,510,946,717,000
103,570,461
0
0
null
1,505,415,620,000
1,505,415,620,000
null
UTF-8
Lean
false
false
4,670
lean
/- Copyright (c) 2017 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .rewrite open tactic expr namespace hott meta def simplify_plus_d (s : simp_lemmas) (to_unfold : list name := []) (e : expr) (cfg : simp_config := {}) (r : name := ``hott.eq) (discharger : tactic unit := failed) : tactic (expr × expr) := do ((), e', pr) ← ext_simplify_core () cfg s (λ _, discharger) (λ _ s r p e, do e' ← s.dsimplify to_unfold e { cfg with unfold_reducible := ff, md := reducible, fail_if_unchanged := ff }, return ((), e', none, true)) (λ a s r p e, do guard $ r ≠ ``_root_.eq ∧ r ≠ ``_root_.heq, (e', pr) ← s.rewrite e discharger r semireducible, return ((), e', pr, e ≠ e')) r e, return (e', pr) meta def replace_target (new_tgt prf : expr) : tactic unit := do prf ← mk_eq_inv prf, tgt ← target, mk_mapp ``hott.eq.cast [new_tgt, tgt, prf] >>= apply meta def hsimp_target (s : simp_lemmas) (to_unfold : list name := []) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic unit := do t ← target, (new_t, pr) ← simplify_plus_d s to_unfold t {cfg with lift_eq := ff} ``hott.eq discharger, replace_target new_t pr end hott namespace tactic open interactive.types interactive open hott namespace interactive meta def hsimp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic unit := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, (do (new_h_type, pr) ← simplify_plus_d s u h_type cfg ``hott.eq discharger, assert h.local_pp_name new_h_type, mk_app ``hott.eq.cast [pr, h] >>= tactic.exact >> return tt) <|> (return ff) }, goal_simplified ← if tgt then (hsimp_target s u cfg discharger >> return tt) <|> (return ff) else return ff, guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify", to_remove.mmap' (λ h, try (tactic.clear h)) meta def hsimp_core (cfg : simp_config) (discharger : tactic unit) (no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name) (locat : loc) : tactic unit := match locat with | loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt, if all_hyps then fail "hsimp does not support `at *` yet" --tactic.hsimp_all s u cfg discharger else do hyps ← local_context, hsimp_core_aux cfg discharger s u hyps tt | _ := do (s, u) ← mk_simp_set no_dflt attr_names hs, ns ← locat.get_locals, hsimp_core_aux cfg discharger s u ns locat.include_goal end >> try tactic.triv >> try (tactic.reflexivity reducible) /-- This tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. - `hsimp` simplifies the main goal target using lemmas tagged with the attribute `[hsimp]`. - `hsimp [h_1, ..., h_n]` simplifies the main goal target using the lemmas tagged with the attribute `[hsimp]` and the given `h_i`s. The `h_i`'s are terms. If a `h_i` is a definition `f`, then the equational lemmas associated with `f` are used. This is a convenient way to "unfold" `f`. - `hsimp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[hsimp]` and all hypotheses. Remark: `hsimp *` is a shorthand for `hsimp [*]`. - `hsimp only [h_1, ..., h_n]` is like `hsimp [h_1, ..., h_n]` but does not use `[hsimp]` lemmas - `hsimp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[hsimp]`, but removes the ones named `id_i`s. - `hsimp at h_1 ... h_n` simplifies the non dependent hypotheses `h_1 : T_1` ... `h_n : T : n`. The tactic fails if the target or another hypothesis depends on one of them. - `hsimp at *` simplifies all the hypotheses and the target. - `hsimp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses. - `hsimp with attr_1 ... attr_n` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr_1]`, ..., `[attr_n]` or `[hsimp]`. -/ meta def hsimp (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (locat : parse location) (cfg : simp_config_ext := {}) : tactic unit := hsimp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat end interactive end tactic
a838915cbde34f0130de77c22a238082dc16b3e7
3f7cd10697c47d2f635213127d8d459a1271195a
/modal.lean
431045e6362af514ae5832405d8d81f266f4c19f
[ "MIT" ]
permissive
alexpatel/lean-modal
d84eb95646fca90c49fab7e00f92b56d80bd6096
6d92403347b345641aca7b72355f81e8ac46587d
refs/heads/master
1,609,475,326,244
1,503,254,773,000
1,503,254,773,000
97,183,742
10
1
null
null
null
null
UTF-8
Lean
false
false
3,511
lean
namespace modal open classical universe u -- possible world type variable {world : Type u} -- accessibility relation type variable {r : world → world → Prop} -- modal proposition type, lifted over Prop -- a predicate saying whether a given proposition is true in a particular world def σ : Type u := world → Prop -- true, false def mtop := λ w : world, true def mbot := λ w : world, false -- modal connectives def mnot (p : σ) (w : world) : Prop := ¬ (p w) def mand (p₁ p₂ : σ) (w : world) : Prop := p₁ w ∧ p₂ w def mor (p₁ p₂ : σ) (w : world) : Prop := p₁ w ∨ p₂ w def mimplies (p₁ p₂ : σ) (w : world) : Prop := (p₁ w) → (p₂ w) def mequiv (p₁ p₂ : σ) (w : world) : Prop := (p₁ w) ↔ (p₂ w) -- modal quantifiers def mall {α : Type u} (p: α → σ) (w : world) : Prop := ∀ x : α, p x w def mexists {α : Type u} (p: α → σ) (w : world) : Prop := ∃ x : α, p x w -- modal operators def mbox (p : σ) := λ w₁ : world, ∀ w₂ : world, (r w₁ w₂) → (p w₂) def mdia (p : σ) := λ w₁ : world, ∃ w₂ : world, (r w₁ w₂) ∧ (p w₂) -- validity def mvalid (p : σ) := ∀ w : world, p w -- notation mirroring standard operators/quantifiers notation `m¬` p := mnot p infix `m∧`:50 := mand infix `m∨`:50 := mor infix `m→`:50 := mimplies infix `m↔`:50 := mequiv notation `m∀` x, p := mall (λ x, p) notation `m∃` x, p := mexists (λ x, p) notation `□` p := mbox p notation `♢` p := mdia p notation `[` p `]` := mvalid p #check σ #check mnot #check mand #check mor #check mimplies #check mequiv #check mall #check mexists #check mbox #check mdia #check mvalid end modal namespace test open modal #check mnot #check σ universe v constants w₁ α : Type v constant r₁ : w₁ → w₁ → Prop constants p q : w₁ → Prop #check m¬ p #check p m∧ q #check p m→ q #check p m↔ q #check □ p #check ♢ p #check m∀ w, p w #check ∀ w : w₁, p w #check ∃ w, p w #check ∃ w : w₁, p w axiom r_reflex : ∀ w, r₁ w w axiom r_trans : ∀ x y z : w₁, (r₁ x y) → (r₁ y z) → (r₁ x z) axiom r_symm : ∀ x y : w₁, (r₁ x y) → (r₁ y x) #check r_reflex #check r_trans #check r_trans end test namespace exmp open modal constants world : Type constant M : world → Prop constant r : world → world → Prop constants p q : world → Prop variables x₁ x₂ x₃ x₄ x₅ x₆ : world axiom kripe_example : (r x₁ x₂) ∧ (r x₁ x₃) ∧ (r x₂ x₃) ∧ (r x₃ x₂) ∧ (r x₂ x₃) ∧ (r x₃ x₃) ∧ (r x₂ x₂) ∧ (r x₃ x₃) ∧ (r x₅ x₄) ∧ (r x₅ x₆) ∧ ¬ (p x₁) ∧ (q x₁) ∧ (p x₂) ∧ (q x₂) ∧ (p x₃) ∧ ¬ (q x₃) ∧ ¬ (p x₄) ∧ (q x₄) ∧ ¬ (p x₅) ∧ ¬ (q x₅) ∧ (p x₆) ∧ ¬ (q x₆) #check mdia #check (mdia p) x₁ #check (♢ p) x₁ theorem prop_1 : p x₁ := sorry theorem forall_1 : ∀ w : world, p w := sorry theorem exists_1 : ∃ w : world, p w := sorry -- test diamond theorem dia_1 : ∃ w₂ : world, (r x₁ w₂) ∧ (p w₂) theorem dia_2 : (♢ p) x₁ := sorry -- why does this not work... -- test box theorem box_1 : ∀ w₂ : world, (r x₁ w₂) → (p w₂) theorem box_1 : (□ p) x₁ := sorry -- why does this not work... end exmp
25590988c41b9107b990c0e7bcf9c13d34ea407d
1446f520c1db37e157b631385707cc28a17a595e
/src/Init/Lean/Elab/Declaration.lean
abf85a2bc73f5d9591a58480fac461358bec35d1
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,353
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 -/ prelude import Init.Lean.Util.CollectLevelParams import Init.Lean.Elab.Definition namespace Lean namespace Elab namespace Command def expandOptDeclSig (stx : Syntax) : Syntax × Option Syntax := -- many Term.bracktedBinder >> Term.optType let binders := stx.getArg 0; let optType := stx.getArg 1; -- optional (parser! " : " >> termParser) if optType.isNone then (binders, none) else let typeSpec := optType.getArg 0; (binders, some $ typeSpec.getArg 1) def expandDeclSig (stx : Syntax) : Syntax × Syntax := -- many Term.bracktedBinder >> Term.typeSpec let binders := stx.getArg 0; let typeSpec := stx.getArg 1; (binders, typeSpec.getArg 1) def elabAbbrev (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := -- parser! "abbrev " >> declId >> optDeclSig >> declVal let (binders, type) := expandOptDeclSig (stx.getArg 2); let modifiers := modifiers.addAttribute { name := `inline }; let modifiers := modifiers.addAttribute { name := `reducible }; elabDefLike { ref := stx, kind := DefKind.def, modifiers := modifiers, declId := stx.getArg 1, binders := binders, type? := type, val := stx.getArg 3 } def elabDef (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := -- parser! "def " >> declId >> optDeclSig >> declVal let (binders, type) := expandOptDeclSig (stx.getArg 2); elabDefLike { ref := stx, kind := DefKind.def, modifiers := modifiers, declId := stx.getArg 1, binders := binders, type? := type, val := stx.getArg 3 } def elabTheorem (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := -- parser! "theorem " >> declId >> declSig >> declVal let (binders, type) := expandDeclSig (stx.getArg 2); elabDefLike { ref := stx, kind := DefKind.theorem, modifiers := modifiers, declId := stx.getArg 1, binders := binders, type? := some type, val := stx.getArg 3 } def elabConstant (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- parser! "constant " >> declId >> declSig >> optional declValSimple let (binders, type) := expandDeclSig (stx.getArg 2); val ← match (stx.getArg 3).getOptional? with | some val => pure val | none => do { val ← `(arbitrary _); pure $ Syntax.node `Lean.Parser.Command.declValSimple #[ mkAtomFrom stx ":=", val ] }; elabDefLike { ref := stx, kind := DefKind.opaque, modifiers := modifiers, declId := stx.getArg 1, binders := binders, type? := some type, val := val } def elabInstance (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- parser! "instance " >> optional declId >> declSig >> declVal let (binders, type) := expandDeclSig (stx.getArg 2); let modifiers := modifiers.addAttribute { name := `instance }; declId ← match (stx.getArg 1).getOptional? with | some declId => pure declId | none => throwError stx "not implemented yet"; elabDefLike { ref := stx, kind := DefKind.def, modifiers := modifiers, declId := declId, binders := binders, type? := type, val := stx.getArg 3 } def elabExample (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := -- parser! "example " >> declSig >> declVal let (binders, type) := expandDeclSig (stx.getArg 1); let id := mkIdentFrom stx `_example; let declId := Syntax.node `Lean.Parser.Command.declId #[id, mkNullNode]; elabDefLike { ref := stx, kind := DefKind.example, modifiers := modifiers, declId := declId, binders := binders, type? := some type, val := stx.getArg 2 } def elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := -- parser! "axiom " >> declId >> declSig let declId := stx.getArg 1; let (binders, typeStx) := expandDeclSig (stx.getArg 2); withDeclId declId $ fun name => do declName ← mkDeclName modifiers name; applyAttributes stx declName modifiers.attrs AttributeApplicationTime.beforeElaboration; explictLevelNames ← getLevelNames; decl ← runTermElabM declName $ fun vars => Term.elabBinders binders.getArgs $ fun xs => do { type ← Term.elabType typeStx; Term.synthesizeSyntheticMVars false; type ← Term.instantiateMVars typeStx type; type ← Term.mkForall typeStx xs type; (type, _) ← Term.mkForallUsedOnly typeStx vars type; type ← Term.levelMVarToParam type; let usedParams := (collectLevelParams {} type).params; let levelParams := sortDeclLevelParams explictLevelNames usedParams; pure $ Declaration.axiomDecl { name := declName, lparams := levelParams, type := type, isUnsafe := modifiers.isUnsafe } }; addDecl stx decl; applyAttributes stx declName modifiers.attrs AttributeApplicationTime.afterTypeChecking; applyAttributes stx declName modifiers.attrs AttributeApplicationTime.afterCompilation def elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := pure () -- TODO def elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := pure () -- TODO def elabStructure (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := pure () -- TODO @[builtinCommandElab declaration] def elabDeclaration : CommandElab := fun stx => do modifiers ← elabModifiers (stx.getArg 0); let decl := stx.getArg 1; let declKind := decl.getKind; if declKind == `Lean.Parser.Command.abbrev then elabAbbrev modifiers decl else if declKind == `Lean.Parser.Command.def then elabDef modifiers decl else if declKind == `Lean.Parser.Command.theorem then elabTheorem modifiers decl else if declKind == `Lean.Parser.Command.constant then elabConstant modifiers decl else if declKind == `Lean.Parser.Command.instance then elabInstance modifiers decl else if declKind == `Lean.Parser.Command.axiom then elabAxiom modifiers decl else if declKind == `Lean.Parser.Command.example then elabExample modifiers decl else if declKind == `Lean.Parser.Command.inductive then elabInductive modifiers decl else if declKind == `Lean.Parser.Command.classInductive then elabClassInductive modifiers decl else if declKind == `Lean.Parser.Command.structure then elabStructure modifiers decl else throwError stx "unexpected declaration" end Command end Elab end Lean
48ab12eedeaae037c0e04e177d7ce7f8b094d3a7
618003631150032a5676f229d13a079ac875ff77
/src/order/complete_boolean_algebra.lean
c6c91027715497eeb62ba5b77636c963ee0ab509
[ "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
4,667
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 Theory of complete Boolean algebras. -/ import order.complete_lattice import order.boolean_algebra set_option old_structure_cmd true universes u v w variables {α : Type u} {β : Type v} {ι : Sort w} section prio set_option default_priority 100 -- see Note [default priority] /-- A complete distributive lattice is a bit stronger than the name might suggest; perhaps completely distributive lattice is more descriptive, as this class includes a requirement that the lattice join distribute over *arbitrary* infima, and similarly for the dual. -/ class complete_distrib_lattice α extends complete_lattice α := (infi_sup_le_sup_Inf : ∀a s, (⨅ b ∈ s, a ⊔ b) ≤ a ⊔ Inf s) (inf_Sup_le_supr_inf : ∀a s, a ⊓ Sup s ≤ (⨆ b ∈ s, a ⊓ b)) end prio section complete_distrib_lattice variables [complete_distrib_lattice α] {a b : α} {s t : set α} theorem sup_Inf_eq : a ⊔ Inf s = (⨅ b ∈ s, a ⊔ b) := le_antisymm (le_infi $ assume i, le_infi $ assume h, sup_le_sup_left (Inf_le h) _) (complete_distrib_lattice.infi_sup_le_sup_Inf _ _) theorem Inf_sup_eq : Inf s ⊔ b = (⨅ a ∈ s, a ⊔ b) := by simpa [sup_comm] using @sup_Inf_eq α _ b s theorem inf_Sup_eq : a ⊓ Sup s = (⨆ b ∈ s, a ⊓ b) := le_antisymm (complete_distrib_lattice.inf_Sup_le_supr_inf _ _) (supr_le $ assume i, supr_le $ assume h, inf_le_inf_left _ (le_Sup h)) theorem Sup_inf_eq : Sup s ⊓ b = (⨆ a ∈ s, a ⊓ b) := by simpa [inf_comm] using @inf_Sup_eq α _ b s theorem Inf_sup_Inf : Inf s ⊔ Inf t = (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) := begin apply le_antisymm, { finish }, { have : ∀ a ∈ s, (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) ≤ a ⊔ Inf t, { assume a ha, have : (⨅p ∈ set.prod s t, ((p : α × α).1 : α) ⊔ p.2) ≤ (⨅p ∈ prod.mk a '' t, (p : α × α).1 ⊔ p.2), { apply infi_le_infi_of_subset, rintros ⟨x, y⟩, simp only [and_imp, set.mem_image, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq, exists_imp_distrib], assume x' x't ax x'y, rw [← x'y, ← ax], simp [ha, x't] }, rw [infi_image] at this, simp only [] at this, rwa ← sup_Inf_eq at this }, calc (⨅p ∈ set.prod s t, (p : α × α).1 ⊔ p.2) ≤ (⨅a∈s, a ⊔ Inf t) : by simp; exact this ... = Inf s ⊔ Inf t : Inf_sup_eq.symm } end theorem Sup_inf_Sup : Sup s ⊓ Sup t = (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2) := begin apply le_antisymm, { have : ∀ a ∈ s, a ⊓ Sup t ≤ (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2), { assume a ha, have : (⨆p ∈ prod.mk a '' t, (p : α × α).1 ⊓ p.2) ≤ (⨆p ∈ set.prod s t, ((p : α × α).1 : α) ⊓ p.2), { apply supr_le_supr_of_subset, rintros ⟨x, y⟩, simp only [and_imp, set.mem_image, prod.mk.inj_iff, set.prod_mk_mem_set_prod_eq, exists_imp_distrib], assume x' x't ax x'y, rw [← x'y, ← ax], simp [ha, x't] }, rw [supr_image] at this, simp only [] at this, rwa ← inf_Sup_eq at this }, calc Sup s ⊓ Sup t = (⨆a∈s, a ⊓ Sup t) : Sup_inf_eq ... ≤ (⨆p ∈ set.prod s t, (p : α × α).1 ⊓ p.2) : by simp; exact this }, { finish } end end complete_distrib_lattice @[priority 100] -- see Note [lower instance priority] instance complete_distrib_lattice.bounded_distrib_lattice [d : complete_distrib_lattice α] : bounded_distrib_lattice α := { le_sup_inf := λ x y z, by rw [← Inf_pair, ← Inf_pair, sup_Inf_eq, ← Inf_image, set.image_pair], ..d } section prio set_option default_priority 100 -- see Note [default priority] /-- A complete boolean algebra is a completely distributive boolean algebra. -/ class complete_boolean_algebra α extends boolean_algebra α, complete_distrib_lattice α end prio section complete_boolean_algebra variables [complete_boolean_algebra α] {a b : α} {s : set α} {f : ι → α} theorem compl_infi : - infi f = (⨆i, - f i) := le_antisymm (compl_le_of_compl_le $ le_infi $ assume i, compl_le_of_compl_le $ le_supr (λi, - f i) i) (supr_le $ assume i, compl_le_compl $ infi_le _ _) theorem compl_supr : - supr f = (⨅i, - f i) := compl_inj (by simp [compl_infi]) theorem compl_Inf : - Inf s = (⨆i∈s, - i) := by simp [Inf_eq_infi, compl_infi] theorem compl_Sup : - Sup s = (⨅i∈s, - i) := by simp [Sup_eq_supr, compl_supr] end complete_boolean_algebra
ffd27aa3a0365c2d539232ab7d086a6a9c1f6669
f1dc39e1c68f71465c8bf79910c4664d03824751
/tests/lean/simp_symm.lean
4cd31e1304b7c8040c6c0bd8d4e97d3369143190
[ "Apache-2.0" ]
permissive
kckennylau/lean-2
6504f45da07bc98b098d726b74130103be25885c
c9a9368bc0fd600d832bd56c5cb2124b8a523ef9
refs/heads/master
1,659,140,308,864
1,589,361,166,000
1,589,361,166,000
263,748,786
0
0
null
1,589,405,915,000
1,589,405,915,000
null
UTF-8
Lean
false
false
1,142
lean
constants f g : nat → nat -- Test `simp` with lemmas in reverse direction axiom f_id : ∀ x, f x = x axiom f_g : ∀ x, f x = g x example (a : nat) : g a = a := by simp [←f_g, f_id] -- works -- Alternate syntax: example (a : nat) : g a = a := by simp [<-f_g, f_id] -- works -- Universe polymorphic lemmas work: universe u variable {α : Type u} constants fu gu : α → α axiom fu_id : ∀ (x : α), fu x = id x axiom fu_gu : ∀ (x : α), fu x = gu x example (a : nat) : gu a = a := by simp [←fu_gu, fu_id] -- works -- Reverse direction also works for `↔` constants p q : α → Prop axiom pq : ∀ (x : α), p x ↔ q x example (a : nat) (h : p a) : q a := by { simp [←pq], assumption } section reverse_conflict open interactive open tactic.interactive open tactic.simp_arg_type def op : nat → nat → nat := sorry @[simp] lemma op_assoc (a b c : nat) : op (op a b) c = op a (op b c) := sorry example (a b c : nat) : op (op a b) c = op a (op b c) := by tactic.try_for 1000 `[ simp [← op_assoc] ] example (a b c : nat) : a + b + c = a + (b + c) := by tactic.try_for 1000 `[ simp [← add_assoc] ] end reverse_conflict
988ce43a433e567ba5ea7129c69e14215d1181ad
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/monoid/canonical/defs.lean
752f4f8ec5cc8aaa1669948860f34a833f92b596
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
10,339
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 order.bounded_order import order.min_max import algebra.ne_zero import algebra.order.monoid.defs /-! # Canonically ordered monoids > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/778 > Any changes to this file require a corresponding PR to mathlib4. -/ universe u variables {α : Type u} set_option old_structure_cmd true /-- An `ordered_comm_monoid` with one-sided 'division' in the sense that if `a ≤ b`, there is some `c` for which `a * c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_monoid`. -/ class has_exists_mul_of_le (α : Type u) [has_mul α] [has_le α] : Prop := (exists_mul_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a * c) /-- An `ordered_add_comm_monoid` with one-sided 'subtraction' in the sense that if `a ≤ b`, then there is some `c` for which `a + c = b`. This is a weaker version of the condition on canonical orderings defined by `canonically_ordered_add_monoid`. -/ class has_exists_add_of_le (α : Type u) [has_add α] [has_le α] : Prop := (exists_add_of_le : ∀ {a b : α}, a ≤ b → ∃ (c : α), b = a + c) attribute [to_additive] has_exists_mul_of_le export has_exists_mul_of_le (exists_mul_of_le) export has_exists_add_of_le (exists_add_of_le) @[priority 100, to_additive] -- See note [lower instance priority] instance group.has_exists_mul_of_le (α : Type u) [group α] [has_le α] : has_exists_mul_of_le α := ⟨λ a b hab, ⟨a⁻¹ * b, (mul_inv_cancel_left _ _).symm⟩⟩ section mul_one_class variables [mul_one_class α] [preorder α] [contravariant_class α α (*) (<)] [has_exists_mul_of_le α] {a b : α} @[to_additive] lemma exists_one_lt_mul_of_lt' (h : a < b) : ∃ c, 1 < c ∧ a * c = b := by { obtain ⟨c, rfl⟩ := exists_mul_of_le h.le, exact ⟨c, one_lt_of_lt_mul_right h, rfl⟩ } end mul_one_class section has_exists_mul_of_le variables [linear_order α] [densely_ordered α] [monoid α] [has_exists_mul_of_le α] [covariant_class α α (*) (<)] [contravariant_class α α (*) (<)] {a b : α} @[to_additive] lemma le_of_forall_one_lt_le_mul (h : ∀ ε : α, 1 < ε → a ≤ b * ε) : a ≤ b := le_of_forall_le_of_dense $ λ x hxb, by { obtain ⟨ε, rfl⟩ := exists_mul_of_le hxb.le, exact h _ ((lt_mul_iff_one_lt_right' b).1 hxb) } @[to_additive] lemma le_of_forall_one_lt_lt_mul' (h : ∀ ε : α, 1 < ε → a < b * ε) : a ≤ b := le_of_forall_one_lt_le_mul $ λ ε hε, (h _ hε).le @[to_additive] lemma le_iff_forall_one_lt_lt_mul' : a ≤ b ↔ ∀ ε, 1 < ε → a < b * ε := ⟨λ h ε, lt_mul_of_le_of_one_lt h, le_of_forall_one_lt_lt_mul'⟩ end has_exists_mul_of_le /-- A canonically ordered additive monoid is an ordered commutative additive monoid in which the ordering coincides with the subtractibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a + c`. This is satisfied by the natural numbers, for example, but not the integers or other nontrivial `ordered_add_comm_group`s. -/ @[protect_proj, ancestor ordered_add_comm_monoid has_bot] class canonically_ordered_add_monoid (α : Type*) extends ordered_add_comm_monoid α, has_bot α := (bot_le : ∀ x : α, ⊥ ≤ x) (exists_add_of_le : ∀ {a b : α}, a ≤ b → ∃ c, b = a + c) (le_self_add : ∀ a b : α, a ≤ a + b) @[priority 100] -- see Note [lower instance priority] instance canonically_ordered_add_monoid.to_order_bot (α : Type u) [h : canonically_ordered_add_monoid α] : order_bot α := { ..h } /-- A canonically ordered monoid is an ordered commutative monoid in which the ordering coincides with the divisibility relation, which is to say, `a ≤ b` iff there exists `c` with `b = a * c`. Examples seem rare; it seems more likely that the `order_dual` of a naturally-occurring lattice satisfies this than the lattice itself (for example, dual of the lattice of ideals of a PID or Dedekind domain satisfy this; collections of all things ≤ 1 seem to be more natural that collections of all things ≥ 1). -/ @[protect_proj, ancestor ordered_comm_monoid has_bot, to_additive] class canonically_ordered_monoid (α : Type*) extends ordered_comm_monoid α, has_bot α := (bot_le : ∀ x : α, ⊥ ≤ x) (exists_mul_of_le : ∀ {a b : α}, a ≤ b → ∃ c, b = a * c) (le_self_mul : ∀ a b : α, a ≤ a * b) @[priority 100, to_additive] -- see Note [lower instance priority] instance canonically_ordered_monoid.to_order_bot (α : Type u) [h : canonically_ordered_monoid α] : order_bot α := { ..h } @[priority 100, to_additive] -- see Note [lower instance priority] instance canonically_ordered_monoid.has_exists_mul_of_le (α : Type u) [h : canonically_ordered_monoid α] : has_exists_mul_of_le α := { ..h } section canonically_ordered_monoid variables [canonically_ordered_monoid α] {a b c d : α} @[to_additive] lemma le_self_mul : a ≤ a * c := canonically_ordered_monoid.le_self_mul _ _ @[to_additive] lemma le_mul_self : a ≤ b * a := by { rw mul_comm, exact le_self_mul } @[to_additive] lemma self_le_mul_right (a b : α) : a ≤ a * b := le_self_mul @[to_additive] lemma self_le_mul_left (a b : α) : a ≤ b * a := le_mul_self @[to_additive] lemma le_of_mul_le_left : a * b ≤ c → a ≤ c := le_self_mul.trans @[to_additive] lemma le_of_mul_le_right : a * b ≤ c → b ≤ c := le_mul_self.trans @[to_additive] lemma le_iff_exists_mul : a ≤ b ↔ ∃ c, b = a * c := ⟨exists_mul_of_le, by { rintro ⟨c, rfl⟩, exact le_self_mul }⟩ @[to_additive] lemma le_iff_exists_mul' : a ≤ b ↔ ∃ c, b = c * a := by simpa only [mul_comm _ a] using le_iff_exists_mul @[simp, to_additive zero_le] lemma one_le (a : α) : 1 ≤ a := le_iff_exists_mul.mpr ⟨a, (one_mul _).symm⟩ @[to_additive] lemma bot_eq_one : (⊥ : α) = 1 := le_antisymm bot_le (one_le ⊥) @[simp, to_additive] lemma mul_eq_one_iff : a * b = 1 ↔ a = 1 ∧ b = 1 := mul_eq_one_iff' (one_le _) (one_le _) @[simp, to_additive] lemma le_one_iff_eq_one : a ≤ 1 ↔ a = 1 := (one_le a).le_iff_eq @[to_additive] lemma one_lt_iff_ne_one : 1 < a ↔ a ≠ 1 := (one_le a).lt_iff_ne.trans ne_comm @[to_additive] lemma eq_one_or_one_lt : a = 1 ∨ 1 < a := (one_le a).eq_or_lt.imp_left eq.symm @[simp, to_additive add_pos_iff] lemma one_lt_mul_iff : 1 < a * b ↔ 1 < a ∨ 1 < b := by simp only [one_lt_iff_ne_one, ne.def, mul_eq_one_iff, not_and_distrib] @[to_additive] lemma exists_one_lt_mul_of_lt (h : a < b) : ∃ c (hc : 1 < c), a * c = b := begin obtain ⟨c, hc⟩ := le_iff_exists_mul.1 h.le, refine ⟨c, one_lt_iff_ne_one.2 _, hc.symm⟩, rintro rfl, simpa [hc, lt_irrefl] using h end @[to_additive] lemma le_mul_left (h : a ≤ c) : a ≤ b * c := calc a = 1 * a : by simp ... ≤ b * c : mul_le_mul' (one_le _) h @[to_additive] lemma le_mul_right (h : a ≤ b) : a ≤ b * c := calc a = a * 1 : by simp ... ≤ b * c : mul_le_mul' h (one_le _) @[to_additive] lemma lt_iff_exists_mul [covariant_class α α (*) (<)] : a < b ↔ ∃ c > 1, b = a * c := begin simp_rw [lt_iff_le_and_ne, and_comm, le_iff_exists_mul, ← exists_and_distrib_left, exists_prop], apply exists_congr, intro c, rw [and.congr_left_iff, gt_iff_lt], rintro rfl, split, { rw [one_lt_iff_ne_one], apply mt, rintro rfl, rw [mul_one] }, { rw [← (self_le_mul_right a c).lt_iff_ne], apply lt_mul_of_one_lt_right' } end end canonically_ordered_monoid lemma pos_of_gt {M : Type*} [canonically_ordered_add_monoid M] {n m : M} (h : n < m) : 0 < m := lt_of_le_of_lt (zero_le _) h namespace ne_zero lemma pos {M} (a : M) [canonically_ordered_add_monoid M] [ne_zero a] : 0 < a := (zero_le a).lt_of_ne $ ne_zero.out.symm lemma of_gt {M} [canonically_ordered_add_monoid M] {x y : M} (h : x < y) : ne_zero y := of_pos $ pos_of_gt h -- 1 < p is still an often-used `fact`, due to `nat.prime` implying it, and it implying `nontrivial` -- on `zmod`'s ring structure. We cannot just set this to be any `x < y`, else that becomes a -- metavariable and it will hugely slow down typeclass inference. @[priority 10] instance of_gt' {M} [canonically_ordered_add_monoid M] [has_one M] {y : M} [fact (1 < y)] : ne_zero y := of_gt $ fact.out $ 1 < y instance bit0 {M} [canonically_ordered_add_monoid M] {x : M} [ne_zero x] : ne_zero (bit0 x) := of_pos $ bit0_pos $ ne_zero.pos x end ne_zero /-- A canonically linear-ordered additive monoid is a canonically ordered additive monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_add_monoid linear_order] class canonically_linear_ordered_add_monoid (α : Type*) extends canonically_ordered_add_monoid α, linear_order α /-- A canonically linear-ordered monoid is a canonically ordered monoid whose ordering is a linear order. -/ @[protect_proj, ancestor canonically_ordered_monoid linear_order, to_additive] class canonically_linear_ordered_monoid (α : Type*) extends canonically_ordered_monoid α, linear_order α section canonically_linear_ordered_monoid variables [canonically_linear_ordered_monoid α] @[priority 100, to_additive] -- see Note [lower instance priority] instance canonically_linear_ordered_monoid.semilattice_sup : semilattice_sup α := { ..linear_order.to_lattice } @[to_additive] lemma min_mul_distrib (a b c : α) : min a (b * c) = min a (min a b * min a c) := begin cases le_total a b with hb hb, { simp [hb, le_mul_right] }, { cases le_total a c with hc hc, { simp [hc, le_mul_left] }, { simp [hb, hc] } } end @[to_additive] lemma min_mul_distrib' (a b c : α) : min (a * b) c = min (min a c * min b c) c := by simpa [min_comm _ c] using min_mul_distrib c a b @[simp, to_additive] lemma one_min (a : α) : min 1 a = 1 := min_eq_left (one_le a) @[simp, to_additive] lemma min_one (a : α) : min a 1 = 1 := min_eq_right (one_le a) /-- In a linearly ordered monoid, we are happy for `bot_eq_one` to be a `@[simp]` lemma. -/ @[simp, to_additive "In a linearly ordered monoid, we are happy for `bot_eq_zero` to be a `@[simp]` lemma"] lemma bot_eq_one' : (⊥ : α) = 1 := bot_eq_one end canonically_linear_ordered_monoid
d85e8f9bfc03d0ca1e75814ad230a790c038d153
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/Data/Repr.lean
fb40c0dc4bd1d8e80293337aecd5a058e5654b14
[ "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
7,411
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.Data.Format.Basic import Init.Data.Int.Basic import Init.Data.Nat.Div import Init.Data.UInt import Init.Control.Id open Sum Subtype Nat open Std class Repr (α : Type u) where reprPrec : α → Nat → Format export Repr (reprPrec) abbrev repr [Repr α] (a : α) : Format := reprPrec a 0 abbrev reprStr [Repr α] (a : α) : String := reprPrec a 0 |>.pretty abbrev reprArg [Repr α] (a : α) : Format := reprPrec a max_prec /-- Auxiliary class for marking types that should be considered atomic by `Repr` methods. We use it at `Repr (List α)` to decide whether `bracketFill` should be used or not. -/ class ReprAtom (α : Type u) -- This instance is needed because `id` is not reducible instance [Repr α] : Repr (id α) := inferInstanceAs (Repr α) instance [Repr α] : Repr (Id α) := inferInstanceAs (Repr α) instance : Repr Bool where reprPrec | true, _ => "true" | false, _ => "false" def Repr.addAppParen (f : Format) (prec : Nat) : Format := if prec >= max_prec then Format.paren f else f instance : Repr (Decidable p) where reprPrec | Decidable.isTrue _, prec => Repr.addAppParen "isTrue _" prec | Decidable.isFalse _, prec => Repr.addAppParen "isFalse _" prec instance : Repr PUnit.{u+1} where reprPrec _ _ := "PUnit.unit" instance [Repr α] : Repr (ULift.{v} α) where reprPrec v prec := Repr.addAppParen ("ULift.up " ++ reprArg v.1) prec instance : Repr Unit where reprPrec _ _ := "()" protected def Option.repr [Repr α] : Option α → Nat → Format | none, _ => "none" | some a, prec => Repr.addAppParen ("some " ++ reprArg a) prec instance [Repr α] : Repr (Option α) where reprPrec := Option.repr protected def Sum.repr [Repr α] [Repr β] : Sum α β → Nat → Format | Sum.inl a, prec => Repr.addAppParen ("Sum.inl " ++ reprArg a) prec | Sum.inr b, prec => Repr.addAppParen ("Sum.inr " ++ reprArg b) prec instance [Repr α] [Repr β] : Repr (Sum α β) where reprPrec := Sum.repr class ReprTuple (α : Type u) where reprTuple : α → List Format → List Format export ReprTuple (reprTuple) instance [Repr α] : ReprTuple α where reprTuple a xs := repr a :: xs instance [Repr α] [ReprTuple β] : ReprTuple (α × β) where reprTuple | (a, b), xs => reprTuple b (repr a :: xs) protected def Prod.repr [Repr α] [ReprTuple β] : α × β → Nat → Format | (a, b), _ => Format.bracket "(" (Format.joinSep (reprTuple b [repr a]).reverse ("," ++ Format.line)) ")" instance [Repr α] [ReprTuple β] : Repr (α × β) where reprPrec := Prod.repr instance {β : α → Type v} [Repr α] [(x : α) → Repr (β x)] : Repr (Sigma β) where reprPrec | ⟨a, b⟩, _ => Format.bracket "⟨" (repr a ++ ", " ++ repr b) "⟩" instance {p : α → Prop} [Repr α] : Repr (Subtype p) where reprPrec s prec := reprPrec s.val prec namespace Nat def digitChar (n : Nat) : Char := if n = 0 then '0' else if n = 1 then '1' else if n = 2 then '2' else if n = 3 then '3' else if n = 4 then '4' else if n = 5 then '5' else if n = 6 then '6' else if n = 7 then '7' else if n = 8 then '8' else if n = 9 then '9' else if n = 0xa then 'a' else if n = 0xb then 'b' else if n = 0xc then 'c' else if n = 0xd then 'd' else if n = 0xe then 'e' else if n = 0xf then 'f' else '*' def toDigitsCore (base : Nat) : Nat → Nat → List Char → List Char | 0, _, ds => ds | fuel+1, n, ds => let d := digitChar <| n % base; let n' := n / base; if n' = 0 then d::ds else toDigitsCore base fuel n' (d::ds) def toDigits (base : Nat) (n : Nat) : List Char := toDigitsCore base (n+1) n [] protected def repr (n : Nat) : String := (toDigits 10 n).asString def superDigitChar (n : Nat) : Char := if n = 0 then '⁰' else if n = 1 then '¹' else if n = 2 then '²' else if n = 3 then '³' else if n = 4 then '⁴' else if n = 5 then '⁵' else if n = 6 then '⁶' else if n = 7 then '⁷' else if n = 8 then '⁸' else if n = 9 then '⁹' else '*' partial def toSuperDigitsAux : Nat → List Char → List Char | n, ds => let d := superDigitChar <| n % 10; let n' := n / 10; if n' = 0 then d::ds else toSuperDigitsAux n' (d::ds) def toSuperDigits (n : Nat) : List Char := toSuperDigitsAux n [] def toSuperscriptString (n : Nat) : String := (toSuperDigits n).asString end Nat instance : Repr Nat where reprPrec n _ := Nat.repr n def Int.repr : Int → String | ofNat m => Nat.repr m | negSucc m => "-" ++ Nat.repr (succ m) instance : Repr Int where reprPrec i _ := i.repr def hexDigitRepr (n : Nat) : String := String.singleton <| Nat.digitChar n def Char.quoteCore (c : Char) : String := if c = '\n' then "\\n" else if c = '\t' then "\\t" else if c = '\\' then "\\\\" else if c = '\"' then "\\\"" else if c.toNat <= 31 ∨ c = '\x7f' then "\\x" ++ smallCharToHex c else String.singleton c where smallCharToHex (c : Char) : String := let n := Char.toNat c; let d2 := n / 16; let d1 := n % 16; hexDigitRepr d2 ++ hexDigitRepr d1 def Char.quote (c : Char) : String := "'" ++ Char.quoteCore c ++ "'" instance : Repr Char where reprPrec c _ := c.quote protected def Char.repr (c : Char) : String := c.quote def String.quote (s : String) : String := if s.isEmpty then "\"\"" else s.foldl (fun s c => s ++ c.quoteCore) "\"" ++ "\"" instance : Repr String where reprPrec s _ := s.quote instance : Repr String.Pos where reprPrec p _ := "{ byteIdx := " ++ repr p.byteIdx ++ " }" instance : Repr Substring where reprPrec s _ := Format.text <| String.quote s.toString ++ ".toSubstring" instance : Repr String.Iterator where reprPrec | ⟨s, pos⟩, prec => Repr.addAppParen ("String.Iterator.mk " ++ reprArg s ++ " " ++ reprArg pos) prec instance (n : Nat) : Repr (Fin n) where reprPrec f _ := repr f.val instance : Repr UInt8 where reprPrec n _ := repr n.toNat instance : Repr UInt16 where reprPrec n _ := repr n.toNat instance : Repr UInt32 where reprPrec n _ := repr n.toNat instance : Repr UInt64 where reprPrec n _ := repr n.toNat instance : Repr USize where reprPrec n _ := repr n.toNat protected def List.repr [Repr α] (a : List α) (n : Nat) : Format := let _ : ToFormat α := ⟨repr⟩ match a, n with | [], _ => "[]" | as, _ => Format.bracket "[" (Format.joinSep as ("," ++ Format.line)) "]" instance [Repr α] : Repr (List α) where reprPrec := List.repr protected def List.repr' [Repr α] [ReprAtom α] (a : List α) (n : Nat) : Format := let _ : ToFormat α := ⟨repr⟩ match a, n with | [], _ => "[]" | as, _ => Format.bracketFill "[" (Format.joinSep as ("," ++ Format.line)) "]" instance [Repr α] [ReprAtom α] : Repr (List α) where reprPrec := List.repr' instance : ReprAtom Bool := ⟨⟩ instance : ReprAtom Nat := ⟨⟩ instance : ReprAtom Int := ⟨⟩ instance : ReprAtom Char := ⟨⟩ instance : ReprAtom String := ⟨⟩ instance : ReprAtom UInt8 := ⟨⟩ instance : ReprAtom UInt16 := ⟨⟩ instance : ReprAtom UInt32 := ⟨⟩ instance : ReprAtom UInt64 := ⟨⟩ instance : ReprAtom USize := ⟨⟩ deriving instance Repr for Lean.SourceInfo
3b9691d1059a854d4d9276c0c9fa83442a0d3a74
c61b91f85121053c627318ad8fcde30dfb8637d2
/Chapter2/2-3.lean
6f72bb4ff1f35a7ae16399d3bc954447a0b247a9
[]
no_license
robkorn/theorem-proving-in-lean-exercises
9e2256360eaf6f8df6cdd8fd656e63dfb04c8cdb
9c51da587105ee047a9db55d52709d881a39be7a
refs/heads/master
1,585,403,341,988
1,540,142,619,000
1,540,142,619,000
148,431,678
2
0
null
null
null
null
UTF-8
Lean
false
false
1,870
lean
-- #check fun x : nat, x + 6 -- #check λ x y : nat, x + 7 -- constants α β : Type -- constants a1 a2 : α -- constants b1 b2 : β -- constant f : α -> α -- constant g : α -> β -- constant h : α -> β -> α -- constant p : α -> α -> bool -- #check fun x : α, f x -- α -> α -- #check λ x : α, f x -- α -> α -- #check λ x : α, f (f x) -- α -> α -- #check λ x : α, h x b1 -- α -> α -- #check λ y : β, h a1 y -- β -> α -- #check λ x : α, p (f (f x)) (h (f a1) b2) -- α -> bool -- #check λ x : α, λ y : β, h (f x) y -- α -> β -> α -- #check λ (x : α) (y : β), h (f x) y -- α -> β -> α -- #check λ x y, h (f x) y -- α -> β -> α -- #check λ (b : nat) (c : int), b -- constant γ : Type -- constant mf : α -> β -- constant mg : β -> γ -- constant b : β -- #check λ x : α, x -- α -> α -- #check λ x : α, b -- α -> β -- #check λ x : α, mg (mf x) -- α -> γ -- #check λ x, mg (mf x) -- #check λ b : β, λ x : α, x -- β -> α -> α -- #check λ (b : β) (x : α), x -- β -> α -> α -- #check λ (g : β -> γ) (f : α -> β) (x : α), g (f x) -- -- (β -> γ) -> (α -> β) -> α -> γ -- #check λ (α β : Type) (b : β) (x : α), x -- #check λ (α β γ : Type) (g : β -> γ) (f : α -> β) (x : α), g (f x) constants α β γ : Type constant f : α -> β constant g : β -> γ constant h : α -> α constants (a : α) (b : β) #check (λ x : α, x) a -- α #check (λ x : α, b) a -- β #check (λ x : α, b) (h a) -- β #check (λ x : α, g (f x)) (h (h a)) -- γ #check (λ (v : β -> γ) (u : α -> β) x, v (u x)) g f a -- γ #check (λ (Q R S : Type) (v : R -> S) (u : Q -> R) (x : Q), v (u x)) α β γ g f a -- γ #reduce (λ (Q R S : Type) (v : R -> S) (u : Q -> R) (x : Q), v (u x)) α β γ g f a -- γ #eval 23523342 * 234234
dda985810c78c26633b20d2615028d76ba7ec1fe
4fa161becb8ce7378a709f5992a594764699e268
/src/data/polynomial.lean
bf85f49321262ca3a5dd9f8d5672db1bc3da8792
[ "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
109,623
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.monoid_algebra import algebra.gcd_domain import ring_theory.euclidean_domain import ring_theory.multiplicity import tactic.ring_exp import deprecated.field /-! # Theory of univariate polynomials Polynomials are represented as `add_monoid_algebra R ℕ`, where `R` is a commutative semiring. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable local attribute [instance, priority 10] is_semiring_hom.comp is_ring_hom.comp /-- `polynomial R` is the type of univariate polynomials over `R`. Polynomials should be seen as (semi-)rings with the additional constructor `X`. The embedding from `R` is called `C`. -/ def polynomial (R : Type*) [semiring R] := add_monoid_algebra R ℕ open finsupp finset add_monoid_algebra open_locale big_operators namespace polynomial universes u v w x y z variables {R : Type u} {S : Type v} {T : Type w} {ι : Type x} {k : Type y} {A : Type z} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : polynomial R} instance : inhabited (polynomial R) := finsupp.inhabited instance : semiring (polynomial R) := add_monoid_algebra.semiring instance : has_scalar R (polynomial R) := add_monoid_algebra.has_scalar instance : semimodule R (polynomial R) := add_monoid_algebra.semimodule /-- The coercion turning a `polynomial` into the function which reports the coefficient of a given monomial `X^n` -/ def coeff_coe_to_fun : has_coe_to_fun (polynomial R) := finsupp.has_coe_to_fun local attribute [instance] coeff_coe_to_fun @[simp] lemma support_zero : (0 : polynomial R).support = ∅ := rfl /-- `monomial s a` is the monomial `a * X^s` -/ @[reducible] def monomial (n : ℕ) (a : R) : polynomial R := finsupp.single n a /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial R := monomial 1 1 /-- coeff p n is the coefficient of X^n in p -/ def coeff (p : polynomial R) := p.to_fun @[simp] lemma coeff_mk (s) (f) (h) : coeff (finsupp.mk s f h : polynomial R) = f := rfl instance [has_repr R] : has_repr (polynomial R) := ⟨λ p, if p = 0 then "0" else (p.support.sort (≤)).foldr (λ n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (coeff p n) ++ ")" else if n = 1 then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X" else if (coeff p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩ theorem ext_iff {p q : polynomial R} : p = q ↔ ∀ n, coeff p n = coeff q n := ⟨λ h n, h ▸ rfl, finsupp.ext⟩ @[ext] lemma ext {p q : polynomial R} : (∀ n, coeff p n = coeff q n) → p = q := (@ext_iff _ _ p q).2 /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial R) : with_bot ℕ := p.support.sup some lemma degree_lt_wf : well_founded (λp q : polynomial R, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) instance : has_well_founded (polynomial R) := ⟨_, degree_lt_wf⟩ /-- `nat_degree p` forces `degree p` to ℕ, by defining nat_degree 0 = 0. -/ def nat_degree (p : polynomial R) : ℕ := (degree p).get_or_else 0 section coeff lemma apply_eq_coeff : p n = coeff p n := rfl @[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial R) n = 0 := rfl lemma coeff_single : coeff (single n a) m = if n = m then a else 0 := by { dsimp [single, finsupp.single], congr } @[simp] lemma coeff_one_zero : coeff (1 : polynomial R) 0 = 1 := coeff_single @[simp] lemma coeff_add (p q : polynomial R) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := rfl instance coeff.is_add_monoid_hom {n : ℕ} : is_add_monoid_hom (λ p : polynomial R, p.coeff n) := { map_add := λ p q, coeff_add p q n, map_zero := coeff_zero _ } @[simp] lemma coeff_X_one : coeff (X : polynomial R) 1 = 1 := coeff_single @[simp] lemma coeff_X_zero : coeff (X : polynomial R) 0 = 0 := coeff_single lemma coeff_X : coeff (X : polynomial R) n = if 1 = n then 1 else 0 := coeff_single lemma coeff_sum [semiring S] (n : ℕ) (f : ℕ → R → polynomial S) : coeff (p.sum f) n = p.sum (λ a b, coeff (f a b) n) := finsupp.sum_apply @[simp] lemma coeff_smul (p : polynomial R) (r : R) (n : ℕ) : coeff (r • p) n = r * coeff p n := finsupp.smul_apply @[simp, priority 990] lemma coeff_one (n : ℕ) : coeff (1 : polynomial R) n = if 0 = n then 1 else 0 := coeff_single lemma coeff_mul (p q : polynomial R) (n : ℕ) : coeff (p * q) n = ∑ x in nat.antidiagonal n, coeff p x.1 * coeff q x.2 := have hite : ∀ a : ℕ × ℕ, ite (a.1 + a.2 = n) (coeff p (a.fst) * coeff q (a.snd)) 0 ≠ 0 → a.1 + a.2 = n, from λ a ha, by_contradiction (λ h, absurd (eq.refl (0 : R)) (by rwa if_neg h at ha)), calc coeff (p * q) n = ∑ a in p.support, ∑ b in q.support, ite (a + b = n) (coeff p a * coeff q b) 0 : by simp only [mul_def, coeff_sum, coeff_single]; refl ... = ∑ v in p.support.product q.support, ite (v.1 + v.2 = n) (coeff p v.1 * coeff q v.2) 0 : by rw sum_product ... = ∑ x in nat.antidiagonal n, coeff p x.1 * coeff q x.2 : begin refine sum_bij_ne_zero (λ x _ _, x) (λ x _ hx, nat.mem_antidiagonal.2 (hite x hx)) (λ _ _ _ _ _ _ h, h) (λ x h₁ h₂, ⟨x, _, _, rfl⟩) _, { rw [mem_product, mem_support_iff, mem_support_iff], exact ⟨ne_zero_of_mul_ne_zero_right h₂, ne_zero_of_mul_ne_zero_left h₂⟩ }, { rw nat.mem_antidiagonal at h₁, rwa [if_pos h₁] }, { intros x h hx, rw [if_pos (hite x hx)] } end lemma monomial_one_eq_X_pow : ∀{n}, monomial n (1 : R) = X^n | 0 := rfl | (n+1) := calc monomial (n + 1) (1 : R) = monomial n 1 * X : by rw [X, single_mul_single, mul_one] ... = X^n * X : by rw [monomial_one_eq_X_pow] ... = X^(n+1) : by simp only [pow_add, pow_one] lemma monomial_eq_smul_X {n} : monomial n (a : R) = a • X^n := begin calc monomial n a = monomial n (a * 1) : by simp ... = a • monomial n 1 : (smul_single' _ _ _).symm ... = a • X^n : by rw monomial_one_eq_X_pow end @[simp] lemma coeff_X_pow (k n : ℕ) : coeff (X^k : polynomial R) n = if n = k then 1 else 0 := by rw [← monomial_one_eq_X_pow]; simp [monomial, single, eq_comm, coeff]; congr theorem coeff_mul_X_pow (p : polynomial R) (n d : ℕ) : coeff (p * polynomial.X ^ n) (d + n) = coeff p d := begin rw [coeff_mul, sum_eq_single (d,n), coeff_X_pow, if_pos rfl, mul_one], { rintros ⟨i,j⟩ h1 h2, rw [coeff_X_pow, if_neg, mul_zero], rintro rfl, apply h2, rw [nat.mem_antidiagonal, add_right_cancel_iff] at h1, subst h1 }, { exact λ h1, (h1 (nat.mem_antidiagonal.2 rfl)).elim } end theorem coeff_mul_X (p : polynomial R) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n theorem mul_X_pow_eq_zero {p : polynomial R} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext $ λ k, (coeff_mul_X_pow p n k).symm.trans $ ext_iff.1 H (k+n) end coeff end semiring section ring variables [ring R] instance : ring (polynomial R) := add_monoid_algebra.ring end ring section comm_semiring variables [comm_semiring R] {p q r : polynomial R} local attribute [instance] coeff_coe_to_fun instance : comm_semiring (polynomial R) := add_monoid_algebra.comm_semiring instance : algebra R (polynomial R) := add_monoid_algebra.algebra /-- `C a` is the constant polynomial `a`. -/ def C : R →ₐ[R] polynomial R := algebra.of_id R (polynomial R) lemma C_def (a : R) : C a = single 0 a := rfl lemma single_eq_C_mul_X : ∀{n}, monomial n a = C a * X^n | 0 := (mul_one _).symm | (n+1) := calc monomial (n + 1) a = monomial n a * X : by rw [X, single_mul_single, mul_one] ... = (C a * X^n) * X : by rw [single_eq_C_mul_X] ... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one] lemma sum_C_mul_X_eq (p : polynomial R) : p.sum (λn a, C a * X^n) = p := eq.trans (sum_congr rfl $ assume n hn, single_eq_C_mul_X.symm) (finsupp.sum_single _) @[elab_as_eliminator] protected lemma induction_on {M : polynomial R → Prop} (p : polynomial R) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : R), M (C a * X^n) → M (C a * X^(n+1))) : M p := have ∀{n:ℕ} {a}, M (C a * X^n), begin assume n a, induction n with n ih, { simp only [pow_zero, mul_one, h_C] }, { exact h_monomial _ _ ih } end, finsupp.induction p (suffices M (C 0), by { convert this, exact single_zero.symm, }, h_C 0) (assume n a p _ _ hp, suffices M (C a * X^n + p), by { convert this, exact single_eq_C_mul_X }, h_add _ _ this hp) lemma C_0 : C (0 : R) = 0 := single_zero lemma C_1 : C (1 : R) = 1 := rfl lemma C_mul : C (a * b) = C a * C b := C.map_mul a b lemma C_add : C (a + b) = C a + C b := C.map_add a b instance C.is_semiring_hom : is_semiring_hom (C : R → polynomial R) := C.to_ring_hom.is_semiring_hom lemma C_pow : C (a ^ n) = C a ^ n := C.map_pow a n lemma nat_cast_eq_C (n : ℕ) : (n : polynomial R) = C (n : R) := (C.to_ring_hom.map_nat_cast n).symm section coeff lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 := by simp [coeff, eq_comm, C_def, monomial, single]; congr @[simp] lemma coeff_C_zero : coeff (C a) 0 = a := coeff_single lemma coeff_C_mul_X (x : R) (k n : ℕ) : coeff (C x * X^k : polynomial R) n = if n = k then x else 0 := by rw [← single_eq_C_mul_X]; simp [monomial, single, eq_comm, coeff]; congr @[simp] lemma coeff_C_mul (p : polynomial R) : coeff (C a * p) n = a * coeff p n := begin conv in (a * _) { rw [← @sum_single _ _ _ p, coeff_sum] }, rw [mul_def, C_def, sum_single_index], { simp [coeff_single, finsupp.mul_sum, coeff_sum], apply sum_congr rfl, assume i hi, by_cases i = n; simp [h] }, { simp [finsupp.sum] } end lemma C_mul' (a : R) (f : polynomial R) : C a * f = a • f := ext $ λ n, coeff_C_mul f end coeff lemma C_inj : C a = C b ↔ a = b := ⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩ section eval₂ variables [semiring S] variables (f : R → S) (x : S) open is_semiring_hom /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial R) : S := p.sum (λ e a, f a * x ^ e) variables [is_semiring_hom f] @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [pow_zero, mul_one] @[simp] lemma eval₂_X : X.eval₂ f x = x := (sum_single_index $ by rw [map_zero f, zero_mul]).trans $ by rw [map_one f, one_mul, pow_one] @[simp] lemma eval₂_zero : (0 : polynomial R).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (λ _, by rw [map_zero f, zero_mul]) (λ _ _ _, by rw [map_add f, add_mul]) @[simp] lemma eval₂_one : (1 : polynomial R).eval₂ f x = 1 := by rw [← C_1, eval₂_C, map_one f] instance eval₂.is_add_monoid_hom : is_add_monoid_hom (eval₂ f x) := { map_zero := eval₂_zero _ _, map_add := λ _ _, eval₂_add _ _ } end eval₂ section eval₂ variables [comm_semiring S] variables (f : R → S) [is_semiring_hom f] (x : S) open is_semiring_hom @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin dunfold eval₂, rw [mul_def, finsupp.sum_mul _ p], simp only [finsupp.mul_sum _ q], rw [sum_sum_index], { apply sum_congr rfl, assume i hi, dsimp only, rw [sum_sum_index], { apply sum_congr rfl, assume j hj, dsimp only, rw [sum_single_index, map_mul f, pow_add], { simp only [mul_assoc, mul_left_comm] }, { rw [map_zero f, zero_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } }, { intro, rw [map_zero f, zero_mul] }, { intros, rw [map_add f, add_mul] } end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom (f : R →+* S) (x) : polynomial R →+* S := ring_hom.of (eval₂ f x) @[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := map_pow _ _ _ lemma eval₂_sum (p : polynomial R) (g : ℕ → R → polynomial R) (x : S) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := finsupp.sum_sum_index (by simp [is_add_monoid_hom.map_zero f]) (by intros; simp [right_distrib, is_add_monoid_hom.map_add f]) end eval₂ section eval variable {x : R} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : R → polynomial R → R := eval₂ id @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_zero : (0 : polynomial R).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial R).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ lemma eval_sum (p : polynomial R) (f : ℕ → R → polynomial R) (x : R) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval₂_hom [comm_semiring S] (f : R → S) [is_semiring_hom f] (x : R) : p.eval₂ f (f x) = f (p.eval x) := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, eval_pow, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial R) (a : R) : Prop := p.eval a = 0 instance [decidable_eq R] : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma root_mul_left_of_is_root (p : polynomial R) {q : polynomial R} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : polynomial R} (q : polynomial R) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] lemma coeff_zero_eq_eval_zero (p : polynomial R) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) lemma zero_is_root_of_coeff_zero_eq_zero {p : polynomial R} (hp : p.coeff 0 = 0) : is_root p 0 := by rwa coeff_zero_eq_eval_zero at hp end eval section comp def comp (p q : polynomial R) : polynomial R := p.eval₂ C q lemma eval₂_comp [comm_semiring S] (f : R → S) [is_semiring_hom f] {x : S} : (p.comp q).eval₂ f x = p.eval₂ f (q.eval₂ f x) := show (p.sum (λ e a, C a * q ^ e)).eval₂ f x = p.eval₂ f (eval₂ f x q), by simp only [eval₂_mul, eval₂_C, eval₂_pow, eval₂_sum]; refl lemma eval_comp : (p.comp q).eval a = p.eval (q.eval a) := eval₂_comp _ @[simp] lemma comp_X : p.comp X = p := begin refine ext (λ n, _), rw [comp, eval₂], conv in (C _ * _) { rw ← single_eq_C_mul_X }, rw finsupp.sum_single end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := begin dsimp [comp, eval₂, eval, finsupp.sum], rw [← p.support.sum_hom (@C R _)], apply finset.sum_congr rfl; simp end @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma comp_zero : p.comp (0 : polynomial R) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : polynomial R) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : polynomial R) p = 1 := by rw [← C_1, C_comp] instance : is_semiring_hom (λ q : polynomial R, q.comp p) := by unfold comp; apply_instance @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma mul_comp : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ end comp /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial R) : R := coeff p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial R) := leading_coeff p = (1 : R) lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable [decidable_eq R] : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma monic.leading_coeff {p : polynomial R} (hp : p.monic) : leading_coeff p = 1 := hp @[simp] lemma degree_zero : degree (0 : polynomial R) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial R) = 0 := rfl @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw if_neg ha; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; [rw [h, C_0], rw [degree_C h]]; [exact bot_le, exact le_refl _] lemma degree_one_le : degree (1 : polynomial R) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := classical.not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl lemma degree_eq_iff_nat_degree_eq {p : polynomial R} {n : ℕ} (hp : p ≠ 0) : p.degree = n ↔ p.nat_degree = n := by rw [degree_eq_nat_degree hp, with_bot.coe_eq_coe] lemma degree_eq_iff_nat_degree_eq_of_pos {p : polynomial R} {n : ℕ} (hn : n > 0) : p.degree = n ↔ p.nat_degree = n := begin split, { intro H, rwa ← degree_eq_iff_nat_degree_eq, rintro rfl, rw degree_zero at H, exact option.no_confusion H }, { intro H, rwa degree_eq_iff_nat_degree_eq, rintro rfl, rw nat_degree_zero at H, rw H at hn, exact lt_irrefl _ hn } end lemma nat_degree_eq_of_degree_eq_some {p : polynomial R} {n : ℕ} (h : degree p = n) : nat_degree p = n := have hp0 : p ≠ 0, from λ hp0, by rw hp0 at h; exact option.no_confusion h, option.some_inj.1 $ show (nat_degree p : with_bot ℕ) = n, by rwa [← degree_eq_nat_degree hp0] @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := begin by_cases hp : p = 0, { rw hp, exact bot_le }, rw [degree_eq_nat_degree hp], exact le_refl _ end lemma nat_degree_eq_of_degree_eq [comm_semiring S] {q : polynomial S} (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : coeff p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup (finsupp.mem_support_iff.2 h) lemma le_nat_degree_of_ne_zero (h : coeff p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma degree_le_degree (h : coeff q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { rw hp, exact bot_le }, { rw degree_eq_nat_degree hp, exact le_degree_of_ne_zero h } end @[simp] lemma nat_degree_C (a : R) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { rw [ha, C_0] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma nat_degree_one : nat_degree (1 : polynomial R) = 0 := nat_degree_C 1 @[simp] lemma nat_degree_nat_cast (n : ℕ) : nat_degree (n : polynomial R) = 0 := by simp [nat_cast_eq_C] @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl lemma degree_monomial_le (n : ℕ) (a : R) : degree (C a * X ^ n) ≤ n := if h : a = 0 then by rw [h, C_0, zero_mul]; exact bot_le else le_of_eq (degree_monomial n h) lemma coeff_eq_zero_of_degree_lt (h : degree p < n) : coeff p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma coeff_eq_zero_of_nat_degree_lt {p : polynomial R} {n : ℕ} (h : p.nat_degree < n) : p.coeff n = 0 := begin apply coeff_eq_zero_of_degree_lt, by_cases hp : p = 0, { subst hp, exact with_bot.bot_lt_coe n }, { rwa [degree_eq_nat_degree hp, with_bot.coe_lt_coe] } end -- TODO find a home (this file) @[simp] lemma finset_sum_coeff (s : finset ι) (f : ι → polynomial R) (n : ℕ) : coeff (∑ b in s, f b) n = ∑ b in s, coeff (f b) n := (s.sum_hom (λ q : polynomial R, q.coeff n)).symm -- We need the explicit `decidable` argument here because an exotic one shows up in a moment! lemma ite_le_nat_degree_coeff (p : polynomial R) (n : ℕ) (I : decidable (n < 1 + nat_degree p)) : @ite (n < 1 + nat_degree p) I _ (coeff p n) 0 = coeff p n := begin split_ifs, { refl }, { exact (coeff_eq_zero_of_nat_degree_lt (not_le.1 (λ w, h (nat.lt_one_add_iff.2 w)))).symm, } end lemma as_sum (p : polynomial R) : p = ∑ i in range (p.nat_degree + 1), C (p.coeff i) * X^i := begin ext n, simp only [add_comm, coeff_X_pow, coeff_C_mul, finset.mem_range, finset.sum_mul_boole, finset_sum_coeff, ite_le_nat_degree_coeff], end lemma monic.as_sum {p : polynomial R} (hp : p.monic) : p = X^(p.nat_degree) + (∑ i in finset.range p.nat_degree, C (p.coeff i) * X^i) := begin conv_lhs { rw [p.as_sum, finset.sum_range_succ] }, suffices : C (p.coeff p.nat_degree) = 1, { rw [this, one_mul] }, exact congr_arg C hp end section map variables [comm_semiring S] variables (f : R →+* S) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial R → polynomial S := eval₂ (C ∘ f) X instance is_semiring_hom_C_f : is_semiring_hom (C ∘ f) := is_semiring_hom.comp _ _ @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_zero : (0 : polynomial R).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial R).map f = 1 := eval₂_one _ _ @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := eval₂_mul _ _ instance map.is_semiring_hom : is_semiring_hom (map f) := eval₂.is_semiring_hom _ _ @[simp] lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := eval₂_pow _ _ _ lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum], conv_rhs { rw [← sum_C_mul_X_eq p, coeff_sum, finsupp.sum, ← p.support.sum_hom f], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X, is_semiring_hom.map_mul f], split_ifs; simp [is_semiring_hom.map_zero f], end lemma map_map [comm_semiring T] (g : S →+* T) (p : polynomial R) : (p.map f).map g = p.map (g.comp f) := ext (by simp [coeff_map]) lemma eval₂_map [comm_semiring T] (g : S → T) [is_semiring_hom g] (x : T) : (p.map f).eval₂ g x = p.eval₂ (λ y, g (f y)) x := polynomial.induction_on p (by simp) (by simp [is_semiring_hom.map_add f] {contextual := tt}) (by simp [is_semiring_hom.map_mul f, is_semiring_hom.map_pow f, pow_succ', (mul_assoc _ _ _).symm] {contextual := tt}) lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x := eval₂_map _ _ _ @[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map] lemma mem_map_range {p : polynomial S} : p ∈ set.range (map f) ↔ ∀ n, p.coeff n ∈ (set.range f) := begin split, { rintro ⟨p, rfl⟩ n, rw coeff_map, exact set.mem_range_self _ }, { intro h, rw p.as_sum, apply is_add_submonoid.finset_sum_mem, intros i hi, rcases h i with ⟨c, hc⟩, use [C c * X^i], rw [map_mul, map_C, hc, map_pow, map_X] } end end map section variables [comm_semiring S] [comm_semiring T] variables (f : R →+* S) (g : S →+* T) (p) lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g ∘ f) (g x) := begin apply polynomial.induction_on p; clear p, { intros a, rw [eval₂_C, eval₂_C] }, { intros p q hp hq, simp only [hp, hq, eval₂_add, is_semiring_hom.map_add g] }, { intros n a ih, replace ih := congr_arg (λ y, y * g x) ih, simpa [pow_succ', is_semiring_hom.map_mul g, (mul_assoc _ _ _).symm, eval₂_C, eval₂_mul, eval₂_X] using ih } end end lemma coeff_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : coeff p (nat_degree q) = 0 := coeff_eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (coeff p 0) := begin refine ext (λ n, _), cases n, { simp }, { have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)), rw [coeff_C, if_neg (nat.succ_ne_zero _), coeff_eq_zero_of_degree_lt this] } end lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (coeff p 0) := eq_C_of_degree_le_zero (h ▸ le_refl _) lemma degree_le_zero_iff : degree p ≤ 0 ↔ p = C (coeff p 0) := ⟨eq_C_of_degree_le_zero, λ h, h.symm ▸ degree_C_le⟩ lemma degree_add_le (p q : polynomial R) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : by convert sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : by convert sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial R) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt mem_support_iff.1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), λ h, h.symm ▸ leading_coeff_zero⟩ lemma leading_coeff_eq_zero_iff_deg_eq_bot : leading_coeff p = 0 ↔ degree p = ⊥ := by rw [leading_coeff_eq_zero, degree_eq_bot] lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [coeff_add, coeff_nat_degree_eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_C (hp : 0 < degree p) : degree (p + C a) = degree p := add_comm (C a) p ▸ degree_add_eq_of_degree_lt $ lt_of_le_of_lt degree_C_le hp lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← coeff_add], exact coeff_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial R) (n : ℕ) : degree (p.erase n) ≤ degree p := by convert sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ (by convert λ h, not_mem_erase _ _ (mem_of_max h)) lemma degree_sum_le (s : finset ι) (f : ι → polynomial R) : degree (∑ i in s, f i) ≤ s.sup (λ b, degree (f b)) := finset.induction_on s (by simp only [sum_empty, sup_empty, degree_zero, le_refl]) $ assume a s has ih, calc degree (∑ i in insert a s, f i) ≤ max (degree (f a)) (degree (∑ i in s, f i)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial R) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (coeff p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (coeff p i * coeff q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_monomial_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add' (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial R) : ∀ n, degree (p ^ n) ≤ n •ℕ (degree p) | 0 := by rw [pow_zero, zero_nsmul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_nsmul; exact add_le_add' (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : R) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp only [ha, C_0, zero_mul, leading_coeff_zero] }, { rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X], exact @finsupp.single_eq_same _ _ _ n a } end @[simp] lemma leading_coeff_C (a : R) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by rwa [pow_zero, mul_one] at this, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial R) = 1 := suffices leading_coeff (C (1:R) * X^1) = 1, by rwa [C_1, pow_one, one_mul] at this, leading_coeff_monomial 1 1 @[simp] lemma monic_X : monic (X : polynomial R) := leading_coeff_X @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial R) = 1 := suffices leading_coeff (C (1:R) * X^0) = 1, by rwa [C_1, pow_zero, mul_one] at this, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial R) := leading_coeff_C _ lemma monic.ne_zero_of_zero_ne_one (h : (0:R) ≠ 1) {p : polynomial R} (hp : p.monic) : p ≠ 0 := by { contrapose! h, rwa [h] at hp } lemma monic.ne_zero {R : Type*} [comm_semiring R] [nonzero R] {p : polynomial R} (hp : p.monic) : p ≠ 0 := hp.ne_zero_of_zero_ne_one zero_ne_one lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have coeff p (nat_degree q) = 0, from coeff_nat_degree_eq_zero_of_degree_lt h, by simp only [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h), this, coeff_add, zero_add] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp only [leading_coeff, this, nat_degree_eq_of_degree_eq h, coeff_add] @[simp] lemma coeff_mul_degree_add_degree (p q : polynomial R) : coeff (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := calc coeff (p * q) (nat_degree p + nat_degree q) = ∑ x in nat.antidiagonal (nat_degree p + nat_degree q), coeff p x.1 * coeff q x.2 : coeff_mul _ _ _ ... = coeff p (nat_degree p) * coeff q (nat_degree q) : begin refine finset.sum_eq_single (nat_degree p, nat_degree q) _ _, { rintro ⟨i,j⟩ h₁ h₂, rw nat.mem_antidiagonal at h₁, by_cases H : nat_degree p < i, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 H)), zero_mul] }, { rw not_lt_iff_eq_or_lt at H, cases H, { subst H, rw add_left_cancel_iff at h₁, dsimp at h₁, subst h₁, exfalso, exact h₂ rfl }, { suffices : nat_degree q < j, { rw [coeff_eq_zero_of_degree_lt (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 this)), mul_zero] }, { by_contra H', rw not_lt at H', exact ne_of_lt (nat.lt_of_lt_of_le (nat.add_lt_add_right H j) (nat.add_le_add_left H' _)) h₁ } } } }, { intro H, exfalso, apply H, rw nat.mem_antidiagonal } end lemma degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; exact λ hp, by rw [hp, leading_coeff_zero, zero_mul], have hq : q ≠ 0 := by refine mt _ h; exact λ hq, by rw [hq, leading_coeff_zero, mul_zero], le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa coeff_mul_degree_add_degree end lemma nat_degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, zero_mul]), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, h $ by rw [h₁, mul_zero]), have hpq : p * q ≠ 0 := λ hpq, by rw [← coeff_mul_degree_add_degree, hpq, coeff_zero] at h; exact h rfl, option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q, by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq]) lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul_eq' h, coeff_mul_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = n •ℕ (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, zero_nsmul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, h $ by rw [pow_succ, h₁, mul_zero], have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul_eq' h₂, succ_nsmul, degree_pow_eq' h₁] lemma nat_degree_pow_eq' {n : ℕ} (h : leading_coeff p ^ n ≠ 0) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp * else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else have hpn : p ^ n ≠ 0, from λ hpn0, have h1 : _ := h, by rw [← leading_coeff_pow' h1, hpn0, leading_coeff_zero] at h; exact h rfl, option.some_inj.1 $ show (nat_degree (p ^ n) : with_bot ℕ) = (n * nat_degree p : ℕ), by rw [← degree_eq_nat_degree hpn, degree_pow_eq' h, degree_eq_nat_degree hp0, ← with_bot.coe_nsmul]; simp @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial R) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : R) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial R) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact h10, by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul] lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... ≤ _ : degree_sum_le _ _ ... ≤ _ : sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + n •ℕ (degree q) : add_le_add' degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + n •ℕ (nat_degree q) : add_le_add_left' (nsmul_le_nsmul_of_le_right (@degree_le_nat_degree _ _ q) n) ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_nsmul, nsmul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (finsupp.mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_map_le [comm_semiring S] (f : R →+* S) : degree (p.map f) ≤ degree p := if h : p.map f = 0 then by simp [h] else begin rw [degree_eq_nat_degree h], refine le_degree_of_ne_zero (mt (congr_arg f) _), rw [← coeff_map f, is_semiring_hom.map_zero f], exact mt leading_coeff_eq_zero.1 h end lemma subsingleton_of_monic_zero (h : monic (0 : polynomial R)) : (∀ p q : polynomial R, p = q) ∧ (∀ a b : R, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma degree_map_eq_of_leading_coeff_ne_zero [comm_semiring S] (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f) $ have hp0 : p ≠ 0, from λ hp0, by simpa [hp0, is_semiring_hom.map_zero f] using hf, begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma monic_map [comm_semiring S] (f : R →+* S) (hp : monic p) : monic (p.map f) := if h : (0 : S) = 1 then by haveI := subsingleton_of_zero_eq_one S h; exact subsingleton.elim _ _ else have f (leading_coeff p) ≠ 0, by rwa [show _ = _, from hp, is_semiring_hom.map_one f, ne.def, eq_comm], by erw [monic, leading_coeff, nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f this), coeff_map, ← leading_coeff, show _ = _, from hp, is_semiring_hom.map_one f] lemma zero_le_degree_iff {p : polynomial R} : 0 ≤ degree p ↔ p ≠ 0 := by rw [ne.def, ← degree_eq_bot]; cases degree p; exact dec_trivial @[simp] lemma coeff_mul_X_zero (p : polynomial R) : coeff (p * X) 0 = 0 := by rw [coeff_mul, nat.antidiagonal_zero]; simp only [polynomial.coeff_X_zero, finset.sum_singleton, mul_zero] lemma is_unit_C {x : R} : is_unit (C x) ↔ is_unit x := begin rw [is_unit_iff_dvd_one, is_unit_iff_dvd_one], split, { rintros ⟨g, hg⟩, replace hg := congr_arg (eval 0) hg, rw [eval_one, eval_mul, eval_C] at hg, exact ⟨g.eval 0, hg⟩ }, { rintros ⟨y, hy⟩, exact ⟨C y, by rw [← C_mul, ← hy, C_1]⟩ } end lemma degree_nonneg_iff_ne_zero : 0 ≤ degree p ↔ p ≠ 0 := ⟨λ h0p hp0, absurd h0p (by rw [hp0, degree_zero]; exact dec_trivial), λ hp0, le_of_not_gt (λ h, by simp [gt, degree_eq_bot, *] at *)⟩ lemma nat_degree_eq_zero_iff_degree_le_zero : p.nat_degree = 0 ↔ p.degree ≤ 0 := if hp0 : p = 0 then by simp [hp0] else by rw [degree_eq_nat_degree hp0, ← with_bot.coe_zero, with_bot.coe_le_coe, nat.le_zero_iff] lemma eq_one_of_is_unit_of_monic (hm : monic p) (hpu : is_unit p) : p = 1 := have degree p ≤ 0, from calc degree p ≤ degree (1 : polynomial R) : let ⟨u, hu⟩ := is_unit_iff_dvd_one.1 hpu in if hu0 : u = 0 then begin rw [hu0, mul_zero] at hu, rw [← mul_one p, hu, mul_zero], simp end else have p.leading_coeff * u.leading_coeff ≠ 0, by rw [hm.leading_coeff, one_mul, ne.def, leading_coeff_eq_zero]; exact hu0, by rw [hu, degree_mul_eq' this]; exact le_add_of_nonneg_right' (degree_nonneg_iff_ne_zero.2 hu0) ... ≤ 0 : degree_one_le, by rw [eq_C_of_degree_le_zero this, ← nat_degree_eq_zero_iff_degree_le_zero.2 this, ← leading_coeff, hm.leading_coeff, C_1] end comm_semiring instance subsingleton [subsingleton R] [comm_semiring R] : subsingleton (polynomial R) := ⟨λ _ _, ext (λ _, subsingleton.elim _ _)⟩ section comm_semiring variables [comm_semiring R] {p q r : polynomial R} lemma ne_zero_of_monic_of_zero_ne_one (hp : monic p) (h : (0 : R) ≠ 1) : p ≠ 0 := mt (congr_arg leading_coeff) $ by rw [monic.def.1 hp, leading_coeff_zero]; cc lemma eq_X_add_C_of_degree_le_one (h : degree p ≤ 1) : p = C (p.coeff 1) * X + C (p.coeff 0) := ext (λ n, nat.cases_on n (by simp) (λ n, nat.cases_on n (by simp [coeff_C]) (λ m, have degree p < m.succ.succ, from lt_of_le_of_lt h dec_trivial, by simp [coeff_eq_zero_of_degree_lt this, coeff_C, nat.succ_ne_zero, coeff_X, nat.succ_inj', @eq_comm ℕ 0]))) lemma eq_X_add_C_of_degree_eq_one (h : degree p = 1) : p = C (p.leading_coeff) * X + C (p.coeff 0) := (eq_X_add_C_of_degree_le_one (show degree p ≤ 1, from h ▸ le_refl _)).trans (by simp [leading_coeff, nat_degree_eq_of_degree_eq_some h]) theorem degree_C_mul_X_pow_le (r : R) (n : ℕ) : degree (C r * X^n) ≤ n := begin rw [← single_eq_C_mul_X], refine finset.sup_le (λ b hb, _), rw list.eq_of_mem_singleton (finsupp.support_single_subset hb), exact le_refl _ end theorem degree_X_pow_le (n : ℕ) : degree (X^n : polynomial R) ≤ n := by simpa only [C_1, one_mul] using degree_C_mul_X_pow_le (1:R) n theorem degree_X_le : degree (X : polynomial R) ≤ 1 := by simpa only [C_1, one_mul, pow_one] using degree_C_mul_X_pow_le (1:R) 1 section injective open function variables [comm_semiring S] {f : R →+* S} (hf : function.injective f) include hf lemma degree_map_eq_of_injective (p : polynomial R) : degree (p.map f) = degree p := if h : p = 0 then by simp [h] else degree_map_eq_of_leading_coeff_ne_zero _ (by rw [← is_semiring_hom.map_zero f]; exact mt hf.eq_iff.1 (mt leading_coeff_eq_zero.1 h)) lemma degree_map' (p : polynomial R) : degree (p.map f) = degree p := p.degree_map_eq_of_injective hf lemma nat_degree_map' (p : polynomial R) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map' hf p) lemma map_injective : injective (map f) := λ p q h, ext $ λ m, hf $ begin rw ext_iff at h, specialize h m, rw [coeff_map f, coeff_map f] at h, exact h end lemma leading_coeff_of_injective (p : polynomial R) : leading_coeff (p.map f) = f (leading_coeff p) := begin delta leading_coeff, rw [coeff_map f, nat_degree_map' hf p] end lemma monic_of_injective {p : polynomial R} (hp : (p.map f).monic) : p.monic := begin apply hf, rw [← leading_coeff_of_injective hf, hp.leading_coeff, is_semiring_hom.map_one f] end end injective theorem monic_of_degree_le (n : ℕ) (H1 : degree p ≤ n) (H2 : coeff p n = 1) : monic p := decidable.by_cases (assume H : degree p < n, @subsingleton.elim _ (subsingleton_of_zero_eq_one R $ H2 ▸ (coeff_eq_zero_of_degree_lt H).symm) _ _) (assume H : ¬degree p < n, by rwa [monic, leading_coeff, nat_degree, (lt_or_eq_of_le H1).resolve_left H]) theorem monic_X_pow_add {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) + p) := have H1 : degree p < n+1, from lt_of_le_of_lt H (with_bot.coe_lt_coe.2 (nat.lt_succ_self n)), monic_of_degree_le (n+1) (le_trans (degree_add_le _ _) (max_le (degree_X_pow_le _) (le_of_lt H1))) (by rw [coeff_add, coeff_X_pow, if_pos rfl, coeff_eq_zero_of_degree_lt H1, add_zero]) theorem monic_X_add_C (x : R) : monic (X + C x) := pow_one (X : polynomial R) ▸ monic_X_pow_add degree_C_le theorem degree_le_iff_coeff_zero (f : polynomial R) (n : with_bot ℕ) : degree f ≤ n ↔ ∀ m : ℕ, n < m → coeff f m = 0 := ⟨λ (H : finset.sup (f.support) some ≤ n) m (Hm : n < (m : with_bot ℕ)), decidable.of_not_not $ λ H4, have H1 : m ∉ f.support, from λ H2, not_lt_of_ge ((finset.sup_le_iff.1 H) m H2 : ((m : with_bot ℕ) ≤ n)) Hm, H1 $ (finsupp.mem_support_to_fun f m).2 H4, λ H, finset.sup_le $ λ b Hb, decidable.of_not_not $ λ Hn, (finsupp.mem_support_to_fun f b).1 Hb $ H b $ lt_of_not_ge Hn⟩ theorem nat_degree_le_of_degree_le {p : polynomial R} {n : ℕ} (H : degree p ≤ n) : nat_degree p ≤ n := show option.get_or_else (degree p) 0 ≤ n, from match degree p, H with | none, H := zero_le _ | (some d), H := with_bot.coe_le_coe.1 H end theorem leading_coeff_mul_X_pow {p : polynomial R} {n : ℕ} : leading_coeff (p * X ^ n) = leading_coeff p := decidable.by_cases (λ H : leading_coeff p = 0, by rw [H, leading_coeff_eq_zero.1 H, zero_mul, leading_coeff_zero]) (λ H : leading_coeff p ≠ 0, by rw [leading_coeff_mul', leading_coeff_X_pow, mul_one]; rwa [leading_coeff_X_pow, mul_one]) lemma monic_mul (hp : monic p) (hq : monic q) : monic (p * q) := if h0 : (0 : R) = 1 then by haveI := subsingleton_of_zero_eq_one _ h0; exact subsingleton.elim _ _ else have leading_coeff p * leading_coeff q ≠ 0, by simp [monic.def.1 hp, monic.def.1 hq, ne.symm h0], by rw [monic.def, leading_coeff_mul' this, monic.def.1 hp, monic.def.1 hq, one_mul] lemma monic_pow (hp : monic p) : ∀ (n : ℕ), monic (p ^ n) | 0 := monic_one | (n+1) := monic_mul hp (monic_pow n) lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : R) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact hq (subsingleton.elim _ _), ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hpn0 : p ^ (nat_degree q + 1) ≠ 0, from mt leading_coeff_eq_zero.2 $ by rw [leading_coeff_pow' hpn0', show _ = _, from hmp, one_pow]; exact zn0.symm, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul_eq' hpnr0, nat_degree_pow_eq' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_one_le_right' (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section nonzero_comm_semiring variables [comm_semiring R] [nonzero R] {p q : polynomial R} instance : nonzero (polynomial R) := { zero_ne_one := λ (h : (0 : polynomial R) = 1), zero_ne_one $ calc (0 : R) = eval 0 0 : eval_zero.symm ... = eval 0 1 : congr_arg _ h ... = 1 : eval_C } @[simp] lemma degree_one : degree (1 : polynomial R) = (0 : with_bot ℕ) := degree_C (show (1 : R) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial R) = 1 := begin unfold X degree monomial single finsupp.support, rw if_neg (one_ne_zero : (1 : R) ≠ 0), refl end lemma X_ne_zero : (X : polynomial R) ≠ 0 := mt (congr_arg (λ p, coeff p 1)) (by simp) @[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial R) ^ n) = n | 0 := by simp only [pow_zero, degree_one]; refl | (n+1) := have h : leading_coeff (X : polynomial R) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact zero_ne_one.symm, by rw [pow_succ, degree_mul_eq' h, degree_X, degree_X_pow, add_comm]; refl @[simp] lemma not_monic_zero : ¬monic (0 : polynomial R) := by simpa only [monic, leading_coeff_zero] using (zero_ne_one : (0 : R) ≠ 1) lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero R _ _ (h₁ ▸ h) end nonzero_comm_semiring section comm_semiring variables [comm_semiring R] {p q : polynomial R} /-- `dix_X p` return a polynomial `q` such that `q * X + C (p.coeff 0) = p`. It can be used in a semiring where the usual division algorithm is not possible -/ def div_X (p : polynomial R) : polynomial R := { to_fun := λ n, p.coeff (n + 1), support := ⟨(p.support.filter (> 0)).1.map (λ n, n - 1), multiset.nodup_map_on begin simp only [finset.mem_def.symm, finset.mem_erase, finset.mem_filter], assume x hx y hy hxy, rwa [← @add_right_cancel_iff _ _ 1, nat.sub_add_cancel hx.2, nat.sub_add_cancel hy.2] at hxy end (p.support.filter (> 0)).2⟩, mem_support_to_fun := λ n, suffices (∃ (a : ℕ), (¬coeff p a = 0 ∧ a > 0) ∧ a - 1 = n) ↔ ¬coeff p (n + 1) = 0, by simpa [finset.mem_def.symm, apply_eq_coeff], ⟨λ ⟨a, ha⟩, by rw [← ha.2, nat.sub_add_cancel ha.1.2]; exact ha.1.1, λ h, ⟨n + 1, ⟨h, nat.succ_pos _⟩, nat.succ_sub_one _⟩⟩ } lemma div_X_mul_X_add (p : polynomial R) : div_X p * X + C (p.coeff 0) = p := ext $ λ n, nat.cases_on n (by simp) (by simp [coeff_C, nat.succ_ne_zero, coeff_mul_X, div_X]) @[simp] lemma div_X_C (a : R) : div_X (C a) = 0 := ext $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff] lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) := ⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p, λ h, by rw [h, div_X_C]⟩ lemma div_X_add : div_X (p + q) = div_X p + div_X q := ext $ by simp [div_X] theorem nonzero.of_polynomial_ne (h : p ≠ q) : nonzero R := { zero_ne_one := λ h01 : 0 = 1, h $ by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero] } lemma degree_lt_degree_mul_X (hp : p ≠ 0) : p.degree < (p * X).degree := by haveI := nonzero.of_polynomial_ne hp; exact have leading_coeff p * leading_coeff X ≠ 0, by simpa, by erw [degree_mul_eq' this, degree_eq_nat_degree hp, degree_X, ← with_bot.coe_one, ← with_bot.coe_add, with_bot.coe_lt_coe]; exact nat.lt_succ_self _ lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree := by haveI := nonzero.of_polynomial_ne hp0; exact calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree : if h : degree p ≤ 0 then begin have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h], rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 $ by simp [h'])), end else have hXp0 : div_X p ≠ 0, by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h, have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa, have degree (C (p.coeff 0)) < degree (div_X p * X), from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le ... < 1 : dec_trivial ... = degree (X : polynomial R) : degree_X.symm ... ≤ degree (div_X p * X) : by rw [← zero_add (degree X), degree_mul_eq' this]; exact add_le_add' (by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff]; exact λ h0, h (h0.symm ▸ degree_C_le)) (le_refl _), by rw [add_comm, degree_add_eq_of_degree_lt this]; exact degree_lt_degree_mul_X hXp0 ... = p.degree : by rw div_X_mul_X_add @[elab_as_eliminator] noncomputable def rec_on_horner {M : polynomial R → Sort*} : Π (p : polynomial R), M 0 → (Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) → (Π p, p ≠ 0 → M p → M (p * X)) → M p | p := λ M0 MC MX, if hp : p = 0 then eq.rec_on hp.symm M0 else have wf : degree (div_X p) < degree p, from degree_div_X_lt hp, by rw [← div_X_mul_X_add p] at *; exact if hcp0 : coeff p 0 = 0 then by rw [hcp0, C_0, add_zero]; exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp) (rec_on_horner _ M0 MC MX) else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0 then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0 else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX)) using_well_founded {dec_tac := tactic.assumption} @[elab_as_eliminator] lemma degree_pos_induction_on {P : polynomial R → Prop} (p : polynomial R) (h0 : 0 < degree p) (hC : ∀ {a}, a ≠ 0 → P (C a * X)) (hX : ∀ {p}, 0 < degree p → P p → P (p * X)) (hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p := rec_on_horner p (λ h, by rw degree_zero at h; exact absurd h dec_trivial) (λ p a _ _ ih h0, have 0 < degree p, from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $ by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0), hadd this (ih this)) (λ p _ ih h0', if h0 : 0 < degree p then hX h0 (ih h0) else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *; exact hC (λ h : coeff p 0 = 0, by simpa [h, nat.not_lt_zero] using h0')) h0 end comm_semiring section comm_ring variables [comm_ring R] {p q : polynomial R} instance : comm_ring (polynomial R) := add_monoid_algebra.comm_ring variable (R) def lcoeff (n : ℕ) : polynomial R →ₗ[R] R := { to_fun := λ f, coeff f n, map_add' := λ f g, coeff_add f g n, map_smul' := λ r p, coeff_smul p r n } variable {R} @[simp] lemma lcoeff_apply (n : ℕ) (f : polynomial R) : lcoeff R n f = coeff f n := rfl instance : is_ring_hom (C : R → polynomial R) := (C : R →ₐ[R] polynomial R).to_ring_hom.is_ring_hom lemma int_cast_eq_C (n : ℤ) : (n : polynomial R) = C ↑n := ((C : R →ₐ[R] _).to_ring_hom.map_int_cast n).symm lemma C_neg : C (-a) = -C a := alg_hom.map_neg C a lemma C_sub : C (a - b) = C a - C b := alg_hom.map_sub C a b instance eval₂.is_ring_hom {S} [comm_ring S] (f : R → S) [is_ring_hom f] {x : S} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : R} : is_ring_hom (eval x) := eval₂.is_ring_hom _ instance map.is_ring_hom {S} [comm_ring S] (f : R →+* S) : is_ring_hom (map f) := eval₂.is_ring_hom (C ∘ f) @[simp] lemma map_sub {S} [comm_ring S] (f : R →+* S) : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _ @[simp] lemma map_neg {S} [comm_ring S] (f : R →+* S) : (-p).map f = -(p.map f) := is_ring_hom.map_neg _ @[simp] lemma degree_neg (p : polynomial R) : degree (-p) = degree p := by unfold degree; rw support_neg lemma degree_sub_le (p q : polynomial R) : degree (p - q) ≤ max (degree p) (degree q) := degree_neg q ▸ degree_add_le p (-q) @[simp] lemma nat_degree_neg (p : polynomial R) : nat_degree (-p) = nat_degree p := by simp [nat_degree] @[simp] lemma nat_degree_int_cast (n : ℤ) : nat_degree (n : polynomial R) = 0 := by simp [int_cast_eq_C] @[simp] lemma coeff_neg (p : polynomial R) (n : ℕ) : coeff (-p) n = -coeff p n := rfl @[simp] lemma coeff_sub (p q : polynomial R) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl @[simp] lemma eval₂_neg {S} [comm_ring S] (f : R → S) [is_ring_hom f] {x : S} : (-p).eval₂ f x = -p.eval₂ f x := is_ring_hom.map_neg _ @[simp] lemma eval₂_sub {S} [comm_ring S] (f : R → S) [is_ring_hom f] {x : S} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := is_ring_hom.map_sub _ @[simp] lemma eval_neg (p : polynomial R) (x : R) : (-p).eval x = -p.eval x := is_ring_hom.map_neg _ @[simp] lemma eval_sub (p q : polynomial R) (x : R) : (p - q).eval x = p.eval x - q.eval x := is_ring_hom.map_sub _ section aeval /-- `R[X]` is the generator of the category `R-Alg`. -/ instance polynomial (R : Type u) [comm_semiring R] : algebra R (polynomial R) := { commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, (polynomial.C_mul' c p).symm, .. polynomial.semimodule, .. ring_hom.of polynomial.C } variables (R) (A) variables [comm_ring A] [algebra R A] variables (x : A) /-- Given a valuation `x` of the variable in an `R`-algebra `A`, `aeval R A x` is the unique `R`-algebra homomorphism from `R[X]` to `A` sending `X` to `x`. -/ def aeval : polynomial R →ₐ[R] A := { commutes' := λ r, eval₂_C _ _, ..eval₂_ring_hom (algebra_map R A) x } variables {R A} theorem aeval_def (p : polynomial R) : aeval R A x p = eval₂ (algebra_map R A) x p := rfl @[simp] lemma aeval_X : aeval R A x X = x := eval₂_X _ x @[simp] lemma aeval_C (r : R) : aeval R A x (C r) = algebra_map R A r := eval₂_C _ x theorem eval_unique (φ : polynomial R →ₐ[R] A) (p) : φ p = eval₂ (algebra_map R A) (φ X) p := begin apply polynomial.induction_on p, { intro r, rw eval₂_C, exact φ.commutes r }, { intros f g ih1 ih2, rw [φ.map_add, ih1, ih2, eval₂_add] }, { intros n r ih, rw [pow_succ', ← mul_assoc, φ.map_mul, eval₂_mul (algebra_map R A), eval₂_X, ih] } end end aeval lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 | h := begin rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) * leading_coeff q ≠ 0, by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one], if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one]) noncomputable def div_mod_by_monic_aux : Π (p : polynomial R) {q : polynomial R}, monic q → polynomial R × polynomial R | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial R) : polynomial R := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial R) : polynomial R := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q) (hq0 : q ≠ 0), degree (p %ₘ q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq0)), end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : polynomial R) {q : polynomial R} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) @[simp] lemma zero_mod_by_monic (p : polynomial R) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : polynomial R) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : polynomial R) : p %ₘ 0 = p := if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : polynomial R) : p /ₘ 0 = 0 := if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := if hq0 : q = 0 then have ∀ (p : polynomial R), p = 0, from λ p, (@subsingleton_of_monic_zero R _ (hq0 ▸ hq)).1 _ _, by rw [this (p /ₘ q), this p, this q]; refl else have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0 ... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) lemma degree_div_by_monic_le (p q : polynomial R) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if h : degree q ≤ degree p then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial R) {q : polynomial R} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if hpq : degree p < degree q then begin rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_some _ end else begin rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q)) end lemma div_mod_by_monic_unique {f g} (q r : polynomial R) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := if hg0 : g = 0 then by split; exact (subsingleton_of_monic_zero (hg0 ▸ hg : monic (0 : polynomial R))).1 _ _ else have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (-(f %ₘ g))) : degree_add_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, by rw degree_neg; exact degree_mod_by_monic_lt _ hg hg0⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg0, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul_eq']; simpa [monic.def.1 hg]), ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ lemma map_mod_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := if h01 : (0 : S) = 1 then by haveI := subsingleton_of_zero_eq_one S h01; exact ⟨subsingleton.elim _ _, subsingleton.elim _ _⟩ else have h01R : (0 : R) ≠ 1, from mt (congr_arg f) (by rwa [is_semiring_hom.map_one f, is_semiring_hom.map_zero f]), have map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), from (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq) ⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ ... < degree q : degree_mod_by_monic_lt _ hq $ (ne_zero_of_monic_of_zero_ne_one hq h01R) ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, is_semiring_hom.map_one f]; exact ne.symm h01)⟩), ⟨this.1.symm, this.2.symm⟩ lemma map_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, if hq0 : q = 0 then by rw hq0 at hq; exact (subsingleton_of_monic_zero hq).1 _ _ else let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in by_contradiction (λ hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q) := by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr], have degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq hq0, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this; exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩ @[simp] lemma mod_by_monic_one (p : polynomial R) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero monic_one).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : polynomial R) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, exact hp (finsupp.ext (λ n, show coeff p n = 0, from nat.cases_on n h (λ _, coeff_eq_zero_of_degree_lt (lt_of_le_of_lt hlt (with_bot.coe_lt_coe.2 (nat.succ_pos _)))))), end theorem monic_X_sub_C (x : R) : monic (X - C x) := by simpa only [C_neg] using monic_X_add_C (-x) theorem monic_X_pow_sub {n : ℕ} (H : degree p ≤ n) : monic (X ^ (n+1) - p) := monic_X_pow_add ((degree_neg p).symm ▸ H) theorem degree_mod_by_monic_le (p : polynomial R) {q : polynomial R} (hq : monic q) : degree (p %ₘ q) ≤ degree q := decidable.by_cases (assume H : q = 0, by rw [monic, H, leading_coeff_zero] at hq; have : (0:polynomial R) = 1 := (by rw [← C_0, ← C_1, hq]); rw [eq_zero_of_zero_eq_one _ this (p %ₘ q), eq_zero_of_zero_eq_one _ this q]; exact le_refl _) (assume H : q ≠ 0, le_of_lt $ degree_mod_by_monic_lt _ hq H) lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] end comm_ring section nonzero_comm_ring variables [comm_ring R] [nonzero R] {p q : polynomial R} @[simp] lemma degree_X_sub_C (a : R) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X R], by_cases ha : a = 0, { simp only [ha, C_0, neg_zero, zero_add] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : degree ((X : polynomial R) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial R) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial R) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : R) : (X : polynomial R) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial R) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn a; exact dec_trivial) end nonzero_comm_ring section comm_ring variables [comm_ring R] {p q : polynomial R} @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p %ₘ (X - C a) = C (p.eval a) := if h0 : (0 : R) = 1 then by letI := subsingleton_of_zero_eq_one R h0; exact subsingleton.elim _ _ else by letI : nonzero R := nonzero.of_ne h0; exact have h : (p %ₘ (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ ne_zero_of_monic (monic_X_sub_C _)), have degree (p %ₘ (X - C a)) ≤ 0 := begin cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } end, begin rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma mod_by_monic_X (p : polynomial R) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] section multiplicity def decidable_dvd_monic (p : polynomial R) (hq : monic q) : decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) open_locale classical lemma multiplicity_X_sub_C_finite (a : R) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := multiplicity_finite_of_degree_pos_of_monic (have (0 : R) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one _ h; exact h0 (subsingleton.elim _ _)), by haveI : nonzero R := ⟨this⟩; rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) h0 def root_multiplicity (a : R) (p : polynomial R) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : polynomial R) (a : R) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, roption.dom]; congr; funext; congr lemma pow_root_multiplicity_dvd (p : polynomial R) (a : R) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : polynomial R) (a : R) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from monic_pow (monic_X_sub_C _) _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : polynomial R} (a : R) (hp : p ≠ 0) : (p /ₘ ((X - C a) ^ root_multiplicity a p)).eval a ≠ 0 := begin haveI : nonzero R := nonzero.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring section integral_domain variables [integral_domain R] {p q : polynomial R} @[simp] lemma degree_mul_eq : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp only [hp0, degree_zero, zero_mul, with_bot.bot_add] else if hq0 : q = 0 then by simp only [hq0, degree_zero, mul_zero, with_bot.add_bot] else degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow_eq (p : polynomial R) (n : ℕ) : degree (p ^ n) = n •ℕ (degree p) := by induction n; [simp only [pow_zero, degree_one, zero_nsmul], simp only [*, pow_succ, succ_nsmul, degree_mul_eq]] @[simp] lemma leading_coeff_mul (p q : polynomial R) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp only [hp, zero_mul, leading_coeff_zero] }, { by_cases hq : q = 0, { simp only [hq, mul_zero, leading_coeff_zero] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_pow (p : polynomial R) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := by induction n; [simp only [pow_zero, leading_coeff_one], simp only [*, pow_succ, leading_coeff_mul]] instance : integral_domain (polynomial R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, erw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nonzero, ..polynomial.comm_ring } lemma nat_degree_mul_eq (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul_eq] @[simp] lemma nat_degree_pow_eq (p : polynomial R) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow_eq' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := by rw [is_root, eval_mul] at h; exact eq_zero_or_eq_zero_of_mul_eq_zero h lemma degree_le_mul_left (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul_eq, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) lemma exists_finset_roots : ∀ {p : polynomial R} (hp : p ≠ 0), ∃ s : finset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 : with_bot.coe_le_coe.2 $ finset.card_insert_le _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add' (le_refl (1 : with_bot ℕ)) htd, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by simpa only [not_mem_empty, false_iff, not_exists] using h⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial R) : finset R := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_finset_roots hp0)).1 end lemma card_roots' {p : polynomial R} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) lemma card_roots_sub_C {p : polynomial R} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : polynomial R} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ @[simp] lemma mem_roots_sub_C {p : polynomial R} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : polynomial R) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial R) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial R) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots {R : Type*} [integral_domain R] (n : ℕ) (a : R) : finset R := roots ((X : polynomial R) ^ n - C a) @[simp] lemma mem_nth_roots {R : Type*} [integral_domain R] {n : ℕ} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] lemma card_nth_roots {R : Type*} [integral_domain R] (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : polynomial R) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, card_empty] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← C_1, ← @is_ring_hom.map_sub _ _ _ _ (@C R _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, rwa [← apply_eq_coeff, ← finsupp.mem_support_iff], dsimp [apply_eq_coeff], refine coeff_eq_zero_of_degree_lt _, rw [degree_mul_eq, degree_C this, degree_pow_eq, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_nsmul, nsmul_eq_mul, with_bot.coe_lt_coe, nat.cast_id], exact (mul_lt_mul_right (nat.pos_of_ne_zero hqd0)).2 (lt_of_le_of_ne (with_bot.coe_le_coe.1 (by rw ← degree_eq_nat_degree hp0; exact le_sup hbs)) hbp) end (by rw [finsupp.mem_support_iff, apply_eq_coeff, ← leading_coeff, ne.def, leading_coeff_eq_zero, classical.not_not]; simp {contextual := tt}) ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow_eq], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial R) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul_eq hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial R)) : degree (u : polynomial R) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ @[simp] lemma nat_degree_coe_units (u : units (polynomial R)) : nat_degree (u : polynomial R) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma coeff_coe_units_zero_ne_zero (u : units (polynomial R)) : coeff (u : polynomial R) 0 ≠ 0 := begin conv in (0) {rw [← nat_degree_coe_units u]}, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.coe_ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.2 _ _ hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul_eq, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) lemma prime_of_degree_eq_one_of_monic (hp1 : degree p = 1) (hm : monic p) : prime p := have p = X - C (- p.coeff 0), by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1, ⟨mt degree_eq_bot.2 $ hp1.symm ▸ dec_trivial, mt degree_eq_zero_of_is_unit (by simp [hp1]; exact dec_trivial), λ _ _, begin rw [this, dvd_iff_is_root, dvd_iff_is_root, dvd_iff_is_root, is_root, is_root, is_root, eval_mul, mul_eq_zero], exact id end⟩ lemma irreducible_of_degree_eq_one_of_monic (hp1 : degree p = 1) (hm : monic p) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one_of_monic hp1 hm) end integral_domain section field variables [field R] {p q : polynomial R} lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, by rw [eq_C_of_degree_le_zero h] at hp0 hp; exact (hp $ is_unit.map' C $ is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))) lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial R) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul_eq, degree_C h₁, add_zero] def div (p q : polynomial R) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) def mod (p q : polynomial R) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial R) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial R) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial R) := ⟨div⟩ instance : has_mod (polynomial R) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial R) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial R) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial R) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq), .. polynomial.comm_ring, .. polynomial.nonzero } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm, degree_add_eq_of_degree_lt this, degree_mul_eq]} lemma degree_div_le (p q : polynomial R) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [field k] (p : polynomial R) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective (is_ring_hom.injective f) @[simp] lemma nat_degree_map [field k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [field k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp [leading_coeff, coeff_map f] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [is_ring_hom.map_inv f, leading_coeff, coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← is_ring_hom.map_inv f, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] @[simp] lemma map_eq_zero [field k] (f : R →+* k) : p.map f = 0 ↔ p = 0 := by simp [polynomial.ext_iff, is_ring_hom.map_eq_zero f, coeff_map] lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial R)) (n : ℕ) : ((↑u : polynomial R).coeff n)⁻¹ = ((↑u⁻¹ : polynomial R).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end instance : normalization_domain (polynomial R) := { norm_unit := λ p, if hp0 : p = 0 then 1 else ⟨C p.leading_coeff⁻¹, C p.leading_coeff, by rw [← C_mul, inv_mul_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0, by rw [← C_mul, mul_inv_cancel, C_1]; exact mt leading_coeff_eq_zero.1 hp0,⟩, norm_unit_zero := dif_pos rfl, norm_unit_mul := λ p q hp0 hq0, begin rw [dif_neg hp0, dif_neg hq0, dif_neg (mul_ne_zero hp0 hq0)], apply units.ext, show C (leading_coeff (p * q))⁻¹ = C (leading_coeff p)⁻¹ * C (leading_coeff q)⁻¹, rw [leading_coeff_mul, mul_inv', C_mul, mul_comm] end, norm_unit_coe_units := λ u, have hu : degree ↑u⁻¹ = 0, from degree_eq_zero_of_is_unit ⟨u⁻¹, rfl⟩, begin apply units.ext, rw [dif_neg (units.coe_ne_zero u)], conv_rhs {rw eq_C_of_degree_eq_zero hu}, refine C_inj.2 _, rw [← nat_degree_eq_of_degree_eq_some hu, leading_coeff, coeff_inv_units], simp end, ..polynomial.integral_domain } lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := show leading_coeff (p * ↑(dite _ _ _)) = 1, by rw dif_neg hp0; exact monic_mul_leading_coeff_inv hp0 lemma coe_norm_unit (hp : p ≠ 0) : (norm_unit p : polynomial R) = C p.leading_coeff⁻¹ := show ↑(dite _ _ _) = C p.leading_coeff⁻¹, by rw dif_neg hp; refl @[simp] lemma degree_normalize : degree (normalize p) = degree p := if hp0 : p = 0 then by simp [hp0] else by rw [normalize, degree_mul_eq, degree_eq_zero_of_is_unit (is_unit_unit _), add_zero] lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p := have prime (normalize p), from prime_of_degree_eq_one_of_monic (hp1 ▸ degree_normalize) (monic_normalize (λ hp0, absurd hp1 (hp0.symm ▸ by simp; exact dec_trivial))), prime_of_associated normalize_associated this lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one hp1) theorem pairwise_coprime_X_sub {α : Type u} [field α] {I : Type v} {s : I → α} (H : function.injective s) : pairwise (is_coprime on (λ i : I, polynomial.X - polynomial.C (s i))) := λ i j hij, have h : s j - s i ≠ 0, from sub_ne_zero_of_ne $ function.injective.ne H hij.symm, ⟨polynomial.C (s j - s i)⁻¹, -polynomial.C (s j - s i)⁻¹, by rw [neg_mul_eq_neg_mul_symm, ← sub_eq_add_neg, ← mul_sub, sub_sub_sub_cancel_left, ← polynomial.C_sub, ← polynomial.C_mul, inv_mul_cancel h, polynomial.C_1]⟩ end field section derivative variables [comm_semiring R] /-- `derivative p` is the formal derivative of the polynomial `p` -/ def derivative (p : polynomial R) : polynomial R := p.sum (λn a, C (a * n) * X^(n - 1)) lemma coeff_derivative (p : polynomial R) (n : ℕ) : coeff (derivative p) n = coeff p (n + 1) * (n + 1) := begin rw [derivative], simp only [coeff_X_pow, coeff_sum, coeff_C_mul], rw [finsupp.sum, finset.sum_eq_single (n + 1), apply_eq_coeff], { rw [if_pos (nat.add_sub_cancel _ _).symm, mul_one, nat.cast_add, nat.cast_one] }, { assume b, cases b, { intros, rw [nat.cast_zero, mul_zero, zero_mul] }, { intros _ H, rw [nat.succ_sub_one b, if_neg (mt (congr_arg nat.succ) H.symm), mul_zero] } }, { intro H, rw [not_mem_support_iff.1 H, zero_mul, zero_mul] } end @[simp] lemma derivative_zero : derivative (0 : polynomial R) = 0 := finsupp.sum_zero_index lemma derivative_monomial (a : R) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, sum_single_index, single_eq_C_mul_X]; simp only [zero_mul, C_0]; refl @[simp] lemma derivative_C {a : R} : derivative (C a) = 0 := suffices derivative (C a * X^0) = C (a * 0:R) * X ^ 0, by simpa only [mul_one, zero_mul, C_0, mul_zero, pow_zero], derivative_monomial a 0 @[simp] lemma derivative_X : derivative (X : polynomial R) = 1 := by simpa only [mul_one, one_mul, C_1, pow_one, nat.cast_one, pow_zero] using derivative_monomial (1:R) 1 @[simp] lemma derivative_one : derivative (1 : polynomial R) = 0 := derivative_C @[simp] lemma derivative_add {f g : polynomial R} : derivative (f + g) = derivative f + derivative g := by refine finsupp.sum_add_index _ _; intros; simp only [add_mul, zero_mul, C_0, C_add, C_mul] /-- The formal derivative of polynomials, as additive homomorphism. -/ def derivative_hom (R : Type*) [comm_semiring R] : polynomial R →+ polynomial R := { to_fun := derivative, map_zero' := derivative_zero, map_add' := λ p q, derivative_add } @[simp] lemma derivative_neg {R : Type*} [comm_ring R] (f : polynomial R) : derivative (-f) = -derivative f := (derivative_hom R).map_neg f @[simp] lemma derivative_sub {R : Type*} [comm_ring R] (f g : polynomial R) : derivative (f - g) = derivative f - derivative g := (derivative_hom R).map_sub f g instance : is_add_monoid_hom (derivative : polynomial R → polynomial R) := (derivative_hom R).is_add_monoid_hom @[simp] lemma derivative_sum {s : finset ι} {f : ι → polynomial R} : derivative (∑ b in s, f b) = ∑ b in s, derivative (f b) := (derivative_hom R).map_sum f s @[simp] lemma derivative_mul {f g : polynomial R} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_monomial _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C a * X^n) * (C (b * m) * X^(m - 1)))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by simp only [nat.cast_add, mul_add, add_mul, C_add, C_mul]; cases n; simp only [nat.succ_sub_succ, pow_zero]; cases m; simp only [nat.cast_zero, C_0, nat.succ_sub_succ, zero_mul, mul_zero, nat.sub_zero, pow_zero, pow_add, one_mul, pow_succ, mul_comm, mul_left_comm] ... = derivative f * g + f * derivative g : begin conv { to_rhs, congr, { rw [← sum_C_mul_X_eq g] }, { rw [← sum_C_mul_X_eq f] } }, unfold derivative finsupp.sum, simp only [sum_add_distrib, finset.mul_sum, finset.sum_mul] end lemma derivative_eval (p : polynomial R) (x : R) : p.derivative.eval x = p.sum (λ n a, (a * n)*x^(n-1)) := by simp [derivative, eval_sum, eval_pow] @[simp] lemma derivative_smul (r : R) (p : polynomial R) : derivative (r • p) = r • derivative p := by { ext, simp only [coeff_derivative, mul_assoc, coeff_smul], } /-- The formal derivative of polynomials, as linear homomorphism. -/ def derivative_lhom (R : Type*) [comm_ring R] : polynomial R →ₗ[R] polynomial R := { to_fun := derivative, map_add' := λ p q, derivative_add, map_smul' := λ r p, derivative_smul r p } /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : polynomial K) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : polynomial K) (f /ₘ (X - C a)) := begin refine or.resolve_left (dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end end derivative section domain variables [integral_domain R] lemma mem_support_derivative [char_zero R] (p : polynomial R) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(coeff p (n + 1) = 0 ∨ ((n + 1:ℕ) : R) = 0)) ↔ coeff p (n + 1) ≠ 0, by simpa only [coeff_derivative, apply_eq_coeff, mem_support_iff, ne.def, mul_eq_zero], by rw [nat.cast_eq_zero]; simp only [nat.succ_ne_zero, or_false] @[simp] lemma degree_derivative_eq [char_zero R] (p : polynomial R) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := le_antisymm (le_trans (degree_sum_le _ _) $ sup_le $ assume n hn, have n ≤ nat_degree p, begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], { refine le_degree_of_ne_zero _, simpa only [mem_support_iff] using hn }, { assume h, simpa only [h, support_zero] using hn } end, le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _) begin refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp end end domain section identities /- @TODO: pow_add_expansion and pow_sub_pow_factor are not specific to polynomials. These belong somewhere else. But not in group_power because they depend on tactic.ring Maybe use data.nat.choose to prove it. -/ def pow_add_expansion {R : Type*} [comm_semiring R] (x y : R) : ∀ (n : ℕ), {k // (x + y)^n = x^n + n*x^(n-1)*y + k * y^2} | 0 := ⟨0, by simp⟩ | 1 := ⟨0, by simp⟩ | (n+2) := begin cases pow_add_expansion (n+1) with z hz, existsi x*z + (n+1)*x^n+z*y, calc (x + y) ^ (n + 2) = (x + y) * (x + y) ^ (n + 1) : by ring_exp ... = (x + y) * (x ^ (n + 1) + ↑(n + 1) * x ^ (n + 1 - 1) * y + z * y ^ 2) : by rw hz ... = x ^ (n + 2) + ↑(n + 2) * x ^ (n + 1) * y + (x*z + (n+1)*x^n+z*y) * y ^ 2 : by { push_cast, ring_exp! } end variables [comm_ring R] private def poly_binom_aux1 (x y : R) (e : ℕ) (a : R) : {k : R // a * (x + y)^e = a * (x^e + e*x^(e-1)*y + k*y^2)} := begin existsi (pow_add_expansion x y e).val, congr, apply (pow_add_expansion _ _ _).property end private lemma poly_binom_aux2 (f : polynomial R) (x y : R) : f.eval (x + y) = f.sum (λ e a, a * (x^e + e*x^(e-1)*y + (poly_binom_aux1 x y e a).val*y^2)) := begin unfold eval eval₂, congr, ext, apply (poly_binom_aux1 x y _ _).property end private lemma poly_binom_aux3 (f : polynomial R) (x y : R) : f.eval (x + y) = f.sum (λ e a, a * x^e) + f.sum (λ e a, (a * e * x^(e-1)) * y) + f.sum (λ e a, (a *(poly_binom_aux1 x y e a).val)*y^2) := by rw poly_binom_aux2; simp [left_distrib, finsupp.sum_add, mul_assoc] def binom_expansion (f : polynomial R) (x y : R) : {k : R // f.eval (x + y) = f.eval x + (f.derivative.eval x) * y + k * y^2} := begin existsi f.sum (λ e a, a *((poly_binom_aux1 x y e a).val)), rw poly_binom_aux3, congr, { rw derivative_eval, symmetry, apply finsupp.sum_mul }, { symmetry, apply finsupp.sum_mul } end def pow_sub_pow_factor (x y : R) : Π (i : ℕ), {z : R // x^i - y^i = z * (x - y)} | 0 := ⟨0, by simp⟩ | 1 := ⟨1, by simp⟩ | (k+2) := begin cases @pow_sub_pow_factor (k+1) with z hz, existsi z*x + y^(k+1), calc x ^ (k + 2) - y ^ (k + 2) = x * (x ^ (k + 1) - y ^ (k + 1)) + (x * y ^ (k + 1) - y ^ (k + 2)) : by ring_exp ... = x * (z * (x - y)) + (x * y ^ (k + 1) - y ^ (k + 2)) : by rw hz ... = (z * x + y ^ (k + 1)) * (x - y) : by ring_exp end def eval_sub_factor (f : polynomial R) (x y : R) : {z : R // f.eval x - f.eval y = z * (x - y)} := begin refine ⟨f.sum (λ i r, r * (pow_sub_pow_factor x y i).val), _⟩, delta eval eval₂, rw ← finsupp.sum_sub, rw finsupp.sum_mul, delta finsupp.sum, congr, ext i r, dsimp, rw [mul_assoc, ←(pow_sub_pow_factor x y _).property, mul_sub], end end identities end polynomial namespace is_integral_domain variables {R : Type*} [comm_ring R] /-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/ lemma polynomial (h : is_integral_domain R) : is_integral_domain (polynomial R) := @integral_domain.to_is_integral_domain _ (@polynomial.integral_domain _ (h.to_integral_domain _)) end is_integral_domain
6f10998ad407d3604eb821cb0f19b54aaca669cb
e61a235b8468b03aee0120bf26ec615c045005d2
/src/Init/Lean/Compiler/IR/RC.lean
c0160eb0302c64ecb900694aa0d445f81160ff7e
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,639
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 -/ prelude import Init.Lean.Runtime import Init.Lean.Compiler.IR.CompilerM import Init.Lean.Compiler.IR.LiveVars namespace Lean namespace IR namespace ExplicitRC /- Insert explicit RC instructions. So, it assumes the input code does not contain `inc` nor `dec` instructions. This transformation is applied before lower level optimizations that introduce the instructions `release` and `set` -/ structure VarInfo := (ref : Bool := true) -- true if the variable may be a reference (aka pointer) at runtime (persistent : Bool := false) -- true if the variable is statically known to be marked a Persistent at runtime (consume : Bool := false) -- true if the variable RC must be "consumed" abbrev VarMap := RBMap VarId VarInfo (fun x y => x.idx < y.idx) structure Context := (env : Environment) (decls : Array Decl) (varMap : VarMap := {}) (jpLiveVarMap : JPLiveVarMap := {}) -- map: join point => live variables (localCtx : LocalContext := {}) -- we use it to store the join point declarations def getDecl (ctx : Context) (fid : FunId) : Decl := match findEnvDecl' ctx.env fid ctx.decls with | some decl => decl | none => arbitrary _ -- unreachable if well-formed def getVarInfo (ctx : Context) (x : VarId) : VarInfo := match ctx.varMap.find? x with | some info => info | none => {} -- unreachable in well-formed code def getJPParams (ctx : Context) (j : JoinPointId) : Array Param := match ctx.localCtx.getJPParams j with | some ps => ps | none => #[] -- unreachable in well-formed code def getJPLiveVars (ctx : Context) (j : JoinPointId) : LiveVarSet := match ctx.jpLiveVarMap.find? j with | some s => s | none => {} def mustConsume (ctx : Context) (x : VarId) : Bool := let info := getVarInfo ctx x; info.ref && info.consume @[inline] def addInc (ctx : Context) (x : VarId) (b : FnBody) (n := 1) : FnBody := let info := getVarInfo ctx x; if n == 0 then b else FnBody.inc x n true info.persistent b @[inline] def addDec (ctx : Context) (x : VarId) (b : FnBody) : FnBody := let info := getVarInfo ctx x; FnBody.dec x 1 true info.persistent b private def updateRefUsingCtorInfo (ctx : Context) (x : VarId) (c : CtorInfo) : Context := if c.isRef then ctx else let m := ctx.varMap; { ctx with varMap := match m.find? x with | some info => m.insert x { info with ref := false } -- I really want a Lenses library + notation | none => m } private def addDecForAlt (ctx : Context) (caseLiveVars altLiveVars : LiveVarSet) (b : FnBody) : FnBody := caseLiveVars.fold (fun b x => if !altLiveVars.contains x && mustConsume ctx x then addDec ctx x b else b) b /- `isFirstOcc xs x i = true` if `xs[i]` is the first occurrence of `xs[i]` in `xs` -/ private def isFirstOcc (xs : Array Arg) (i : Nat) : Bool := let x := xs.get! i; i.all $ fun j => xs.get! j != x /- Return true if `x` also occurs in `ys` in a position that is not consumed. That is, it is also passed as a borrow reference. -/ @[specialize] private def isBorrowParamAux (x : VarId) (ys : Array Arg) (consumeParamPred : Nat → Bool) : Bool := ys.size.any $ fun i => let y := ys.get! i; match y with | Arg.irrelevant => false | Arg.var y => x == y && !consumeParamPred i private def isBorrowParam (x : VarId) (ys : Array Arg) (ps : Array Param) : Bool := isBorrowParamAux x ys (fun i => not (ps.get! i).borrow) /- Return `n`, the number of times `x` is consumed. - `ys` is a sequence of instruction parameters where we search for `x`. - `consumeParamPred i = true` if parameter `i` is consumed. -/ @[specialize] private def getNumConsumptions (x : VarId) (ys : Array Arg) (consumeParamPred : Nat → Bool) : Nat := ys.size.fold (fun i n => let y := ys.get! i; match y with | Arg.irrelevant => n | Arg.var y => if x == y && consumeParamPred i then n+1 else n) 0 @[specialize] private def addIncBeforeAux (ctx : Context) (xs : Array Arg) (consumeParamPred : Nat → Bool) (b : FnBody) (liveVarsAfter : LiveVarSet) : FnBody := xs.size.fold (fun i b => let x := xs.get! i; match x with | Arg.irrelevant => b | Arg.var x => let info := getVarInfo ctx x; if !info.ref || !isFirstOcc xs i then b else let numConsuptions := getNumConsumptions x xs consumeParamPred; -- number of times the argument is let numIncs := if !info.consume || -- `x` is not a variable that must be consumed by the current procedure liveVarsAfter.contains x || -- `x` is live after executing instruction isBorrowParamAux x xs consumeParamPred -- `x` is used in a position that is passed as a borrow reference then numConsuptions else numConsuptions - 1; -- dbgTrace ("addInc " ++ toString x ++ " nconsumptions: " ++ toString numConsuptions ++ " incs: " ++ toString numIncs -- ++ " consume: " ++ toString info.consume ++ " live: " ++ toString (liveVarsAfter.contains x) -- ++ " borrowParam : " ++ toString (isBorrowParamAux x xs consumeParamPred)) $ fun _ => addInc ctx x b numIncs) b private def addIncBefore (ctx : Context) (xs : Array Arg) (ps : Array Param) (b : FnBody) (liveVarsAfter : LiveVarSet) : FnBody := addIncBeforeAux ctx xs (fun i => not (ps.get! i).borrow) b liveVarsAfter /- See `addIncBeforeAux`/`addIncBefore` for the procedure that inserts `inc` operations before an application. -/ private def addDecAfterFullApp (ctx : Context) (xs : Array Arg) (ps : Array Param) (b : FnBody) (bLiveVars : LiveVarSet) : FnBody := xs.size.fold (fun i b => match xs.get! i with | Arg.irrelevant => b | Arg.var x => /- We must add a `dec` if `x` must be consumed, it is alive after the application, and it has been borrowed by the application. Remark: `x` may occur multiple times in the application (e.g., `f x y x`). This is why we check whether it is the first occurrence. -/ if mustConsume ctx x && isFirstOcc xs i && isBorrowParam x xs ps && !bLiveVars.contains x then addDec ctx x b else b) b private def addIncBeforeConsumeAll (ctx : Context) (xs : Array Arg) (b : FnBody) (liveVarsAfter : LiveVarSet) : FnBody := addIncBeforeAux ctx xs (fun i => true) b liveVarsAfter /- Add `dec` instructions for parameters that are references, are not alive in `b`, and are not borrow. That is, we must make sure these parameters are consumed. -/ private def addDecForDeadParams (ctx : Context) (ps : Array Param) (b : FnBody) (bLiveVars : LiveVarSet) : FnBody := ps.foldl (fun b p => if !p.borrow && p.ty.isObj && !bLiveVars.contains p.x then addDec ctx p.x b else b) b private def isPersistent : Expr → Bool | Expr.fap c xs => xs.isEmpty -- all global constants are persistent objects | _ => false /- We do not need to consume the projection of a variable that is not consumed -/ private def consumeExpr (m : VarMap) : Expr → Bool | Expr.proj i x => match m.find? x with | some info => info.consume | none => true | other => true /- Return true iff `v` at runtime is a scalar value stored in a tagged pointer. We do not need RC operations for this kind of value. -/ private def isScalarBoxedInTaggedPtr (v : Expr) : Bool := match v with | Expr.ctor c ys => c.size == 0 && c.ssize == 0 && c.usize == 0 | Expr.lit (LitVal.num n) => n ≤ maxSmallNat | _ => false private def updateVarInfo (ctx : Context) (x : VarId) (t : IRType) (v : Expr) : Context := { ctx with varMap := ctx.varMap.insert x { ref := t.isObj && !isScalarBoxedInTaggedPtr v, persistent := isPersistent v, consume := consumeExpr ctx.varMap v } } private def addDecIfNeeded (ctx : Context) (x : VarId) (b : FnBody) (bLiveVars : LiveVarSet) : FnBody := if mustConsume ctx x && !bLiveVars.contains x then addDec ctx x b else b private def processVDecl (ctx : Context) (z : VarId) (t : IRType) (v : Expr) (b : FnBody) (bLiveVars : LiveVarSet) : FnBody × LiveVarSet := -- dbgTrace ("processVDecl " ++ toString z ++ " " ++ toString (format v)) $ fun _ => let b := match v with | (Expr.ctor _ ys) => addIncBeforeConsumeAll ctx ys (FnBody.vdecl z t v b) bLiveVars | (Expr.reuse _ _ _ ys) => addIncBeforeConsumeAll ctx ys (FnBody.vdecl z t v b) bLiveVars | (Expr.proj _ x) => let b := addDecIfNeeded ctx x b bLiveVars; let b := if (getVarInfo ctx x).consume then addInc ctx z b else b; (FnBody.vdecl z t v b) | (Expr.uproj _ x) => FnBody.vdecl z t v (addDecIfNeeded ctx x b bLiveVars) | (Expr.sproj _ _ x) => FnBody.vdecl z t v (addDecIfNeeded ctx x b bLiveVars) | (Expr.fap f ys) => -- dbgTrace ("processVDecl " ++ toString v) $ fun _ => let ps := (getDecl ctx f).params; let b := addDecAfterFullApp ctx ys ps b bLiveVars; let b := FnBody.vdecl z t v b; addIncBefore ctx ys ps b bLiveVars | (Expr.pap _ ys) => addIncBeforeConsumeAll ctx ys (FnBody.vdecl z t v b) bLiveVars | (Expr.ap x ys) => let ysx := ys.push (Arg.var x); -- TODO: avoid temporary array allocation addIncBeforeConsumeAll ctx ysx (FnBody.vdecl z t v b) bLiveVars | (Expr.unbox x) => FnBody.vdecl z t v (addDecIfNeeded ctx x b bLiveVars) | other => FnBody.vdecl z t v b; -- Expr.reset, Expr.box, Expr.lit are handled here let liveVars := updateLiveVars v bLiveVars; let liveVars := liveVars.erase z; (b, liveVars) def updateVarInfoWithParams (ctx : Context) (ps : Array Param) : Context := let m := ps.foldl (fun (m : VarMap) p => m.insert p.x { ref := p.ty.isObj, consume := !p.borrow }) ctx.varMap; { ctx with varMap := m } partial def visitFnBody : FnBody → Context → (FnBody × LiveVarSet) | FnBody.vdecl x t v b, ctx => let ctx := updateVarInfo ctx x t v; let (b, bLiveVars) := visitFnBody b ctx; processVDecl ctx x t v b bLiveVars | FnBody.jdecl j xs v b, ctx => let (v, vLiveVars) := visitFnBody v (updateVarInfoWithParams ctx xs); let v := addDecForDeadParams ctx xs v vLiveVars; let ctx := { ctx with jpLiveVarMap := updateJPLiveVarMap j xs v ctx.jpLiveVarMap }; let (b, bLiveVars) := visitFnBody b ctx; (FnBody.jdecl j xs v b, bLiveVars) | FnBody.uset x i y b, ctx => let (b, s) := visitFnBody b ctx; -- We don't need to insert `y` since we only need to track live variables that are references at runtime let s := s.insert x; (FnBody.uset x i y b, s) | FnBody.sset x i o y t b, ctx => let (b, s) := visitFnBody b ctx; -- We don't need to insert `y` since we only need to track live variables that are references at runtime let s := s.insert x; (FnBody.sset x i o y t b, s) | FnBody.mdata m b, ctx => let (b, s) := visitFnBody b ctx; (FnBody.mdata m b, s) | b@(FnBody.case tid x xType alts), ctx => let caseLiveVars := collectLiveVars b ctx.jpLiveVarMap; let alts := alts.map $ fun alt => match alt with | Alt.ctor c b => let ctx := updateRefUsingCtorInfo ctx x c; let (b, altLiveVars) := visitFnBody b ctx; let b := addDecForAlt ctx caseLiveVars altLiveVars b; Alt.ctor c b | Alt.default b => let (b, altLiveVars) := visitFnBody b ctx; let b := addDecForAlt ctx caseLiveVars altLiveVars b; Alt.default b; (FnBody.case tid x xType alts, caseLiveVars) | b@(FnBody.ret x), ctx => match x with | Arg.var x => let info := getVarInfo ctx x; if info.ref && !info.consume then (addInc ctx x b, mkLiveVarSet x) else (b, mkLiveVarSet x) | _ => (b, {}) | b@(FnBody.jmp j xs), ctx => let jLiveVars := getJPLiveVars ctx j; let ps := getJPParams ctx j; let b := addIncBefore ctx xs ps b jLiveVars; let bLiveVars := collectLiveVars b ctx.jpLiveVarMap; (b, bLiveVars) | FnBody.unreachable, _ => (FnBody.unreachable, {}) | other, ctx => (other, {}) -- unreachable if well-formed partial def visitDecl (env : Environment) (decls : Array Decl) : Decl → Decl | Decl.fdecl f xs t b => let ctx : Context := { env := env, decls := decls }; let ctx := updateVarInfoWithParams ctx xs; let (b, bLiveVars) := visitFnBody b ctx; let b := addDecForDeadParams ctx xs b bLiveVars; Decl.fdecl f xs t b | other => other end ExplicitRC def explicitRC (decls : Array Decl) : CompilerM (Array Decl) := do env ← getEnv; pure $ decls.map (ExplicitRC.visitDecl env decls) end IR end Lean
f1626f7332c9cd180b7b486d8d6ea7858b9f2813
618003631150032a5676f229d13a079ac875ff77
/src/topology/instances/real.lean
8ae95f6a1ede600056f8370ed2799d56f0117d1f
[ "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
14,883
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 The real numbers ℝ. They are constructed as the topological completion of ℚ. With the following steps: (1) prove that ℚ forms a uniform space. (2) subtraction and addition are uniform continuous functions in this space (3) for multiplication and inverse this only holds on bounded subsets (4) ℝ is defined as separated Cauchy filters over ℚ (the separation requires a quotient construction) (5) extend the uniform continuous functions along the completion (6) proof field properties using the principle of extension of identities TODO generalizations: * topological groups & rings * order topologies * Archimedean fields -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring noncomputable theory open classical set filter topological_space metric open_locale classical open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl section low_prio -- we want to ignore this instance for the next declaration local attribute [instance, priority 10] int.uniform_space instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), have : (abs (↑a - ↑b) : ℝ) < 1 := h, have : abs (a - b) < 1, by norm_cast at this; assumption, have : abs (a - b) ≤ 0 := (@int.lt_add_one_iff _ 0).mp this, norm_cast, assumption end end low_prio theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, hl, hu, h⟩ := (mem_nhds_unbounded (no_top _) (no_bot _)).mp (mem_nhds_sets hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by simp; exact ⟨q, p, rat.cast_lt.1 $ lt_trans hqa hap, rfl⟩, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h _ (lt_trans hlq hqa') (lt_trans ha'p hpu)⟩) instance : second_countable_topology ℝ := ⟨⟨(⋃(a b : ℚ) (h : a < b), {Ioo a b}), by simp [countable_Union, countable_Union_Prop], real.is_topological_basis_Ioo_rat.2.2⟩⟩ /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma real.continuous_abs : continuous (abs : ℝ → ℝ) := real.uniform_continuous_abs.continuous lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma rat.continuous_abs : continuous (abs : ℚ → ℚ) := rat.uniform_continuous_abs.continuous lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos_iff at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (mem_nhds_sets (real.continuous_abs _ $ is_open_lt' (abs r / 2)) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.2 $ λ ε ε0, begin cases no_top (abs x) with y xy, have y0 := lt_of_le_of_lt (abs_nonneg _) xy, refine ⟨_, div_pos ε0 y0, λ a b h, _⟩, rw [real.dist_eq, ← mul_sub, abs_mul, ← mul_div_cancel' ε (ne_of_gt y0)], exact mul_lt_mul' (le_of_lt xy) h (abs_nonneg _) y0 end lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (mem_nhds_sets (is_open_prod (real.continuous_abs _ $ is_open_gt' (abs a₁ + 1)) (real.continuous_abs _ $ is_open_gt' (abs a₂ + 1))) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance -- short-circuit type class inference lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] lemma real.totally_bounded_Ioo (a b : ℝ) : totally_bounded (Ioo a b) := metric.totally_bounded_iff.2 $ λ ε ε0, begin rcases exists_nat_gt ((b - a) / ε) with ⟨n, ba⟩, rw [div_lt_iff' ε0, sub_lt_iff_lt_add'] at ba, let s := (λ i:ℕ, a + ε * i) '' {i:ℕ | i < n}, refine ⟨s, finite_image _ ⟨set.fintype_lt_nat _⟩, λ x h, _⟩, rcases h with ⟨ax, xb⟩, let i : ℕ := ⌊(x - a) / ε⌋.to_nat, have : (i : ℤ) = ⌊(x - a) / ε⌋ := int.to_nat_of_nonneg (floor_nonneg.2 $ le_of_lt (div_pos (sub_pos.2 ax) ε0)), simp, use i, split, { rw [← int.coe_nat_lt, this], refine int.cast_lt.1 (lt_of_le_of_lt (floor_le _) _), rw [int.cast_coe_nat, div_lt_iff' ε0, sub_lt_iff_lt_add'], exact lt_trans xb ba }, { rw [real.dist_eq, ← int.cast_coe_nat, this, abs_of_nonneg, ← sub_sub, sub_lt_iff_lt_add'], { have := lt_floor_add_one ((x - a) / ε), rwa [div_lt_iff' ε0, mul_add, mul_one] at this }, { have := floor_le ((x - a) / ε), rwa [ge, sub_nonneg, ← le_sub_iff_add_le', ← le_div_iff' ε0] } } end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply real.totally_bounded_Ioo lemma real.totally_bounded_Ico (a b : ℝ) : totally_bounded (Ico a b) := let ⟨c, ac⟩ := no_bot a in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨lt_of_lt_of_le ac h₁, h₂⟩) (real.totally_bounded_Ioo c b) lemma real.totally_bounded_Icc (a b : ℝ) : totally_bounded (Icc a b) := let ⟨c, bc⟩ := no_top b in totally_bounded_subset (by exact λ x ⟨h₁, h₂⟩, ⟨h₁, lt_of_le_of_lt h₂ bc⟩) (real.totally_bounded_Ico a c) lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (real.totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end lemma tendsto_coe_nat_real_at_top_iff {f : α → ℕ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, nat.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨n, le_of_lt hn⟩ lemma tendsto_coe_nat_real_at_top_at_top : tendsto (coe : ℕ → ℝ) at_top at_top := tendsto_coe_nat_real_at_top_iff.2 tendsto_id lemma tendsto_coe_int_real_at_top_iff {f : α → ℤ} {l : filter α} : tendsto (λ n, (f n : ℝ)) l at_top ↔ tendsto f l at_top := tendsto_at_top_embedding (assume a₁ a₂, int.cast_le) $ assume r, let ⟨n, hn⟩ := exists_nat_gt r in ⟨(n:ℤ), le_of_lt $ by rwa [int.cast_coe_nat]⟩ lemma tendsto_coe_int_real_at_top_at_top : tendsto (coe : ℤ → ℝ) at_top at_top := tendsto_coe_int_real_at_top_iff.2 tendsto_id section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((closure_subset_iff_subset_of_is_closed (is_closed_ge' _)).2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma compact_Icc {a b : ℝ} : compact (Icc a b) := compact_of_totally_bounded_is_closed (real.totally_bounded_Icc a b) (is_closed_inter (is_closed_ge' a) (is_closed_le' b)) instance : proper_space ℝ := { compact_ball := λx r, by rw closed_ball_Icc; apply compact_Icc } lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm hx, hM hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ end
0b24cc71394b6cbd28582be52f3c42db6f5b85e9
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/openExport.lean
85e3408921d03da63ca357a33c855cf86e437b8b
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
464
lean
new_frontend def A.x := 10 namespace B export A (x) def y := 20 #check x -- works #check y -- works end B #check A.x -- works #check B.x -- works, but fails in old frontend and Lean3 :) #check B.y -- works #check x -- fails as expected #check y -- fails as expected open B #check x -- works #check y -- works namespace B #check x -- works #check y -- works def z := 30 #check z -- works end B #check z -- works, but fails in old frontend and Lean3 :)
1c158635e58e14485c2a423f1cedf11371d90119
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/order/extension.lean
aeb7172a4b11d8e6cef0e5c2c205dbac69bfe47a
[ "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
3,906
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import data.set.lattice import order.zorn /-! # Extend a partial order to a linear order This file constructs a linear order which is an extension of the given partial order, using Zorn's lemma. -/ universes u open set classical open_locale classical /-- Any partial order can be extended to a linear order. -/ theorem extend_partial_order {α : Type u} (r : α → α → Prop) [is_partial_order α r] : ∃ (s : α → α → Prop) (_ : is_linear_order α s), r ≤ s := begin let S := {s | is_partial_order α s}, have hS : ∀ c, c ⊆ S → zorn.chain (≤) c → ∀ y ∈ c, (∃ ub ∈ S, ∀ z ∈ c, z ≤ ub), { rintro c hc₁ hc₂ s hs, haveI := (hc₁ hs).1, refine ⟨Sup c, _, λ z hz, le_Sup hz⟩, refine { refl := _, trans := _, antisymm := _ }; simp_rw binary_relation_Sup_iff, { intro x, exact ⟨s, hs, refl x⟩ }, { rintro x y z ⟨s₁, h₁s₁, h₂s₁⟩ ⟨s₂, h₁s₂, h₂s₂⟩, haveI : is_partial_order _ _ := hc₁ h₁s₁, haveI : is_partial_order _ _ := hc₁ h₁s₂, cases hc₂.total_of_refl h₁s₁ h₁s₂, { exact ⟨s₂, h₁s₂, trans (h _ _ h₂s₁) h₂s₂⟩ }, { exact ⟨s₁, h₁s₁, trans h₂s₁ (h _ _ h₂s₂)⟩ } }, { rintro x y ⟨s₁, h₁s₁, h₂s₁⟩ ⟨s₂, h₁s₂, h₂s₂⟩, haveI : is_partial_order _ _ := hc₁ h₁s₁, haveI : is_partial_order _ _ := hc₁ h₁s₂, cases hc₂.total_of_refl h₁s₁ h₁s₂, { exact antisymm (h _ _ h₂s₁) h₂s₂ }, { apply antisymm h₂s₁ (h _ _ h₂s₂) } } }, obtain ⟨s, hs₁ : is_partial_order _ _, rs, hs₂⟩ := zorn.zorn_nonempty_partial_order₀ S hS r ‹_›, resetI, refine ⟨s, { total := _ }, rs⟩, intros x y, by_contra h, push_neg at h, let s' := λ x' y', s x' y' ∨ s x' x ∧ s y y', rw ←hs₂ s' _ (λ _ _, or.inl) at h, { apply h.1 (or.inr ⟨refl _, refl _⟩) }, { refine { refl := λ x, or.inl (refl _), trans := _, antisymm := _ }, { rintro a b c (ab | ⟨ax : s a x, yb : s y b⟩) (bc | ⟨bx : s b x, yc : s y c⟩), { exact or.inl (trans ab bc), }, { exact or.inr ⟨trans ab bx, yc⟩ }, { exact or.inr ⟨ax, trans yb bc⟩ }, { exact or.inr ⟨ax, yc⟩ } }, { rintro a b (ab | ⟨ax : s a x, yb : s y b⟩) (ba | ⟨bx : s b x, ya : s y a⟩), { exact antisymm ab ba }, { exact (h.2 (trans ya (trans ab bx))).elim }, { exact (h.2 (trans yb (trans ba ax))).elim }, { exact (h.2 (trans yb bx)).elim } } }, end /-- A type alias for `α`, intended to extend a partial order on `α` to a linear order. -/ def linear_extension (α : Type u) : Type u := α noncomputable instance {α : Type u} [partial_order α] : linear_order (linear_extension α) := { le := (extend_partial_order ((≤) : α → α → Prop)).some, le_refl := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.1.1.1, le_trans := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.1.2.1, le_antisymm := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.1.2.1, le_total := (extend_partial_order ((≤) : α → α → Prop)).some_spec.some.2.1, decidable_le := classical.dec_rel _ } /-- The embedding of `α` into `linear_extension α` as a relation homomorphism. -/ def to_linear_extension {α : Type u} [partial_order α] : ((≤) : α → α → Prop) →r ((≤) : linear_extension α → linear_extension α → Prop) := { to_fun := λ x, x, map_rel' := λ a b, (extend_partial_order ((≤) : α → α → Prop)).some_spec.some_spec _ _ } instance {α : Type u} [inhabited α] : inhabited (linear_extension α) := ⟨(default _ : α)⟩
bc9c29b3b15b1af1d5dff5497365965b57ea005c
9028d228ac200bbefe3a711342514dd4e4458bff
/src/topology/uniform_space/compact_separated.lean
23d4ca210290b21417a7522ea41e8d622ea95ba4
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,603
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.separation /-! # Compact separated uniform spaces ## Main statements * `compact_space_uniformity`: On a separated compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. * `uniform_space_of_compact_t2`: every compact T2 topological structure is induced by a uniform structure. This uniform structure is described in the previous item. * Heine-Cantor theorem: continuous functions on compact separated uniform spaces with values in uniform spaces are automatically uniformly continuous. There are several variations, the main one is `compact_space.uniform_continuous_of_continuous`. ## Implementation notes The construction `uniform_space_of_compact_t2` is not declared as an instance, as it would badly loop. ## tags uniform space, uniform continuity, compact space -/ open_locale classical uniformity topological_space filter open filter uniform_space set variables {α β : Type*} [uniform_space α] [uniform_space β] /-! ### Uniformity on compact separated spaces -/ lemma compact_space_uniformity [compact_space α] [separated_space α] : 𝓤 α = ⨆ x : α, 𝓝 (x, x) := begin symmetry, refine le_antisymm nhds_le_uniformity _, by_contra H, obtain ⟨V, hV, h⟩ : ∃ V : set (α × α), (∀ x : α, V ∈ 𝓝 (x, x)) ∧ ne_bot (𝓤 α ⊓ 𝓟 Vᶜ), { rw le_iff_forall_inf_principal_compl at H, push_neg at H, simpa only [mem_supr_sets] using H }, let F := 𝓤 α ⊓ 𝓟 Vᶜ, haveI : ne_bot F := h, obtain ⟨⟨x, y⟩, hx⟩ : ∃ (p : α × α), cluster_pt p F := cluster_point_of_compact F, have : cluster_pt (x, y) (𝓤 α) := hx.of_inf_left, have hxy : x = y := eq_of_uniformity_inf_nhds this, subst hxy, have : cluster_pt (x, x) (𝓟 Vᶜ) := hx.of_inf_right, have : (x, x) ∉ interior V, { have : (x, x) ∈ closure Vᶜ, by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have : (x, x) ∈ interior V, { rw mem_interior_iff_mem_nhds, exact hV x }, contradiction end lemma unique_uniformity_of_compact_t2 {α : Type*} [t : topological_space α] [compact_space α] [t2_space α] {u u' : uniform_space α} (h : u.to_topological_space = t) (h' : u'.to_topological_space = t) : u = u' := begin apply uniform_space_eq, change uniformity _ = uniformity _, haveI : @compact_space α u.to_topological_space := by rw h ; assumption, haveI : @compact_space α u'.to_topological_space := by rw h' ; assumption, haveI : @separated_space α u := by rwa [separated_iff_t2, h], haveI : @separated_space α u' := by rwa [separated_iff_t2, h'], rw [compact_space_uniformity, compact_space_uniformity, h, h'] end /-- The unique uniform structure inducing a given compact Hausdorff topological structure. -/ def uniform_space_of_compact_t2 {α : Type*} [topological_space α] [compact_space α] [t2_space α] : uniform_space α := { uniformity := ⨆ x, 𝓝 (x, x), refl := begin simp_rw [filter.principal_le_iff, mem_supr_sets], rintros V V_in ⟨x, _⟩ ⟨⟩, exact mem_of_nhds (V_in x), end, symm := begin refine le_of_eq _, rw map_supr, congr' with x : 1, erw [nhds_prod_eq, ← prod_comm], end, comp := begin /- This is the difficult part of the proof. We need to prove that, for each neighborhood W of the diagonal Δ, W ○ W is still a neighborhood of the diagonal. -/ set 𝓝Δ := ⨆ x : α, 𝓝 (x, x), -- The filter of neighborhoods of Δ set F := 𝓝Δ.lift' (λ (s : set (α × α)), s ○ s), -- Compositions of neighborhoods of Δ -- If this weren't true, then there would be V ∈ 𝓝Δ such that F ⊓ 𝓟 Vᶜ ≠ ⊥ rw le_iff_forall_inf_principal_compl, intros V V_in, by_contra H, haveI : ne_bot (F ⊓ 𝓟 Vᶜ) := H, -- Hence compactness would give us a cluster point (x, y) for F ⊓ 𝓟 Vᶜ obtain ⟨⟨x, y⟩, hxy⟩ : ∃ (p : α × α), cluster_pt p (F ⊓ 𝓟 Vᶜ) := cluster_point_of_compact _, -- In particular (x, y) is a cluster point of 𝓟 Vᶜ, hence is not in the interior of V, -- and a fortiori not in Δ, so x ≠ y have clV : cluster_pt (x, y) (𝓟 $ Vᶜ) := hxy.of_inf_right, have : (x, y) ∉ interior V, { have : (x, y) ∈ closure (Vᶜ), by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have diag_subset : diagonal α ⊆ interior V, { rw subset_interior_iff_nhds, rintros ⟨x, x⟩ ⟨⟩, exact (mem_supr_sets.mp V_in : _) x }, have x_ne_y : x ≠ y, { intro h, apply this, apply diag_subset, simp [h] }, -- Since α is compact and Hausdorff, it is normal, hence regular. haveI : normal_space α := normal_of_compact_t2, -- So there are closed neighboords V₁ and V₂ of x and y contained in disjoint open neighborhoods -- U₁ and U₂. obtain ⟨U₁, V₁, U₁_in, V₁_in, U₂, V₂, U₂_in₂, V₂_in, V₁_cl, V₂_cl, U₁_op, U₂_op, VU₁, VU₂, hU₁₂⟩ : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ U₁ ∩ U₂ = ∅ := disjoint_nested_nhds x_ne_y, -- We set U₃ := (V₁ ∪ V₂)ᶜ so that W := (U₁.prod U₁) ∪ (U₂.prod U₂) ∪ (U₃.prod U₃) is an open -- neighborhood of Δ. let U₃ := (V₁ ∪ V₂)ᶜ, have U₃_op : is_open U₃ := is_open_compl_iff.mpr (is_closed_union V₁_cl V₂_cl), let W := (U₁.prod U₁) ∪ (U₂.prod U₂) ∪ (U₃.prod U₃), have W_in : W ∈ 𝓝Δ, { rw mem_supr_sets, intros x, apply mem_nhds_sets (is_open_union (is_open_union _ _) _), { by_cases hx : x ∈ V₁ ∪ V₂, { left, cases hx with hx hx ; [left, right] ; split ; tauto }, { right, rw mem_prod, tauto }, }, all_goals { simp only [is_open.prod, *] } }, -- So W ○ W ∈ F by definition of F have : W ○ W ∈ F, { dsimp [F],-- Lean has weird elaboration trouble with this line exact mem_lift' W_in }, -- And V₁.prod V₂ ∈ 𝓝 (x, y) have hV₁₂ : V₁.prod V₂ ∈ 𝓝 (x, y) := prod_mem_nhds_sets V₁_in V₂_in, -- But (x, y) is also a cluster point of F so (V₁.prod V₂) ∩ (W ○ W) ≠ ∅ have clF : cluster_pt (x, y) F := hxy.of_inf_left, obtain ⟨p, p_in⟩ : ∃ p, p ∈ (V₁.prod V₂) ∩ (W ○ W) := cluster_pt_iff.mp clF hV₁₂ this, -- However the construction of W implies (V₁.prod V₂) ∩ (W ○ W) = ∅. -- Indeed assume for contradiction there is some (u, v) in the intersection. -- So u ∈ V₁, v ∈ V₂, and there exists some w such that (u, w) ∈ W and (w ,v) ∈ W. -- Because u is in V₁ which is disjoint from U₂ and U₃, (u, w) ∈ W forces (u, w) ∈ U₁.prod U₁. -- Similarly, because v ∈ V₂, (w ,v) ∈ W forces (w, v) ∈ U₂.prod U₂. -- Hence w ∈ U₁ ∩ U₂ which is empty. have inter_empty : (V₁.prod V₂) ∩ (W ○ W) = ∅, { rw eq_empty_iff_forall_not_mem, rintros ⟨u, v⟩ ⟨⟨u_in, v_in⟩, w, huw, hwv⟩, have uw_in : (u, w) ∈ U₁.prod U₁ := set.mem_prod.2 ((huw.resolve_right (λ h, (h.1 $ or.inl u_in))).resolve_right (λ h, have u ∈ U₁ ∩ U₂, from ⟨VU₁ u_in, h.1⟩, by rwa hU₁₂ at this)), have wv_in : (w, v) ∈ U₂.prod U₂ := set.mem_prod.2 ((hwv.resolve_right (λ h, (h.2 $ or.inr v_in))).resolve_left (λ h, have v ∈ U₁ ∩ U₂, from ⟨h.2, VU₂ v_in⟩, by rwa hU₁₂ at this)), have : w ∈ U₁ ∩ U₂ := ⟨uw_in.2, wv_in.1⟩, rwa hU₁₂ at this }, -- So we have a contradiction rwa inter_empty at p_in, end, is_open_uniformity := begin -- Here we need to prove the topology induced by the constructed uniformity is the -- topology we started with. suffices : ∀ x : α, comap (prod.mk x) (⨆ y, 𝓝 (y ,y)) = 𝓝 x, { intros s, change is_open s ↔ _, simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity_aux, this] }, intros x, simp_rw [comap_supr, nhds_prod_eq, comap_prod, show prod.fst ∘ prod.mk x = λ y : α, x, by ext ; simp, show prod.snd ∘ (prod.mk x) = (id : α → α), by ext ; refl, comap_id], rw [supr_split_single _ x, comap_const_of_mem (λ V, mem_of_nhds)], suffices : ∀ y ≠ x, comap (λ (y : α), x) (𝓝 y) ⊓ 𝓝 y ≤ 𝓝 x, by simpa, intros y hxy, simp [comap_const_of_not_mem (compl_singleton_mem_nhds hxy) (by simp)], end } /-! ### Heine-Cantor theorem -/ /-- Heine-Cantor: a continuous function on a compact separated uniform space is uniformly continuous. -/ lemma compact_space.uniform_continuous_of_continuous [compact_space α] [separated_space α] {f : α → β} (h : continuous f) : uniform_continuous f := calc map (prod.map f f) (𝓤 α) = map (prod.map f f) (⨆ x, 𝓝 (x, x)) : by rw compact_space_uniformity ... = ⨆ x, map (prod.map f f) (𝓝 (x, x)) : by rw map_supr ... ≤ ⨆ x, 𝓝 (f x, f x) : supr_le_supr (λ x, (h.prod_map h).continuous_at) ... ≤ ⨆ y, 𝓝 (y, y) : supr_comp_le (λ y, 𝓝 (y, y)) f ... ≤ 𝓤 β : nhds_le_uniformity /-- Heine-Cantor: a continuous function on a compact separated set of a uniform space is uniformly continuous. -/ lemma is_compact.uniform_continuous_on_of_continuous' {s : set α} {f : α → β} (hs : is_compact s) (hs' : is_separated s) (hf : continuous_on f s) : uniform_continuous_on f s := begin rw uniform_continuous_on_iff_restrict, rw is_separated_iff_induced at hs', rw compact_iff_compact_space at hs, rw continuous_on_iff_continuous_restrict at hf, resetI, exact compact_space.uniform_continuous_of_continuous hf, end /-- Heine-Cantor: a continuous function on a compact set of a separated uniform space is uniformly continuous. -/ lemma is_compact.uniform_continuous_on_of_continuous [separated_space α] {s : set α} {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : uniform_continuous_on f s := hs.uniform_continuous_on_of_continuous' (is_separated_of_separated_space s) hf
74a34486fcbb3a3d99ed8be2a3ca75d995596fad
3dd1b66af77106badae6edb1c4dea91a146ead30
/library/hott/string.lean
9c168d2c659a9869f272771d951d1906d73e6b8b
[ "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
394
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import bool namespace string inductive char : Type := | ascii : bool → bool → bool → bool → bool → bool → bool → bool → char inductive string : Type := | empty : string | str : char → string → string end
a63529680fc390812eebdaa95be9a7dad7b2ba01
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/hw6_quiz/cleaned up notes/propositional_logic_test.lean
4827d18cd456ef2a26b522bdc3b19927e51d4269
[]
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
2,195
lean
--justin import .propositional_logic_syntax_and_semantics #check pAnd P Q #check P ∧ Q #check P ∨ Q #check ¬ P #check P > Q #eval pEval P interp_all_false #eval pEval P interp_all_true #eval pEval Q #eval pEval R -- Examples of larger expressions #eval pEval (pOr (pAnd P Q) R) -- (P ∧ Q) ∨ R #eval pEval ((P ∧ Q) ∨ R) -- if you want to evaluate it, you have to do it under an interpretation #eval pEval ((P ∧ Q) ∨ R) interp_all_false #eval pEval ((P ∧ Q) ∨ R) interp_all_true #eval pEval (pAnd (pOr P Q ) (pAnd P Q ) ) interp_all_true -- Let's rewrite in nicer notation #eval pEval ((P ∨ Q) ∧ (P ∧ Q)) interp_all_true #eval pEval (P > Q) interp_all_false #eval pEval (P > Q) interp_all_true def tt_ff_interp : var → bool | (var.mk 0) := tt-- P_var | (var.mk 1) := ff -- Q_var | _ := ff #eval pEval (P > Q) tt_ff_interp def lots_of_fun := pAnd (pOr P Q) (pNot P) def lots_of_fun' := (P ∨ Q) ∧ ¬ P def sat : var → bool | (var.mk 0) := ff -- P_var | (var.mk 1) := tt -- Q_var | (var.mk _) := ff -- otherwise #eval pEval lots_of_fun sat -- We have found a *satisfying solution* -- An interpretation that makes an expression true! -- A problem that has a solution is said to be *satisfiable* -- A problem that has no solution is said be *unsatisfiable* -- A problem for which every interp is a solution is said to be *valid* -- Satisfiable but not valid -- pAnd P (pNot P) -- P ∧ ¬ P -- never true -- pOr P (pNot P) -- P ∨ ¬ P /- Proof by case analysis - P=true: true ∨ false = true - P=false: false ∨ true = true -/ /- VALID RULES OF REASON -- (P ∧ Q) → (Q ∧ P) ¬ (P ∧ Q) → (¬ P) ∨ (¬ Q) ¬ (P ∨ Q) → (¬ P ∧ ¬ Q) -- not valid (P → Q) → (Q → P) -/ #eval pEval pTrue #eval pEval pFalse #eval pEval (pNot pTrue) #eval pEval (pNot pFalse) def p1 := pTrue def p2 := pFalse def p25 := pNot p2 def p3 := pAnd pTrue pFalse def p4 := pOr p3 p2 #eval pEval p3 #eval pEval p4 #eval pEval (pImp p3 p4)
9304b1b1e811e2d91f782bd6172a9c60d56a098a
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/nat_bug7.lean
c0bcfb924c42802f826335a070e8a0cc8ebcd237
[ "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
418
lean
namespace experiment inductive nat : Type | zero : nat | succ : nat → nat namespace nat definition add (x y : nat) : nat := nat.rec x (λn r, succ r) y infixl `+` := add axiom add_right_comm (n m k : nat) : n + m + k = n + k + m open eq print "===========================" theorem bug (a b c d : nat) : a + b + c + d = a + c + b + d := subst (add_right_comm a b c) (eq.refl (a + b + c + d)) end nat end experiment
980932b2d51d81cca6cd7b0e410a05548a05e593
c777c32c8e484e195053731103c5e52af26a25d1
/src/combinatorics/simple_graph/regularity/equitabilise.lean
32e964da201a549cfedd2cadf093a917fe71d52e
[ "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
10,691
lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import order.partition.equipartition /-! # Equitabilising a partition > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file allows to blow partitions up into parts of controlled size. Given a partition `P` and `a b m : ℕ`, we want to find a partition `Q` with `a` parts of size `m` and `b` parts of size `m + 1` such that all parts of `P` are "as close as possible" to unions of parts of `Q`. By "as close as possible", we mean that each part of `P` can be written as the union of some parts of `Q` along with at most `m` other elements. ## Main declarations * `finpartition.equitabilise`: `P.equitabilise h` where `h : a * m + b * (m + 1)` is a partition with `a` parts of size `m` and `b` parts of size `m + 1` which almost refines `P`. * `finpartition.exists_equipartition_card_eq`: We can find equipartitions of arbitrary size. -/ open finset nat namespace finpartition variables {α : Type*} [decidable_eq α] {s t : finset α} {m n a b : ℕ} {P : finpartition s} /-- Given a partition `P` of `s`, as well as a proof that `a * m + b * (m + 1) = s.card`, we can find a new partition `Q` of `s` where each part has size `m` or `m + 1`, every part of `P` is the union of parts of `Q` plus at most `m` extra elements, there are `b` parts of size `m + 1` and (provided `m > 0`, because a partition does not have parts of size `0`) there are `a` parts of size `m` and hence `a + b` parts in total. -/ lemma equitabilise_aux (P : finpartition s) (hs : a * m + b * (m + 1) = s.card) : ∃ Q : finpartition s, (∀ x : finset α, x ∈ Q.parts → x.card = m ∨ x.card = m + 1) ∧ (∀ x, x ∈ P.parts → (x \ (Q.parts.filter $ λ y, y ⊆ x).bUnion id).card ≤ m) ∧ (Q.parts.filter $ λ i, card i = m + 1).card = b := begin -- Get rid of the easy case `m = 0` obtain rfl | m_pos := m.eq_zero_or_pos, { refine ⟨⊥, by simp, _, by simpa using hs.symm⟩, simp only [le_zero_iff, card_eq_zero, mem_bUnion, exists_prop, mem_filter, id.def, and_assoc, sdiff_eq_empty_iff_subset, subset_iff], exact λ x hx a ha, ⟨{a}, mem_map_of_mem _ (P.le hx ha), singleton_subset_iff.2 ha, mem_singleton_self _⟩ }, -- Prove the case `m > 0` by strong induction on `s` induction s using finset.strong_induction with s ih generalizing P a b, -- If `a = b = 0`, then `s = ∅` and we can partition into zero parts by_cases hab : a = 0 ∧ b = 0, { simp only [hab.1, hab.2, add_zero, zero_mul, eq_comm, card_eq_zero] at hs, subst hs, exact ⟨finpartition.empty _, by simp, by simp [unique.eq_default P], by simp [hab.2]⟩ }, simp_rw [not_and_distrib, ←ne.def, ←pos_iff_ne_zero] at hab, -- `n` will be the size of the smallest part set n := if 0 < a then m else m + 1 with hn, -- Some easy facts about it obtain ⟨hn₀, hn₁, hn₂, hn₃⟩ : 0 < n ∧ n ≤ m + 1 ∧ n ≤ a * m + b * (m + 1) ∧ ite (0 < a) (a - 1) a * m + ite (0 < a) b (b - 1) * (m + 1) = s.card - n, { rw [hn, ←hs], split_ifs; rw [tsub_mul, one_mul], { refine ⟨m_pos, le_succ _, le_add_right (le_mul_of_pos_left ‹0 < a›), _⟩, rw tsub_add_eq_add_tsub (le_mul_of_pos_left h), }, { refine ⟨succ_pos', le_rfl, le_add_left (le_mul_of_pos_left $ hab.resolve_left ‹¬0 < a›), _⟩, rw ←add_tsub_assoc_of_le (le_mul_of_pos_left $ hab.resolve_left ‹¬0 < a›) } }, /- We will call the inductive hypothesis on a partition of `s \ t` for a carefully chosen `t ⊆ s`. To decide which, however, we must distinguish the case where all parts of `P` have size `m` (in which case we take `t` to be an arbitrary subset of `s` of size `n`) from the case where at least one part `u` of `P` has size `m + 1` (in which case we take `t` to be an arbitrary subset of `u` of size `n`). The rest of each branch is just tedious calculations to satisfy the induction hypothesis. -/ by_cases ∀ u ∈ P.parts, card u < m + 1, { obtain ⟨t, hts, htn⟩ := exists_smaller_set s n (hn₂.trans_eq hs), have ht : t.nonempty := by rwa [←card_pos, htn], have hcard : ite (0 < a) (a - 1) a * m + ite (0 < a) b (b - 1) * (m + 1) = (s \ t).card, { rw [card_sdiff ‹t ⊆ s›, htn, hn₃] }, obtain ⟨R, hR₁, hR₂, hR₃⟩ := @ih (s \ t) (sdiff_ssubset hts ‹t.nonempty›) (P.avoid t) (if 0 < a then a-1 else a) (if 0 < a then b else b-1) hcard, refine ⟨R.extend ht.ne_empty sdiff_disjoint (sdiff_sup_cancel hts), _, _, _⟩, { simp only [extend_parts, mem_insert, forall_eq_or_imp, and_iff_left hR₁, htn, hn], exact ite_eq_or_eq _ _ _ }, { exact λ x hx, (card_le_of_subset $ sdiff_subset _ _).trans (lt_succ_iff.1 $ h _ hx) }, simp_rw [extend_parts, filter_insert, htn, hn, m.succ_ne_self.symm.ite_eq_right_iff], split_ifs with ha, { rw [hR₃, if_pos ha] }, rw [card_insert_of_not_mem (λ H, _), hR₃, if_neg ha, tsub_add_cancel_of_le], { exact hab.resolve_left ha }, { exact ht.ne_empty (le_sdiff_iff.1 $ R.le $ filter_subset _ _ H) } }, push_neg at h, obtain ⟨u, hu₁, hu₂⟩ := h, obtain ⟨t, htu, htn⟩ := exists_smaller_set _ _ (hn₁.trans hu₂), have ht : t.nonempty := by rwa [←card_pos, htn], have hcard : ite (0 < a) (a - 1) a * m + ite (0 < a) b (b - 1) * (m + 1) = (s \ t).card, { rw [card_sdiff (htu.trans $ P.le hu₁), htn, hn₃] }, obtain ⟨R, hR₁, hR₂, hR₃⟩ := @ih (s \ t) (sdiff_ssubset (htu.trans $ P.le hu₁) ht) (P.avoid t) (if 0 < a then a-1 else a) (if 0 < a then b else b-1) hcard, refine ⟨R.extend ht.ne_empty sdiff_disjoint (sdiff_sup_cancel $ htu.trans $ P.le hu₁), _, _, _⟩, { simp only [mem_insert, forall_eq_or_imp, extend_parts, and_iff_left hR₁, htn, hn], exact ite_eq_or_eq _ _ _ }, { conv in (_ ∈ _) {rw ←insert_erase hu₁}, simp only [and_imp, mem_insert, forall_eq_or_imp, ne.def, extend_parts], refine ⟨_, λ x hx, (card_le_of_subset _).trans $ hR₂ x _⟩, { simp only [filter_insert, if_pos htu, bUnion_insert, mem_erase, id.def], obtain rfl | hut := eq_or_ne u t, { rw sdiff_eq_empty_iff_subset.2 (subset_union_left _ _), exact bot_le }, refine (card_le_of_subset $ λ i, _).trans (hR₂ (u \ t) $ P.mem_avoid.2 ⟨u, hu₁, λ i, hut $ i.antisymm htu, rfl⟩), simp only [not_exists, mem_bUnion, and_imp, mem_union, mem_filter, mem_sdiff, id.def, not_or_distrib], exact λ hi₁ hi₂ hi₃, ⟨⟨hi₁, hi₂⟩, λ x hx hx', hi₃ _ hx $ hx'.trans $ sdiff_subset _ _⟩ }, { apply sdiff_subset_sdiff subset.rfl (bUnion_subset_bUnion_of_subset_left _ _), exact filter_subset_filter _ (subset_insert _ _) }, simp only [avoid, of_erase, mem_erase, mem_image, bot_eq_empty], exact ⟨(nonempty_of_mem_parts _ $ mem_of_mem_erase hx).ne_empty, _, mem_of_mem_erase hx, (disjoint_of_subset_right htu $ P.disjoint (mem_of_mem_erase hx) hu₁ $ ne_of_mem_erase hx).sdiff_eq_left⟩ }, simp only [extend_parts, filter_insert, htn, hn, m.succ_ne_self.symm.ite_eq_right_iff], split_ifs, { rw [hR₃, if_pos h] }, { rw [card_insert_of_not_mem (λ H, _), hR₃, if_neg h, nat.sub_add_cancel (hab.resolve_left h)], exact ht.ne_empty (le_sdiff_iff.1 $ R.le $ filter_subset _ _ H) } end variables (P) (h : a * m + b * (m + 1) = s.card) /-- Given a partition `P` of `s`, as well as a proof that `a * m + b * (m + 1) = s.card`, build a new partition `Q` of `s` where each part has size `m` or `m + 1`, every part of `P` is the union of parts of `Q` plus at most `m` extra elements, there are `b` parts of size `m + 1` and (provided `m > 0`, because a partition does not have parts of size `0`) there are `a` parts of size `m` and hence `a + b` parts in total. -/ noncomputable def equitabilise : finpartition s := (P.equitabilise_aux h).some variables {P h} lemma card_eq_of_mem_parts_equitabilise : t ∈ (P.equitabilise h).parts → t.card = m ∨ t.card = m + 1 := (P.equitabilise_aux h).some_spec.1 _ lemma equitabilise_is_equipartition : (P.equitabilise h).is_equipartition := set.equitable_on_iff_exists_eq_eq_add_one.2 ⟨m, λ u, card_eq_of_mem_parts_equitabilise⟩ variables (P h) lemma card_filter_equitabilise_big : ((P.equitabilise h).parts.filter $ λ u : finset α, u.card = m + 1).card = b := (P.equitabilise_aux h).some_spec.2.2 lemma card_filter_equitabilise_small (hm : m ≠ 0) : ((P.equitabilise h).parts.filter $ λ u : finset α, u.card = m).card = a := begin refine (mul_eq_mul_right_iff.1 $ (add_left_inj (b * (m + 1))).1 _).resolve_right hm, rw [h, ←(P.equitabilise h).sum_card_parts], have hunion : (P.equitabilise h).parts = (P.equitabilise h).parts.filter (λ u, u.card = m) ∪ (P.equitabilise h).parts.filter (λ u, u.card = m + 1), { rw [←filter_or, filter_true_of_mem], exact λ x, card_eq_of_mem_parts_equitabilise }, nth_rewrite 1 hunion, rw [sum_union, sum_const_nat (λ x hx, (mem_filter.1 hx).2), sum_const_nat (λ x hx, (mem_filter.1 hx).2), P.card_filter_equitabilise_big], refine disjoint_filter_filter' _ _ _, intros x ha hb i h, apply succ_ne_self m _, exact (hb i h).symm.trans (ha i h), end lemma card_parts_equitabilise (hm : m ≠ 0) : (P.equitabilise h).parts.card = a + b := begin rw [←filter_true_of_mem (λ x, card_eq_of_mem_parts_equitabilise), filter_or, card_union_eq, P.card_filter_equitabilise_small _ hm, P.card_filter_equitabilise_big], exact disjoint_filter.2 (λ x _ h₀ h₁, nat.succ_ne_self m $ h₁.symm.trans h₀), apply_instance end lemma card_parts_equitabilise_subset_le : t ∈ P.parts → (t \ ((P.equitabilise h).parts.filter $ λ u, u ⊆ t).bUnion id).card ≤ m := (classical.some_spec $ P.equitabilise_aux h).2.1 t variables (s) /-- We can find equipartitions of arbitrary size. -/ lemma exists_equipartition_card_eq (hn : n ≠ 0) (hs : n ≤ s.card) : ∃ P : finpartition s, P.is_equipartition ∧ P.parts.card = n := begin rw ←pos_iff_ne_zero at hn, have : (n - s.card % n) * (s.card / n) + (s.card % n) * (s.card / n + 1) = s.card, { rw [tsub_mul, mul_add, ←add_assoc, tsub_add_cancel_of_le (nat.mul_le_mul_right _ (mod_lt _ hn).le), mul_one, add_comm, mod_add_div] }, refine ⟨(indiscrete (card_pos.1 $ hn.trans_le hs).ne_empty).equitabilise this, equitabilise_is_equipartition, _⟩, rw [card_parts_equitabilise _ _ (nat.div_pos hs hn).ne', tsub_add_cancel_of_le (mod_lt _ hn).le], end end finpartition
d16f972ab9aa486eb824c2445dbc0924bf15b3ba
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/measure_theory/bochner_integration.lean
957dfcf557c386fafcc80affd523e6b951e51fb3
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
65,152
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.simple_func_dense import analysis.normed_space.bounded_linear_maps import topology.sequences /-! # Bochner integral The Bochner integral extends the definition of the Lebesgue integral to functions that map from a measure space into a Banach space (complete normed vector space). It is constructed here by extending the integral on simple functions. ## Main definitions The Bochner integral is defined following these steps: 1. Define the integral on simple functions of the type `simple_func α E` (notation : `α →ₛ E`) where `E` is a real normed space. (See `simple_func.bintegral` and section `bintegral` for details. Also see `simple_func.integral` for the integral on simple functions of the type `simple_func α ennreal`.) 2. Use `α →ₛ E` to cut out the simple functions from L1 functions, and define integral on these. The type of simple functions in L1 space is written as `α →₁ₛ[μ] E`. 3. Show that the embedding of `α →₁ₛ[μ] E` into L1 is a dense and uniform one. 4. Show that the integral defined on `α →₁ₛ[μ] E` is a continuous linear map. 5. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ[μ] E` using `continuous_linear_map.extend`. Define the Bochner integral on functions as the Bochner integral of its equivalence class in L1 space. ## Main statements 1. Basic properties of the Bochner integral on functions of type `α → E`, where `α` is a measure space and `E` is a real normed space. * `integral_zero` : `∫ 0 ∂μ = 0` * `integral_add` : `∫ x, f x + g x ∂μ = ∫ x, f ∂μ + ∫ x, g x ∂μ` * `integral_neg` : `∫ x, - f x ∂μ = - ∫ x, f x ∂μ` * `integral_sub` : `∫ x, f x - g x ∂μ = ∫ x, f x ∂μ - ∫ x, g x ∂μ` * `integral_smul` : `∫ x, r • f x ∂μ = r • ∫ x, f x ∂μ` * `integral_congr_ae` : `f =ᵐ[μ] g → ∫ x, f x ∂μ = ∫ x, g x ∂μ` * `norm_integral_le_integral_norm` : `∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ` 2. Basic properties of the Bochner integral on functions of type `α → ℝ`, where `α` is a measure space. * `integral_nonneg_of_ae` : `0 ≤ᵐ[μ] f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos_of_ae` : `f ≤ᵐ[μ] 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono_ae` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` * `integral_nonneg` : `0 ≤ f → 0 ≤ ∫ x, f x ∂μ` * `integral_nonpos` : `f ≤ 0 → ∫ x, f x ∂μ ≤ 0` * `integral_mono` : `f ≤ᵐ[μ] g → ∫ x, f x ∂μ ≤ ∫ x, g x ∂μ` 3. Propositions connecting the Bochner integral with the integral on `ennreal`-valued functions, which is called `lintegral` and has the notation `∫⁻`. * `integral_eq_lintegral_max_sub_lintegral_min` : `∫ x, f x ∂μ = ∫⁻ x, f⁺ x ∂μ - ∫⁻ x, f⁻ x ∂μ`, where `f⁺` is the positive part of `f` and `f⁻` is the negative part of `f`. * `integral_eq_lintegral_of_nonneg_ae` : `0 ≤ᵐ[μ] f → ∫ x, f x ∂μ = ∫⁻ x, f x ∂μ` 4. `tendsto_integral_of_dominated_convergence` : the Lebesgue dominated convergence theorem ## Notes Some tips on how to prove a proposition if the API for the Bochner integral is not enough so that you need to unfold the definition of the Bochner integral and go back to simple functions. One method is to use the theorem `integrable.induction` in the file `set_integral`, which allows you to prove something for an arbitrary measurable + integrable function. Another method is using the following steps. See `integral_eq_lintegral_max_sub_lintegral_min` for a complicated example, which proves that `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, with the first integral sign being the Bochner integral of a real-valued function `f : α → ℝ`, and second and third integral sign being the integral on ennreal-valued functions (called `lintegral`). The proof of `integral_eq_lintegral_max_sub_lintegral_min` is scattered in sections with the name `pos_part`. Here are the usual steps of proving that a property `p`, say `∫ f = ∫⁻ f⁺ - ∫⁻ f⁻`, holds for all functions : 1. First go to the `L¹` space. For example, if you see `ennreal.to_real (∫⁻ a, ennreal.of_real $ ∥f a∥)`, that is the norm of `f` in `L¹` space. Rewrite using `l1.norm_of_fun_eq_lintegral_norm`. 2. Show that the set `{f ∈ L¹ | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻}` is closed in `L¹` using `is_closed_eq`. 3. Show that the property holds for all simple functions `s` in `L¹` space. Typically, you need to convert various notions to their `simple_func` counterpart, using lemmas like `l1.integral_coe_eq_integral`. 4. Since simple functions are dense in `L¹`, ``` univ = closure {s simple} = closure {s simple | ∫ s = ∫⁻ s⁺ - ∫⁻ s⁻} : the property holds for all simple functions ⊆ closure {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} = {f | ∫ f = ∫⁻ f⁺ - ∫⁻ f⁻} : closure of a closed set is itself ``` Use `is_closed_property` or `dense_range.induction_on` for this argument. ## Notations * `α →ₛ E` : simple functions (defined in `measure_theory/integration`) * `α →₁[μ] E` : functions in L1 space, i.e., equivalence classes of integrable functions (defined in `measure_theory/l1_space`) * `α →₁ₛ[μ] E` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ noncomputable theory open_locale classical topological_space big_operators namespace measure_theory variables {α E : Type*} [measurable_space α] [decidable_linear_order E] [has_zero E] local infixr ` →ₛ `:25 := simple_func namespace simple_func section pos_part /-- Positive part of a simple function. -/ def pos_part (f : α →ₛ E) : α →ₛ E := f.map (λb, max b 0) /-- Negative part of a simple function. -/ def neg_part [has_neg E] (f : α →ₛ E) : α →ₛ E := pos_part (-f) lemma pos_part_map_norm (f : α →ₛ ℝ) : (pos_part f).map norm = pos_part f := begin ext, rw [map_apply, real.norm_eq_abs, abs_of_nonneg], rw [pos_part, map_apply], exact le_max_right _ _ end lemma neg_part_map_norm (f : α →ₛ ℝ) : (neg_part f).map norm = neg_part f := by { rw neg_part, exact pos_part_map_norm _ } lemma pos_part_sub_neg_part (f : α →ₛ ℝ) : f.pos_part - f.neg_part = f := begin simp only [pos_part, neg_part], ext, exact max_zero_sub_eq_self (f a) end end pos_part end simple_func end measure_theory namespace measure_theory open set filter topological_space ennreal emetric variables {α E F : Type*} [measurable_space α] local infixr ` →ₛ `:25 := simple_func namespace simple_func section integral /-! ### The Bochner integral of simple functions Define the Bochner integral of simple functions of the type `α →ₛ β` where `β` is a normed group, and prove basic property of this integral. -/ open finset variables [normed_group E] [measurable_space E] [normed_group F] variables {μ : measure α} /-- For simple functions with a `normed_group` as codomain, being integrable is the same as having finite volume support. -/ lemma integrable_iff_fin_meas_supp {f : α →ₛ E} {μ : measure α} : integrable f μ ↔ f.fin_meas_supp μ := calc integrable f μ ↔ ∫⁻ x, f.map (coe ∘ nnnorm : E → ennreal) x ∂μ < ⊤ : and_iff_right f.measurable ... ↔ (f.map (coe ∘ nnnorm : E → ennreal)).lintegral μ < ⊤ : by rw lintegral_eq_lintegral ... ↔ (f.map (coe ∘ nnnorm : E → ennreal)).fin_meas_supp μ : iff.symm $ fin_meas_supp.iff_lintegral_lt_top $ eventually_of_forall $ λ x, coe_lt_top ... ↔ _ : fin_meas_supp.map_iff $ λ b, coe_eq_zero.trans nnnorm_eq_zero lemma fin_meas_supp.integrable {f : α →ₛ E} (h : f.fin_meas_supp μ) : integrable f μ := integrable_iff_fin_meas_supp.2 h lemma integrable_pair [measurable_space F] {f : α →ₛ E} {g : α →ₛ F} : integrable f μ → integrable g μ → integrable (pair f g) μ := by simpa only [integrable_iff_fin_meas_supp] using fin_meas_supp.pair variables [normed_space ℝ F] /-- Bochner integral of simple functions whose codomain is a real `normed_space`. -/ def integral (μ : measure α) (f : α →ₛ F) : F := ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • x lemma integral_eq_sum_filter (f : α →ₛ F) (μ) : f.integral μ = ∑ x in f.range.filter (λ x, x ≠ 0), (ennreal.to_real (μ (f ⁻¹' {x}))) • x := eq.symm $ sum_filter_of_ne $ λ x _, mt $ λ h0, h0.symm ▸ smul_zero _ /-- The Bochner integral is equal to a sum over any set that includes `f.range` (except `0`). -/ lemma integral_eq_sum_of_subset {f : α →ₛ F} {μ : measure α} {s : finset F} (hs : f.range.filter (λ x, x ≠ 0) ⊆ s) : f.integral μ = ∑ x in s, (μ (f ⁻¹' {x})).to_real • x := begin rw [simple_func.integral_eq_sum_filter, finset.sum_subset hs], rintro x - hx, rw [finset.mem_filter, not_and_distrib, ne.def, not_not] at hx, rcases hx with hx|rfl; [skip, simp], rw [simple_func.mem_range] at hx, rw [preimage_eq_empty]; simp [disjoint_singleton_left, hx] end /-- Calculate the integral of `g ∘ f : α →ₛ F`, where `f` is an integrable function from `α` to `E` and `g` is a function from `E` to `F`. We require `g 0 = 0` so that `g ∘ f` is integrable. -/ lemma map_integral (f : α →ₛ E) (g : E → F) (hf : integrable f μ) (hg : g 0 = 0) : (f.map g).integral μ = ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • (g x) := begin -- We start as in the proof of `map_lintegral` simp only [integral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← sum_measure_preimage_singleton _ (λ _ _, f.is_measurable_preimage _)], -- Now we use `hf : integrable f μ` to show that `ennreal.to_real` is additive. by_cases ha : g (f a) = 0, { simp only [ha, smul_zero], refine (sum_eq_zero $ λ x hx, _).symm, simp only [mem_filter] at hx, simp [hx.2] }, { rw [to_real_sum, sum_smul], { refine sum_congr rfl (λ x hx, _), simp only [mem_filter] at hx, rw [hx.2] }, { intros x hx, simp only [mem_filter] at hx, refine (integrable_iff_fin_meas_supp.1 hf).meas_preimage_singleton_ne_zero _, exact λ h0, ha (hx.2 ▸ h0.symm ▸ hg) } }, end /-- `simple_func.integral` and `simple_func.lintegral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. See `integral_eq_lintegral` for a simpler version. -/ lemma integral_eq_lintegral' {f : α →ₛ E} {g : E → ennreal} (hf : integrable f μ) (hg0 : g 0 = 0) (hgt : ∀b, g b < ⊤): (f.map (ennreal.to_real ∘ g)).integral μ = ennreal.to_real (∫⁻ a, g (f a) ∂μ) := begin have hf' : f.fin_meas_supp μ := integrable_iff_fin_meas_supp.1 hf, simp only [← map_apply g f, lintegral_eq_lintegral], rw [map_integral f _ hf, map_lintegral, ennreal.to_real_sum], { refine finset.sum_congr rfl (λb hb, _), rw [smul_eq_mul, to_real_mul_to_real, mul_comm] }, { assume a ha, by_cases a0 : a = 0, { rw [a0, hg0, zero_mul], exact with_top.zero_lt_top }, { apply mul_lt_top (hgt a) (hf'.meas_preimage_singleton_ne_zero a0) } }, { simp [hg0] } end variables [normed_space ℝ E] lemma integral_congr {f g : α →ₛ E} (hf : integrable f μ) (h : f =ᵐ[μ] g): f.integral μ = g.integral μ := show ((pair f g).map prod.fst).integral μ = ((pair f g).map prod.snd).integral μ, from begin have inte := integrable_pair hf (hf.congr g.measurable h), rw [map_integral (pair f g) _ inte prod.fst_zero, map_integral (pair f g) _ inte prod.snd_zero], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : μ ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine measure_mono_null (assume a' ha', _) h, simp only [set.mem_preimage, mem_singleton_iff, pair_apply, prod.mk.inj_iff] at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp only [this, pair_apply, zero_smul, ennreal.zero_to_real] }, end /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ennreal`. But since `ennreal` is not a `normed_space`, we need some form of coercion. -/ lemma integral_eq_lintegral {f : α →ₛ ℝ} (hf : integrable f μ) (h_pos : 0 ≤ᵐ[μ] f) : f.integral μ = ennreal.to_real (∫⁻ a, ennreal.of_real (f a) ∂μ) := begin have : f =ᵐ[μ] f.map (ennreal.to_real ∘ ennreal.of_real) := h_pos.mono (λ a h, (ennreal.to_real_of_real h).symm), rw [← integral_eq_lintegral' hf], { exact integral_congr hf this }, { exact ennreal.of_real_zero }, { assume b, rw ennreal.lt_top_iff_ne_top, exact ennreal.of_real_ne_top } end lemma integral_add {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f + g) = integral μ f + integral μ g := calc integral μ (f + g) = ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • (x.fst + x.snd) : begin rw [add_eq_map₂, map_integral (pair f g)], { exact integrable_pair hf hg }, { simp only [add_zero, prod.fst_zero, prod.snd_zero] } end ... = ∑ x in (pair f g).range, (ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst + ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd) : finset.sum_congr rfl $ assume a ha, smul_add _ _ _ ... = ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.fst + ∑ x in (pair f g).range, ennreal.to_real (μ ((pair f g) ⁻¹' {x})) • x.snd : by rw finset.sum_add_distrib ... = ((pair f g).map prod.fst).integral μ + ((pair f g).map prod.snd).integral μ : begin rw [map_integral (pair f g), map_integral (pair f g)], { exact integrable_pair hf hg }, { refl }, { exact integrable_pair hf hg }, { refl } end ... = integral μ f + integral μ g : rfl lemma integral_neg {f : α →ₛ E} (hf : integrable f μ) : integral μ (-f) = - integral μ f := calc integral μ (-f) = integral μ (f.map (has_neg.neg)) : rfl ... = - integral μ f : begin rw [map_integral f _ hf neg_zero, integral, ← sum_neg_distrib], refine finset.sum_congr rfl (λx h, smul_neg _ _), end lemma integral_sub [borel_space E] {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f - g) = integral μ f - integral μ g := begin rw [sub_eq_add_neg, integral_add hf, integral_neg hg, sub_eq_add_neg], exact hg.neg end lemma integral_smul (r : ℝ) {f : α →ₛ E} (hf : integrable f μ) : integral μ (r • f) = r • integral μ f := calc integral μ (r • f) = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • r • x : by rw [smul_eq_map r f, map_integral f _ hf (smul_zero _)] ... = ∑ x in f.range, ((ennreal.to_real (μ (f ⁻¹' {x}))) * r) • x : finset.sum_congr rfl $ λb hb, by apply smul_smul ... = r • integral μ f : by simp only [integral, smul_sum, smul_smul, mul_comm] lemma norm_integral_le_integral_norm (f : α →ₛ E) (hf : integrable f μ) : ∥f.integral μ∥ ≤ (f.map norm).integral μ := begin rw [map_integral f norm hf norm_zero, integral], calc ∥∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • x∥ ≤ ∑ x in f.range, ∥ennreal.to_real (μ (f ⁻¹' {x})) • x∥ : norm_sum_le _ _ ... = ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) • ∥x∥ : begin refine finset.sum_congr rfl (λb hb, _), rw [norm_smul, smul_eq_mul, real.norm_eq_abs, abs_of_nonneg to_real_nonneg] end end lemma integral_add_measure {ν} (f : α →ₛ E) (hf : integrable f (μ + ν)) : f.integral (μ + ν) = f.integral μ + f.integral ν := begin simp only [integral_eq_sum_filter, ← sum_add_distrib, ← add_smul, measure.add_apply], refine sum_congr rfl (λ x hx, _), rw [to_real_add]; refine ne_of_lt ((integrable_iff_fin_meas_supp.1 _).meas_preimage_singleton_ne_zero (mem_filter.1 hx).2), exacts [hf.left_of_add_measure, hf.right_of_add_measure] end end integral end simple_func namespace l1 open ae_eq_fun variables [normed_group E] [second_countable_topology E] [measurable_space E] [borel_space E] [normed_group F] [second_countable_topology F] [measurable_space F] [borel_space F] {μ : measure α} variables (α E μ) -- We use `Type*` instead of `add_subgroup` because otherwise we loose dot notation. /-- `l1.simple_func` is a subspace of L1 consisting of equivalence classes of an integrable simple function. -/ def simple_func : Type* := ↥({ carrier := {f : α →₁[μ] E | ∃ (s : α →ₛ E), (ae_eq_fun.mk s s.measurable : α →ₘ[μ] E) = f}, zero_mem' := ⟨0, rfl⟩, add_mem' := λ f g ⟨s, hs⟩ ⟨t, ht⟩, ⟨s + t, by simp only [coe_add, ← hs, ← ht, mk_add_mk, ← simple_func.coe_add]⟩, neg_mem' := λ f ⟨s, hs⟩, ⟨-s, by simp only [coe_neg, ← hs, neg_mk, ← simple_func.coe_neg]⟩ } : add_subgroup (α →₁[μ] E)) variables {α E μ} notation α ` →₁ₛ[`:25 μ `] ` E := measure_theory.l1.simple_func α E μ namespace simple_func section instances /-! Simple functions in L1 space form a `normed_space`. -/ instance : has_coe (α →₁ₛ[μ] E) (α →₁[μ] E) := coe_subtype instance : has_coe_to_fun (α →₁ₛ[μ] E) := ⟨λ f, α → E, λ f, ⇑(f : α →₁[μ] E)⟩ @[simp, norm_cast] lemma coe_coe (f : α →₁ₛ[μ] E) : ⇑(f : α →₁[μ] E) = f := rfl protected lemma eq {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = (g : α →₁[μ] E) → f = g := subtype.eq protected lemma eq' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = (g : α →ₘ[μ] E) → f = g := subtype.eq ∘ subtype.eq @[norm_cast] protected lemma eq_iff {f g : α →₁ₛ[μ] E} : (f : α →₁[μ] E) = g ↔ f = g := subtype.ext_iff.symm @[norm_cast] protected lemma eq_iff' {f g : α →₁ₛ[μ] E} : (f : α →ₘ[μ] E) = g ↔ f = g := iff.intro (simple_func.eq') (congr_arg _) /-- L1 simple functions forms a `emetric_space`, with the emetric being inherited from L1 space, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. Not declared as an instance as `α →₁ₛ[μ] β` will only be useful in the construction of the bochner integral. -/ protected def emetric_space : emetric_space (α →₁ₛ[μ] E) := subtype.emetric_space /-- L1 simple functions forms a `metric_space`, with the metric being inherited from L1 space, i.e., `dist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a)`). Not declared as an instance as `α →₁ₛ[μ] β` will only be useful in the construction of the bochner integral. -/ protected def metric_space : metric_space (α →₁ₛ[μ] E) := subtype.metric_space local attribute [instance] simple_func.metric_space simple_func.emetric_space /-- Functions `α →₁ₛ[μ] E` form an additive commutative group. -/ local attribute [instance, priority 10000] protected def add_comm_group : add_comm_group (α →₁ₛ[μ] E) := add_subgroup.to_add_comm_group _ instance : inhabited (α →₁ₛ[μ] E) := ⟨0⟩ @[simp, norm_cast] lemma coe_zero : ((0 : α →₁ₛ[μ] E) : α →₁[μ] E) = 0 := rfl @[simp, norm_cast] lemma coe_add (f g : α →₁ₛ[μ] E) : ((f + g : α →₁ₛ[μ] E) : α →₁[μ] E) = f + g := rfl @[simp, norm_cast] lemma coe_neg (f : α →₁ₛ[μ] E) : ((-f : α →₁ₛ[μ] E) : α →₁[μ] E) = -f := rfl @[simp, norm_cast] lemma coe_sub (f g : α →₁ₛ[μ] E) : ((f - g : α →₁ₛ[μ] E) : α →₁[μ] E) = f - g := rfl @[simp] lemma edist_eq (f g : α →₁ₛ[μ] E) : edist f g = edist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl @[simp] lemma dist_eq (f g : α →₁ₛ[μ] E) : dist f g = dist (f : α →₁[μ] E) (g : α →₁[μ] E) := rfl /-- The norm on `α →₁ₛ[μ] E` is inherited from L1 space. That is, `∥f∥ = ∫⁻ a, edist (f a) 0`. Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the bochner integral. -/ protected def has_norm : has_norm (α →₁ₛ[μ] E) := ⟨λf, ∥(f : α →₁[μ] E)∥⟩ local attribute [instance] simple_func.has_norm lemma norm_eq (f : α →₁ₛ[μ] E) : ∥f∥ = ∥(f : α →₁[μ] E)∥ := rfl lemma norm_eq' (f : α →₁ₛ[μ] E) : ∥f∥ = ennreal.to_real (edist (f : α →ₘ[μ] E) 0) := rfl /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the bochner integral. -/ protected def normed_group : normed_group (α →₁ₛ[μ] E) := normed_group.of_add_dist (λ x, rfl) $ by { intros, simp only [dist_eq, coe_add, l1.dist_eq, l1.coe_add], rw edist_add_right } variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the bochner integral. -/ protected def has_scalar : has_scalar 𝕜 (α →₁ₛ[μ] E) := ⟨λk f, ⟨k • f, begin rcases f with ⟨f, ⟨s, hs⟩⟩, use k • s, rw [coe_smul, subtype.coe_mk, ← hs], refl end ⟩⟩ local attribute [instance, priority 10000] simple_func.has_scalar @[simp, norm_cast] lemma coe_smul (c : 𝕜) (f : α →₁ₛ[μ] E) : ((c • f : α →₁ₛ[μ] E) : α →₁[μ] E) = c • (f : α →₁[μ] E) := rfl /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the bochner integral. -/ protected def semimodule : semimodule 𝕜 (α →₁ₛ[μ] E) := { one_smul := λf, simple_func.eq (by { simp only [coe_smul], exact one_smul _ _ }), mul_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact mul_smul _ _ _ }), smul_add := λx f g, simple_func.eq (by { simp only [coe_smul, coe_add], exact smul_add _ _ _ }), smul_zero := λx, simple_func.eq (by { simp only [coe_zero, coe_smul], exact smul_zero _ }), add_smul := λx y f, simple_func.eq (by { simp only [coe_smul], exact add_smul _ _ _ }), zero_smul := λf, simple_func.eq (by { simp only [coe_smul], exact zero_smul _ _ }) } local attribute [instance] simple_func.normed_group simple_func.semimodule /-- Not declared as an instance as `α →₁ₛ[μ] E` will only be useful in the construction of the bochner integral. -/ protected def normed_space : normed_space 𝕜 (α →₁ₛ[μ] E) := ⟨ λc f, by { rw [norm_eq, norm_eq, coe_smul, norm_smul] } ⟩ end instances local attribute [instance] simple_func.normed_group simple_func.normed_space section of_simple_func /-- Construct the equivalence class `[f]` of an integrable simple function `f`. -/ @[reducible] def of_simple_func (f : α →ₛ E) (hf : integrable f μ) : (α →₁ₛ[μ] E) := ⟨l1.of_fun f hf, ⟨f, rfl⟩⟩ lemma of_simple_func_eq_of_fun (f : α →ₛ E) (hf : integrable f μ) : (of_simple_func f hf : α →₁[μ] E) = l1.of_fun f hf := rfl lemma of_simple_func_eq_mk (f : α →ₛ E) (hf : integrable f μ) : (of_simple_func f hf : α →ₘ[μ] E) = ae_eq_fun.mk f f.measurable := rfl lemma of_simple_func_zero : of_simple_func (0 : α →ₛ E) (integrable_zero α E μ) = 0 := rfl lemma of_simple_func_add (f g : α →ₛ E) (hf : integrable f μ) (hg : integrable g μ) : of_simple_func (f + g) (hf.add hg) = of_simple_func f hf + of_simple_func g hg := rfl lemma of_simple_func_neg (f : α →ₛ E) (hf : integrable f μ) : of_simple_func (-f) hf.neg = -of_simple_func f hf := rfl lemma of_simple_func_sub (f g : α →ₛ E) (hf : integrable f μ) (hg : integrable g μ) : of_simple_func (f - g) (hf.sub hg) = of_simple_func f hf - of_simple_func g hg := rfl variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma of_simple_func_smul (f : α →ₛ E) (hf : integrable f μ) (c : 𝕜) : of_simple_func (c • f) (hf.smul c) = c • of_simple_func f hf := rfl lemma norm_of_simple_func (f : α →ₛ E) (hf : integrable f μ) : ∥of_simple_func f hf∥ = ennreal.to_real (∫⁻ a, edist (f a) 0 ∂μ) := rfl end of_simple_func section to_simple_func /-- Find a representative of a `l1.simple_func`. -/ def to_simple_func (f : α →₁ₛ[μ] E) : α →ₛ E := classical.some f.2 /-- `f.to_simple_func` is measurable. -/ protected lemma measurable (f : α →₁ₛ[μ] E) : measurable f.to_simple_func := f.to_simple_func.measurable /-- `f.to_simple_func` is integrable. -/ protected lemma integrable (f : α →₁ₛ[μ] E) : integrable f.to_simple_func μ := let h := classical.some_spec f.2 in (integrable_mk f.measurable).1 $ h.symm ▸ (f : α →₁[μ] E).2 lemma of_simple_func_to_simple_func (f : α →₁ₛ[μ] E) : of_simple_func (f.to_simple_func) f.integrable = f := by { rw ← simple_func.eq_iff', exact classical.some_spec f.2 } lemma to_simple_func_of_simple_func (f : α →ₛ E) (hfi : integrable f μ) : (of_simple_func f hfi).to_simple_func =ᵐ[μ] f := by { rw ← mk_eq_mk, exact classical.some_spec (of_simple_func f hfi).2 } lemma to_simple_func_eq_to_fun (f : α →₁ₛ[μ] E) : f.to_simple_func =ᵐ[μ] f := begin rw [← of_fun_eq_of_fun f.to_simple_func f f.integrable (f : α →₁[μ] E).integrable, ← l1.eq_iff], simp only [of_fun_eq_mk, ← coe_coe, mk_to_fun], exact classical.some_spec f.coe_prop end variables (α E) lemma zero_to_simple_func : (0 : α →₁ₛ[μ] E).to_simple_func =ᵐ[μ] 0 := begin filter_upwards [to_simple_func_eq_to_fun (0 : α →₁ₛ[μ] E), l1.zero_to_fun α E], simp only [mem_set_of_eq], assume a h, rw h, exact id end variables {α E} lemma add_to_simple_func (f g : α →₁ₛ[μ] E) : (f + g).to_simple_func =ᵐ[μ] f.to_simple_func + g.to_simple_func := begin filter_upwards [to_simple_func_eq_to_fun (f + g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, l1.add_to_fun (f : α →₁[μ] E) g], assume a, simp only [mem_set_of_eq, ← coe_coe, coe_add, pi.add_apply], iterate 4 { assume h, rw h } end lemma neg_to_simple_func (f : α →₁ₛ[μ] E) : (-f).to_simple_func =ᵐ[μ] - f.to_simple_func := begin filter_upwards [to_simple_func_eq_to_fun (-f), to_simple_func_eq_to_fun f, l1.neg_to_fun (f : α →₁[μ] E)], assume a, simp only [mem_set_of_eq, pi.neg_apply, coe_neg, ← coe_coe], repeat { assume h, rw h } end lemma sub_to_simple_func (f g : α →₁ₛ[μ] E) : (f - g).to_simple_func =ᵐ[μ] f.to_simple_func - g.to_simple_func := begin filter_upwards [to_simple_func_eq_to_fun (f - g), to_simple_func_eq_to_fun f, to_simple_func_eq_to_fun g, l1.sub_to_fun (f : α →₁[μ] E) g], assume a, simp only [mem_set_of_eq, coe_sub, pi.sub_apply, ← coe_coe], repeat { assume h, rw h } end variables {𝕜 : Type*} [normed_field 𝕜] [normed_space 𝕜 E] lemma smul_to_simple_func (k : 𝕜) (f : α →₁ₛ[μ] E) : (k • f).to_simple_func =ᵐ[μ] k • f.to_simple_func := begin filter_upwards [to_simple_func_eq_to_fun (k • f), to_simple_func_eq_to_fun f, l1.smul_to_fun k (f : α →₁[μ] E)], assume a, simp only [mem_set_of_eq, pi.smul_apply, coe_smul, ← coe_coe], repeat { assume h, rw h } end lemma lintegral_edist_to_simple_func_lt_top (f g : α →₁ₛ[μ] E) : ∫⁻ (x : α), edist ((to_simple_func f) x) ((to_simple_func g) x) ∂μ < ⊤ := begin rw lintegral_rw₂ (to_simple_func_eq_to_fun f) (to_simple_func_eq_to_fun g), exact lintegral_edist_to_fun_lt_top _ _ end lemma dist_to_simple_func (f g : α →₁ₛ[μ] E) : dist f g = ennreal.to_real (∫⁻ x, edist (f.to_simple_func x) (g.to_simple_func x) ∂μ) := begin rw [dist_eq, l1.dist_to_fun, ennreal.to_real_eq_to_real], { rw lintegral_rw₂, repeat { exact ae_eq_symm (to_simple_func_eq_to_fun _) } }, { exact l1.lintegral_edist_to_fun_lt_top _ _ }, { exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_to_simple_func (f : α →₁ₛ[μ] E) : ∥f∥ = ennreal.to_real (∫⁻ (a : α), nnnorm ((to_simple_func f) a) ∂μ) := calc ∥f∥ = ennreal.to_real (∫⁻x, edist (f.to_simple_func x) ((0 : α →₁ₛ[μ] E).to_simple_func x) ∂μ) : begin rw [← dist_zero_right, dist_to_simple_func] end ... = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x) ∂μ) : begin rw lintegral_nnnorm_eq_lintegral_edist, have : ∫⁻ x, edist ((to_simple_func f) x) ((to_simple_func (0 : α →₁ₛ[μ] E)) x) ∂μ = ∫⁻ x, edist ((to_simple_func f) x) 0 ∂μ, { refine lintegral_congr_ae ((zero_to_simple_func α E).mono (λ a h, _)), rw [h, pi.zero_apply] }, rw [ennreal.to_real_eq_to_real], { exact this }, { exact lintegral_edist_to_simple_func_lt_top _ _ }, { rw ← this, exact lintegral_edist_to_simple_func_lt_top _ _ } end lemma norm_eq_integral (f : α →₁ₛ[μ] E) : ∥f∥ = (f.to_simple_func.map norm).integral μ := -- calc ∥f∥ = ennreal.to_real (∫⁻ (x : α), (coe ∘ nnnorm) (f.to_simple_func x) ∂μ) : -- by { rw norm_to_simple_func } -- ... = (f.to_simple_func.map norm).integral μ : begin rw [norm_to_simple_func, simple_func.integral_eq_lintegral], { simp only [simple_func.map_apply, of_real_norm_eq_coe_nnnorm] }, { exact f.integrable.norm }, { exact eventually_of_forall (λ x, norm_nonneg _) } end end to_simple_func section coe_to_l1 protected lemma uniform_continuous : uniform_continuous (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := uniform_continuous_comap protected lemma uniform_embedding : uniform_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := uniform_embedding_comap subtype.val_injective protected lemma uniform_inducing : uniform_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.uniform_embedding.to_uniform_inducing protected lemma dense_embedding : dense_embedding (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := begin apply simple_func.uniform_embedding.dense_embedding, rintros ⟨⟨f, hfm⟩, hfi⟩, rw mem_closure_iff_seq_limit, have hfi' := (integrable_mk hfm).1 hfi, refine ⟨λ n, ↑(of_simple_func (simple_func.approx_on f hfm univ 0 trivial n) (simple_func.integrable_approx_on_univ hfi' n)), λ n, mem_range_self _, _⟩, rw tendsto_iff_edist_tendsto_0, simpa [edist_mk_mk] using simple_func.tendsto_approx_on_univ_l1_edist hfi' end protected lemma dense_inducing : dense_inducing (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.dense_embedding.to_dense_inducing protected lemma dense_range : dense_range (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)) := simple_func.dense_inducing.dense variables (𝕜 : Type*) [normed_field 𝕜] [normed_space 𝕜 E] variables (α E) /-- The uniform and dense embedding of L1 simple functions into L1 functions. -/ def coe_to_l1 : (α →₁ₛ[μ] E) →L[𝕜] (α →₁[μ] E) := { to_fun := (coe : (α →₁ₛ[μ] E) → (α →₁[μ] E)), map_add' := λf g, rfl, map_smul' := λk f, rfl, cont := l1.simple_func.uniform_continuous.continuous, } variables {α E 𝕜} end coe_to_l1 section pos_part /-- Positive part of a simple function in L1 space. -/ def pos_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := ⟨l1.pos_part (f : α →₁[μ] ℝ), begin rcases f with ⟨f, s, hsf⟩, use s.pos_part, simp only [subtype.coe_mk, l1.coe_pos_part, ← hsf, ae_eq_fun.pos_part_mk, simple_func.pos_part, simple_func.coe_map] end ⟩ /-- Negative part of a simple function in L1 space. -/ def neg_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := pos_part (-f) @[norm_cast] lemma coe_pos_part (f : α →₁ₛ[μ] ℝ) : (f.pos_part : α →₁[μ] ℝ) = (f : α →₁[μ] ℝ).pos_part := rfl @[norm_cast] lemma coe_neg_part (f : α →₁ₛ[μ] ℝ) : (f.neg_part : α →₁[μ] ℝ) = (f : α →₁[μ] ℝ).neg_part := rfl end pos_part section simple_func_integral /-! Define the Bochner integral on `α →₁ₛ[μ] E` and prove basic properties of this integral. -/ variables [normed_space ℝ E] /-- The Bochner integral over simple functions in l1 space. -/ def integral (f : α →₁ₛ[μ] E) : E := (f.to_simple_func).integral μ lemma integral_eq_integral (f : α →₁ₛ[μ] E) : integral f = (f.to_simple_func).integral μ := rfl lemma integral_eq_lintegral {f : α →₁ₛ[μ] ℝ} (h_pos : 0 ≤ᵐ[μ] f.to_simple_func) : integral f = ennreal.to_real (∫⁻ a, ennreal.of_real (f.to_simple_func a) ∂μ) := by rw [integral, simple_func.integral_eq_lintegral f.integrable h_pos] lemma integral_congr {f g : α →₁ₛ[μ] E} (h : f.to_simple_func =ᵐ[μ] g.to_simple_func) : integral f = integral g := simple_func.integral_congr f.integrable h lemma integral_add (f g : α →₁ₛ[μ] E) : integral (f + g) = integral f + integral g := begin simp only [integral], rw ← simple_func.integral_add f.integrable g.integrable, apply measure_theory.simple_func.integral_congr (f + g).integrable, apply add_to_simple_func end lemma integral_smul (r : ℝ) (f : α →₁ₛ[μ] E) : integral (r • f) = r • integral f := begin simp only [integral], rw ← simple_func.integral_smul _ f.integrable, apply measure_theory.simple_func.integral_congr (r • f).integrable, apply smul_to_simple_func end lemma norm_integral_le_norm (f : α →₁ₛ[μ] E) : ∥ integral f ∥ ≤ ∥f∥ := begin rw [integral, norm_eq_integral], exact f.to_simple_func.norm_integral_le_integral_norm f.integrable end /-- The Bochner integral over simple functions in l1 space as a continuous linear map. -/ def integral_clm : (α →₁ₛ[μ] E) →L[ℝ] E := linear_map.mk_continuous ⟨integral, integral_add, integral_smul⟩ 1 (λf, le_trans (norm_integral_le_norm _) $ by rw one_mul) local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ open continuous_linear_map lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := linear_map.mk_continuous_norm_le _ (zero_le_one) _ section pos_part lemma pos_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : f.pos_part.to_simple_func =ᵐ[μ] f.to_simple_func.pos_part := begin have eq : ∀ a, f.to_simple_func.pos_part a = max (f.to_simple_func a) 0 := λa, rfl, have ae_eq : ∀ᵐ a ∂μ, f.pos_part.to_simple_func a = max (f.to_simple_func a) 0, { filter_upwards [to_simple_func_eq_to_fun f.pos_part, pos_part_to_fun (f : α →₁[μ] ℝ), to_simple_func_eq_to_fun f], simp only [mem_set_of_eq], assume a h₁ h₂ h₃, rw [h₁, ← coe_coe, coe_pos_part, h₂, coe_coe, ← h₃] }, refine ae_eq.mono (assume a h, _), rw [h, eq] end lemma neg_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : f.neg_part.to_simple_func =ᵐ[μ] f.to_simple_func.neg_part := begin rw [simple_func.neg_part, measure_theory.simple_func.neg_part], filter_upwards [pos_part_to_simple_func (-f), neg_to_simple_func f], simp only [mem_set_of_eq], assume a h₁ h₂, rw h₁, show max _ _ = max _ _, rw h₂, refl end lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ[μ] ℝ) : f.integral = ∥f.pos_part∥ - ∥f.neg_part∥ := begin -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₁ : f.to_simple_func.pos_part =ᵐ[μ] (f.pos_part).to_simple_func.map norm, { filter_upwards [pos_part_to_simple_func f], simp only [mem_set_of_eq], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.pos_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₂ : f.to_simple_func.neg_part =ᵐ[μ] (f.neg_part).to_simple_func.map norm, { filter_upwards [neg_part_to_simple_func f], simp only [mem_set_of_eq], assume a h, rw [simple_func.map_apply, h], conv_lhs { rw [← simple_func.neg_part_map_norm, simple_func.map_apply] } }, -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq : ∀ᵐ a ∂μ, f.to_simple_func.pos_part a - f.to_simple_func.neg_part a = (f.pos_part).to_simple_func.map norm a - (f.neg_part).to_simple_func.map norm a, { filter_upwards [ae_eq₁, ae_eq₂], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂] }, rw [integral, norm_eq_integral, norm_eq_integral, ← simple_func.integral_sub], { show f.to_simple_func.integral μ = ((f.pos_part.to_simple_func).map norm - f.neg_part.to_simple_func.map norm).integral μ, apply measure_theory.simple_func.integral_congr f.integrable, filter_upwards [ae_eq₁, ae_eq₂], simp only [mem_set_of_eq], assume a h₁ h₂, show _ = _ - _, rw [← h₁, ← h₂], have := f.to_simple_func.pos_part_sub_neg_part, conv_lhs {rw ← this}, refl }, { exact f.integrable.max_zero.congr (measure_theory.simple_func.measurable _) ae_eq₁ }, { exact f.integrable.neg.max_zero.congr (measure_theory.simple_func.measurable _) ae_eq₂ } end end pos_part end simple_func_integral end simple_func open simple_func variables [normed_space ℝ E] [normed_space ℝ F] [complete_space E] section integration_in_l1 local notation `to_l1` := coe_to_l1 α E ℝ local attribute [instance] simple_func.normed_group simple_func.normed_space open continuous_linear_map /-- The Bochner integral in l1 space as a continuous linear map. -/ def integral_clm : (α →₁[μ] E) →L[ℝ] E := integral_clm.extend to_l1 simple_func.dense_range simple_func.uniform_inducing /-- The Bochner integral in l1 space -/ def integral (f : α →₁[μ] E) : E := integral_clm f lemma integral_eq (f : α →₁[μ] E) : integral f = integral_clm f := rfl @[norm_cast] lemma simple_func.integral_l1_eq_integral (f : α →₁ₛ[μ] E) : integral (f : α →₁[μ] E) = f.integral := uniformly_extend_of_ind simple_func.uniform_inducing simple_func.dense_range simple_func.integral_clm.uniform_continuous _ variables (α E) @[simp] lemma integral_zero : integral (0 : α →₁[μ] E) = 0 := map_zero integral_clm variables {α E} lemma integral_add (f g : α →₁[μ] E) : integral (f + g) = integral f + integral g := map_add integral_clm f g lemma integral_neg (f : α →₁[μ] E) : integral (-f) = - integral f := map_neg integral_clm f lemma integral_sub (f g : α →₁[μ] E) : integral (f - g) = integral f - integral g := map_sub integral_clm f g lemma integral_smul (r : ℝ) (f : α →₁[μ] E) : integral (r • f) = r • integral f := map_smul r integral_clm f local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ _ local notation `sIntegral` := @simple_func.integral_clm α E _ _ _ _ _ μ _ lemma norm_Integral_le_one : ∥Integral∥ ≤ 1 := calc ∥Integral∥ ≤ (1 : nnreal) * ∥sIntegral∥ : op_norm_extend_le _ _ _ $ λs, by {rw [nnreal.coe_one, one_mul], refl} ... = ∥sIntegral∥ : one_mul _ ... ≤ 1 : norm_Integral_le_one lemma norm_integral_le (f : α →₁[μ] E) : ∥integral f∥ ≤ ∥f∥ := calc ∥integral f∥ = ∥Integral f∥ : rfl ... ≤ ∥Integral∥ * ∥f∥ : le_op_norm _ _ ... ≤ 1 * ∥f∥ : mul_le_mul_of_nonneg_right norm_Integral_le_one $ norm_nonneg _ ... = ∥f∥ : one_mul _ @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), f.integral) := by simp [l1.integral, l1.integral_clm.continuous] section pos_part lemma integral_eq_norm_pos_part_sub (f : α →₁[μ] ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ := begin -- Use `is_closed_property` and `is_closed_eq` refine @is_closed_property _ _ _ (coe : (α →₁ₛ[μ] ℝ) → (α →₁[μ] ℝ)) (λ f : α →₁[μ] ℝ, integral f = ∥pos_part f∥ - ∥neg_part f∥) l1.simple_func.dense_range (is_closed_eq _ _) _ f, { exact cont _ }, { refine continuous.sub (continuous_norm.comp l1.continuous_pos_part) (continuous_norm.comp l1.continuous_neg_part) }, -- Show that the property holds for all simple functions in the `L¹` space. { assume s, norm_cast, rw [← simple_func.norm_eq, ← simple_func.norm_eq], exact simple_func.integral_eq_norm_pos_part_sub _} end end pos_part end integration_in_l1 end l1 variables [normed_group E] [second_countable_topology E] [normed_space ℝ E] [complete_space E] [measurable_space E] [borel_space E] [normed_group F] [second_countable_topology F] [normed_space ℝ F] [complete_space F] [measurable_space F] [borel_space F] /-- The Bochner integral -/ def integral (μ : measure α) (f : α → E) : E := if hf : integrable f μ then (l1.of_fun f hf).integral else 0 /-! In the notation for integrals, an expression like `∫ x, g ∥x∥ ∂μ` will not be parsed correctly, and needs parentheses. We do not set the binding power of `r` to `0`, because then `∫ x, f x = 0` will be parsed incorrectly. -/ notation `∫` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral μ r notation `∫` binders `, ` r:(scoped:60 f, integral volume f) := r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := integral (measure.restrict μ s) r notation `∫` binders ` in ` s `, ` r:(scoped:60 f, integral (measure.restrict volume s) f) := r section properties open continuous_linear_map measure_theory.simple_func variables {f g : α → E} {μ : measure α} lemma integral_eq (f : α → E) (hf : integrable f μ) : ∫ a, f a ∂μ = (l1.of_fun f hf).integral := dif_pos hf lemma l1.integral_eq_integral (f : α →₁[μ] E) : f.integral = ∫ a, f a ∂μ := by rw [integral_eq, l1.of_fun_to_fun] lemma integral_undef (h : ¬ integrable f μ) : ∫ a, f a ∂μ = 0 := dif_neg h lemma integral_non_measurable (h : ¬ measurable f) : ∫ a, f a ∂μ = 0 := integral_undef $ not_and_of_not_left _ h variables (α E) lemma integral_zero : ∫ a : α, (0:E) ∂μ = 0 := by rw [integral_eq, l1.of_fun_zero, l1.integral_zero] @[simp] lemma integral_zero' : integral μ (0 : α → E) = 0 := integral_zero α E variables {α E} lemma integral_add (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a + g a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := by { rw [integral_eq, integral_eq f hf, integral_eq g hg, ← l1.integral_add, ← l1.of_fun_add], refl } lemma integral_add' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f + g) a ∂μ = ∫ a, f a ∂μ + ∫ a, g a ∂μ := integral_add hf hg lemma integral_neg (f : α → E) : ∫ a, -f a ∂μ = - ∫ a, f a ∂μ := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, integral_eq (λa, - f a) hf.neg, ← l1.integral_neg, ← l1.of_fun_neg], refl }, { rw [integral_undef hf, integral_undef, neg_zero], rwa [← integrable_neg_iff] at hf } end lemma integral_neg' (f : α → E) : ∫ a, (-f) a ∂μ = - ∫ a, f a ∂μ := integral_neg f lemma integral_sub (hf : integrable f μ) (hg : integrable g μ) : ∫ a, f a - g a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := by { rw [sub_eq_add_neg, ← integral_neg], exact integral_add hf hg.neg } lemma integral_sub' (hf : integrable f μ) (hg : integrable g μ) : ∫ a, (f - g) a ∂μ = ∫ a, f a ∂μ - ∫ a, g a ∂μ := integral_sub hf hg lemma integral_smul (r : ℝ) (f : α → E) : ∫ a, r • (f a) ∂μ = r • ∫ a, f a ∂μ := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, integral_eq (λa, r • (f a)), l1.of_fun_smul, l1.integral_smul] }, { by_cases hr : r = 0, { simp only [hr, measure_theory.integral_zero, zero_smul] }, have hf' : ¬ integrable (λ x, r • f x) μ, { change ¬ integrable (r • f) μ, rwa [integrable_smul_iff hr f] }, rw [integral_undef hf, integral_undef hf', smul_zero] } end lemma integral_mul_left (r : ℝ) (f : α → ℝ) : ∫ a, r * (f a) ∂μ = r * ∫ a, f a ∂μ := integral_smul r f lemma integral_mul_right (r : ℝ) (f : α → ℝ) : ∫ a, (f a) * r ∂μ = ∫ a, f a ∂μ * r := by { simp only [mul_comm], exact integral_mul_left r f } lemma integral_div (r : ℝ) (f : α → ℝ) : ∫ a, (f a) / r ∂μ = ∫ a, f a ∂μ / r := integral_mul_right r⁻¹ f lemma integral_congr_ae (hfm : measurable f) (hgm : measurable g) (h : f =ᵐ[μ] g) : ∫ a, f a ∂μ = ∫ a, g a ∂μ := begin by_cases hfi : integrable f μ, { have hgi : integrable g μ := hfi.congr hgm h, rw [integral_eq f hfi, integral_eq g hgi, (l1.of_fun_eq_of_fun f g hfi hgi).2 h] }, { have hgi : ¬ integrable g μ, { rw integrable_congr hfm hgm h at hfi, exact hfi }, rw [integral_undef hfi, integral_undef hgi] }, end @[simp] lemma l1.integral_of_fun_eq_integral {f : α → E} (hf : integrable f μ) : ∫ a, (l1.of_fun f hf) a ∂μ = ∫ a, f a ∂μ := integral_congr_ae (l1.measurable _) hf.measurable (l1.to_fun_of_fun f hf) @[continuity] lemma continuous_integral : continuous (λ (f : α →₁[μ] E), ∫ a, f a ∂μ) := by { simp only [← l1.integral_eq_integral], exact l1.continuous_integral } lemma norm_integral_le_lintegral_norm (f : α → E) : ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) := begin by_cases hf : integrable f μ, { rw [integral_eq f hf, ← l1.norm_of_fun_eq_lintegral_norm f hf], exact l1.norm_integral_le _ }, { rw [integral_undef hf, norm_zero], exact to_real_nonneg } end lemma ennnorm_integral_le_lintegral_ennnorm (f : α → E) : (nnnorm (∫ a, f a ∂μ) : ennreal) ≤ ∫⁻ a, (nnnorm (f a)) ∂μ := by { simp_rw [← of_real_norm_eq_coe_nnnorm], apply ennreal.of_real_le_of_le_to_real, exact norm_integral_le_lintegral_norm f } lemma integral_eq_zero_of_ae {f : α → E} (hf : f =ᵐ[μ] 0) : ∫ a, f a ∂μ = 0 := if hfm : measurable f then by simp [integral_congr_ae hfm measurable_zero hf, integral_zero] else integral_non_measurable hfm /-- If `F i → f` in `L1`, then `∫ x, F i x ∂μ → ∫ x, f x∂μ`. -/ lemma tendsto_integral_of_l1 {ι} (f : α → E) (hfi : integrable f μ) {F : ι → α → E} {l : filter ι} (hFi : ∀ᶠ i in l, integrable (F i) μ) (hF : tendsto (λ i, ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0)) : tendsto (λ i, ∫ x, F i x ∂μ) l (𝓝 $ ∫ x, f x ∂μ) := begin rw [tendsto_iff_norm_tendsto_zero], replace hF : tendsto (λ i, ennreal.to_real $ ∫⁻ x, edist (F i x) (f x) ∂μ) l (𝓝 0) := (ennreal.tendsto_to_real zero_ne_top).comp hF, refine squeeze_zero_norm' (hFi.mp $ hFi.mono $ λ i hFi hFm, _) hF, simp only [norm_norm, ← integral_sub hFi hfi, edist_dist, dist_eq_norm], apply norm_integral_le_lintegral_norm end /-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost everywhere convergence of a sequence of functions implies the convergence of their integrals. -/ theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → E} {f : α → E} (bound : α → ℝ) (F_measurable : ∀ n, measurable (F n)) (f_measurable : measurable f) (bound_integrable : integrable 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, F n a ∂μ) at_top (𝓝 $ ∫ a, f a ∂μ) := begin /- To show `(∫ a, F n a) --> (∫ f)`, suffices to show `∥∫ a, F n a - ∫ f∥ --> 0` -/ rw tendsto_iff_norm_tendsto_zero, /- But `0 ≤ ∥∫ a, F n a - ∫ f∥ = ∥∫ a, (F n a - f a) ∥ ≤ ∫ a, ∥F n a - f a∥, and thus we apply the sandwich theorem and prove that `∫ a, ∥F n a - f a∥ --> 0` -/ have lintegral_norm_tendsto_zero : tendsto (λn, ennreal.to_real $ ∫⁻ a, (ennreal.of_real ∥F n a - f a∥) ∂μ) at_top (𝓝 0) := (tendsto_to_real zero_ne_top).comp (tendsto_lintegral_norm_of_dominated_convergence F_measurable f_measurable bound_integrable.has_finite_integral h_bound h_lim), -- Use the sandwich theorem refine squeeze_zero (λ n, norm_nonneg _) _ lintegral_norm_tendsto_zero, -- Show `∥∫ a, F n a - ∫ f∥ ≤ ∫ a, ∥F n a - f a∥` for all `n` { assume n, have h₁ : integrable (F n) μ := bound_integrable.mono' (F_measurable n) (h_bound _), have h₂ : integrable f μ := ⟨f_measurable, has_finite_integral_of_dominated_convergence bound_integrable.has_finite_integral h_bound h_lim⟩, rw ← integral_sub h₁ h₂, exact norm_integral_le_lintegral_norm _ } end /-- Lebesgue dominated convergence theorem for filters with a countable basis -/ lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → E} {f : α → E} (bound : α → ℝ) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, measurable (F n)) (f_measurable : measurable f) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, ∥F n a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫ a, F n a ∂μ) l (𝓝 $ ∫ a, f a ∂μ) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_integral_of_dominated_convergence _ _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { assumption }, { assumption }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { filter_upwards [h_lim], simp only [mem_set_of_eq], assume a h_lim, apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end /-- The Bochner integral of a real-valued function `f : α → ℝ` is the difference between the integral of the positive part of `f` and the integral of the negative part of `f`. -/ lemma integral_eq_lintegral_max_sub_lintegral_min {f : α → ℝ} (hf : integrable f μ) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ max (f a) 0) ∂μ) - ennreal.to_real (∫⁻ a, (ennreal.of_real $ - min (f a) 0) ∂μ) := let f₁ : α →₁[μ] ℝ := l1.of_fun f hf in -- Go to the `L¹` space have eq₁ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ max (f a) 0) ∂μ) = ∥l1.pos_part f₁∥ := begin rw l1.norm_eq_norm_to_fun, congr' 1, apply lintegral_congr_ae, filter_upwards [l1.pos_part_to_fun f₁, l1.to_fun_of_fun f hf], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], exact le_max_right _ _ end, -- Go to the `L¹` space have eq₂ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ -min (f a) 0) ∂μ) = ∥l1.neg_part f₁∥ := begin rw l1.norm_eq_norm_to_fun, congr' 1, apply lintegral_congr_ae, filter_upwards [l1.neg_part_to_fun_eq_min f₁, l1.to_fun_of_fun f hf], simp only [mem_set_of_eq], assume a h₁ h₂, rw [h₁, h₂, real.norm_eq_abs, abs_of_nonneg], rw [min_eq_neg_max_neg_neg, _root_.neg_neg, neg_zero], exact le_max_right _ _ end, begin rw [eq₁, eq₂, integral, dif_pos], exact l1.integral_eq_norm_pos_part_sub _ end lemma integral_eq_lintegral_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfm : measurable f) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) := begin by_cases hfi : integrable f μ, { rw integral_eq_lintegral_max_sub_lintegral_min hfi, have h_min : ∫⁻ a, ennreal.of_real (-min (f a) 0) ∂μ = 0, { rw lintegral_eq_zero_iff, { refine hf.mono _, simp only [pi.zero_apply], assume a h, simp only [min_eq_right h, neg_zero, ennreal.of_real_zero] }, { exact measurable_of_real.comp (measurable_id.neg.comp $ hfm.min measurable_const) } }, have h_max : ∫⁻ a, ennreal.of_real (max (f a) 0) ∂μ = ∫⁻ a, ennreal.of_real (f a) ∂μ, { refine lintegral_congr_ae (hf.mono (λ a h, _)), rw [pi.zero_apply] at h, rw max_eq_left h }, rw [h_min, h_max, zero_to_real, _root_.sub_zero] }, { rw integral_undef hfi, simp_rw [integrable, hfm, has_finite_integral_iff_norm, lt_top_iff_ne_top, ne.def, true_and, not_not] at hfi, have : ∫⁻ (a : α), ennreal.of_real (f a) ∂μ = ∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ, { refine lintegral_congr_ae (hf.mono $ assume a h, _), rw [real.norm_eq_abs, abs_of_nonneg h] }, rw [this, hfi], refl } end lemma integral_nonneg_of_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a, f a ∂μ := begin by_cases hfm : measurable f, { rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg }, { rw integral_non_measurable hfm } end lemma lintegral_coe_eq_integral (f : α → nnreal) (hfi : integrable (λ x, (f x : real)) μ) : ∫⁻ a, f a ∂μ = ennreal.of_real ∫ a, f a ∂μ := begin simp_rw [integral_eq_lintegral_of_nonneg_ae (eventually_of_forall (λ x, (f x).coe_nonneg)) hfi.measurable, ← ennreal.coe_nnreal_eq], rw [ennreal.of_real_to_real], rw [← lt_top_iff_ne_top], convert hfi.has_finite_integral, ext1 x, rw [real.nnnorm_coe_eq_self] end lemma integral_to_real {f : α → ennreal} (hfm : measurable f) (hf : ∀ᵐ x ∂μ, f x < ⊤) : ∫ a, (f a).to_real ∂μ = (∫⁻ a, f a ∂μ).to_real := begin rw [integral_eq_lintegral_of_nonneg_ae _ hfm.to_real], { rw lintegral_congr_ae, refine hf.mp (eventually_of_forall _), intros x hx, rw [lt_top_iff_ne_top] at hx, simp [hx] }, { exact (eventually_of_forall $ λ x, ennreal.to_real_nonneg) } end lemma integral_nonneg {f : α → ℝ} (hf : 0 ≤ f) : 0 ≤ ∫ a, f a ∂μ := integral_nonneg_of_ae $ eventually_of_forall hf lemma integral_nonpos_of_ae {f : α → ℝ} (hf : f ≤ᵐ[μ] 0) : ∫ a, f a ∂μ ≤ 0 := begin have hf : 0 ≤ᵐ[μ] (-f) := hf.mono (assume a h, by rwa [pi.neg_apply, pi.zero_apply, neg_nonneg]), have : 0 ≤ ∫ a, -f a ∂μ := integral_nonneg_of_ae hf, rwa [integral_neg, neg_nonneg] at this, end lemma integral_nonpos {f : α → ℝ} (hf : f ≤ 0) : ∫ a, f a ∂μ ≤ 0 := integral_nonpos_of_ae $ eventually_of_forall hf lemma integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := by simp_rw [integral_eq_lintegral_of_nonneg_ae hf hfi.1, ennreal.to_real_eq_zero_iff, lintegral_eq_zero_iff (ennreal.measurable_of_real.comp hfi.1), ← ennreal.not_lt_top, ← has_finite_integral_iff_of_real hf, hfi.2, not_true, or_false, ← hf.le_iff_eq, filter.eventually_eq, filter.eventually_le, (∘), pi.zero_apply, ennreal.of_real_eq_zero] lemma integral_eq_zero_iff_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : ∫ x, f x ∂μ = 0 ↔ f =ᵐ[μ] 0 := integral_eq_zero_iff_of_nonneg_ae (eventually_of_forall hf) hfi lemma integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := by simp_rw [(integral_nonneg_of_ae hf).lt_iff_ne, zero_lt_iff_ne_zero, ne.def, @eq_comm ℝ 0, integral_eq_zero_iff_of_nonneg_ae hf hfi, filter.eventually_eq, ae_iff, pi.zero_apply, function.support] lemma integral_pos_iff_support_of_nonneg {f : α → ℝ} (hf : 0 ≤ f) (hfi : integrable f μ) : (0 < ∫ x, f x ∂μ) ↔ 0 < μ (function.support f) := integral_pos_iff_support_of_nonneg_ae (eventually_of_forall hf) hfi section normed_group variables {H : Type*} [normed_group H] [second_countable_topology H] [measurable_space H] [borel_space H] lemma l1.norm_eq_integral_norm (f : α →₁[μ] H) : ∥f∥ = ∫ a, ∥f a∥ ∂μ := by rw [l1.norm_eq_norm_to_fun, integral_eq_lintegral_of_nonneg_ae (eventually_of_forall $ by simp [norm_nonneg]) (continuous_norm.measurable.comp f.measurable)] lemma l1.norm_of_fun_eq_integral_norm {f : α → H} (hf : integrable f μ) : ∥ l1.of_fun f hf ∥ = ∫ a, ∥f a∥ ∂μ := begin rw l1.norm_eq_integral_norm, refine integral_congr_ae (l1.measurable_norm _) hf.measurable.norm _, apply (l1.to_fun_of_fun f hf).mono, intros a ha, simp [ha] end end normed_group lemma integral_mono_ae {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := le_of_sub_nonneg $ integral_sub hg hf ▸ integral_nonneg_of_ae $ h.mono (λ a, sub_nonneg_of_le) lemma integral_mono {f g : α → ℝ} (hf : integrable f μ) (hg : integrable g μ) (h : f ≤ g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := integral_mono_ae hf hg $ eventually_of_forall h lemma integral_mono_of_nonneg {f g : α → ℝ} (hf : 0 ≤ᵐ[μ] f) (hgi : integrable g μ) (h : f ≤ᵐ[μ] g) : ∫ a, f a ∂μ ≤ ∫ a, g a ∂μ := begin by_cases hfm : measurable f, { refine integral_mono_ae ⟨hfm, _⟩ hgi h, refine (hgi.has_finite_integral.mono $ h.mp $ hf.mono $ λ x hf hfg, _), simpa [real.norm_eq_abs, abs_of_nonneg hf, abs_of_nonneg (le_trans hf hfg)] }, { rw [integral_non_measurable hfm], exact integral_nonneg_of_ae (hf.trans h) } end lemma norm_integral_le_integral_norm (f : α → E) : ∥(∫ a, f a ∂μ)∥ ≤ ∫ a, ∥f a∥ ∂μ := have le_ae : ∀ᵐ a ∂μ, 0 ≤ ∥f a∥ := eventually_of_forall (λa, norm_nonneg _), classical.by_cases ( λh : measurable f, calc ∥∫ a, f a ∂μ∥ ≤ ennreal.to_real (∫⁻ a, (ennreal.of_real ∥f a∥) ∂μ) : norm_integral_le_lintegral_norm _ ... = ∫ a, ∥f a∥ ∂μ : (integral_eq_lintegral_of_nonneg_ae le_ae $ measurable.norm h).symm ) ( λh : ¬measurable f, begin rw [integral_non_measurable h, norm_zero], exact integral_nonneg_of_ae le_ae end ) lemma norm_integral_le_of_norm_le {f : α → E} {g : α → ℝ} (hg : integrable g μ) (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ g x) : ∥∫ x, f x ∂μ∥ ≤ ∫ x, g x ∂μ := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, ∥f x∥ ∂μ : norm_integral_le_integral_norm f ... ≤ ∫ x, g x ∂μ : integral_mono_of_nonneg (eventually_of_forall $ λ x, norm_nonneg _) hg h lemma integral_finset_sum {ι} (s : finset ι) {f : ι → α → E} (hf : ∀ i, integrable (f i) μ) : ∫ a, ∑ i in s, f i a ∂μ = ∑ i in s, ∫ a, f i a ∂μ := begin refine finset.induction_on s _ _, { simp only [integral_zero, finset.sum_empty] }, { assume i s his ih, simp only [his, finset.sum_insert, not_false_iff], rw [integral_add (hf _) (integrable_finset_sum s hf), ih] } end lemma simple_func.integral_eq_integral (f : α →ₛ E) (hfi : integrable f μ) : f.integral μ = ∫ x, f x ∂μ := begin rw [integral_eq f hfi, ← l1.simple_func.of_simple_func_eq_of_fun, l1.simple_func.integral_l1_eq_integral, l1.simple_func.integral_eq_integral], exact simple_func.integral_congr hfi (l1.simple_func.to_simple_func_of_simple_func _ _).symm end @[simp] lemma integral_const (c : E) : ∫ x : α, c ∂μ = (μ univ).to_real • c := begin by_cases hμ : μ univ < ⊤, { haveI : finite_measure μ := ⟨hμ⟩, calc ∫ x : α, c ∂μ = (simple_func.const α c).integral μ : ((simple_func.const α c).integral_eq_integral (integrable_const _)).symm ... = _ : _, rw [simple_func.integral], by_cases ha : nonempty α, { resetI, simp [preimage_const_of_mem] }, { simp [μ.eq_zero_of_not_nonempty ha] } }, { by_cases hc : c = 0, { simp [hc, integral_zero] }, { have : ¬integrable (λ x : α, c) μ, { simp only [integrable_const_iff, not_or_distrib], exact ⟨hc, hμ⟩ }, simp only [not_lt, top_le_iff] at hμ, simp [integral_undef, *] } } end lemma norm_integral_le_of_norm_le_const [finite_measure μ] {f : α → E} {C : ℝ} (h : ∀ᵐ x ∂μ, ∥f x∥ ≤ C) : ∥∫ x, f x ∂μ∥ ≤ C * (μ univ).to_real := calc ∥∫ x, f x ∂μ∥ ≤ ∫ x, C ∂μ : norm_integral_le_of_norm_le (integrable_const C) h ... = C * (μ univ).to_real : by rw [integral_const, smul_eq_mul, mul_comm] lemma tendsto_integral_approx_on_univ {f : α → E} (hf : integrable f μ) : tendsto (λ n, (simple_func.approx_on f hf.1 univ 0 trivial n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ) := begin have : tendsto (λ n, ∫ x, simple_func.approx_on f hf.1 univ 0 trivial n x ∂μ) at_top (𝓝 $ ∫ x, f x ∂μ) := tendsto_integral_of_l1 _ hf (eventually_of_forall $ simple_func.integrable_approx_on_univ hf) (simple_func.tendsto_approx_on_univ_l1_edist hf), simpa only [simple_func.integral_eq_integral, simple_func.integrable_approx_on_univ hf] end variable {ν : measure α} lemma integral_add_measure {f : α → E} (hμ : integrable f μ) (hν : integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin have hfi := hμ.add_measure hν, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ hfi) _, simpa only [simple_func.integral_add_measure _ (simple_func.integrable_approx_on_univ hfi _)] using (tendsto_integral_approx_on_univ hμ).add (tendsto_integral_approx_on_univ hν) end lemma integral_add_measure' {f : α → E} (hμ : has_finite_integral f μ) (hν : has_finite_integral f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin by_cases hfm : measurable f, { exact integral_add_measure ⟨hfm, hμ⟩ ⟨hfm, hν⟩ }, { simp only [integral_non_measurable hfm, zero_add] } end @[simp] lemma integral_zero_measure (f : α → E) : ∫ x, f x ∂0 = 0 := norm_le_zero_iff.1 $ le_trans (norm_integral_le_lintegral_norm f) $ by simp @[simp] lemma integral_smul_measure (f : α → E) (c : ennreal) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin -- First we consider “degenerate” cases: -- `f` is not measurable by_cases hfm : measurable f, swap, { simp [integral_non_measurable hfm] }, -- `c = 0` rcases (zero_le c).eq_or_lt with rfl|h0, { simp }, -- `c = ⊤` rcases (le_top : c ≤ ⊤).eq_or_lt with rfl|hc, { rw [ennreal.top_to_real, zero_smul], by_cases hf : f =ᵐ[μ] 0, { have : f =ᵐ[⊤ • μ] 0 := ae_smul_measure hf ⊤, exact integral_eq_zero_of_ae this }, { apply integral_undef, rw [integrable, has_finite_integral, iff_true_intro hfm, true_and, lintegral_smul_measure, top_mul, if_neg], { apply lt_irrefl }, { rw [lintegral_eq_zero_iff hfm.ennnorm], refine λ h, hf (h.mono $ λ x, _), simp } } }, -- `f` is not integrable and `0 < c < ⊤` by_cases hfi : integrable f μ, swap, { rw [integral_undef hfi, smul_zero], refine integral_undef (mt (λ h, _) hfi), convert h.smul_measure (ennreal.inv_lt_top.2 h0), rw [smul_smul, ennreal.inv_mul_cancel (ne_of_gt h0) (ne_of_lt hc), one_smul] }, -- Main case: `0 < c < ⊤`, `f` is measurable and integrable refine tendsto_nhds_unique _ (tendsto_const_nhds.smul (tendsto_integral_approx_on_univ hfi)), convert tendsto_integral_approx_on_univ (hfi.smul_measure hc), simp only [simple_func.integral, measure.smul_apply, finset.smul_sum, smul_smul, ennreal.to_real_mul_to_real] end lemma integral_map {β} [measurable_space β] {φ : α → β} (hφ : measurable φ) {f : β → E} (hfm : measurable f) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := begin by_cases hfi : integrable f (measure.map φ μ), swap, { rw [integral_undef hfi, integral_undef], rwa [← integrable_map_measure hφ hfm] }, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ hfi) _, convert tendsto_integral_approx_on_univ ((integrable_map_measure hφ hfm).1 hfi), ext1 i, simp only [simple_func.approx_on_comp, simple_func.integral, measure.map_apply, hφ, simple_func.is_measurable_preimage, ← preimage_comp, simple_func.coe_comp], refine (finset.sum_subset (simple_func.range_comp_subset_range _ hφ) (λ y _ hy, _)).symm, rw [simple_func.mem_range, ← set.preimage_singleton_eq_empty, simple_func.coe_comp] at hy, simp [hy] end lemma integral_dirac (f : α → E) (a : α) (hfm : measurable f) : ∫ x, f x ∂(measure.dirac a) = f a := calc ∫ x, f x ∂(measure.dirac a) = ∫ x, f a ∂(measure.dirac a) : integral_congr_ae hfm measurable_const $ eventually_eq_dirac hfm ... = f a : by simp [measure.dirac_apply_of_mem] end properties mk_simp_attribute integral_simps "Simp set for integral rules." attribute [integral_simps] integral_neg integral_smul l1.integral_add l1.integral_sub l1.integral_smul l1.integral_neg attribute [irreducible] integral l1.integral end measure_theory
09308b48457a78be378292d66ec39fc0f7fa105b
5a8eb1c11f93715e070b588e85f2961065c3714d
/books/theorem-proving-in-lean/ch02-01.lean
09146b76459445e6dc2a392cd3baba3061f10d0e
[ "MIT" ]
permissive
luksamuk/study
0e19bf99d33e0793127c3d3f8ad3936fbeb36505
6a9417e071a8624c4cd9db696c16a3abcc430219
refs/heads/master
1,677,960,533,266
1,676,234,529,000
1,676,234,529,000
151,009,060
4
1
MIT
1,676,234,531,000
1,538,343,224,000
C++
UTF-8
Lean
false
false
662
lean
/- Constant declaration -/ -- m and n are natural numbers constant m : ℕ constant n : ℕ constants b1 b2 : bool -- two declarations /- Check types -/ #check m #check n #check n + 0 #check m * (n + 0) #check b1 #check b1 && b2 #check b1 || b2 #check b1 || b2 #check tt #check n / m constant f : ℕ → ℕ constant f' : nat -> nat constant p : ℕ × ℕ constant p' : prod ℕ ℕ constant g : ℕ → ℕ → ℕ constant F : (ℕ → ℕ) → ℕ -- Curried function of two arguments constant G : ℕ → (ℕ → ℕ) #check f m #check g m n #check (m, n) #check p.1 #check p.2 #check (m, n).1 #check (p.1, n) #check F f #check G m #check G m n
1b4188a914bc95ff4bfcbee0a4b0d4040bea4864
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/tactic/basic.lean
05542956aaa9455e6a42062c100dd930c721d772
[ "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
886
lean
import tactic.alias import tactic.clear import tactic.choose import tactic.converter.apply_congr import tactic.congr import tactic.dec_trivial import tactic.delta_instance import tactic.elide import tactic.explode import tactic.find import tactic.finish import tactic.generalizes import tactic.generalize_proofs import tactic.lift import tactic.lint import tactic.localized import tactic.mk_iff_of_inductive_prop import tactic.norm_cast import tactic.obviously import tactic.pretty_cases import tactic.protected import tactic.push_neg import tactic.replacer import tactic.rename_var import tactic.restate_axiom import tactic.rewrite import tactic.show_term import tactic.simp_rw import tactic.simp_command import tactic.simp_result import tactic.simps import tactic.split_ifs import tactic.squeeze import tactic.suggest import tactic.tauto import tactic.trunc_cases import tactic.where
b36ad86e4521fc5408e94be345a6a413694697e3
a4673261e60b025e2c8c825dfa4ab9108246c32e
/src/Init/Control/Basic.lean
5cca3d0ad0775e10d0291d619212d7fc973dd0b2
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,808
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Core universes u v w @[reducible] def Functor.mapRev {f : Type u → Type v} [Functor f] {α β : Type u} : f α → (α → β) → f β := fun a f => f <$> a infixr:100 " <&> " => Fuctor.mapRev def Functor.discard {f : Type u → Type v} {α : Type u} [Functor f] (x : f α) : f PUnit := Functor.mapConst PUnit.unit x export Functor (discard) @[macroInline] def when {m : Type → Type u} [Applicative m] (c : Prop) [h : Decidable c] (t : m Unit) : m Unit := if c then t else pure () @[macroInline] def «unless» {m : Type → Type u} [Applicative m] (c : Prop) [h : Decidable c] (e : m Unit) : m Unit := if c then pure () else e 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 α) instance (f : Type u → Type v) (α : Type u) [Alternative f] : OrElse (f α) := ⟨Alternative.orElse⟩ variables {f : Type u → Type v} [Alternative f] {α : Type u} export Alternative (failure) @[inline] def guard {f : Type → Type v} [Alternative f] (p : Prop) [Decidable p] : f Unit := if p then pure () else failure @[inline] def assert {f : Type → Type v} [Alternative f] (p : Prop) [Decidable p] : f (Inhabited p) := if h : p then pure ⟨h⟩ else failure @[inline] def optional (x : f α) : f (Option α) := some <$> x <|> pure none class ToBool (α : Type u) := (toBool : α → Bool) export ToBool (toBool) instance : ToBool Bool := ⟨id⟩ @[macroInline] def bool {β : Type u} {α : Type v} [ToBool β] (f t : α) (b : β) : α := match toBool b with | true => t | false => f @[macroInline] def orM {m : Type u → Type v} {β : Type u} [Monad m] [ToBool β] (x y : m β) : m β := do let b ← x match toBool b with | true => pure b | false => y infixr:30 " <||> " => orM @[macroInline] def andM {m : Type u → Type v} {β : Type u} [Monad m] [ToBool β] (x y : m β) : m β := do let b ← x match toBool b with | true => y | false => pure b infixr:35 " <&&> " => andM @[macroInline] def notM {m : Type → Type v} [Applicative m] (x : m Bool) : m Bool := not <$> x class MonadControl (m : Type u → Type v) (n : Type u → Type w) := (stM : Type u → Type u) (liftWith : {α : Type u} → (({β : Type u} → n β → m (stM β)) → m α) → n α) (restoreM : {α : Type u} → m (stM α) → n α) class MonadControlT (m : Type u → Type v) (n : Type u → Type w) := (stM : Type u → Type u) (liftWith : {α : Type u} → (({β : Type u} → n β → m (stM β)) → m α) → n α) (restoreM {α : Type u} : stM α → n α) export MonadControlT (stM liftWith restoreM) instance (m n o) [MonadControlT m n] [MonadControl n o] : MonadControlT m o := { stM := fun α => stM m n (MonadControl.stM n o α) liftWith := fun f => MonadControl.liftWith fun x₂ => liftWith fun x₁ => f (x₁ ∘ x₂) restoreM := MonadControl.restoreM ∘ restoreM } instance (m : Type u → Type v) [Pure m] : MonadControlT m m := { stM := fun α => α liftWith := fun f => f fun x => x restoreM := fun x => pure x } @[inline] def controlAt (m : Type u → Type v) {n : Type u → Type w} [s1 : MonadControlT m n] [s2 : Bind n] {α : Type u} (f : ({β : Type u} → n β → m (stM m n β)) → m (stM m n α)) : n α := liftWith f >>= restoreM @[inline] def control {m : Type u → Type v} {n : Type u → Type w} [MonadControlT m n] [Bind n] {α : Type u} (f : ({β : Type u} → n β → m (stM m n β)) → m (stM m n α)) : n α := controlAt m f
e927bf661232db97db1b5ea9779c469165a406f0
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/mono_coprod.lean
4a5b437d63efb6aaf268c38ee5a257afc98c544d
[ "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
3,910
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.limits.shapes.regular_mono import category_theory.limits.shapes.zero_morphisms /-! # Categories where inclusions into coproducts are monomorphisms If `C` is a category, the class `mono_coprod C` expresses that left inclusions `A ⟶ A ⨿ B` are monomorphisms when `has_coproduct A B` is satisfied. If it is so, it is shown that right inclusions are also monomorphisms. TODO @joelriou: show that if `X : I → C` and `ι : J → I` is an injective map, then the canonical morphism `∐ (X ∘ ι) ⟶ ∐ X` is a monomorphism. TODO: define distributive categories, and show that they satisfy `mono_coprod`, see <https://ncatlab.org/toddtrimble/published/distributivity+implies+monicity+of+coproduct+inclusions> -/ noncomputable theory open category_theory category_theory.category category_theory.limits universe u namespace category_theory namespace limits variables (C : Type*) [category C] /-- This condition expresses that inclusion morphisms into coproducts are monomorphisms. -/ class mono_coprod : Prop := (binary_cofan_inl : ∀ ⦃A B : C⦄ (c : binary_cofan A B) (hc : is_colimit c), mono c.inl) variable {C} @[priority 100] instance mono_coprod_of_has_zero_morphisms [has_zero_morphisms C] : mono_coprod C := ⟨λ A B c hc, begin haveI : is_split_mono c.inl := is_split_mono.mk' (split_mono.mk (hc.desc (binary_cofan.mk (𝟙 A) 0)) (is_colimit.fac _ _ _)), apply_instance, end⟩ namespace mono_coprod lemma binary_cofan_inr {A B : C}[mono_coprod C] (c : binary_cofan A B) (hc : is_colimit c) : mono c.inr := begin have hc' : is_colimit (binary_cofan.mk c.inr c.inl) := binary_cofan.is_colimit_mk (λ s, hc.desc (binary_cofan.mk s.inr s.inl)) (by tidy) (by tidy) (λ s m h₁ h₂, binary_cofan.is_colimit.hom_ext hc (by simp only [h₂, is_colimit.fac, binary_cofan.ι_app_left, binary_cofan.mk_inl]) (by simp only [h₁, is_colimit.fac, binary_cofan.ι_app_right, binary_cofan.mk_inr])), exact binary_cofan_inl _ hc', end instance {A B : C} [mono_coprod C] [has_binary_coproduct A B] : mono (coprod.inl : A ⟶ A ⨿ B) := binary_cofan_inl _ (colimit.is_colimit _) instance {A B : C} [mono_coprod C] [has_binary_coproduct A B] : mono (coprod.inr : B ⟶ A ⨿ B) := binary_cofan_inr _ (colimit.is_colimit _) lemma mono_inl_iff {A B : C} {c₁ c₂ : binary_cofan A B} (hc₁ : is_colimit c₁) (hc₂ : is_colimit c₂) : mono c₁.inl ↔ mono c₂.inl := begin suffices : ∀ (c₁ c₂ : binary_cofan A B) (hc₁ : is_colimit c₁) (hc₂ : is_colimit c₂) (h : mono c₁.inl), mono c₂.inl, { exact ⟨λ h₁, this _ _ hc₁ hc₂ h₁, λ h₂, this _ _ hc₂ hc₁ h₂⟩, }, intros c₁ c₂ hc₁ hc₂, introI, simpa only [is_colimit.comp_cocone_point_unique_up_to_iso_hom] using mono_comp c₁.inl (hc₁.cocone_point_unique_up_to_iso hc₂).hom, end lemma mk' (h : ∀ (A B : C), ∃ (c : binary_cofan A B) (hc : is_colimit c), mono c.inl) : mono_coprod C := ⟨λ A B c' hc', begin obtain ⟨c, hc₁, hc₂⟩ := h A B, simpa only [mono_inl_iff hc' hc₁] using hc₂, end⟩ instance mono_coprod_type : mono_coprod (Type u) := mono_coprod.mk' (λ A B, begin refine ⟨binary_cofan.mk (sum.inl : A ⟶ A ⊕ B) sum.inr, _, _⟩, { refine binary_cofan.is_colimit.mk _ (λ Y f₁ f₂ x, by { cases x, exacts [f₁ x, f₂ x], }) (λ Y f₁ f₂, rfl) (λ Y f₁ f₂, rfl) _, intros Y f₁ f₂ m h₁ h₂, ext x, cases x, { dsimp, exact congr_fun h₁ x, }, { dsimp, exact congr_fun h₂ x, }, }, { rw mono_iff_injective, intros a₁ a₂ h, simp only [binary_cofan.mk_inl] at h, dsimp at h, simpa only using h, }, end) end mono_coprod end limits end category_theory
d2339f59d1ddaa288a0199ddae0efe7c6f62f2f9
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/tactic_state_pp.lean
00b52de6b0e398c49e05459eb4e5a967ea10a983
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
1,100
lean
universe variables u inductive Vec (α : Type u) : nat → Type (max 1 u) | nil : Vec 0 | cons : ∀ {n}, α → Vec n → Vec (nat.succ n) constant f {α : Type u} {n : nat} : Vec α n → nat axiom fax1 (α : Type u) : f (Vec.nil α) = 0 axiom fax2 {α : Type u} {n : nat} (v : Vec α (nat.succ n)) : f v = 1 open tactic meta def pp_state_core : tactic format := do t ← target, t_fmt ← pp t, return $ to_fmt "Goal: " ++ t_fmt meta def pp_state (s : tactic_state) : format := match pp_state_core s with | tactic_result.success r _ := r | tactic_result.exception .format _ _ _ := "failed to pretty print" end meta instance i2 : has_to_format tactic_state := ⟨λ s, to_fmt "My custom goal visualizer" ++ format.line ++ pp_state s⟩ example {α : Type u} {n : nat} (v : Vec α n) : f v ≠ 2 := begin destruct v, intros, intro, note h := fax1 α, cc, -- intros n1 h t, intros, intro, note h := fax2 (Vec.cons h t), cc end open nat example : ∀ n, 0 < n → succ (pred n) = n := begin intro n, destruct n, dsimp, intros, note h := lt_irrefl 0, cc, end
01b36fa8d9816206f864e625b861844fb2708068
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/topology/constructions.lean
5997db2e48c0d2ed517f958e0b745017222f3bea
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
40,384
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 -/ import topology.maps /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter open_locale classical topological_space filter universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced coe t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) := t.induced ulift.down /-- The image of a dense set under `quotient.mk` is a dense set. -/ lemma dense.quotient [setoid α] [topological_space α] {s : set α} (H : dense s) : dense (quotient.mk '' s) := (surjective_quotient_mk α).dense_range.dense_image continuous_coinduced_rng H /-- The composition of `quotient.mk` and a function with dense range has dense range. -/ lemma dense_range.quotient [setoid α] [topological_space α] {f : β → α} (hf : dense_range f) : dense_range (quotient.mk ∘ f) := (surjective_quotient_mk α).dense_range.comp hf continuous_coinduced_rng instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t := mem_nhds_induced coe a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap coe (𝓝 (a : α)) := nhds_induced coe a end topα end constructions section prod variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] @[continuity] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p := continuous_fst.continuous_at @[continuity] lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p := continuous_snd.continuous_at @[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) : continuous (λ x : γ × δ, (f x.1, g x.2)) := (hf.comp continuous_fst).prod_mk (hg.comp continuous_snd) lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 := continuous_at_fst h lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) : ∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 := continuous_at_snd h lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x) {pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) : ∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl_nhds b).and (hb.prod_inr_nhds a) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma continuous_uncurry_left {f : α → β → γ} (a : α) (h : continuous (function.uncurry f)) : continuous (f a) := show continuous (function.uncurry f ∘ (λ b, (a, b))), from h.comp (by continuity) lemma continuous_uncurry_right {f : α → β → γ} (b : β) (h : continuous (function.uncurry f)) : continuous (λ a, f a b) := show continuous (function.uncurry f ∘ (λ a, (a, b))), from h.comp (by continuity) lemma continuous_curry {g : α × β → γ} (a : α) (h : continuous g) : continuous (function.curry g a) := show continuous (g ∘ (λ b, (a, b))), from h.comp (by continuity) lemma is_open.prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (hs.preimage continuous_fst) (ht.preimage continuous_snd) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = 𝓝 a ×ᶠ 𝓝 b := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] lemma mem_nhds_prod_iff {a : α} {b : β} {s : set (α × β)} : s ∈ 𝓝 (a, b) ↔ ∃ (u ∈ 𝓝 a) (v ∈ 𝓝 b), set.prod u v ⊆ s := by rw [nhds_prod_eq, mem_prod_iff] lemma filter.has_basis.prod_nhds {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {a : α} {b : β} (ha : (𝓝 a).has_basis pa sa) (hb : (𝓝 b).has_basis pb sb) : (𝓝 (a, b)).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := by { rw nhds_prod_eq, exact ha.prod hb } lemma filter.has_basis.prod_nhds' {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop} {sa : ιa → set α} {sb : ιb → set β} {ab : α × β} (ha : (𝓝 ab.1).has_basis pa sa) (hb : (𝓝 ab.2).has_basis pb sb) : (𝓝 ab).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) := by { cases ab, exact ha.prod_nhds hb } instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_iff {s : set α} {t : set β} {a : α} {b : β} : s.prod t ∈ 𝓝 (a, b) ↔ s ∈ 𝓝 a ∧ t ∈ 𝓝 b := by rw [nhds_prod_eq, prod_mem_prod_iff] lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) := prod_mem_nhds_iff.2 ⟨ha, hb⟩ lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) : ∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') := by { rw [nhds_prod_eq] at h, exact h.curry } lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := hf.prod_mk_nhds hg lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β} (hf : continuous_at f p.fst) (hg : continuous_at g p.snd) : continuous_at (λ p : α × β, (f p.1, g p.2)) p := (hf.comp continuous_at_fst).prod (hg.comp continuous_at_snd) lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β} (hf : continuous_at f x) (hg : continuous_at g y) : continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) := have hf : continuous_at f (x, y).fst, from hf, have hg : continuous_at g (x, y).snd, from hg, hf.prod_map hg lemma prod_generate_from_generate_from_eq {α β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open.prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ hs.prod ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp_rw [le_principal_iff, prod.forall, ((nhds_basis_opens _).prod_nhds (nhds_basis_opens _)).mem_iff, prod.exists, exists_prop], simp only [and_assoc, and.left_comm] end lemma continuous_uncurry_of_discrete_topology_left [discrete_topology α] {f : α → β → γ} (h : ∀ a, continuous (f a)) : continuous (function.uncurry f) := continuous_iff_continuous_at.2 $ λ ⟨a, b⟩, by simp only [continuous_at, nhds_prod_eq, nhds_discrete α, pure_prod, tendsto_map'_iff, (∘), function.uncurry, (h a).tendsto] /-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood that is a subset of `s`. -/ lemma exists_nhds_square {s : set (α × α)} {x : α} (hx : s ∈ 𝓝 (x, x)) : ∃U, is_open U ∧ x ∈ U ∧ set.prod U U ⊆ s := by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and.assoc, and.left_comm] using hx /-- `prod.fst` maps neighborhood of `x : α × β` within the section `prod.snd ⁻¹' {x.2}` to `𝓝 x.1`. -/ lemma map_fst_nhds_within (x : α × β) : map prod.fst (𝓝[prod.snd ⁻¹' {x.2}] x) = 𝓝 x.1 := begin refine le_antisymm (continuous_at_fst.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_sets_of_superset hu (λ z hz, H _ hz _ (mem_of_nhds hv) rfl) end @[simp] lemma map_fst_nhds (x : α × β) : map prod.fst (𝓝 x) = 𝓝 x.1 := le_antisymm continuous_at_fst $ (map_fst_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_fst_nhds x).ge /-- `prod.snd` maps neighborhood of `x : α × β` within the section `prod.fst ⁻¹' {x.1}` to `𝓝 x.2`. -/ lemma map_snd_nhds_within (x : α × β) : map prod.snd (𝓝[prod.fst ⁻¹' {x.1}] x) = 𝓝 x.2 := begin refine le_antisymm (continuous_at_snd.mono_left inf_le_left) (λ s hs, _), rcases x with ⟨x, y⟩, rw [mem_map, nhds_within, mem_inf_principal, mem_nhds_prod_iff] at hs, rcases hs with ⟨u, hu, v, hv, H⟩, simp only [prod_subset_iff, mem_singleton_iff, mem_set_of_eq, mem_preimage] at H, exact mem_sets_of_superset hv (λ z hz, H _ (mem_of_nhds hu) _ hz rfl) end @[simp] lemma map_snd_nhds (x : α × β) : map prod.snd (𝓝 x) = 𝓝 x.2 := le_antisymm continuous_at_snd $ (map_snd_nhds_within x).symm.trans_le (map_mono inf_le_left) /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := is_open_map_iff_nhds_le.2 $ λ x, (map_snd_nhds x).ge /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin cases (set.prod s t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h, split, { assume H : is_open (set.prod s t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false] at H, exact H.1.prod H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have (𝓝 a ×ᶠ 𝓝 b) ⊓ 𝓟 (set.prod s t) = (𝓝 a ⊓ 𝓟 s) ×ᶠ (𝓝 b ⊓ 𝓟 t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot lemma interior_prod_eq (s : set α) (t : set β) : interior (s.prod t) = (interior s).prod (interior t) := set.ext $ λ ⟨a, b⟩, by simp only [mem_interior_iff_mem_nhds, mem_prod, prod_mem_nhds_iff] lemma frontier_prod_eq (s : set α) (t : set β) : frontier (s.prod t) = (closure s).prod (frontier t) ∪ (frontier s).prod (closure t) := by simp only [frontier, closure_prod_eq, interior_prod_eq, prod_diff_prod] @[simp] lemma frontier_prod_univ_eq (s : set α) : frontier (s.prod (univ : set β)) = (frontier s).prod univ := by simp [frontier_prod_eq] @[simp] lemma frontier_univ_prod_eq (s : set β) : frontier ((univ : set α).prod s) = (univ : set α).prod (frontier s) := by simp [frontier_prod_eq] lemma map_mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from map_mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed.prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq] /-- The product of two dense sets is a dense set. -/ lemma dense.prod {s : set α} {t : set β} (hs : dense s) (ht : dense t) : dense (s.prod t) := λ x, by { rw closure_prod_eq, exact ⟨hs x.1, ht x.2⟩ } /-- If `f` and `g` are maps with dense range, then `prod.map f g` has dense range. -/ lemma dense_range.prod_map {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (prod.map f g) := by simpa only [dense_range, prod_range_range_eq] using hf.prod hg lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum open sum variables [topological_space α] [topological_space β] [topological_space γ] @[continuity] lemma continuous_inl : continuous (@inl α β) := continuous_sup_rng_left continuous_coinduced_rng @[continuity] lemma continuous_inr : continuous (@inr α β) := continuous_sup_rng_right continuous_coinduced_rng @[continuity] lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := begin apply continuous_sup_dom; rw continuous_def at hf hg ⊢; assumption end lemma is_open_sum_iff {s : set (α ⊕ β)} : is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) := iff.rfl lemma is_open_map_sum {f : α ⊕ β → γ} (h₁ : is_open_map (λ a, f (inl a))) (h₂ : is_open_map (λ b, f (inr b))) : is_open_map f := begin intros u hu, rw is_open_sum_iff at hu, cases hu with hu₁ hu₂, have : u = inl '' (inl ⁻¹' u) ∪ inr '' (inr ⁻¹' u), { ext (_|_); simp }, rw [this, set.image_union, set.image_image, set.image_image], exact is_open_union (h₁ _ hu₁) (h₂ _ hu₂) end lemma embedding_inl : embedding (@inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_left }, { intros u hu, existsi (inl '' u), change (is_open (inl ⁻¹' (@inl α β '' u)) ∧ is_open (inr ⁻¹' (@inl α β '' u))) ∧ inl ⁻¹' (inl '' u) = u, have : inl ⁻¹' (@inl α β '' u) = u := preimage_image_eq u (λ _ _, inl.inj_iff.mp), rw this, have : inr ⁻¹' (@inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, inl.inj_iff.mp } lemma embedding_inr : embedding (@inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_right }, { intros u hu, existsi (inr '' u), change (is_open (inl ⁻¹' (@inr α β '' u)) ∧ is_open (inr ⁻¹' (@inr α β '' u))) ∧ inr ⁻¹' (inr '' u) = u, have : inl ⁻¹' (@inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, inr_ne_inl h), rw this, have : inr ⁻¹' (@inr α β '' u) = u := preimage_image_eq u (λ _ _, inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, inr.inj_iff.mp } lemma is_open_range_inl : is_open (range (inl : α → α ⊕ β)) := is_open_sum_iff.2 $ by simp lemma is_open_range_inr : is_open (range (inr : β → α ⊕ β)) := is_open_sum_iff.2 $ by simp lemma open_embedding_inl : open_embedding (inl : α → α ⊕ β) := { open_range := is_open_range_inl, .. embedding_inl } lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) := { open_range := is_open_range_inr, .. embedding_inr } end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_subtype_coe : embedding (coe : subtype p → α) := ⟨⟨rfl⟩, subtype.coe_injective⟩ lemma closed_embedding_subtype_coe (h : is_closed {a | p a}) : closed_embedding (coe : subtype p → α) := ⟨embedding_subtype_coe, by rwa [subtype.range_coe_subtype]⟩ @[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_coe : continuous (coe : subtype p → α) := continuous_subtype_val lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) : open_embedding (coe : s → α) := { induced := rfl, inj := subtype.coe_injective, open_range := (subtype.range_coe : range coe = s).symm ▸ hs } lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) : is_open_map (coe : s → α) := hs.open_embedding_subtype_coe.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (s.restrict f) := hf.comp hs.is_open_map_subtype_coe lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) : closed_embedding (coe : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.coe_injective, closed_range := (subtype.range_coe : range coe = s).symm ▸ hs } @[continuity] lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_coe lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} : continuous_at (coe : subtype p → α) a := continuous_iff_continuous_at.mp continuous_subtype_coe _ lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_of_mem $ by simpa only [subtype.coe_mk, subtype.range_coe] using h lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α)) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map coe (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from assume i, (closed_embedding_subtype_coe (h_is_closed _)).is_closed_map _ (hs.preimage (f_cont i)), have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), from locally_finite.is_closed_Union (h_lf.subset $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) := closure_induced end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ @[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng @[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} @[continuity] lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i @[continuity] lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom lemma continuous_at_apply [∀i, topological_space (π i)] (i : ι) (x : Π i, π i) : continuous_at (λ p : Π i, π i, p i) x := (continuous_apply i).continuous_at lemma filter.tendsto.apply [∀i, topological_space (π i)] {l : filter α} {f : α → Π i, π i} {x : Π i, π i} (h : tendsto f l (𝓝 x)) (i : ι) : tendsto (λ a, f a i) l (𝓝 $ x i) := (continuous_at_apply i _).tendsto.comp h lemma continuous_pi_iff [topological_space α] [∀ i, topological_space (π i)] {f : α → Π i, π i} : continuous f ↔ ∀ i, continuous (λ y, f y i) := iff.intro (λ h i, (continuous_apply i).comp h) continuous_pi lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : 𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) := calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced] lemma tendsto_pi [t : ∀i, topological_space (π i)] {f : α → Πi, π i} {g : Πi, π i} {u : filter α} : tendsto f u (𝓝 g) ↔ ∀ x, tendsto (λ i, f i x) u (𝓝 (g x)) := by simp [nhds_pi, filter.tendsto_comap_iff] lemma continuous_at_pi [∀ i, topological_space (π i)] [topological_space α] {f : α → Π i, π i} {x : α} : continuous_at f x ↔ ∀ i, continuous_at (λ y, f y i) x := tendsto_pi lemma filter.tendsto.update [∀i, topological_space (π i)] [decidable_eq ι] {l : filter α} {f : α → Π i, π i} {x : Π i, π i} (hf : tendsto f l (𝓝 x)) (i : ι) {g : α → π i} {xi : π i} (hg : tendsto g l (𝓝 xi)) : tendsto (λ a, function.update (f a) i (g a)) l (𝓝 $ function.update x i xi) := tendsto_pi.2 $ λ j, by { rcases em (j = i) with rfl|hj; simp [*, hf.apply] } lemma continuous_at.update [∀i, topological_space (π i)] [topological_space α] [decidable_eq ι] {f : α → Π i, π i} {a : α} (hf : continuous_at f a) (i : ι) {g : α → π i} (hg : continuous_at g a) : continuous_at (λ a, function.update (f a) i (g a)) a := hf.update i hg lemma continuous.update [∀i, topological_space (π i)] [topological_space α] [decidable_eq ι] {f : α → Π i, π i} (hf : continuous f) (i : ι) {g : α → π i} (hg : continuous g) : continuous (λ a, function.update (f a) i (g a)) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.update i hg.continuous_at /-- `function.update f i x` is continuous in `(f, x)`. -/ @[continuity] lemma continuous_update [∀i, topological_space (π i)] [decidable_eq ι] (i : ι) : continuous (λ f : (Π j, π j) × π i, function.update f.1 i f.2) := continuous_fst.update i continuous_snd lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, (hs _ ha).preimage (continuous_apply _)) lemma is_closed_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hs : ∀a∈i, is_closed (s a)) : is_closed (pi i s) := by rw [pi_def]; exact (is_closed_Inter $ λ a, is_closed_Inter $ λ ha, (hs _ ha).preimage (continuous_apply _)) lemma set_pi_mem_nhds [Π a, topological_space (π a)] {i : set ι} {s : Π a, set (π a)} {x : Π a, π a} (hi : finite i) (hs : ∀ a ∈ i, s a ∈ 𝓝 (x a)) : pi i s ∈ 𝓝 x := by { rw [pi_def, bInter_mem_sets hi], exact λ a ha, (continuous_apply a).continuous_at (hs a ha) } lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } } end variables [fintype ι] [∀ i, topological_space (π i)] [∀ i, discrete_topology (π i)] /-- A finite product of discrete spaces is discrete. -/ instance Pi.discrete_topology : discrete_topology (Π i, π i) := singletons_open_iff_discrete.mp (λ x, begin rw show {x} = ⋂ i, {y : Π i, π i | y i = x i}, { ext, simp only [function.funext_iff, set.mem_singleton_iff, set.mem_Inter, set.mem_set_of_eq] }, exact is_open_Inter (λ i, (continuous_apply i).is_open_preimage {x i} (is_open_discrete {x i})) end) end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] @[continuity] lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := by simp [← is_open_compl_iff, is_open_sigma_iff] lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ sigma_mk_injective }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ } lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ sigma_mk_injective }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ @[continuity] lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) @[continuity] lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s), { rw Union_image_preimage_sigma_mk_eq_self }, rw this, rw [image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, function.injective_id.sigma_map (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma section ulift @[continuity] lemma continuous_ulift_down [topological_space α] : continuous (ulift.down : ulift.{v u} α → α) := continuous_induced_dom @[continuity] lemma continuous_ulift_up [topological_space α] : continuous (ulift.up : α → ulift.{v u} α) := continuous_induced_rng continuous_id end ulift lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : maps_to f s (closure t)) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure t : closure_minimal h.image_subset is_closed_closure lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
458dd7c6ed9df4cbd4ad1330bdaa4ce9fc85306b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/pfunctor/univariate/basic.lean
ba63040d31e2b59c630e2caf42d1178bd0981c0a
[ "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,293
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.W.basic /-! # Polynomial functors This file defines polynomial functors and the W-type construction as a polynomial functor. (For the M-type construction, see pfunctor/M.lean.) -/ universe u /-- A polynomial functor `P` is given by a type `A` and a family `B` of types over `A`. `P` maps any type `α` to a new type `P.obj α`, which is defined as the sigma type `Σ x, P.B x → α`. An element of `P.obj α` is a pair `⟨a, f⟩`, where `a` is an element of a type `A` and `f : B a → α`. Think of `a` as the shape of the object and `f` as an index to the relevant elements of `α`. -/ structure pfunctor := (A : Type u) (B : A → Type u) namespace pfunctor instance : inhabited pfunctor := ⟨⟨default, default⟩⟩ variables (P : pfunctor) {α β : Type u} /-- Applying `P` to an object of `Type` -/ def obj (α : Type*) := Σ x : P.A, P.B x → α /-- Applying `P` to a morphism of `Type` -/ def map {α β : Type*} (f : α → β) : P.obj α → P.obj β := λ ⟨a, g⟩, ⟨a, f ∘ g⟩ instance obj.inhabited [inhabited P.A] [inhabited α] : inhabited (P.obj α) := ⟨⟨default, default⟩⟩ instance : functor P.obj := {map := @map P} protected theorem map_eq {α β : Type*} (f : α → β) (a : P.A) (g : P.B a → α) : @functor.map P.obj _ _ _ f ⟨a, g⟩ = ⟨a, f ∘ g⟩ := rfl protected theorem id_map {α : Type*} : ∀ x : P.obj α, id <$> x = id x := λ ⟨a, b⟩, rfl protected theorem comp_map {α β γ : Type*} (f : α → β) (g : β → γ) : ∀ x : P.obj α, (g ∘ f) <$> x = g <$> (f <$> x) := λ ⟨a, b⟩, rfl instance : is_lawful_functor P.obj := {id_map := @pfunctor.id_map P, comp_map := @pfunctor.comp_map P} /-- re-export existing definition of W-types and adapt it to a packaged definition of polynomial functor -/ def W := _root_.W_type P.B /- inhabitants of W types is awkward to encode as an instance assumption because there needs to be a value `a : P.A` such that `P.B a` is empty to yield a finite tree -/ attribute [nolint has_nonempty_instance] W variables {P} /-- root element of a W tree -/ def W.head : W P → P.A | ⟨a, f⟩ := a /-- children of the root of a W tree -/ def W.children : Π x : W P, P.B (W.head x) → W P | ⟨a, f⟩ := f /-- destructor for W-types -/ def W.dest : W P → P.obj (W P) | ⟨a, f⟩ := ⟨a, f⟩ /-- constructor for W-types -/ def W.mk : P.obj (W P) → W P | ⟨a, f⟩ := ⟨a, f⟩ @[simp] theorem W.dest_mk (p : P.obj (W P)) : W.dest (W.mk p) = p := by cases p; reflexivity @[simp] theorem W.mk_dest (p : W P) : W.mk (W.dest p) = p := by cases p; reflexivity variables (P) /-- `Idx` identifies a location inside the application of a pfunctor. For `F : pfunctor`, `x : F.obj α` and `i : F.Idx`, `i` can designate one part of `x` or is invalid, if `i.1 ≠ x.1` -/ def Idx := Σ x : P.A, P.B x instance Idx.inhabited [inhabited P.A] [inhabited (P.B default)] : inhabited P.Idx := ⟨⟨default, default⟩⟩ variables {P} /-- `x.iget i` takes the component of `x` designated by `i` if any is or returns a default value -/ def obj.iget [decidable_eq P.A] {α} [inhabited α] (x : P.obj α) (i : P.Idx) : α := if h : i.1 = x.1 then x.2 (cast (congr_arg _ h) i.2) else default @[simp] lemma fst_map {α β : Type u} (x : P.obj α) (f : α → β) : (f <$> x).1 = x.1 := by { cases x; refl } @[simp] lemma iget_map [decidable_eq P.A] {α β : Type u} [inhabited α] [inhabited β] (x : P.obj α) (f : α → β) (i : P.Idx) (h : i.1 = x.1) : (f <$> x).iget i = f (x.iget i) := by { simp only [obj.iget, fst_map, *, dif_pos, eq_self_iff_true], cases x, refl } end pfunctor /- Composition of polynomial functors. -/ namespace pfunctor /-- functor composition for polynomial functors -/ def comp (P₂ P₁ : pfunctor.{u}) : pfunctor.{u} := ⟨ Σ a₂ : P₂.1, P₂.2 a₂ → P₁.1, λ a₂a₁, Σ u : P₂.2 a₂a₁.1, P₁.2 (a₂a₁.2 u) ⟩ /-- constructor for composition -/ def comp.mk (P₂ P₁ : pfunctor.{u}) {α : Type} (x : P₂.obj (P₁.obj α)) : (comp P₂ P₁).obj α := ⟨ ⟨ x.1, sigma.fst ∘ x.2 ⟩, λ a₂a₁, (x.2 a₂a₁.1).2 a₂a₁.2 ⟩ /-- destructor for composition -/ def comp.get (P₂ P₁ : pfunctor.{u}) {α : Type} (x : (comp P₂ P₁).obj α) : P₂.obj (P₁.obj α) := ⟨ x.1.1, λ a₂, ⟨x.1.2 a₂, λ a₁, x.2 ⟨a₂,a₁⟩ ⟩ ⟩ end pfunctor /- Lifting predicates and relations. -/ namespace pfunctor variables {P : pfunctor.{u}} open functor theorem liftp_iff {α : Type u} (p : α → Prop) (x : P.obj α) : liftp p x ↔ ∃ a f, x = ⟨a, f⟩ ∧ ∀ i, p (f i) := begin split, { rintros ⟨y, hy⟩, cases h : y with a f, refine ⟨a, λ i, (f i).val, _, λ i, (f i).property⟩, rw [←hy, h, pfunctor.map_eq] }, rintros ⟨a, f, xeq, pf⟩, use ⟨a, λ i, ⟨f i, pf i⟩⟩, rw [xeq], reflexivity end theorem liftp_iff' {α : Type u} (p : α → Prop) (a : P.A) (f : P.B a → α) : @liftp.{u} P.obj _ α p ⟨a,f⟩ ↔ ∀ i, p (f i) := begin simp only [liftp_iff, sigma.mk.inj_iff]; split; intro, { casesm* [Exists _, _ ∧ _], subst_vars, assumption }, repeat { constructor <|> assumption } end theorem liftr_iff {α : Type u} (r : α → α → Prop) (x y : P.obj α) : liftr r x y ↔ ∃ a f₀ f₁, x = ⟨a, f₀⟩ ∧ y = ⟨a, f₁⟩ ∧ ∀ i, r (f₀ i) (f₁ i) := begin split, { rintros ⟨u, xeq, yeq⟩, cases h : u with a f, use [a, λ i, (f i).val.fst, λ i, (f i).val.snd], split, { rw [←xeq, h], refl }, split, { rw [←yeq, h], refl }, intro i, exact (f i).property }, rintros ⟨a, f₀, f₁, xeq, yeq, h⟩, use ⟨a, λ i, ⟨(f₀ i, f₁ i), h i⟩⟩, split, { rw [xeq], refl }, rw [yeq], refl end open set theorem supp_eq {α : Type u} (a : P.A) (f : P.B a → α) : @supp.{u} P.obj _ α (⟨a,f⟩ : P.obj α) = f '' univ := begin ext, simp only [supp, image_univ, mem_range, mem_set_of_eq], split; intro h, { apply @h (λ x, ∃ (y : P.B a), f y = x), rw liftp_iff', intro, refine ⟨_,rfl⟩ }, { simp only [liftp_iff'], cases h, subst x, tauto } end end pfunctor
89ac002ca7ff34f55cca200c43743f2c6deaba96
737dc4b96c97368cb66b925eeea3ab633ec3d702
/tests/lean/run/654.lean
78385ab443d6fe0c231623d21e2191000c1bc54f
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,459
lean
inductive Foo where | a | b | c def f : Foo → Nat | Foo.a => 10 | Foo.b => 20 | Foo.c => 35 inductive CXCursorKind where | CXCursor_UnexposedDecl | CXCursor_StructDecl | CXCursor_UnionDecl | CXCursor_ClassDecl | CXCursor_EnumDecl | CXCursor_FieldDecl | CXCursor_EnumConstantDecl | CXCursor_FunctionDecl | CXCursor_VarDecl | CXCursor_ParmDecl | CXCursor_ObjCInterfaceDecl | CXCursor_ObjCCategoryDecl | CXCursor_ObjCProtocolDecl | CXCursor_ObjCPropertyDecl | CXCursor_ObjCIvarDecl | CXCursor_ObjCInstanceMethodDecl | CXCursor_ObjCClassMethodDecl | CXCursor_ObjCImplementationDecl | CXCursor_ObjCCategoryImplDecl | CXCursor_TypedefDecl | CXCursor_CXXMethod | CXCursor_Namespace | CXCursor_LinkageSpec | CXCursor_Constructor | CXCursor_Destructor | CXCursor_ConversionFunction | CXCursor_TemplateTypeParameter | CXCursor_NonTypeTemplateParameter | CXCursor_TemplateTemplateParameter | CXCursor_FunctionTemplate | CXCursor_ClassTemplate | CXCursor_ClassTemplatePartialSpecialization | CXCursor_NamespaceAlias | CXCursor_UsingDirective | CXCursor_UsingDeclaration | CXCursor_TypeAliasDecl | CXCursor_ObjCSynthesizeDecl | CXCursor_ObjCDynamicDecl | CXCursor_CXXAccessSpecifier | CXCursor_FirstDecl | CXCursor_LastDecl | CXCursor_FirstRef | CXCursor_ObjCSuperClassRef | CXCursor_ObjCProtocolRef | CXCursor_ObjCClassRef | CXCursor_TypeRef | CXCursor_CXXBaseSpecifier | CXCursor_TemplateRef | CXCursor_NamespaceRef | CXCursor_MemberRef | CXCursor_LabelRef | CXCursor_OverloadedDeclRef | CXCursor_VariableRef | CXCursor_LastRef | CXCursor_FirstInvalid | CXCursor_InvalidFile | CXCursor_NoDeclFound | CXCursor_NotImplemented | CXCursor_InvalidCode | CXCursor_LastInvalid | CXCursor_FirstExpr | CXCursor_UnexposedExpr | CXCursor_DeclRefExpr | CXCursor_MemberRefExpr | CXCursor_CallExpr | CXCursor_ObjCMessageExpr | CXCursor_BlockExpr | CXCursor_IntegerLiteral | CXCursor_FloatingLiteral | CXCursor_ImaginaryLiteral | CXCursor_StringLiteral | CXCursor_CharacterLiteral | CXCursor_ParenExpr | CXCursor_UnaryOperator | CXCursor_ArraySubscriptExpr | CXCursor_BinaryOperator | CXCursor_CompoundAssignOperator | CXCursor_ConditionalOperator | CXCursor_CStyleCastExpr | CXCursor_CompoundLiteralExpr | CXCursor_InitListExpr | CXCursor_AddrLabelExpr | CXCursor_StmtExpr | CXCursor_GenericSelectionExpr | CXCursor_GNUNullExpr | CXCursor_CXXStaticCastExpr | CXCursor_CXXDynamicCastExpr | CXCursor_CXXReinterpretCastExpr | CXCursor_CXXConstCastExpr | CXCursor_CXXFunctionalCastExpr | CXCursor_CXXTypeidExpr | CXCursor_CXXBoolLiteralExpr | CXCursor_CXXNullPtrLiteralExpr | CXCursor_CXXThisExpr | CXCursor_CXXThrowExpr | CXCursor_CXXNewExpr | CXCursor_CXXDeleteExpr | CXCursor_UnaryExpr | CXCursor_ObjCStringLiteral | CXCursor_ObjCEncodeExpr | CXCursor_ObjCSelectorExpr | CXCursor_ObjCProtocolExpr | CXCursor_ObjCBridgedCastExpr | CXCursor_PackExpansionExpr | CXCursor_SizeOfPackExpr | CXCursor_LambdaExpr | CXCursor_ObjCBoolLiteralExpr | CXCursor_ObjCSelfExpr | CXCursor_OMPArraySectionExpr | CXCursor_ObjCAvailabilityCheckExpr | CXCursor_FixedPointLiteral | CXCursor_OMPArrayShapingExpr | CXCursor_OMPIteratorExpr | CXCursor_CXXAddrspaceCastExpr | CXCursor_LastExpr | CXCursor_FirstStmt | CXCursor_UnexposedStmt | CXCursor_LabelStmt | CXCursor_CompoundStmt | CXCursor_CaseStmt | CXCursor_DefaultStmt | CXCursor_IfStmt | CXCursor_SwitchStmt | CXCursor_WhileStmt | CXCursor_DoStmt | CXCursor_ForStmt | CXCursor_GotoStmt | CXCursor_IndirectGotoStmt | CXCursor_ContinueStmt | CXCursor_BreakStmt | CXCursor_ReturnStmt | CXCursor_GCCAsmStmt | CXCursor_AsmStmt | CXCursor_ObjCAtTryStmt | CXCursor_ObjCAtCatchStmt | CXCursor_ObjCAtFinallyStmt | CXCursor_ObjCAtThrowStmt | CXCursor_ObjCAtSynchronizedStmt | CXCursor_ObjCAutoreleasePoolStmt | CXCursor_ObjCForCollectionStmt | CXCursor_CXXCatchStmt | CXCursor_CXXTryStmt | CXCursor_CXXForRangeStmt | CXCursor_SEHTryStmt | CXCursor_SEHExceptStmt | CXCursor_SEHFinallyStmt | CXCursor_MSAsmStmt | CXCursor_NullStmt | CXCursor_DeclStmt | CXCursor_OMPParallelDirective | CXCursor_OMPSimdDirective | CXCursor_OMPForDirective | CXCursor_OMPSectionsDirective | CXCursor_OMPSectionDirective | CXCursor_OMPSingleDirective | CXCursor_OMPParallelForDirective | CXCursor_OMPParallelSectionsDirective | CXCursor_OMPTaskDirective | CXCursor_OMPMasterDirective | CXCursor_OMPCriticalDirective | CXCursor_OMPTaskyieldDirective | CXCursor_OMPBarrierDirective | CXCursor_OMPTaskwaitDirective | CXCursor_OMPFlushDirective | CXCursor_SEHLeaveStmt | CXCursor_OMPOrderedDirective | CXCursor_OMPAtomicDirective | CXCursor_OMPForSimdDirective | CXCursor_OMPParallelForSimdDirective | CXCursor_OMPTargetDirective | CXCursor_OMPTeamsDirective | CXCursor_OMPTaskgroupDirective | CXCursor_OMPCancellationPointDirective | CXCursor_OMPCancelDirective | CXCursor_OMPTargetDataDirective | CXCursor_OMPTaskLoopDirective | CXCursor_OMPTaskLoopSimdDirective | CXCursor_OMPDistributeDirective | CXCursor_OMPTargetEnterDataDirective | CXCursor_OMPTargetExitDataDirective | CXCursor_OMPTargetParallelDirective | CXCursor_OMPTargetParallelForDirective | CXCursor_OMPTargetUpdateDirective | CXCursor_OMPDistributeParallelForDirective | CXCursor_OMPDistributeParallelForSimdDirective | CXCursor_OMPDistributeSimdDirective | CXCursor_OMPTargetParallelForSimdDirective | CXCursor_OMPTargetSimdDirective | CXCursor_OMPTeamsDistributeDirective | CXCursor_OMPTeamsDistributeSimdDirective | CXCursor_OMPTeamsDistributeParallelForSimdDirective | CXCursor_OMPTeamsDistributeParallelForDirective | CXCursor_OMPTargetTeamsDirective | CXCursor_OMPTargetTeamsDistributeDirective | CXCursor_OMPTargetTeamsDistributeParallelForDirective | CXCursor_OMPTargetTeamsDistributeParallelForSimdDirective | CXCursor_OMPTargetTeamsDistributeSimdDirective | CXCursor_BuiltinBitCastExpr | CXCursor_OMPMasterTaskLoopDirective | CXCursor_OMPParallelMasterTaskLoopDirective | CXCursor_OMPMasterTaskLoopSimdDirective | CXCursor_OMPParallelMasterTaskLoopSimdDirective | CXCursor_OMPParallelMasterDirective | CXCursor_OMPDepobjDirective | CXCursor_OMPScanDirective | CXCursor_OMPTileDirective | CXCursor_OMPCanonicalLoop | CXCursor_OMPInteropDirective | CXCursor_OMPDispatchDirective | CXCursor_OMPMaskedDirective | CXCursor_OMPUnrollDirective | CXCursor_LastStmt | CXCursor_TranslationUnit | CXCursor_FirstAttr | CXCursor_UnexposedAttr | CXCursor_IBActionAttr | CXCursor_IBOutletAttr | CXCursor_IBOutletCollectionAttr | CXCursor_CXXFinalAttr | CXCursor_CXXOverrideAttr | CXCursor_AnnotateAttr | CXCursor_AsmLabelAttr | CXCursor_PackedAttr | CXCursor_PureAttr | CXCursor_ConstAttr | CXCursor_NoDuplicateAttr | CXCursor_CUDAConstantAttr | CXCursor_CUDADeviceAttr | CXCursor_CUDAGlobalAttr | CXCursor_CUDAHostAttr | CXCursor_CUDASharedAttr | CXCursor_VisibilityAttr | CXCursor_DLLExport | CXCursor_DLLImport | CXCursor_NSReturnsRetained | CXCursor_NSReturnsNotRetained | CXCursor_NSReturnsAutoreleased | CXCursor_NSConsumesSelf | CXCursor_NSConsumed | CXCursor_ObjCException | CXCursor_ObjCNSObject | CXCursor_ObjCIndependentClass | CXCursor_ObjCPreciseLifetime | CXCursor_ObjCReturnsInnerPointer | CXCursor_ObjCRequiresSuper | CXCursor_ObjCRootClass | CXCursor_ObjCSubclassingRestricted | CXCursor_ObjCExplicitProtocolImpl | CXCursor_ObjCDesignatedInitializer | CXCursor_ObjCRuntimeVisible | CXCursor_ObjCBoxable | CXCursor_FlagEnum | CXCursor_ConvergentAttr | CXCursor_WarnUnusedAttr | CXCursor_WarnUnusedResultAttr | CXCursor_AlignedAttr | CXCursor_LastAttr | CXCursor_PreprocessingDirective | CXCursor_MacroDefinition | CXCursor_MacroExpansion | CXCursor_MacroInstantiation | CXCursor_InclusionDirective | CXCursor_FirstPreprocessing | CXCursor_LastPreprocessing | CXCursor_ModuleImportDecl | CXCursor_TypeAliasTemplateDecl | CXCursor_StaticAssert | CXCursor_FriendDecl | CXCursor_FirstExtraDecl | CXCursor_LastExtraDecl | CXCursor_OverloadCandidate open CXCursorKind example (h : CXCursor_CUDAGlobalAttr = CXCursor_CUDAHostAttr) : False := by contradiction
a5a6636c7a97cf37bc638d1486fe3021a8ef037f
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/algebra/field_power.lean
a6752b600d05bc0119a58ecf01bcff850493c900
[ "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
9,006
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 algebra.group_with_zero.power import tactic.linarith /-! # Integer power operation on fields and division rings This file collects basic facts about the operation of raising an element of a `division_ring` to an integer power. More specialised results are provided in the case of a linearly ordered field. -/ universe u @[simp] lemma ring_hom.map_fpow {K L : Type*} [division_ring K] [division_ring L] (f : K →+* L) : ∀ (a : K) (n : ℤ), f (a ^ n) = f a ^ n := f.to_monoid_with_zero_hom.map_fpow @[simp] lemma fpow_bit0_neg {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit0 n) = x ^ bit0 n := by rw [fpow_bit0', fpow_bit0', neg_mul_neg] lemma fpow_even_neg {K : Type*} [division_ring K] (a : K) {n : ℤ} (h : even n) : (-a) ^ n = a ^ n := begin obtain ⟨k, rfl⟩ := h, rw [←bit0_eq_two_mul, fpow_bit0_neg], end @[simp] lemma fpow_bit1_neg {K : Type*} [division_ring K] (x : K) (n : ℤ) : (-x) ^ (bit1 n) = - x ^ bit1 n := by rw [fpow_bit1', fpow_bit1', neg_mul_neg, neg_mul_eq_mul_neg] section ordered_field_power open int variables {K : Type u} [linear_ordered_field K] {a : K} {n : ℤ} lemma fpow_eq_zero_iff (hn : 0 < n) : a ^ n = 0 ↔ a = 0 := begin refine ⟨fpow_eq_zero, _⟩, rintros rfl, exact zero_fpow _ hn.ne' end lemma fpow_nonneg {a : K} (ha : 0 ≤ a) : ∀ (z : ℤ), 0 ≤ a ^ z | (n : ℕ) := by { rw gpow_coe_nat, exact pow_nonneg ha _ } | -[1+n] := by { rw gpow_neg_succ_of_nat, exact inv_nonneg.2 (pow_nonneg ha _) } lemma fpow_pos_of_pos {a : K} (ha : 0 < a) : ∀ (z : ℤ), 0 < a ^ z | (n : ℕ) := by { rw gpow_coe_nat, exact pow_pos ha _ } | -[1+n] := by { rw gpow_neg_succ_of_nat, exact inv_pos.2 (pow_pos ha _) } lemma fpow_le_of_le {x : K} (hx : 1 ≤ x) {a b : ℤ} (h : a ≤ b) : x ^ a ≤ x ^ b := begin induction a with a a; induction b with b b, { simp only [of_nat_eq_coe, gpow_coe_nat], apply pow_le_pow hx, apply le_of_coe_nat_le_coe_nat h }, { apply absurd h, apply not_le_of_gt, exact lt_of_lt_of_le (neg_succ_lt_zero _) (of_nat_nonneg _) }, { simp only [gpow_neg_succ_of_nat, one_div, of_nat_eq_coe, gpow_coe_nat], apply le_trans (inv_le_one _); apply one_le_pow_of_one_le hx }, { simp only [gpow_neg_succ_of_nat], apply (inv_le_inv _ _).2, { apply pow_le_pow hx, have : -(↑(a+1) : ℤ) ≤ -(↑(b+1) : ℤ), from h, have h' := le_of_neg_le_neg this, apply le_of_coe_nat_le_coe_nat h' }, repeat { apply pow_pos (lt_of_lt_of_le zero_lt_one hx) } } end lemma pow_le_max_of_min_le {x : K} (hx : 1 ≤ x) {a b c : ℤ} (h : min a b ≤ c) : x ^ (-c) ≤ max (x ^ (-a)) (x ^ (-b)) := begin wlog hle : a ≤ b, have hnle : -b ≤ -a, from neg_le_neg hle, have hfle : x ^ (-b) ≤ x ^ (-a), from fpow_le_of_le hx hnle, have : x ^ (-c) ≤ x ^ (-a), { apply fpow_le_of_le hx, simpa only [min_eq_left hle, neg_le_neg_iff] using h }, simpa only [max_eq_left hfle] end lemma fpow_le_one_of_nonpos {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : z ≤ 0) : p ^ z ≤ 1 := calc p ^ z ≤ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp lemma one_le_fpow_of_nonneg {p : K} (hp : 1 ≤ p) {z : ℤ} (hz : 0 ≤ z) : 1 ≤ p ^ z := calc p ^ z ≥ p ^ 0 : fpow_le_of_le hp hz ... = 1 : by simp theorem fpow_bit0_nonneg (a : K) (n : ℤ) : 0 ≤ a ^ bit0 n := by { rw fpow_bit0, exact mul_self_nonneg _ } theorem fpow_two_nonneg (a : K) : 0 ≤ a ^ 2 := pow_bit0_nonneg a 1 theorem fpow_bit0_pos {a : K} (h : a ≠ 0) (n : ℤ) : 0 < a ^ bit0 n := (fpow_bit0_nonneg a n).lt_of_ne (fpow_ne_zero _ h).symm theorem fpow_two_pos_of_ne_zero (a : K) (h : a ≠ 0) : 0 < a ^ 2 := pow_bit0_pos h 1 @[simp] theorem fpow_bit1_neg_iff : a ^ bit1 n < 0 ↔ a < 0 := ⟨λ h, not_le.1 $ λ h', not_le.2 h $ fpow_nonneg h' _, λ h, by rw [bit1, fpow_add_one h.ne]; exact mul_neg_of_pos_of_neg (fpow_bit0_pos h.ne _) h⟩ @[simp] theorem fpow_bit1_nonneg_iff : 0 ≤ a ^ bit1 n ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 fpow_bit1_neg_iff @[simp] theorem fpow_bit1_nonpos_iff : a ^ bit1 n ≤ 0 ↔ a ≤ 0 := begin rw [le_iff_lt_or_eq, fpow_bit1_neg_iff], split, { rintro (h | h), { exact h.le }, { exact (fpow_eq_zero h).le } }, { intro h, rcases eq_or_lt_of_le h with rfl|h, { exact or.inr (zero_fpow _ (bit1_ne_zero n)) }, { exact or.inl h } } end @[simp] theorem fpow_bit1_pos_iff : 0 < a ^ bit1 n ↔ 0 < a := lt_iff_lt_of_le_iff_le fpow_bit1_nonpos_iff lemma fpow_even_nonneg (a : K) {n : ℤ} (hn : even n) : 0 ≤ a ^ n := begin cases le_or_lt 0 a with h h, { exact fpow_nonneg h _ }, { rw [←fpow_even_neg _ hn], replace h : 0 ≤ -a := neg_nonneg_of_nonpos (le_of_lt h), exact fpow_nonneg h _ } end theorem fpow_even_pos (ha : a ≠ 0) (hn : even n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit0_pos ha k theorem fpow_odd_nonneg (ha : 0 ≤ a) (hn : odd n) : 0 ≤ a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_nonneg_iff.mpr ha theorem fpow_odd_pos (ha : 0 < a) (hn : odd n) : 0 < a ^ n := by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_pos_iff.mpr ha theorem fpow_odd_nonpos (ha : a ≤ 0) (hn : odd n) : a ^ n ≤ 0:= by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_nonpos_iff.mpr ha theorem fpow_odd_neg (ha : a < 0) (hn : odd n) : a ^ n < 0:= by cases hn with k hk; simpa only [hk, two_mul] using fpow_bit1_neg_iff.mpr ha lemma fpow_even_abs (a : K) {p : ℤ} (hp : even p) : |a| ^ p = a ^ p := begin cases abs_choice a with h h; simp only [h, fpow_even_neg _ hp], end @[simp] lemma fpow_bit0_abs (a : K) (p : ℤ) : (|a|) ^ bit0 p = a ^ bit0 p := fpow_even_abs _ (even_bit0 _) lemma abs_fpow_even (a : K) {p : ℤ} (hp : even p) : |a ^ p| = a ^ p := begin rw [abs_eq_self], exact fpow_even_nonneg _ hp end @[simp] lemma abs_fpow_bit0 (a : K) (p : ℤ) : |a ^ bit0 p| = a ^ bit0 p := abs_fpow_even _ (even_bit0 _) end ordered_field_power lemma one_lt_pow {K} [linear_ordered_semiring K] {p : K} (hp : 1 < p) : ∀ {n : ℕ}, 1 ≤ n → 1 < p ^ n | 1 h := by simp; assumption | (k+2) h := begin rw [←one_mul (1 : K), pow_succ], apply mul_lt_mul, { assumption }, { apply le_of_lt, simpa using one_lt_pow (nat.le_add_left 1 k)}, { apply zero_lt_one }, { apply le_of_lt (lt_trans zero_lt_one hp) } end lemma one_lt_fpow {K} [linear_ordered_field K] {p : K} (hp : 1 < p) : ∀ z : ℤ, 0 < z → 1 < p ^ z | (n : ℕ) h := by { rw [gpow_coe_nat], exact one_lt_pow hp (nat.succ_le_of_lt (int.lt_of_coe_nat_lt_coe_nat h)) } | -[1+ n] h := ((int.neg_succ_not_pos _).mp h).elim section ordered variables {K : Type*} [linear_ordered_field K] lemma nat.fpow_pos_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : 0 < (p:K)^n := by { apply fpow_pos_of_pos, exact_mod_cast h } lemma nat.fpow_ne_zero_of_pos {p : ℕ} (h : 0 < p) (n:ℤ) : (p:K)^n ≠ 0 := ne_of_gt (nat.fpow_pos_of_pos h n) lemma fpow_strict_mono {x : K} (hx : 1 < x) : strict_mono (λ n:ℤ, x ^ n) := λ m n h, show x ^ m < x ^ n, begin have xpos : 0 < x := zero_lt_one.trans hx, have h₀ : x ≠ 0 := xpos.ne', have hxm : 0 < x^m := fpow_pos_of_pos xpos m, have h : 1 < x ^ (n - m) := one_lt_fpow hx _ (sub_pos_of_lt h), replace h := mul_lt_mul_of_pos_right h hxm, rwa [sub_eq_add_neg, fpow_add h₀, mul_assoc, fpow_neg_mul_fpow_self _ h₀, one_mul, mul_one] at h, end @[simp] lemma fpow_lt_iff_lt {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m < x ^ n ↔ m < n := (fpow_strict_mono hx).lt_iff_lt @[simp] lemma fpow_le_iff_le {x : K} (hx : 1 < x) {m n : ℤ} : x ^ m ≤ x ^ n ↔ m ≤ n := (fpow_strict_mono hx).le_iff_le @[simp] lemma pos_div_pow_pos {a b : K} (ha : 0 < a) (hb : 0 < b) (k : ℕ) : 0 < a/b^k := div_pos ha (pow_pos hb k) @[simp] lemma div_pow_le {a b : K} (ha : 0 < a) (hb : 1 ≤ b) (k : ℕ) : a/b^k ≤ a := (div_le_iff $ pow_pos (lt_of_lt_of_le zero_lt_one hb) k).mpr (calc a = a * 1 : (mul_one a).symm ... ≤ a*b^k : (mul_le_mul_left ha).mpr $ one_le_pow_of_one_le hb _) lemma fpow_injective {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) : function.injective ((^) x : ℤ → K) := begin intros m n h, rcases h₁.lt_or_lt with H|H, { apply (fpow_strict_mono (one_lt_inv h₀ H)).injective, show x⁻¹ ^ m = x⁻¹ ^ n, rw [← fpow_neg_one, ← fpow_mul, ← fpow_mul, mul_comm _ m, mul_comm _ n, fpow_mul, fpow_mul, h], }, { exact (fpow_strict_mono H).injective h, }, end @[simp] lemma fpow_inj {x : K} (h₀ : 0 < x) (h₁ : x ≠ 1) {m n : ℤ} : x ^ m = x ^ n ↔ m = n := (fpow_injective h₀ h₁).eq_iff end ordered section variables {K : Type*} [field K] @[simp, norm_cast] theorem rat.cast_fpow [char_zero K] (q : ℚ) (n : ℤ) : ((q ^ n : ℚ) : K) = q ^ n := (rat.cast_hom K).map_fpow q n end
0bfae89ae5ed78931dc56a20cc1f266c0f9f7333
e30ff3aabdac29f8ea40ad76887544d0f9be9018
/ircbot/login.lean
a7d6ac96ad5c66fe50cec9d8ccd6fbe46824d341
[]
no_license
forked-from-1kasper/leanbot
bdef0efa3e4d0eb75b06c1707fb4e35086bb57fa
c61c8c7fdad7b05877e0d232719ce23d2999557f
refs/heads/master
1,651,846,081,986
1,646,404,009,000
1,646,404,009,000
127,132,795
12
1
null
1,605,183,650,000
1,522,237,998,000
Lean
UTF-8
Lean
false
false
3,195
lean
import data.buffer.parser import ircbot.types ircbot.support ircbot.parsing open types support parsing parser namespace login /-- Standard messages for using on login (“USER” and “NICK”). -/ def login_messages (nick : string) (ident : string) := [ irc_text.raw_text $ sformat! "USER {ident} " ++ "https://leanprover.github.io/ 1 :A bot written in Lean", irc_text.raw_text $ sformat! "NICK {nick}" ] def relogin_func (input : irc_text) : list irc_text := match input with | irc_text.parsed_normal { object := some _, type := message.kick, args := [channel, who], text := _ } := [ join channel ] | _ := [] end /-- Autorelogin when kicked. -/ def relogin : bot_function := { name := "relogin", syntax := none, description := "Autorelogin when kicked", func := pure ∘ relogin_func } def no_login_func (nick : string) (messages : list irc_text) (input : irc_text) : list irc_text := match input with | irc_text.parsed_normal v := if v.type = message.mode ∧ v.args = [nick, "+i"] then messages else [] | _ := [] end /-- No authentication, just send some messages. -/ def no_login (info : bot_info) (messages : list irc_text) : bot_function := { name := "NickServ authentication", syntax := none, description := sformat! "Send some messages on start.", func := pure ∘ no_login_func info.nickname messages } def nickserv_login_func (info : bot_info) (messages : list irc_text) (acc : account) : irc_text → list irc_text | (irc_text.parsed_normal v) := if v.type = message.mode ∧ v.args = [info.nickname, "+i"] then (privmsg "NickServ" $ sformat! "identify {acc.login} {acc.password}") :: messages else [] | _ := [] /-- NickServ authentication. -/ def nickserv (info : bot_info) (messages : list irc_text) (acc : account) : bot_function := { name := "NickServ authentication", syntax := none, description := sformat! "Sign in to {acc.login} account using NickServ.", func := pure ∘ nickserv_login_func info messages acc } def sasl_func (info : bot_info) (messages : list irc_text) (acc : account) : irc_text → list irc_text | (irc_text.raw_text "AUTHENTICATE +") := [ irc_text.raw_text $ sformat! "AUTHENTICATE {acc.get_hash}" ] | (irc_text.raw_text v) := match run_string LoginWords v with | (sum.inr { status := "NOTICE", message := some "*** Checking Ident", server := _, args := _ }) := [ irc_text.raw_text "CAP REQ :multi-prefix sasl" ] | (sum.inr { status := "CAP", args := ["ACK"], message := some "multi-prefix sasl ", server := _ }) := [ irc_text.raw_text "AUTHENTICATE PLAIN" ] | (sum.inr { status := "903", message := some "SASL authentication successful", server := _, args := _ }) := [ irc_text.raw_text "CAP END" ] ++ login_messages info.nickname info.ident ++ messages | _ := [] end | _ := [] /-- SASL authentication -/ def sasl (info : bot_info) (messages : list irc_text) (acc : account) : bot_function := { name := "SASL authentication", syntax := none, description := sformat! "Sign in to {acc.login} account.", func := pure ∘ sasl_func info messages acc } end login
4cb4fafc098bcbb91b93f542a604d3a8c2259671
4727251e0cd73359b15b664c3170e5d754078599
/src/algebraic_geometry/projective_spectrum/structure_sheaf.lean
a863673d33f9c5eaeaa52dcb79565b4f07e00e0b
[ "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
17,735
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import algebraic_geometry.projective_spectrum.topology import topology.sheaves.local_predicate import ring_theory.graded_algebra.homogeneous_localization import algebraic_geometry.locally_ringed_space /-! # The structure sheaf on `projective_spectrum 𝒜`. In `src/algebraic_geometry/topology.lean`, we have given a topology on `projective_spectrum 𝒜`; in this file we will construct a sheaf on `projective_spectrum 𝒜`. ## Notation - `R` is a commutative semiring; - `A` is a commutative ring and an `R`-algebra; - `𝒜 : ℕ → submodule R A` is the grading of `A`; - `U` is opposite object of some open subset of `projective_spectrum.Top`. ## Main definitions and results We define the structure sheaf as the subsheaf of all dependent function `f : Π x : U, homogeneous_localization 𝒜 x` such that `f` is locally expressible as ratio of two elements of the *same grading*, i.e. `∀ y ∈ U, ∃ (V ⊆ U) (i : ℕ) (a b ∈ 𝒜 i), ∀ z ∈ V, f z = a / b`. * `algebraic_geometry.projective_spectrum.structure_sheaf.is_locally_fraction`: the predicate that a dependent function is locally expressible as a ratio of two elements of the same grading. * `algebraic_geometry.projective_spectrum.structure_sheaf.sections_subring`: the dependent functions satisfying the above local property forms a subring of all dependent functions `Π x : U, homogeneous_localization 𝒜 x`. * `algebraic_geometry.Proj.structure_sheaf`: the sheaf with `U ↦ sections_subring U` and natural restriction map. Then we establish that `Proj 𝒜` is a `LocallyRingedSpace`: * `algebraic_geometry.Proj.stalk_iso'`: for any `x : projective_spectrum 𝒜`, the stalk of `Proj.structure_sheaf` at `x` is isomorphic to `homogeneous_localization 𝒜 x`. * `algebraic_geometry.Proj.to_LocallyRingedSpace`: `Proj` as a locally ringed space. ## References * [Robin Hartshorne, *Algebraic Geometry*][Har77] -/ noncomputable theory namespace algebraic_geometry open_locale direct_sum big_operators pointwise open direct_sum set_like localization Top topological_space category_theory opposite variables {R A: Type*} variables [comm_ring R] [comm_ring A] [algebra R A] variables (𝒜 : ℕ → submodule R A) [graded_algebra 𝒜] local notation `at ` x := homogeneous_localization 𝒜 x.as_homogeneous_ideal.to_ideal namespace projective_spectrum.structure_sheaf variables {𝒜} /-- The predicate saying that a dependent function on an open `U` is realised as a fixed fraction `r / s` of *same grading* in each of the stalks (which are localizations at various prime ideals). -/ def is_fraction {U : opens (projective_spectrum.Top 𝒜)} (f : Π x : U, at x.1) : Prop := ∃ (i : ℕ) (r s : 𝒜 i), ∀ x : U, ∃ (s_nin : s.1 ∉ x.1.as_homogeneous_ideal), (f x) = quotient.mk' ⟨i, r, s, s_nin⟩ variables (𝒜) /-- The predicate `is_fraction` is "prelocal", in the sense that if it holds on `U` it holds on any open subset `V` of `U`. -/ def is_fraction_prelocal : prelocal_predicate (λ (x : projective_spectrum.Top 𝒜), at x) := { pred := λ U f, is_fraction f, res := by rintros V U i f ⟨j, r, s, w⟩; exact ⟨j, r, s, λ y, w (i y)⟩ } /-- We will define the structure sheaf as the subsheaf of all dependent functions in `Π x : U, homogeneous_localization 𝒜 x` consisting of those functions which can locally be expressed as a ratio of `A` of same grading.-/ def is_locally_fraction : local_predicate (λ (x : projective_spectrum.Top 𝒜), at x) := (is_fraction_prelocal 𝒜).sheafify namespace section_subring variable {𝒜} open submodule set_like.graded_monoid homogeneous_localization lemma zero_mem' (U : (opens (projective_spectrum.Top 𝒜))ᵒᵖ) : (is_locally_fraction 𝒜).pred (0 : Π x : unop U, at x.1) := λ x, ⟨unop U, x.2, 𝟙 (unop U), ⟨0, ⟨0, zero_mem _⟩, ⟨1, one_mem⟩, λ y, ⟨_, rfl⟩⟩⟩ lemma one_mem' (U : (opens (projective_spectrum.Top 𝒜))ᵒᵖ) : (is_locally_fraction 𝒜).pred (1 : Π x : unop U, at x.1) := λ x, ⟨unop U, x.2, 𝟙 (unop U), ⟨0, ⟨1, one_mem⟩, ⟨1, one_mem⟩, λ y, ⟨_, rfl⟩⟩⟩ lemma add_mem' (U : (opens (projective_spectrum.Top 𝒜))ᵒᵖ) (a b : Π x : unop U, at x.1) (ha : (is_locally_fraction 𝒜).pred a) (hb : (is_locally_fraction 𝒜).pred b) : (is_locally_fraction 𝒜).pred (a + b) := λ x, begin rcases ha x with ⟨Va, ma, ia, ja, ⟨ra, ra_mem⟩, ⟨sa, sa_mem⟩, wa⟩, rcases hb x with ⟨Vb, mb, ib, jb, ⟨rb, rb_mem⟩, ⟨sb, sb_mem⟩, wb⟩, refine ⟨Va ⊓ Vb, ⟨ma, mb⟩, opens.inf_le_left _ _ ≫ ia, ja + jb, ⟨sb * ra + sa * rb, add_mem (add_comm jb ja ▸ mul_mem sb_mem ra_mem : sb * ra ∈ 𝒜 (ja + jb)) (mul_mem sa_mem rb_mem)⟩, ⟨sa * sb, mul_mem sa_mem sb_mem⟩, λ y, ⟨λ h, _, _⟩⟩, { cases (y : projective_spectrum.Top 𝒜).is_prime.mem_or_mem h with h h, { obtain ⟨nin, -⟩ := (wa ⟨y, (opens.inf_le_left Va Vb y).2⟩), exact nin h }, { obtain ⟨nin, -⟩ := (wb ⟨y, (opens.inf_le_right Va Vb y).2⟩), exact nin h } }, { simp only [add_mul, map_add, pi.add_apply, ring_hom.map_mul, ext_iff_val, add_val], obtain ⟨nin1, hy1⟩ := (wa (opens.inf_le_left Va Vb y)), obtain ⟨nin2, hy2⟩ := (wb (opens.inf_le_right Va Vb y)), dsimp only at hy1 hy2, erw [hy1, hy2], simpa only [val_mk', add_mk, ← subtype.val_eq_coe, add_comm], } end lemma neg_mem' (U : (opens (projective_spectrum.Top 𝒜))ᵒᵖ) (a : Π x : unop U, at x.1) (ha : (is_locally_fraction 𝒜).pred a) : (is_locally_fraction 𝒜).pred (-a) := λ x, begin rcases ha x with ⟨V, m, i, j, ⟨r, r_mem⟩, ⟨s, s_mem⟩, w⟩, choose nin hy using w, refine ⟨V, m, i, j, ⟨-r, submodule.neg_mem _ r_mem⟩, ⟨s, s_mem⟩, λ y, ⟨nin y, _⟩⟩, simp only [ext_iff_val, val_mk', ←subtype.val_eq_coe] at hy, simp only [pi.neg_apply, ext_iff_val, neg_val, hy, val_mk', ←subtype.val_eq_coe, neg_mk], end lemma mul_mem' (U : (opens (projective_spectrum.Top 𝒜))ᵒᵖ) (a b : Π x : unop U, at x.1) (ha : (is_locally_fraction 𝒜).pred a) (hb : (is_locally_fraction 𝒜).pred b) : (is_locally_fraction 𝒜).pred (a * b) := λ x, begin rcases ha x with ⟨Va, ma, ia, ja, ⟨ra, ra_mem⟩, ⟨sa, sa_mem⟩, wa⟩, rcases hb x with ⟨Vb, mb, ib, jb, ⟨rb, rb_mem⟩, ⟨sb, sb_mem⟩, wb⟩, refine ⟨Va ⊓ Vb, ⟨ma, mb⟩, opens.inf_le_left _ _ ≫ ia, ja + jb, ⟨ra * rb, set_like.graded_monoid.mul_mem ra_mem rb_mem⟩, ⟨sa * sb, set_like.graded_monoid.mul_mem sa_mem sb_mem⟩, λ y, ⟨λ h, _, _⟩⟩, { cases (y : projective_spectrum.Top 𝒜).is_prime.mem_or_mem h with h h, { choose nin hy using wa ⟨y, (opens.inf_le_left Va Vb y).2⟩, exact nin h }, { choose nin hy using wb ⟨y, (opens.inf_le_right Va Vb y).2⟩, exact nin h }, }, { simp only [pi.mul_apply, ring_hom.map_mul], choose nin1 hy1 using wa (opens.inf_le_left Va Vb y), choose nin2 hy2 using wb (opens.inf_le_right Va Vb y), rw ext_iff_val at hy1 hy2 ⊢, erw [mul_val, hy1, hy2], simpa only [val_mk', mk_mul, ← subtype.val_eq_coe] } end end section_subring section open section_subring variable {𝒜} /--The functions satisfying `is_locally_fraction` form a subring of all dependent functions `Π x : U, homogeneous_localization 𝒜 x`.-/ def sections_subring (U : (opens (projective_spectrum.Top 𝒜))ᵒᵖ) : subring (Π x : unop U, at x.1) := { carrier := { f | (is_locally_fraction 𝒜).pred f }, zero_mem' := zero_mem' U, one_mem' := one_mem' U, add_mem' := add_mem' U, neg_mem' := neg_mem' U, mul_mem' := mul_mem' U } end /--The structure sheaf (valued in `Type`, not yet `CommRing`) is the subsheaf consisting of functions satisfying `is_locally_fraction`.-/ def structure_sheaf_in_Type : sheaf Type* (projective_spectrum.Top 𝒜):= subsheaf_to_Types (is_locally_fraction 𝒜) instance comm_ring_structure_sheaf_in_Type_obj (U : (opens (projective_spectrum.Top 𝒜))ᵒᵖ) : comm_ring ((structure_sheaf_in_Type 𝒜).1.obj U) := (sections_subring U).to_comm_ring /--The structure presheaf, valued in `CommRing`, constructed by dressing up the `Type` valued structure presheaf.-/ @[simps] def structure_presheaf_in_CommRing : presheaf CommRing (projective_spectrum.Top 𝒜) := { obj := λ U, CommRing.of ((structure_sheaf_in_Type 𝒜).1.obj U), map := λ U V i, { to_fun := ((structure_sheaf_in_Type 𝒜).1.map i), map_zero' := rfl, map_add' := λ x y, rfl, map_one' := rfl, map_mul' := λ x y, rfl, }, } /--Some glue, verifying that that structure presheaf valued in `CommRing` agrees with the `Type` valued structure presheaf.-/ def structure_presheaf_comp_forget : structure_presheaf_in_CommRing 𝒜 ⋙ (forget CommRing) ≅ (structure_sheaf_in_Type 𝒜).1 := nat_iso.of_components (λ U, iso.refl _) (by tidy) end projective_spectrum.structure_sheaf namespace projective_spectrum open Top.presheaf projective_spectrum.structure_sheaf opens /--The structure sheaf on `Proj` 𝒜, valued in `CommRing`.-/ def Proj.structure_sheaf : sheaf CommRing (projective_spectrum.Top 𝒜) := ⟨structure_presheaf_in_CommRing 𝒜, -- We check the sheaf condition under `forget CommRing`. (is_sheaf_iff_is_sheaf_comp _ _).mpr (is_sheaf_of_iso (structure_presheaf_comp_forget 𝒜).symm (structure_sheaf_in_Type 𝒜).property)⟩ end projective_spectrum section open projective_spectrum projective_spectrum.structure_sheaf opens @[simp] lemma res_apply (U V : opens (projective_spectrum.Top 𝒜)) (i : V ⟶ U) (s : (Proj.structure_sheaf 𝒜).1.obj (op U)) (x : V) : ((Proj.structure_sheaf 𝒜).1.map i.op s).1 x = (s.1 (i x) : _) := rfl /--`Proj` of a graded ring as a `SheafedSpace`-/ def Proj.to_SheafedSpace : SheafedSpace CommRing := { carrier := Top.of (projective_spectrum 𝒜), presheaf := (Proj.structure_sheaf 𝒜).1, is_sheaf := (Proj.structure_sheaf 𝒜).2 } /-- The ring homomorphism that takes a section of the structure sheaf of `Proj` on the open set `U`, implemented as a subtype of dependent functions to localizations at homogeneous prime ideals, and evaluates the section on the point corresponding to a given homogeneous prime ideal. -/ def open_to_localization (U : opens (projective_spectrum.Top 𝒜)) (x : projective_spectrum.Top 𝒜) (hx : x ∈ U) : (Proj.structure_sheaf 𝒜).1.obj (op U) ⟶ CommRing.of (at x) := { to_fun := λ s, (s.1 ⟨x, hx⟩ : _), map_one' := rfl, map_mul' := λ _ _, rfl, map_zero' := rfl, map_add' := λ _ _, rfl } /-- The ring homomorphism from the stalk of the structure sheaf of `Proj` at a point corresponding to a homogeneous prime ideal `x` to the *homogeneous localization* at `x`, formed by gluing the `open_to_localization` maps. -/ def stalk_to_fiber_ring_hom (x : projective_spectrum.Top 𝒜) : (Proj.structure_sheaf 𝒜).1.stalk x ⟶ CommRing.of (at x) := limits.colimit.desc (((open_nhds.inclusion x).op) ⋙ (Proj.structure_sheaf 𝒜).1) { X := _, ι := { app := λ U, open_to_localization 𝒜 ((open_nhds.inclusion _).obj (unop U)) x (unop U).2, } } @[simp] lemma germ_comp_stalk_to_fiber_ring_hom (U : opens (projective_spectrum.Top 𝒜)) (x : U) : (Proj.structure_sheaf 𝒜).1.germ x ≫ stalk_to_fiber_ring_hom 𝒜 x = open_to_localization 𝒜 U x x.2 := limits.colimit.ι_desc _ _ @[simp] lemma stalk_to_fiber_ring_hom_germ' (U : opens (projective_spectrum.Top 𝒜)) (x : projective_spectrum.Top 𝒜) (hx : x ∈ U) (s : (Proj.structure_sheaf 𝒜).1.obj (op U)) : stalk_to_fiber_ring_hom 𝒜 x ((Proj.structure_sheaf 𝒜).1.germ ⟨x, hx⟩ s) = (s.1 ⟨x, hx⟩ : _) := ring_hom.ext_iff.1 (germ_comp_stalk_to_fiber_ring_hom 𝒜 U ⟨x, hx⟩ : _) s @[simp] lemma stalk_to_fiber_ring_hom_germ (U : opens (projective_spectrum.Top 𝒜)) (x : U) (s : (Proj.structure_sheaf 𝒜).1.obj (op U)) : stalk_to_fiber_ring_hom 𝒜 x ((Proj.structure_sheaf 𝒜).1.germ x s) = s.1 x := by { cases x, exact stalk_to_fiber_ring_hom_germ' 𝒜 U _ _ _ } lemma homogeneous_localization.mem_basic_open (x : projective_spectrum.Top 𝒜) (f : at x) : x ∈ projective_spectrum.basic_open 𝒜 f.denom := begin rw projective_spectrum.mem_basic_open, exact homogeneous_localization.denom_not_mem _, end variable (𝒜) /--Given a point `x` corresponding to a homogeneous prime ideal, there is a (dependent) function such that, for any `f` in the homogeneous localization at `x`, it returns the obvious section in the basic open set `D(f.denom)`-/ def section_in_basic_open (x : projective_spectrum.Top 𝒜) : Π (f : at x), (Proj.structure_sheaf 𝒜).1.obj (op (projective_spectrum.basic_open 𝒜 f.denom)) := λ f, ⟨λ y, quotient.mk' ⟨f.deg, ⟨f.num, f.num_mem⟩, ⟨f.denom, f.denom_mem⟩, y.2⟩, λ y, ⟨projective_spectrum.basic_open 𝒜 f.denom, y.2, ⟨𝟙 _, ⟨f.deg, ⟨⟨f.num, f.num_mem⟩, ⟨f.denom, f.denom_mem⟩, λ z, ⟨z.2, rfl⟩⟩⟩⟩⟩⟩ /--Given any point `x` and `f` in the homogeneous localizatoin at `x`, there is an element in the stalk at `x` obtained by `section_in_basic_open`. This is the inverse of `stalk_to_fiber_ring_hom`. -/ def homogeneous_localization_to_stalk (x : projective_spectrum.Top 𝒜) : (at x) → (Proj.structure_sheaf 𝒜).1.stalk x := λ f, (Proj.structure_sheaf 𝒜).1.germ (⟨x, homogeneous_localization.mem_basic_open _ x f⟩ : projective_spectrum.basic_open _ f.denom) (section_in_basic_open _ x f) /--Using `homogeneous_localization_to_stalk`, we construct a ring isomorphism between stalk at `x` and homogeneous localization at `x` for any point `x` in `Proj`.-/ def Proj.stalk_iso' (x : projective_spectrum.Top 𝒜) : (Proj.structure_sheaf 𝒜).1.stalk x ≃+* CommRing.of (at x) := ring_equiv.of_bijective (stalk_to_fiber_ring_hom _ x) ⟨λ z1 z2 eq1, begin obtain ⟨u1, memu1, s1, rfl⟩ := (Proj.structure_sheaf 𝒜).1.germ_exist x z1, obtain ⟨u2, memu2, s2, rfl⟩ := (Proj.structure_sheaf 𝒜).1.germ_exist x z2, obtain ⟨v1, memv1, i1, ⟨j1, ⟨a1, a1_mem⟩, ⟨b1, b1_mem⟩, hs1⟩⟩ := s1.2 ⟨x, memu1⟩, obtain ⟨v2, memv2, i2, ⟨j2, ⟨a2, a2_mem⟩, ⟨b2, b2_mem⟩, hs2⟩⟩ := s2.2 ⟨x, memu2⟩, obtain ⟨b1_nin_x, eq2⟩ := hs1 ⟨x, memv1⟩, obtain ⟨b2_nin_x, eq3⟩ := hs2 ⟨x, memv2⟩, dsimp only at eq1 eq2 eq3, erw [stalk_to_fiber_ring_hom_germ 𝒜 u1 ⟨x, memu1⟩ s1, stalk_to_fiber_ring_hom_germ 𝒜 u2 ⟨x, memu2⟩ s2] at eq1, erw eq1 at eq2, erw [eq2, quotient.eq] at eq3, change localization.mk _ _ = localization.mk _ _ at eq3, rw [localization.mk_eq_mk', is_localization.eq] at eq3, obtain ⟨⟨c, hc⟩, eq3⟩ := eq3, simp only [← subtype.val_eq_coe] at eq3, have eq3' : ∀ (y : projective_spectrum.Top 𝒜) (hy : y ∈ projective_spectrum.basic_open 𝒜 b1 ⊓ projective_spectrum.basic_open 𝒜 b2 ⊓ projective_spectrum.basic_open 𝒜 c), (localization.mk a1 ⟨b1, show b1 ∉ y.as_homogeneous_ideal, by rw ←projective_spectrum.mem_basic_open; exact le_of_hom (opens.inf_le_left _ _ ≫ opens.inf_le_left _ _) hy⟩ : localization.at_prime y.1.to_ideal) = localization.mk a2 ⟨b2, show b2 ∉ y.as_homogeneous_ideal, by rw ←projective_spectrum.mem_basic_open; exact le_of_hom (opens.inf_le_left _ _ ≫ opens.inf_le_right _ _) hy⟩, { intros y hy, rw [localization.mk_eq_mk', is_localization.eq], exact ⟨⟨c, show c ∉ y.as_homogeneous_ideal, by rw ←projective_spectrum.mem_basic_open; exact le_of_hom (opens.inf_le_right _ _) hy⟩, eq3⟩ }, refine presheaf.germ_ext (Proj.structure_sheaf 𝒜).1 (projective_spectrum.basic_open _ b1 ⊓ projective_spectrum.basic_open _ b2 ⊓ projective_spectrum.basic_open _ c ⊓ v1 ⊓ v2) ⟨⟨⟨⟨b1_nin_x, b2_nin_x⟩, hc⟩, memv1⟩, memv2⟩ (opens.inf_le_left _ _ ≫ opens.inf_le_right _ _ ≫ i1) (opens.inf_le_right _ _ ≫ i2) _, rw subtype.ext_iff_val, ext1 y, simp only [res_apply], obtain ⟨b1_nin_y, eq6⟩ := hs1 ⟨_, le_of_hom (opens.inf_le_left _ _ ≫ opens.inf_le_right _ _) y.2⟩, obtain ⟨b2_nin_y, eq7⟩ := hs2 ⟨_, le_of_hom (opens.inf_le_right _ _) y.2⟩, simp only at eq6 eq7, erw [eq6, eq7, quotient.eq], change localization.mk _ _ = localization.mk _ _, exact eq3' _ ⟨⟨le_of_hom (opens.inf_le_left _ _ ≫ opens.inf_le_left _ _ ≫ opens.inf_le_left _ _ ≫ opens.inf_le_left _ _) y.2, le_of_hom (opens.inf_le_left _ _ ≫ opens.inf_le_left _ _ ≫ opens.inf_le_left _ _ ≫ opens.inf_le_right _ _) y.2⟩, le_of_hom (opens.inf_le_left _ _ ≫ opens.inf_le_left _ _ ≫ opens.inf_le_right _ _) y.2⟩, end, function.surjective_iff_has_right_inverse.mpr ⟨homogeneous_localization_to_stalk 𝒜 x, λ f, begin rw homogeneous_localization_to_stalk, erw stalk_to_fiber_ring_hom_germ 𝒜 (projective_spectrum.basic_open 𝒜 f.denom) ⟨x, _⟩ (section_in_basic_open _ x f), simp only [section_in_basic_open, subtype.ext_iff_val, homogeneous_localization.ext_iff_val, homogeneous_localization.val_mk', f.eq_num_div_denom], refl, end⟩⟩ /--`Proj` of a graded ring as a `LocallyRingedSpace`-/ def Proj.to_LocallyRingedSpace : LocallyRingedSpace := { local_ring := λ x, @@ring_equiv.local_ring _ (show local_ring (at x), from infer_instance) _ (Proj.stalk_iso' 𝒜 x).symm, ..(Proj.to_SheafedSpace 𝒜) } end end algebraic_geometry
abe4f02b475cdaa1cef11e37e300ba7f0366b702
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/category/FinBoolAlg.lean
0ad67e9e3254ca67088f8b8e6b192483a89433c2
[ "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
3,593
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.fintype.powerset import order.category.BoolAlg import order.category.FinPartialOrder import order.hom.complete_lattice /-! # The category of finite boolean algebras This file defines `FinBoolAlg`, the category of finite boolean algebras. ## TODO Birkhoff's representation for finite Boolean algebras. `Fintype_to_FinBoolAlg_op.left_op ⋙ FinBoolAlg.dual ≅ Fintype_to_FinBoolAlg_op.left_op` `FinBoolAlg` is essentially small. -/ universes u open category_theory order_dual opposite /-- The category of finite boolean algebras with bounded lattice morphisms. -/ structure FinBoolAlg := (to_BoolAlg : BoolAlg) [is_fintype : fintype to_BoolAlg] namespace FinBoolAlg instance : has_coe_to_sort FinBoolAlg Type* := ⟨λ X, X.to_BoolAlg⟩ instance (X : FinBoolAlg) : boolean_algebra X := X.to_BoolAlg.str attribute [instance] FinBoolAlg.is_fintype @[simp] lemma coe_to_BoolAlg (X : FinBoolAlg) : ↥X.to_BoolAlg = ↥X := rfl /-- Construct a bundled `FinBoolAlg` from `boolean_algebra` + `fintype`. -/ def of (α : Type*) [boolean_algebra α] [fintype α] : FinBoolAlg := ⟨⟨α⟩⟩ @[simp] lemma coe_of (α : Type*) [boolean_algebra α] [fintype α] : ↥(of α) = α := rfl instance : inhabited FinBoolAlg := ⟨of punit⟩ instance large_category : large_category FinBoolAlg := induced_category.category FinBoolAlg.to_BoolAlg instance concrete_category : concrete_category FinBoolAlg := induced_category.concrete_category FinBoolAlg.to_BoolAlg instance has_forget_to_BoolAlg : has_forget₂ FinBoolAlg BoolAlg := induced_category.has_forget₂ FinBoolAlg.to_BoolAlg instance forget_to_BoolAlg_full : full (forget₂ FinBoolAlg BoolAlg) := induced_category.full _ instance forget_to_BoolAlg_faithful : faithful (forget₂ FinBoolAlg BoolAlg) := induced_category.faithful _ @[simps] instance has_forget_to_FinPartialOrder : has_forget₂ FinBoolAlg FinPartialOrder := { forget₂ := { obj := λ X, FinPartialOrder.of X, map := λ X Y f, show order_hom X Y, from ↑(show bounded_lattice_hom X Y, from f) } } instance forget_to_FinPartialOrder_faithful : faithful (forget₂ FinBoolAlg FinPartialOrder) := ⟨λ X Y f g h, by { have := congr_arg (coe_fn : _ → X → Y) h, exact fun_like.coe_injective this }⟩ /-- Constructs an equivalence between finite Boolean algebras from an order isomorphism between them. -/ @[simps] def iso.mk {α β : FinBoolAlg.{u}} (e : α ≃o β) : α ≅ β := { hom := (e : bounded_lattice_hom α β), inv := (e.symm : bounded_lattice_hom β α), hom_inv_id' := by { ext, exact e.symm_apply_apply _ }, inv_hom_id' := by { ext, exact e.apply_symm_apply _ } } /-- `order_dual` as a functor. -/ @[simps] def dual : FinBoolAlg ⥤ FinBoolAlg := { obj := λ X, of Xᵒᵈ, map := λ X Y, bounded_lattice_hom.dual } /-- The equivalence between `FinBoolAlg` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : FinBoolAlg ≌ FinBoolAlg := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end FinBoolAlg /-- The powerset functor. `set` as a functor. -/ @[simps] def Fintype_to_FinBoolAlg_op : Fintype ⥤ FinBoolAlgᵒᵖ := { obj := λ X, op $ FinBoolAlg.of (set X), map := λ X Y f, quiver.hom.op $ (complete_lattice_hom.set_preimage f : bounded_lattice_hom (set Y) (set X)) }
072eefa9d254b2b9af7dc1c3bf5ded3f300da77b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/computability/partrec.lean
475352786b69bd08cf7cc44761b83fa7f4d65f38
[]
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
24,198
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.computability.primrec import Mathlib.data.nat.psub import Mathlib.data.pfun import Mathlib.PostPort universes u_1 u_2 u_3 u_4 u_5 namespace Mathlib /-! # The partial recursive functions The partial recursive functions are defined similarly to the primitive recursive functions, but now all functions are partial, implemented using the `roption` monad, and there is an additional operation, called μ-recursion, which performs unbounded minimization. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ namespace nat def rfind_x (p : ℕ →. Bool) (H : ∃ (n : ℕ), tt ∈ p n ∧ ∀ (k : ℕ), k < n → roption.dom (p k)) : Subtype fun (n : ℕ) => tt ∈ p n ∧ ∀ (m : ℕ), m < n → false ∈ p m := (fun (this : (k : ℕ) → (∀ (n : ℕ), n < k → false ∈ p n) → Subtype fun (n : ℕ) => tt ∈ p n ∧ ∀ (m : ℕ), m < n → false ∈ p m) => this 0 sorry) (well_founded.fix (wf_lbp p H) fun (m : ℕ) (IH : (y : ℕ) → lbp p y m → (∀ (n : ℕ), n < y → false ∈ p n) → Subtype fun (n : ℕ) => tt ∈ p n ∧ ∀ (m : ℕ), m < n → false ∈ p m) (al : ∀ (n : ℕ), n < m → false ∈ p n) => (fun (_x : Bool) (e : roption.get (p m) sorry = _x) => bool.cases_on _x (fun (e : roption.get (p m) sorry = false) => IH (m + 1) sorry sorry) (fun (e : roption.get (p m) sorry = tt) => { val := m, property := sorry }) e) (roption.get (p m) sorry) sorry) def rfind (p : ℕ →. Bool) : roption ℕ := roption.mk (∃ (n : ℕ), tt ∈ p n ∧ ∀ (k : ℕ), k < n → roption.dom (p k)) fun (h : ∃ (n : ℕ), tt ∈ p n ∧ ∀ (k : ℕ), k < n → roption.dom (p k)) => subtype.val (rfind_x p h) theorem rfind_spec {p : ℕ →. Bool} {n : ℕ} (h : n ∈ rfind p) : tt ∈ p n := Exists.snd h ▸ and.left (subtype.property (rfind_x p (Exists.fst h))) theorem rfind_min {p : ℕ →. Bool} {n : ℕ} (h : n ∈ rfind p) {m : ℕ} : m < n → false ∈ p m := Exists.snd h ▸ and.right (subtype.property (rfind_x p (Exists.fst h))) @[simp] theorem rfind_dom {p : ℕ →. Bool} : roption.dom (rfind p) ↔ ∃ (n : ℕ), tt ∈ p n ∧ ∀ {m : ℕ}, m < n → roption.dom (p m) := iff.rfl theorem rfind_dom' {p : ℕ →. Bool} : roption.dom (rfind p) ↔ ∃ (n : ℕ), tt ∈ p n ∧ ∀ {m : ℕ}, m ≤ n → roption.dom (p m) := sorry @[simp] theorem mem_rfind {p : ℕ →. Bool} {n : ℕ} : n ∈ rfind p ↔ tt ∈ p n ∧ ∀ {m : ℕ}, m < n → false ∈ p m := sorry theorem rfind_min' {p : ℕ → Bool} {m : ℕ} (pm : ↥(p m)) : ∃ (n : ℕ), ∃ (H : n ∈ rfind ↑p), n ≤ m := sorry theorem rfind_zero_none (p : ℕ →. Bool) (p0 : p 0 = roption.none) : rfind p = roption.none := sorry def rfind_opt {α : Type u_1} (f : ℕ → Option α) : roption α := roption.bind (rfind ↑fun (n : ℕ) => option.is_some (f n)) fun (n : ℕ) => ↑(f n) theorem rfind_opt_spec {α : Type u_1} {f : ℕ → Option α} {a : α} (h : a ∈ rfind_opt f) : ∃ (n : ℕ), a ∈ f n := sorry theorem rfind_opt_dom {α : Type u_1} {f : ℕ → Option α} : roption.dom (rfind_opt f) ↔ ∃ (n : ℕ), ∃ (a : α), a ∈ f n := sorry theorem rfind_opt_mono {α : Type u_1} {f : ℕ → Option α} (H : ∀ {a : α} {m n : ℕ}, m ≤ n → a ∈ f m → a ∈ f n) {a : α} : a ∈ rfind_opt f ↔ ∃ (n : ℕ), a ∈ f n := sorry inductive partrec : (ℕ →. ℕ) → Prop where | zero : partrec (pure 0) | succ : partrec ↑Nat.succ | left : partrec ↑fun (n : ℕ) => prod.fst (unpair n) | right : partrec ↑fun (n : ℕ) => prod.snd (unpair n) | pair : ∀ {f g : ℕ →. ℕ}, partrec f → partrec g → partrec fun (n : ℕ) => mkpair <$> f n <*> g n | comp : ∀ {f g : ℕ →. ℕ}, partrec f → partrec g → partrec fun (n : ℕ) => g n >>= f | prec : ∀ {f g : ℕ →. ℕ}, partrec f → partrec g → partrec (unpaired fun (a n : ℕ) => elim (f a) (fun (y : ℕ) (IH : roption ℕ) => do let i ← IH g (mkpair a (mkpair y i))) n) | rfind : ∀ {f : ℕ →. ℕ}, partrec f → partrec fun (a : ℕ) => rfind fun (n : ℕ) => (fun (m : ℕ) => to_bool (m = 0)) <$> f (mkpair a n) namespace partrec theorem of_eq {f : ℕ →. ℕ} {g : ℕ →. ℕ} (hf : partrec f) (H : ∀ (n : ℕ), f n = g n) : partrec g := funext H ▸ hf theorem of_eq_tot {f : ℕ →. ℕ} {g : ℕ → ℕ} (hf : partrec f) (H : ∀ (n : ℕ), g n ∈ f n) : partrec ↑g := of_eq hf fun (n : ℕ) => iff.mpr roption.eq_some_iff (H n) theorem of_primrec {f : ℕ → ℕ} (hf : primrec f) : partrec ↑f := sorry protected theorem some : partrec roption.some := of_primrec primrec.id theorem none : partrec fun (n : ℕ) => roption.none := sorry theorem prec' {f : ℕ →. ℕ} {g : ℕ →. ℕ} {h : ℕ →. ℕ} (hf : partrec f) (hg : partrec g) (hh : partrec h) : partrec fun (a : ℕ) => roption.bind (f a) fun (n : ℕ) => elim (g a) (fun (y : ℕ) (IH : roption ℕ) => do let i ← IH h (mkpair a (mkpair y i))) n := sorry theorem ppred : partrec fun (n : ℕ) => ↑(ppred n) := sorry end partrec end nat def partrec {α : Type u_1} {σ : Type u_2} [primcodable α] [primcodable σ] (f : α →. σ) := nat.partrec fun (n : ℕ) => roption.bind ↑(encodable.decode α n) fun (a : α) => roption.map encodable.encode (f a) def partrec₂ {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] (f : α → β →. σ) := partrec fun (p : α × β) => f (prod.fst p) (prod.snd p) def computable {α : Type u_1} {σ : Type u_2} [primcodable α] [primcodable σ] (f : α → σ) := partrec ↑f def computable₂ {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := computable fun (p : α × β) => f (prod.fst p) (prod.snd p) theorem primrec.to_comp {α : Type u_1} {σ : Type u_2} [primcodable α] [primcodable σ] {f : α → σ} (hf : primrec f) : computable f := sorry theorem primrec₂.to_comp {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : primrec₂ f) : computable₂ f := primrec.to_comp hf theorem computable.part {α : Type u_1} {σ : Type u_2} [primcodable α] [primcodable σ] {f : α → σ} (hf : computable f) : partrec ↑f := hf theorem computable₂.part {α : Type u_1} {β : Type u_2} {σ : Type u_3} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} (hf : computable₂ f) : partrec₂ fun (a : α) => ↑(f a) := hf namespace computable theorem of_eq {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α → σ} {g : α → σ} (hf : computable f) (H : ∀ (n : α), f n = g n) : computable g := funext H ▸ hf theorem const {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] (s : σ) : computable fun (a : α) => s := primrec.to_comp (primrec.const s) theorem of_option {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → Option β} (hf : computable f) : partrec fun (a : α) => ↑(f a) := sorry theorem to₂ {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α × β → σ} (hf : computable f) : computable₂ fun (a : α) (b : β) => f (a, b) := of_eq hf fun (_x : α × β) => (fun (_a : α × β) => prod.cases_on _a fun (fst : α) (snd : β) => idRhs (f (fst, snd) = f (fst, snd)) rfl) _x protected theorem id {α : Type u_1} [primcodable α] : computable id := primrec.to_comp primrec.id theorem fst {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : computable prod.fst := primrec.to_comp primrec.fst theorem snd {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : computable prod.snd := primrec.to_comp primrec.snd theorem pair {α : Type u_1} {β : Type u_2} {γ : Type u_3} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : computable f) (hg : computable g) : computable fun (a : α) => (f a, g a) := sorry theorem unpair : computable nat.unpair := primrec.to_comp primrec.unpair theorem succ : computable Nat.succ := primrec.to_comp primrec.succ theorem pred : computable Nat.pred := primrec.to_comp primrec.pred theorem nat_bodd : computable nat.bodd := primrec.to_comp primrec.nat_bodd theorem nat_div2 : computable nat.div2 := primrec.to_comp primrec.nat_div2 theorem sum_inl {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : computable sum.inl := primrec.to_comp primrec.sum_inl theorem sum_inr {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] : computable sum.inr := primrec.to_comp primrec.sum_inr theorem list_cons {α : Type u_1} [primcodable α] : computable₂ List.cons := primrec₂.to_comp primrec.list_cons theorem list_reverse {α : Type u_1} [primcodable α] : computable list.reverse := primrec.to_comp primrec.list_reverse theorem list_nth {α : Type u_1} [primcodable α] : computable₂ list.nth := primrec₂.to_comp primrec.list_nth theorem list_append {α : Type u_1} [primcodable α] : computable₂ append := primrec₂.to_comp primrec.list_append theorem list_concat {α : Type u_1} [primcodable α] : computable₂ fun (l : List α) (a : α) => l ++ [a] := primrec₂.to_comp primrec.list_concat theorem list_length {α : Type u_1} [primcodable α] : computable list.length := primrec.to_comp primrec.list_length theorem vector_cons {α : Type u_1} [primcodable α] {n : ℕ} : computable₂ vector.cons := primrec₂.to_comp primrec.vector_cons theorem vector_to_list {α : Type u_1} [primcodable α] {n : ℕ} : computable vector.to_list := primrec.to_comp primrec.vector_to_list theorem vector_length {α : Type u_1} [primcodable α] {n : ℕ} : computable vector.length := primrec.to_comp primrec.vector_length theorem vector_head {α : Type u_1} [primcodable α] {n : ℕ} : computable vector.head := primrec.to_comp primrec.vector_head theorem vector_tail {α : Type u_1} [primcodable α] {n : ℕ} : computable vector.tail := primrec.to_comp primrec.vector_tail theorem vector_nth {α : Type u_1} [primcodable α] {n : ℕ} : computable₂ vector.nth := primrec₂.to_comp primrec.vector_nth theorem vector_nth' {α : Type u_1} [primcodable α] {n : ℕ} : computable vector.nth := primrec.to_comp primrec.vector_nth' theorem vector_of_fn' {α : Type u_1} [primcodable α] {n : ℕ} : computable vector.of_fn := primrec.to_comp primrec.vector_of_fn' theorem fin_app {σ : Type u_4} [primcodable σ] {n : ℕ} : computable₂ id := primrec₂.to_comp primrec.fin_app protected theorem encode {α : Type u_1} [primcodable α] : computable encodable.encode := primrec.to_comp primrec.encode protected theorem decode {α : Type u_1} [primcodable α] : computable (encodable.decode α) := primrec.to_comp primrec.decode protected theorem of_nat (α : Type u_1) [denumerable α] : computable (denumerable.of_nat α) := primrec.to_comp (primrec.of_nat α) theorem encode_iff {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α → σ} : (computable fun (a : α) => encodable.encode (f a)) ↔ computable f := iff.rfl theorem option_some {α : Type u_1} [primcodable α] : computable some := primrec.to_comp primrec.option_some end computable namespace partrec theorem of_eq {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α →. σ} {g : α →. σ} (hf : partrec f) (H : ∀ (n : α), f n = g n) : partrec g := funext H ▸ hf theorem of_eq_tot {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α →. σ} {g : α → σ} (hf : partrec f) (H : ∀ (n : α), g n ∈ f n) : computable g := of_eq hf fun (a : α) => iff.mpr roption.eq_some_iff (H a) theorem none {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] : partrec fun (a : α) => roption.none := sorry protected theorem some {α : Type u_1} [primcodable α] : partrec roption.some := computable.id theorem const' {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] (s : roption σ) : partrec fun (a : α) => s := of_eq (computable.of_option (computable.const (roption.to_option s))) fun (a : α) => roption.of_to_option s protected theorem bind {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α →. β} {g : α → β →. σ} (hf : partrec f) (hg : partrec₂ g) : partrec fun (a : α) => roption.bind (f a) (g a) := sorry theorem map {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α →. β} {g : α → β → σ} (hf : partrec f) (hg : computable₂ g) : partrec fun (a : α) => roption.map (g a) (f a) := sorry theorem to₂ {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α × β →. σ} (hf : partrec f) : partrec₂ fun (a : α) (b : β) => f (a, b) := of_eq hf fun (_x : α × β) => (fun (_a : α × β) => prod.cases_on _a fun (fst : α) (snd : β) => idRhs (f (fst, snd) = f (fst, snd)) rfl) _x theorem nat_elim {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α → ℕ} {g : α →. σ} {h : α → ℕ × σ →. σ} (hf : computable f) (hg : partrec g) (hh : partrec₂ h) : partrec fun (a : α) => nat.elim (g a) (fun (y : ℕ) (IH : roption σ) => roption.bind IH fun (i : σ) => h a (y, i)) (f a) := sorry theorem comp {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : β →. σ} {g : α → β} (hf : partrec f) (hg : computable g) : partrec fun (a : α) => f (g a) := sorry theorem nat_iff {f : ℕ →. ℕ} : partrec f ↔ nat.partrec f := sorry theorem map_encode_iff {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α →. σ} : (partrec fun (a : α) => roption.map encodable.encode (f a)) ↔ partrec f := iff.rfl end partrec namespace partrec₂ theorem unpaired {α : Type u_1} [primcodable α] {f : ℕ → ℕ →. α} : partrec (nat.unpaired f) ↔ partrec₂ f := sorry theorem unpaired' {f : ℕ → ℕ →. ℕ} : nat.partrec (nat.unpaired f) ↔ partrec₂ f := iff.trans (iff.symm partrec.nat_iff) unpaired theorem comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] {f : β → γ →. σ} {g : α → β} {h : α → γ} (hf : partrec₂ f) (hg : computable g) (hh : computable h) : partrec fun (a : α) => f (g a) (h a) := partrec.comp hf (computable.pair hg hh) theorem comp₂ {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] {f : γ → δ →. σ} {g : α → β → γ} {h : α → β → δ} (hf : partrec₂ f) (hg : computable₂ g) (hh : computable₂ h) : partrec₂ fun (a : α) (b : β) => f (g a b) (h a b) := comp hf hg hh end partrec₂ namespace computable theorem comp {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : β → σ} {g : α → β} (hf : computable f) (hg : computable g) : computable fun (a : α) => f (g a) := partrec.comp hf hg theorem comp₂ {α : Type u_1} {β : Type u_2} {γ : Type u_3} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] {f : γ → σ} {g : α → β → γ} (hf : computable f) (hg : computable₂ g) : computable₂ fun (a : α) (b : β) => f (g a b) := comp hf hg end computable namespace computable₂ theorem comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : computable₂ f) (hg : computable g) (hh : computable h) : computable fun (a : α) => f (g a) (h a) := computable.comp hf (computable.pair hg hh) theorem comp₂ {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {σ : Type u_5} [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : computable₂ f) (hg : computable₂ g) (hh : computable₂ h) : computable₂ fun (a : α) (b : β) => f (g a b) (h a b) := comp hf hg hh end computable₂ namespace partrec theorem rfind {α : Type u_1} [primcodable α] {p : α → ℕ →. Bool} (hp : partrec₂ p) : partrec fun (a : α) => nat.rfind (p a) := sorry theorem rfind_opt {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α → ℕ → Option σ} (hf : computable₂ f) : partrec fun (a : α) => nat.rfind_opt (f a) := partrec.bind (rfind (to₂ (computable.part (computable.comp (primrec.to_comp primrec.option_is_some) hf)))) (computable.of_option hf) theorem nat_cases_right {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α → ℕ} {g : α → σ} {h : α → ℕ →. σ} (hf : computable f) (hg : computable g) (hh : partrec₂ h) : partrec fun (a : α) => nat.cases (roption.some (g a)) (h a) (f a) := sorry theorem bind_decode2_iff {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α →. σ} : partrec f ↔ nat.partrec fun (n : ℕ) => roption.bind ↑(encodable.decode2 α n) fun (a : α) => roption.map encodable.encode (f a) := sorry theorem vector_m_of_fn {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {n : ℕ} {f : fin n → α →. σ} : (∀ (i : fin n), partrec (f i)) → partrec fun (a : α) => vector.m_of_fn fun (i : fin n) => f i a := sorry end partrec @[simp] theorem vector.m_of_fn_roption_some {α : Type u_1} {n : ℕ} (f : fin n → α) : (vector.m_of_fn fun (i : fin n) => roption.some (f i)) = roption.some (vector.of_fn f) := vector.m_of_fn_pure namespace computable theorem option_some_iff {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α → σ} : (computable fun (a : α) => some (f a)) ↔ computable f := sorry theorem bind_decode_iff {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → Option σ} : (computable₂ fun (a : α) (n : ℕ) => option.bind (encodable.decode β n) (f a)) ↔ computable₂ f := sorry theorem map_decode_iff {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α → β → σ} : (computable₂ fun (a : α) (n : ℕ) => option.map (f a) (encodable.decode β n)) ↔ computable₂ f := iff.trans bind_decode_iff option_some_iff theorem nat_elim {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α → ℕ} {g : α → σ} {h : α → ℕ × σ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable fun (a : α) => nat.elim (g a) (fun (y : ℕ) (IH : σ) => h a (y, IH)) (f a) := sorry theorem nat_cases {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α → ℕ} {g : α → σ} {h : α → ℕ → σ} (hf : computable f) (hg : computable g) (hh : computable₂ h) : computable fun (a : α) => nat.cases (g a) (h a) (f a) := nat_elim hf hg (to₂ (computable₂.comp hh fst (comp fst snd))) theorem cond {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {c : α → Bool} {f : α → σ} {g : α → σ} (hc : computable c) (hf : computable f) (hg : computable g) : computable fun (a : α) => cond (c a) (f a) (g a) := sorry theorem option_cases {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {o : α → Option β} {f : α → σ} {g : α → β → σ} (ho : computable o) (hf : computable f) (hg : computable₂ g) : computable fun (a : α) => option.cases_on (o a) (f a) (g a) := sorry theorem option_bind {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α → Option β} {g : α → β → Option σ} (hf : computable f) (hg : computable₂ g) : computable fun (a : α) => option.bind (f a) (g a) := sorry theorem option_map {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {f : α → Option β} {g : α → β → σ} (hf : computable f) (hg : computable₂ g) : computable fun (a : α) => option.map (g a) (f a) := option_bind hf (comp₂ option_some hg) theorem option_get_or_else {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → Option β} {g : α → β} (hf : computable f) (hg : computable g) : computable fun (a : α) => option.get_or_else (f a) (g a) := sorry theorem subtype_mk {α : Type u_1} {β : Type u_2} [primcodable α] [primcodable β] {f : α → β} {p : β → Prop} [decidable_pred p] {h : ∀ (a : α), p (f a)} (hp : primrec_pred p) (hf : computable f) : computable fun (a : α) => { val := f a, property := h a } := sorry theorem sum_cases {α : Type u_1} {β : Type u_2} {γ : Type u_3} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : computable f) (hg : computable₂ g) (hh : computable₂ h) : computable fun (a : α) => sum.cases_on (f a) (g a) (h a) := sorry theorem nat_strong_rec {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] (f : α → ℕ → σ) {g : α → List σ → Option σ} (hg : computable₂ g) (H : ∀ (a : α) (n : ℕ), g a (list.map (f a) (list.range n)) = some (f a n)) : computable₂ f := sorry theorem list_of_fn {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {n : ℕ} {f : fin n → α → σ} : (∀ (i : fin n), computable (f i)) → computable fun (a : α) => list.of_fn fun (i : fin n) => f i a := sorry theorem vector_of_fn {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {n : ℕ} {f : fin n → α → σ} (hf : ∀ (i : fin n), computable (f i)) : computable fun (a : α) => vector.of_fn fun (i : fin n) => f i a := sorry end computable namespace partrec theorem option_some_iff {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α →. σ} : (partrec fun (a : α) => roption.map some (f a)) ↔ partrec f := sorry theorem option_cases_right {α : Type u_1} {β : Type u_2} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable σ] {o : α → Option β} {f : α → σ} {g : α → β →. σ} (ho : computable o) (hf : computable f) (hg : partrec₂ g) : partrec fun (a : α) => option.cases_on (o a) (roption.some (f a)) (g a) := sorry theorem sum_cases_right {α : Type u_1} {β : Type u_2} {γ : Type u_3} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ →. σ} (hf : computable f) (hg : computable₂ g) (hh : partrec₂ h) : partrec fun (a : α) => sum.cases_on (f a) (fun (b : β) => roption.some (g a b)) (h a) := sorry theorem sum_cases_left {α : Type u_1} {β : Type u_2} {γ : Type u_3} {σ : Type u_4} [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ → σ} (hf : computable f) (hg : partrec₂ g) (hh : computable₂ h) : partrec fun (a : α) => sum.cases_on (f a) (g a) fun (c : γ) => roption.some (h a c) := sorry theorem fix {α : Type u_1} {σ : Type u_4} [primcodable α] [primcodable σ] {f : α →. σ ⊕ α} (hf : partrec f) : partrec (pfun.fix f) := sorry