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
a3de2ff179873bb74c7a101134d11313a834d7ab
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/constr_tac4.lean
ad18713d7f11277899bbb5f0e901f3653ab4614c
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
546
lean
import data.nat open nat definition lt.trans {a b c : nat} (H₁ : a < b) (H₂ : b < c) : a < c := have aux : a < b → a < c, from le.rec_on H₂ (λ h₁, lt.step h₁) (λ b₁ bb₁ ih h₁, by constructor; exact ih h₁), aux H₁ definition succ_lt_succ {a b : nat} (H : a < b) : succ a < succ b := le.rec_on H (by constructor) (λ b hlt ih, lt.trans ih (by constructor)) definition lt_of_succ_lt {a b : nat} (H : succ a < b) : a < b := le.rec_on H (by constructor; constructor) (λ b h ih, by constructor; exact ih)
9559079a2d969afd71d6b81549371e0b26fc1600
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/lint/default.lean
9253de92a8512647187b046bd8c31fe57d8955e6
[ "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
5,169
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import tactic.to_additive import tactic.lint.frontend import tactic.lint.misc import tactic.lint.simp import tactic.lint.type_classes /-! # Default linters This file defines the list of linters that are run in mathlib CI. Not all linters are considered "default" and run that way. A `linter` is marked as default if it is tagged with the `linter` attribute. -/ open tactic /-- User commands to spot common mistakes in the code * `#lint`: check all declarations in the current file * `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects, and also excluding the current file) * `#lint_all`: check all declarations in the environment (the current file and all imported files) The following linters are run by default: 1. `unused_arguments` checks for unused arguments in declarations. 2. `def_lemma` checks whether a declaration is incorrectly marked as a def/lemma. 3. `dup_namespce` checks whether a namespace is duplicated in the name of a declaration. 4. `ge_or_gt` checks whether ≥/> is used in the declaration. 5. `instance_priority` checks that instances that always apply have priority below default. 6. `doc_blame` checks for missing doc strings on definitions and constants. 7. `has_nonempty_instance` checks whether every type has an associated `inhabited`, `unique` or `nonempty` instance. 8. `impossible_instance` checks for instances that can never fire. 9. `incorrect_type_class_argument` checks for arguments in [square brackets] that are not classes. 10. `dangerous_instance` checks for instances that generate type-class problems with metavariables. 11. `fails_quickly` tests that type-class inference ends (relatively) quickly when applied to variables. 12. `has_coe_variable` tests that there are no instances of type `has_coe α t` for a variable `α`. 13. `inhabited_nonempty` checks for `inhabited` instance arguments that should be changed to `nonempty`. 14. `simp_nf` checks that the left-hand side of simp lemmas is in simp-normal form. 15. `simp_var_head` checks that there are no variables as head symbol of left-hand sides of simp lemmas. 16. `simp_comm` checks that no commutativity lemmas (such as `add_comm`) are marked simp. 17. `decidable_classical` checks for `decidable` hypotheses that are used in the proof of a proposition but not in the statement, and could be removed using `classical`. Theorems in the `decidable` namespace are exempt. 18. `has_coe_to_fun` checks that every type that coerces to a function has a direct `has_coe_to_fun` instance. 19. `check_type` checks that the statement of a declaration is well-typed. 20. `check_univs` checks that there are no bad `max u v` universe levels. 21. `syn_taut` checks that declarations are not syntactic tautologies. 22. `check_reducibility` checks whether non-instances with a class as type are reducible. 23. `unprintable_interactive` checks that interactive tactics have parser documentation. 24. `to_additive_doc` checks if additive versions of lemmas have documentation. The following linters are not run by default: 1. `doc_blame_thm`, checks for missing doc strings on lemmas and theorems. 2. `explicit_vars_of_iff` checks if there are explicit variables used on both sides of an iff. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4). You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint that suppresses the output if all checks pass. A silent lint will fail if any test fails. You can append a `+` to any command (e.g. `#lint_mathlib+`) to run a verbose lint that reports the result of each linter, including the successes. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments` You can add custom linters by defining a term of type `linter` in the `linter` namespace. A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check` or `lint only my_new_check`. If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default. Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration omits it from only the specified linter checks. -/ add_tactic_doc { name := "linting commands", category := doc_category.cmd, decl_names := [`lint_cmd, `lint_mathlib_cmd, `lint_all_cmd, `list_linters], tags := ["linting"] } /-- The default linters used in mathlib CI. -/ meta def mathlib_linters : list name := by do ls ← get_checks tt [] ff, let ls := ls.map (λ ⟨n, _⟩, `linter ++ n) ++ [`assert_not_exists.linter, `assert_no_instance.linter], exact (reflect ls)
92e092e0959b87955c95fd312d693dfdf1695f10
9dc8cecdf3c4634764a18254e94d43da07142918
/src/logic/hydra.lean
7a51cf7b3f2467c0358fa3b2f71f9ebd64ce727c
[ "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
7,198
lean
/- Copyright (c) 2022 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Junyan Xu -/ import data.multiset.basic import order.game_add import order.well_founded /-! # Termination of a hydra game This file deals with the following version of the hydra game: each head of the hydra is labelled by an element in a type `α`, and when you cut off one head with label `a`, it grows back an arbitrary but finite number of heads, all labelled by elements smaller than `a` with respect to a well-founded relation `r` on `α`. We show that no matter how (in what order) you choose cut off the heads, the game always terminates, i.e. all heads will eventually be cut off (but of course it can last arbitrarily long, i.e. takes an arbitrary finite number of steps). This result is stated as the well-foundedness of the `cut_expand` relation defined in this file: we model the heads of the hydra as a multiset of elements of `α`, and the valid "moves" of the game are modelled by the relation `cut_expand r` on `multiset α`: `cut_expand r s' s` is true iff `s'` is obtained by removing one head `a ∈ s` and adding back an arbitrary multiset `t` of heads such that all `a' ∈ t` satisfy `r a' a`. To prove this theorem, we follow the proof by Peter LeFanu Lumsdaine at https://mathoverflow.net/a/229084/3332, and along the way we introduce the notion of `fibration` of relations. TODO: formalize the relations corresponding to more powerful (e.g. Kirby–Paris and Buchholz) hydras, and prove their well-foundedness. -/ namespace relation variables {α β : Type*} section fibration variables (rα : α → α → Prop) (rβ : β → β → Prop) (f : α → β) /-- A function `f : α → β` is a fibration between the relation `rα` and `rβ` if for all `a : α` and `b : β`, whenever `b : β` and `f a` are related by `rβ`, `b` is the image of some `a' : α` under `f`, and `a'` and `a` are related by `rα`. -/ def fibration := ∀ ⦃a b⦄, rβ b (f a) → ∃ a', rα a' a ∧ f a' = b variables {rα rβ} /-- If `f : α → β` is a fibration between relations `rα` and `rβ`, and `a : α` is accessible under `rα`, then `f a` is accessible under `rβ`. -/ lemma _root_.acc.of_fibration (fib : fibration rα rβ f) {a} (ha : acc rα a) : acc rβ (f a) := begin induction ha with a ha ih, refine acc.intro (f a) (λ b hr, _), obtain ⟨a', hr', rfl⟩ := fib hr, exact ih a' hr', end lemma _root_.acc.of_downward_closed (dc : ∀ {a b}, rβ b (f a) → b ∈ set.range f) (a : α) (ha : acc (inv_image rβ f) a) : acc rβ (f a) := ha.of_fibration f (λ a b h, let ⟨a', he⟩ := dc h in ⟨a', he.substr h, he⟩) end fibration section hydra open multiset prod /-- The relation that specifies valid moves in our hydra game. `cut_expand r s' s` means that `s'` is obtained by removing one head `a ∈ s` and adding back an arbitrary multiset `t` of heads such that all `a' ∈ t` satisfy `r a' a`. This is most directly translated into `s' = s.erase a + t`, but `multiset.erase` requires `decidable_eq α`, so we use the equivalent condition `s' + {a} = s + t` instead, which is also easier to verify for explicit multisets `s'`, `s` and `t`. We also don't include the condition `a ∈ s` because `s' + {a} = s + t` already guarantees `a ∈ s + t`, and if `r` is irreflexive then `a ∉ t`, which is the case when `r` is well-founded, the case we are primarily interested in. The lemma `relation.cut_expand_iff` below converts between this convenient definition and the direct translation when `r` is irreflexive. -/ def cut_expand (r : α → α → Prop) (s' s : multiset α) : Prop := ∃ (t : multiset α) (a : α), (∀ a' ∈ t, r a' a) ∧ s' + {a} = s + t variable {r : α → α → Prop} theorem cut_expand_singleton {s x} (h : ∀ x' ∈ s, r x' x) : cut_expand r s {x} := ⟨s, x, h, add_comm s _⟩ theorem cut_expand_singleton_singleton {x' x} (h : r x' x) : cut_expand r {x'} {x} := cut_expand_singleton (λ a h, by rwa mem_singleton.1 h) theorem cut_expand_add_left {t u} (s) : cut_expand r (s + t) (s + u) ↔ cut_expand r t u := exists₂_congr $ λ _ _, and_congr iff.rfl $ by rw [add_assoc, add_assoc, add_left_cancel_iff] lemma cut_expand_iff [decidable_eq α] [is_irrefl α r] {s' s : multiset α} : cut_expand r s' s ↔ ∃ (t : multiset α) a, (∀ a' ∈ t, r a' a) ∧ a ∈ s ∧ s' = s.erase a + t := begin simp_rw [cut_expand, add_singleton_eq_iff], refine exists₂_congr (λ t a, ⟨_, _⟩), { rintro ⟨ht, ha, rfl⟩, obtain (h|h) := mem_add.1 ha, exacts [⟨ht, h, t.erase_add_left_pos h⟩, (@irrefl α r _ a (ht a h)).elim] }, { rintro ⟨ht, h, rfl⟩, exact ⟨ht, mem_add.2 (or.inl h), (t.erase_add_left_pos h).symm⟩ }, end theorem not_cut_expand_zero [is_irrefl α r] (s) : ¬ cut_expand r s 0 := by { classical, rw cut_expand_iff, rintro ⟨_, _, _, ⟨⟩, _⟩ } /-- For any relation `r` on `α`, multiset addition `multiset α × multiset α → multiset α` is a fibration between the game sum of `cut_expand r` with itself and `cut_expand r` itself. -/ lemma cut_expand_fibration (r : α → α → Prop) : fibration (game_add (cut_expand r) (cut_expand r)) (cut_expand r) (λ s, s.1 + s.2) := begin rintro ⟨s₁, s₂⟩ s ⟨t, a, hr, he⟩, dsimp at he ⊢, classical, obtain ⟨ha, rfl⟩ := add_singleton_eq_iff.1 he, rw [add_assoc, mem_add] at ha, obtain (h|h) := ha, { refine ⟨(s₁.erase a + t, s₂), game_add.fst ⟨t, a, hr, _⟩, _⟩, { rw [add_comm, ← add_assoc, singleton_add, cons_erase h] }, { rw [add_assoc s₁, erase_add_left_pos _ h, add_right_comm, add_assoc] } }, { refine ⟨(s₁, (s₂ + t).erase a), game_add.snd ⟨t, a, hr, _⟩, _⟩, { rw [add_comm, singleton_add, cons_erase h] }, { rw [add_assoc, erase_add_right_pos _ h] } }, end /-- A multiset is accessible under `cut_expand` if all its singleton subsets are, assuming `r` is irreflexive. -/ lemma acc_of_singleton [is_irrefl α r] {s : multiset α} : (∀ a ∈ s, acc (cut_expand r) {a}) → acc (cut_expand r) s := begin refine multiset.induction _ _ s, { exact λ _, acc.intro 0 $ λ s h, (not_cut_expand_zero s h).elim }, { intros a s ih hacc, rw ← s.singleton_add a, exact ((hacc a $ s.mem_cons_self a).prod_game_add $ ih $ λ a ha, hacc a $ mem_cons_of_mem ha).of_fibration _ (cut_expand_fibration r) }, end /-- A singleton `{a}` is accessible under `cut_expand r` if `a` is accessible under `r`, assuming `r` is irreflexive. -/ lemma _root_.acc.cut_expand [is_irrefl α r] {a : α} (hacc : acc r a) : acc (cut_expand r) {a} := begin induction hacc with a h ih, refine acc.intro _ (λ s, _), classical, rw cut_expand_iff, rintro ⟨t, a, hr, rfl|⟨⟨⟩⟩, rfl⟩, refine acc_of_singleton (λ a', _), rw [erase_singleton, zero_add], exact ih a' ∘ hr a', end /-- `cut_expand r` is well-founded when `r` is. -/ theorem _root_.well_founded.cut_expand (hr : well_founded r) : well_founded (cut_expand r) := ⟨by { letI h := hr.is_irrefl, exact λ s, acc_of_singleton $ λ a _, (hr.apply a).cut_expand }⟩ end hydra end relation
81fe854c44f2033e35ffb1b4107ab3eb5e8537ef
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/sites/sieves.lean
b890267a824f09249f5069fea39ced83e6a58850
[ "Apache-2.0" ]
permissive
SAAluthwela/mathlib
62044349d72dd63983a8500214736aa7779634d3
83a4b8b990907291421de54a78988c024dc8a552
refs/heads/master
1,679,433,873,417
1,615,998,031,000
1,615,998,031,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,138
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, E. W. Ayers -/ import category_theory.over import category_theory.limits.shapes.finite_limits import category_theory.yoneda import order.complete_lattice import data.set.lattice /-! # Theory of sieves - For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under left-composition. - The complete lattice structure on sieves is given, as well as the Galois insertion given by downward-closing. - A `sieve X` (functorially) induces a presheaf on `C` together with a monomorphism to the yoneda embedding of `X`. ## Tags sieve, pullback -/ universes v u namespace category_theory variables {C : Type u} [category.{v} C] variables {X Y Z : C} (f : Y ⟶ X) /-- A set of arrows all with codomain `X`. -/ @[derive complete_lattice] def presieve (X : C) := Π ⦃Y⦄, set (Y ⟶ X) namespace presieve instance : inhabited (presieve X) := ⟨⊤⟩ /-- Given a set of arrows `S` all with codomain `X`, and a set of arrows with codomain `Y` for each `f : Y ⟶ X` in `S`, produce a set of arrows with codomain `X`: `{ g ≫ f | (f : Y ⟶ X) ∈ S, (g : Z ⟶ Y) ∈ R f }`. -/ def bind (S : presieve X) (R : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → presieve Y) : presieve X := λ Z h, ∃ (Y : C) (g : Z ⟶ Y) (f : Y ⟶ X) (H : S f), R H g ∧ g ≫ f = h @[simp] lemma bind_comp {S : presieve X} {R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → presieve Y} {g : Z ⟶ Y} (h₁ : S f) (h₂ : R h₁ g) : bind S R (g ≫ f) := ⟨_, _, _, h₁, h₂, rfl⟩ /-- The singleton presieve. -/ -- Note we can't make this into `has_singleton` because of the out-param. inductive singleton : presieve X | mk : singleton f @[simp] lemma singleton_eq_iff_domain (f g : Y ⟶ X) : singleton f g ↔ f = g := begin split, { rintro ⟨a, rfl⟩, refl }, { rintro rfl, apply singleton.mk, } end lemma singleton_self : singleton f f := singleton.mk end presieve /-- For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under left-composition. -/ structure sieve {C : Type u} [category.{v} C] (X : C) := (arrows : presieve X) (downward_closed' : ∀ {Y Z f} (hf : arrows f) (g : Z ⟶ Y), arrows (g ≫ f)) namespace sieve instance {X : C} : has_coe_to_fun (sieve X) := ⟨_, sieve.arrows⟩ initialize_simps_projections sieve (arrows → apply) variables {S R : sieve X} @[simp, priority 100] lemma downward_closed (S : sieve X) {f : Y ⟶ X} (hf : S f) (g : Z ⟶ Y) : S (g ≫ f) := S.downward_closed' hf g lemma arrows_ext : Π {R S : sieve X}, R.arrows = S.arrows → R = S | ⟨Ra, _⟩ ⟨Sa, _⟩ rfl := rfl @[ext] protected lemma ext {R S : sieve X} (h : ∀ ⦃Y⦄ (f : Y ⟶ X), R f ↔ S f) : R = S := arrows_ext $ funext $ λ x, funext $ λ f, propext $ h f protected lemma ext_iff {R S : sieve X} : R = S ↔ (∀ ⦃Y⦄ (f : Y ⟶ X), R f ↔ S f) := ⟨λ h Y f, h ▸ iff.rfl, sieve.ext⟩ open lattice /-- The supremum of a collection of sieves: the union of them all. -/ protected def Sup (𝒮 : set (sieve X)) : (sieve X) := { arrows := λ Y, {f | ∃ S ∈ 𝒮, sieve.arrows S f}, downward_closed' := λ Y Z f, by { rintro ⟨S, hS, hf⟩ g, exact ⟨S, hS, S.downward_closed hf _⟩ } } /-- The infimum of a collection of sieves: the intersection of them all. -/ protected def Inf (𝒮 : set (sieve X)) : (sieve X) := { arrows := λ Y, {f | ∀ S ∈ 𝒮, sieve.arrows S f}, downward_closed' := λ Y Z f hf g S H, S.downward_closed (hf S H) g } /-- The union of two sieves is a sieve. -/ protected def union (S R : sieve X) : sieve X := { arrows := λ Y f, S f ∨ R f, downward_closed' := by { rintros Y Z f (h | h) g; simp [h] } } /-- The intersection of two sieves is a sieve. -/ protected def inter (S R : sieve X) : sieve X := { arrows := λ Y f, S f ∧ R f, downward_closed' := by { rintros Y Z f ⟨h₁, h₂⟩ g, simp [h₁, h₂] } } /-- Sieves on an object `X` form a complete lattice. We generate this directly rather than using the galois insertion for nicer definitional properties. -/ instance : complete_lattice (sieve X) := { le := λ S R, ∀ ⦃Y⦄ (f : Y ⟶ X), S f → R f, le_refl := λ S f q, id, le_trans := λ S₁ S₂ S₃ S₁₂ S₂₃ Y f h, S₂₃ _ (S₁₂ _ h), le_antisymm := λ S R p q, sieve.ext (λ Y f, ⟨p _, q _⟩), top := { arrows := λ _, set.univ, downward_closed' := λ Y Z f g h, ⟨⟩ }, bot := { arrows := λ _, ∅, downward_closed' := λ _ _ _ p _, false.elim p }, sup := sieve.union, inf := sieve.inter, Sup := sieve.Sup, Inf := sieve.Inf, le_Sup := λ 𝒮 S hS Y f hf, ⟨S, hS, hf⟩, Sup_le := λ ℰ S hS Y f, by { rintro ⟨R, hR, hf⟩, apply hS R hR _ hf }, Inf_le := λ _ _ hS _ _ h, h _ hS, le_Inf := λ _ _ hS _ _ hf _ hR, hS _ hR _ hf, le_sup_left := λ _ _ _ _, or.inl, le_sup_right := λ _ _ _ _, or.inr, sup_le := λ _ _ _ a b _ _ hf, hf.elim (a _) (b _), inf_le_left := λ _ _ _ _, and.left, inf_le_right := λ _ _ _ _, and.right, le_inf := λ _ _ _ p q _ _ z, ⟨p _ z, q _ z⟩, le_top := λ _ _ _ _, trivial, bot_le := λ _ _ _, false.elim } /-- The maximal sieve always exists. -/ instance sieve_inhabited : inhabited (sieve X) := ⟨⊤⟩ @[simp] lemma Inf_apply {Ss : set (sieve X)} {Y} (f : Y ⟶ X) : Inf Ss f ↔ ∀ (S : sieve X) (H : S ∈ Ss), S f := iff.rfl @[simp] lemma Sup_apply {Ss : set (sieve X)} {Y} (f : Y ⟶ X) : Sup Ss f ↔ ∃ (S : sieve X) (H : S ∈ Ss), S f := iff.rfl @[simp] lemma inter_apply {R S : sieve X} {Y} (f : Y ⟶ X) : (R ⊓ S) f ↔ R f ∧ S f := iff.rfl @[simp] lemma union_apply {R S : sieve X} {Y} (f : Y ⟶ X) : (R ⊔ S) f ↔ R f ∨ S f := iff.rfl @[simp] lemma top_apply (f : Y ⟶ X) : (⊤ : sieve X) f := trivial /-- Generate the smallest sieve containing the given set of arrows. -/ @[simps] def generate (R : presieve X) : sieve X := { arrows := λ Z f, ∃ Y (h : Z ⟶ Y) (g : Y ⟶ X), R g ∧ h ≫ g = f, downward_closed' := begin rintro Y Z _ ⟨W, g, f, hf, rfl⟩ h, exact ⟨_, h ≫ g, _, hf, by simp⟩, end } /-- Given a presieve on `X`, and a sieve on each domain of an arrow in the presieve, we can bind to produce a sieve on `X`. -/ @[simps] def bind (S : presieve X) (R : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) : sieve X := { arrows := S.bind (λ Y f h, R h), downward_closed' := begin rintro Y Z f ⟨W, f, h, hh, hf, rfl⟩ g, exact ⟨_, g ≫ f, _, hh, by simp [hf]⟩, end } open order lattice lemma sets_iff_generate (R : presieve X) (S : sieve X) : generate R ≤ S ↔ R ≤ S := ⟨λ H Y g hg, H _ ⟨_, 𝟙 _, _, hg, category.id_comp _⟩, λ ss Y f, begin rintro ⟨Z, f, g, hg, rfl⟩, exact S.downward_closed (ss Z hg) f, end⟩ /-- Show that there is a galois insertion (generate, set_over). -/ def gi_generate : galois_insertion (generate : presieve X → sieve X) arrows := { gc := sets_iff_generate, choice := λ 𝒢 _, generate 𝒢, choice_eq := λ _ _, rfl, le_l_u := λ S Y f hf, ⟨_, 𝟙 _, _, hf, category.id_comp _⟩ } lemma le_generate (R : presieve X) : R ≤ generate R := gi_generate.gc.le_u_l R /-- If the identity arrow is in a sieve, the sieve is maximal. -/ lemma id_mem_iff_eq_top : S (𝟙 X) ↔ S = ⊤ := ⟨λ h, top_unique $ λ Y f _, by simpa using downward_closed _ h f, λ h, h.symm ▸ trivial⟩ /-- If an arrow set contains a split epi, it generates the maximal sieve. -/ lemma generate_of_contains_split_epi {R : presieve X} (f : Y ⟶ X) [split_epi f] (hf : R f) : generate R = ⊤ := begin rw ← id_mem_iff_eq_top, exact ⟨_, section_ f, f, hf, by simp⟩, end @[simp] lemma generate_of_singleton_split_epi (f : Y ⟶ X) [split_epi f] : generate (presieve.singleton f) = ⊤ := generate_of_contains_split_epi f (presieve.singleton_self _) @[simp] lemma generate_top : generate (⊤ : presieve X) = ⊤ := generate_of_contains_split_epi (𝟙 _) ⟨⟩ /-- Given a morphism `h : Y ⟶ X`, send a sieve S on X to a sieve on Y as the inverse image of S with `_ ≫ h`. That is, `sieve.pullback S h := (≫ h) '⁻¹ S`. -/ @[simps] def pullback (h : Y ⟶ X) (S : sieve X) : sieve Y := { arrows := λ Y sl, S (sl ≫ h), downward_closed' := λ Z W f g h, by simp [g] } @[simp] lemma pullback_id : S.pullback (𝟙 _) = S := by simp [sieve.ext_iff] @[simp] lemma pullback_top {f : Y ⟶ X} : (⊤ : sieve X).pullback f = ⊤ := top_unique (λ _ g, id) lemma pullback_comp {f : Y ⟶ X} {g : Z ⟶ Y} (S : sieve X) : S.pullback (g ≫ f) = (S.pullback f).pullback g := by simp [sieve.ext_iff] @[simp] lemma pullback_inter {f : Y ⟶ X} (S R : sieve X) : (S ⊓ R).pullback f = S.pullback f ⊓ R.pullback f := by simp [sieve.ext_iff] lemma pullback_eq_top_iff_mem (f : Y ⟶ X) : S f ↔ S.pullback f = ⊤ := by rw [← id_mem_iff_eq_top, pullback_apply, category.id_comp] lemma pullback_eq_top_of_mem (S : sieve X) {f : Y ⟶ X} : S f → S.pullback f = ⊤ := (pullback_eq_top_iff_mem f).1 /-- Push a sieve `R` on `Y` forward along an arrow `f : Y ⟶ X`: `gf : Z ⟶ X` is in the sieve if `gf` factors through some `g : Z ⟶ Y` which is in `R`. -/ @[simps] def pushforward (f : Y ⟶ X) (R : sieve Y) : sieve X := { arrows := λ Z gf, ∃ g, g ≫ f = gf ∧ R g, downward_closed' := λ Z₁ Z₂ g ⟨j, k, z⟩ h, ⟨h ≫ j, by simp [k], by simp [z]⟩ } lemma pushforward_apply_comp {R : sieve Y} {Z : C} {g : Z ⟶ Y} (hg : R g) (f : Y ⟶ X) : R.pushforward f (g ≫ f) := ⟨g, rfl, hg⟩ lemma pushforward_comp {f : Y ⟶ X} {g : Z ⟶ Y} (R : sieve Z) : R.pushforward (g ≫ f) = (R.pushforward g).pushforward f := sieve.ext (λ W h, ⟨λ ⟨f₁, hq, hf₁⟩, ⟨f₁ ≫ g, by simpa, f₁, rfl, hf₁⟩, λ ⟨y, hy, z, hR, hz⟩, ⟨z, by rwa reassoc_of hR, hz⟩⟩) lemma galois_connection (f : Y ⟶ X) : galois_connection (sieve.pushforward f) (sieve.pullback f) := λ S R, ⟨λ hR Z g hg, hR _ ⟨g, rfl, hg⟩, λ hS Z g ⟨h, hg, hh⟩, hg ▸ hS h hh⟩ lemma pullback_monotone (f : Y ⟶ X) : monotone (sieve.pullback f) := (galois_connection f).monotone_u lemma pushforward_monotone (f : Y ⟶ X) : monotone (sieve.pushforward f) := (galois_connection f).monotone_l lemma le_pushforward_pullback (f : Y ⟶ X) (R : sieve Y) : R ≤ (R.pushforward f).pullback f := (galois_connection f).le_u_l _ lemma pullback_pushforward_le (f : Y ⟶ X) (R : sieve X) : (R.pullback f).pushforward f ≤ R := (galois_connection f).l_u_le _ lemma pushforward_union {f : Y ⟶ X} (S R : sieve Y) : (S ⊔ R).pushforward f = S.pushforward f ⊔ R.pushforward f := (galois_connection f).l_sup lemma pushforward_le_bind_of_mem (S : presieve X) (R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) (f : Y ⟶ X) (h : S f) : (R h).pushforward f ≤ bind S R := begin rintro Z _ ⟨g, rfl, hg⟩, exact ⟨_, g, f, h, hg, rfl⟩, end lemma le_pullback_bind (S : presieve X) (R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) (f : Y ⟶ X) (h : S f) : R h ≤ (bind S R).pullback f := begin rw ← galois_connection f, apply pushforward_le_bind_of_mem, end /-- If `f` is a monomorphism, the pushforward-pullback adjunction on sieves is coreflective. -/ def galois_coinsertion_of_mono (f : Y ⟶ X) [mono f] : galois_coinsertion (sieve.pushforward f) (sieve.pullback f) := begin apply (galois_connection f).to_galois_coinsertion, rintros S Z g ⟨g₁, hf, hg₁⟩, rw cancel_mono f at hf, rwa ← hf, end /-- If `f` is a split epi, the pushforward-pullback adjunction on sieves is reflective. -/ def galois_insertion_of_split_epi (f : Y ⟶ X) [split_epi f] : galois_insertion (sieve.pushforward f) (sieve.pullback f) := begin apply (galois_connection f).to_galois_insertion, intros S Z g hg, refine ⟨g ≫ section_ f, by simpa⟩, end /-- A sieve induces a presheaf. -/ @[simps] def functor (S : sieve X) : Cᵒᵖ ⥤ Type v := { obj := λ Y, {g : Y.unop ⟶ X // S g}, map := λ Y Z f g, ⟨f.unop ≫ g.1, downward_closed _ g.2 _⟩ } /-- If a sieve S is contained in a sieve T, then we have a morphism of presheaves on their induced presheaves. -/ @[simps] def nat_trans_of_le {S T : sieve X} (h : S ≤ T) : S.functor ⟶ T.functor := { app := λ Y f, ⟨f.1, h _ f.2⟩ }. /-- The natural inclusion from the functor induced by a sieve to the yoneda embedding. -/ @[simps] def functor_inclusion (S : sieve X) : S.functor ⟶ yoneda.obj X := { app := λ Y f, f.1 }. lemma nat_trans_of_le_comm {S T : sieve X} (h : S ≤ T) : nat_trans_of_le h ≫ functor_inclusion _ = functor_inclusion _ := rfl /-- The presheaf induced by a sieve is a subobject of the yoneda embedding. -/ instance functor_inclusion_is_mono : mono S.functor_inclusion := ⟨λ Z f g h, by { ext Y y, apply congr_fun (nat_trans.congr_app h Y) y }⟩ /-- A natural transformation to a representable functor induces a sieve. This is the left inverse of `functor_inclusion`, shown in `sieve_of_functor_inclusion`. -/ -- TODO: Show that when `f` is mono, this is right inverse to `functor_inclusion` up to isomorphism. @[simps] def sieve_of_subfunctor {R} (f : R ⟶ yoneda.obj X) : sieve X := { arrows := λ Y g, ∃ t, f.app (opposite.op Y) t = g, downward_closed' := λ Y Z _, begin rintro ⟨t, rfl⟩ g, refine ⟨R.map g.op t, _⟩, rw functor_to_types.naturality _ _ f, simp, end } lemma sieve_of_subfunctor_functor_inclusion : sieve_of_subfunctor S.functor_inclusion = S := begin ext, simp only [functor_inclusion_app, sieve_of_subfunctor_apply, subtype.val_eq_coe], split, { rintro ⟨⟨f, hf⟩, rfl⟩, exact hf }, { intro hf, exact ⟨⟨_, hf⟩, rfl⟩ } end instance functor_inclusion_top_is_iso : is_iso ((⊤ : sieve X).functor_inclusion) := ⟨{ app := λ Y a, ⟨a, ⟨⟩⟩ }, by tidy⟩ end sieve end category_theory
b39ed951cf7427b4868247fdb653d1bbdc4b418c
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/integral/bochner.lean
cfe2e69980bfaa35d1ce8dc0f79834312bd88cae
[ "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
67,345
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, Sébastien Gouëzel, Rémy Degenne -/ import measure_theory.integral.set_to_l1 import measure_theory.group.basic 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 through the extension process described in the file `set_to_L1`, which follows these steps: 1. Define the integral of the indicator of a set. This is `weighted_smul μ s x = (μ s).to_real * x`. `weighted_smul μ` is shown to be linear in the value `x` and `dominated_fin_meas_additive` (defined in the file `set_to_L1`) with respect to the set `s`. 2. Define the integral on simple functions of the type `simple_func α E` (notation : `α →ₛ E`) where `E` is a real normed space. (See `simple_func.integral` for details.) 3. Transfer this definition to define the integral on `L1.simple_func α E` (notation : `α →₁ₛ[μ] E`), see `L1.simple_func.integral`. Show that this integral is a continuous linear map from `α →₁ₛ[μ] E` to `E`. 4. Define the Bochner integral on L1 functions by extending the integral on integrable simple functions `α →₁ₛ[μ] E` using `continuous_linear_map.extend` and the fact that the embedding of `α →₁ₛ[μ] E` into `α →₁[μ] E` is dense. 5. Define the Bochner integral on functions as the Bochner integral of its equivalence class in L1 space, if it is in L1, and 0 otherwise. The result of that construction is `∫ a, f a ∂μ`, which is definitionally equal to `set_to_fun (dominated_fin_meas_additive_weighted_smul μ) f`. Some basic properties of the integral (like linearity) are particular cases of the properties of `set_to_fun` (which are described in the file `set_to_L1`). ## 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 `ℝ≥0∞`-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 5. (In the file `set_integral`) integration commutes with continuous linear maps. * `continuous_linear_map.integral_comp_comm` * `linear_isometry.integral_comp_comm` ## 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 `simple_func_dense` (or one of the related results, like `Lp.induction` for functions in `Lp`), 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 `ℝ≥0∞`-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/lp_space`) * `α →₁ₛ[μ] E` : simple functions in L1 space, i.e., equivalence classes of integrable simple functions (defined in `measure_theory/simple_func_dense`) * `∫ a, f a ∂μ` : integral of `f` with respect to a measure `μ` * `∫ a, f a` : integral of `f` with respect to `volume`, the default measure on the ambient type We also define notations for integral on a set, which are described in the file `measure_theory/set_integral`. Note : `ₛ` is typed using `\_s`. Sometimes it shows as a box if the font is missing. ## Tags Bochner integral, simple function, function space, Lebesgue dominated convergence theorem -/ noncomputable theory open_locale classical topological_space big_operators nnreal ennreal measure_theory open set filter topological_space ennreal emetric local attribute [instance] fact_one_le_one_ennreal namespace measure_theory variables {α E F 𝕜 : Type*} section weighted_smul open continuous_linear_map variables [normed_group F] [normed_space ℝ F] {m : measurable_space α} {μ : measure α} /-- Given a set `s`, return the continuous linear map `λ x, (μ s).to_real • x`. The extension of that set function through `set_to_L1` gives the Bochner integral of L1 functions. -/ def weighted_smul {m : measurable_space α} (μ : measure α) (s : set α) : F →L[ℝ] F := (μ s).to_real • (continuous_linear_map.id ℝ F) lemma weighted_smul_apply {m : measurable_space α} (μ : measure α) (s : set α) (x : F) : weighted_smul μ s x = (μ s).to_real • x := by simp [weighted_smul] @[simp] lemma weighted_smul_zero_measure {m : measurable_space α} : weighted_smul (0 : measure α) = (0 : set α → F →L[ℝ] F) := by { ext1, simp [weighted_smul], } @[simp] lemma weighted_smul_empty {m : measurable_space α} (μ : measure α) : weighted_smul μ ∅ = (0 : F →L[ℝ] F) := by { ext1 x, rw [weighted_smul_apply], simp, } lemma weighted_smul_add_measure {m : measurable_space α} (μ ν : measure α) {s : set α} (hμs : μ s ≠ ∞) (hνs : ν s ≠ ∞) : (weighted_smul (μ + ν) s : F →L[ℝ] F) = weighted_smul μ s + weighted_smul ν s := begin ext1 x, push_cast, simp_rw [pi.add_apply, weighted_smul_apply], push_cast, rw [pi.add_apply, ennreal.to_real_add hμs hνs, add_smul], end lemma weighted_smul_congr (s t : set α) (hst : μ s = μ t) : (weighted_smul μ s : F →L[ℝ] F) = weighted_smul μ t := by { ext1 x, simp_rw weighted_smul_apply, congr' 2, } lemma weighted_smul_null {s : set α} (h_zero : μ s = 0) : (weighted_smul μ s : F →L[ℝ] F) = 0 := by { ext1 x, rw [weighted_smul_apply, h_zero], simp, } lemma weighted_smul_union (s t : set α) (hs : measurable_set s) (ht : measurable_set t) (hs_finite : μ s ≠ ∞) (ht_finite : μ t ≠ ∞) (h_inter : s ∩ t = ∅) : (weighted_smul μ (s ∪ t) : F →L[ℝ] F) = weighted_smul μ s + weighted_smul μ t := begin ext1 x, simp_rw [add_apply, weighted_smul_apply, measure_union (set.disjoint_iff_inter_eq_empty.mpr h_inter) hs ht, ennreal.to_real_add hs_finite ht_finite, add_smul], end lemma weighted_smul_smul [normed_field 𝕜] [normed_space 𝕜 F] [smul_comm_class ℝ 𝕜 F] (c : 𝕜) (s : set α) (x : F) : weighted_smul μ s (c • x) = c • weighted_smul μ s x := by { simp_rw [weighted_smul_apply, smul_comm], } lemma norm_weighted_smul_le (s : set α) : ∥(weighted_smul μ s : F →L[ℝ] F)∥ ≤ (μ s).to_real := calc ∥(weighted_smul μ s : F →L[ℝ] F)∥ = ∥(μ s).to_real∥ * ∥continuous_linear_map.id ℝ F∥ : norm_smul _ _ ... ≤ ∥(μ s).to_real∥ : (mul_le_mul_of_nonneg_left norm_id_le (norm_nonneg _)).trans (mul_one _).le ... = abs (μ s).to_real : real.norm_eq_abs _ ... = (μ s).to_real : abs_eq_self.mpr ennreal.to_real_nonneg lemma dominated_fin_meas_additive_weighted_smul {m : measurable_space α} (μ : measure α) : dominated_fin_meas_additive μ (weighted_smul μ : set α → F →L[ℝ] F) 1 := ⟨weighted_smul_union, λ s, (norm_weighted_smul_le s).trans (one_mul _).symm.le⟩ end weighted_smul local infixr ` →ₛ `:25 := simple_func namespace simple_func section pos_part variables [linear_order E] [has_zero E] [measurable_space α] /-- 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 := by { ext, rw [map_apply, real.norm_eq_abs, abs_of_nonneg], exact le_max_right _ _ } 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 a, rw coe_sub, exact max_zero_sub_eq_self (f a) end end pos_part 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] [normed_space ℝ F] {p : ℝ≥0∞} {G F' : Type*} [normed_group G] [normed_group F'] [normed_space ℝ F'] {m : measurable_space α} {μ : measure α} /-- Bochner integral of simple functions whose codomain is a real `normed_space`. This is equal to `∑ x in f.range, (μ (f ⁻¹' {x})).to_real • x` (see `integral_eq`). -/ def integral {m : measurable_space α} (μ : measure α) (f : α →ₛ F) : F := f.set_to_simple_func (weighted_smul μ) lemma integral_def {m : measurable_space α} (μ : measure α) (f : α →ₛ F) : f.integral μ = f.set_to_simple_func (weighted_smul μ) := rfl lemma integral_eq {m : measurable_space α} (μ : measure α) (f : α →ₛ F) : f.integral μ = ∑ x in f.range, (μ (f ⁻¹' {x})).to_real • x := by simp [integral, set_to_simple_func, weighted_smul_apply] lemma integral_eq_sum_filter {m : measurable_space α} (f : α →ₛ F) (μ : measure α) : f.integral μ = ∑ x in f.range.filter (λ x, x ≠ 0), (μ (f ⁻¹' {x})).to_real • x := by { rw [integral_def, set_to_simple_func_eq_sum_filter], simp_rw weighted_smul_apply, } /-- 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} {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 [set.disjoint_singleton_left, hx] end @[simp] lemma integral_const {m : measurable_space α} (μ : measure α) (y : F) : (const α y).integral μ = (μ univ).to_real • y := calc (const α y).integral μ = ∑ z in {y}, (μ ((const α y) ⁻¹' {z})).to_real • z : integral_eq_sum_of_subset $ (filter_subset _ _).trans (range_const_subset _ _) ... = (μ univ).to_real • y : by simp @[simp] lemma integral_piecewise_zero {m : measurable_space α} (f : α →ₛ F) (μ : measure α) {s : set α} (hs : measurable_set s) : (piecewise s hs f 0).integral μ = f.integral (μ.restrict s) := begin refine (integral_eq_sum_of_subset _).trans ((sum_congr rfl $ λ y hy, _).trans (integral_eq_sum_filter _ _).symm), { intros y hy, simp only [mem_filter, mem_range, coe_piecewise, coe_zero, piecewise_eq_indicator, mem_range_indicator] at *, rcases hy with ⟨⟨rfl, -⟩|⟨x, hxs, rfl⟩, h₀⟩, exacts [(h₀ rfl).elim, ⟨set.mem_range_self _, h₀⟩] }, { dsimp, rw [indicator_preimage_of_not_mem, measure.restrict_apply (f.measurable_set_preimage _)], exact λ h₀, (mem_filter.1 hy).2 (eq.symm h₀) } 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) := map_set_to_simple_func _ weighted_smul_union hf hg /-- `simple_func.integral` and `simple_func.lintegral` agree when the integrand has type `α →ₛ ℝ≥0∞`. But since `ℝ≥0∞` 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 → ℝ≥0∞} (hf : integrable f μ) (hg0 : g 0 = 0) (ht : ∀ 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, mul_comm] }, { assume a ha, by_cases a0 : a = 0, { rw [a0, hg0, zero_mul], exact with_top.zero_ne_top }, { apply mul_ne_top (ht a) (hf'.meas_preimage_singleton_ne_zero a0).ne } }, { simp [hg0] } end variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space ℝ E] [smul_comm_class ℝ 𝕜 E] lemma integral_congr {f g : α →ₛ E} (hf : integrable f μ) (h : f =ᵐ[μ] g) : f.integral μ = g.integral μ := set_to_simple_func_congr (weighted_smul μ) (λ s hs, weighted_smul_null) weighted_smul_union hf h /-- `simple_func.bintegral` and `simple_func.integral` agree when the integrand has type `α →ₛ ℝ≥0∞`. But since `ℝ≥0∞` 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], exacts [integral_congr hf this, ennreal.of_real_zero, λ b, 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 := set_to_simple_func_add _ weighted_smul_union hf hg lemma integral_neg {f : α →ₛ E} (hf : integrable f μ) : integral μ (-f) = - integral μ f := set_to_simple_func_neg _ weighted_smul_union hf lemma integral_sub {f g : α →ₛ E} (hf : integrable f μ) (hg : integrable g μ) : integral μ (f - g) = integral μ f - integral μ g := set_to_simple_func_sub _ weighted_smul_union hf hg lemma integral_smul (c : 𝕜) {f : α →ₛ E} (hf : integrable f μ) : integral μ (c • f) = c • integral μ f := set_to_simple_func_smul _ weighted_smul_union weighted_smul_smul c hf lemma norm_set_to_simple_func_le_integral_norm (T : set α → E →L[ℝ] F) {C : ℝ} (hT_norm : ∀ s, ∥T s∥ ≤ C * (μ s).to_real) {f : α →ₛ E} (hf : integrable f μ) : ∥f.set_to_simple_func T∥ ≤ C * (f.map norm).integral μ := calc ∥f.set_to_simple_func T∥ ≤ C * ∑ x in f.range, ennreal.to_real (μ (f ⁻¹' {x})) * ∥x∥ : norm_set_to_simple_func_le_sum_mul_norm T hT_norm f ... = C * (f.map norm).integral μ : by { rw map_integral f norm hf norm_zero, simp_rw smul_eq_mul, } lemma norm_integral_le_integral_norm (f : α →ₛ E) (hf : integrable f μ) : ∥f.integral μ∥ ≤ (f.map norm).integral μ := begin refine (norm_set_to_simple_func_le_integral_norm _ (λ s, _) hf).trans (one_mul _).le, exact (norm_weighted_smul_le s).trans (one_mul _).symm.le, end lemma integral_add_measure {ν} (f : α →ₛ E) (hf : integrable f (μ + ν)) : f.integral (μ + ν) = f.integral μ + f.integral ν := begin simp_rw [integral_def], refine set_to_simple_func_add_left' (weighted_smul μ) (weighted_smul ν) (weighted_smul (μ + ν)) (λ s hs hμνs, _) hf, rw [measure.coe_add, pi.add_apply, ennreal.add_ne_top] at hμνs, rw weighted_smul_add_measure _ _ hμνs.1 hμνs.2, end end integral end simple_func namespace L1 open ae_eq_fun Lp.simple_func Lp 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] {m : measurable_space α} {μ : measure α} variables {α E μ} namespace simple_func lemma norm_eq_integral (f : α →₁ₛ[μ] E) : ∥f∥ = ((to_simple_func f).map norm).integral μ := begin rw [norm_eq_sum_mul f, (to_simple_func f).map_integral norm (simple_func.integrable f) norm_zero], simp_rw smul_eq_mul, end section pos_part /-- Positive part of a simple function in L1 space. -/ def pos_part (f : α →₁ₛ[μ] ℝ) : α →₁ₛ[μ] ℝ := ⟨Lp.pos_part (f : α →₁[μ] ℝ), begin rcases f with ⟨f, s, hsf⟩, use s.pos_part, simp only [subtype.coe_mk, Lp.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 : α →₁ₛ[μ] ℝ) : (pos_part f : α →₁[μ] ℝ) = Lp.pos_part (f : α →₁[μ] ℝ) := rfl @[norm_cast] lemma coe_neg_part (f : α →₁ₛ[μ] ℝ) : (neg_part f : α →₁[μ] ℝ) = Lp.neg_part (f : α →₁[μ] ℝ) := rfl end pos_part section simple_func_integral /-! ### The Bochner integral of `L1` Define the Bochner integral on `α →₁ₛ[μ] E` by extension from the simple functions `α →₁ₛ[μ] E`, and prove basic properties of this integral. -/ variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space ℝ E] [smul_comm_class ℝ 𝕜 E] {F' : Type*} [normed_group F'] [normed_space ℝ F'] local attribute [instance] simple_func.normed_space /-- The Bochner integral over simple functions in L1 space. -/ def integral (f : α →₁ₛ[μ] E) : E := ((to_simple_func f)).integral μ lemma integral_eq_integral (f : α →₁ₛ[μ] E) : integral f = ((to_simple_func f)).integral μ := rfl lemma integral_eq_lintegral {f : α →₁ₛ[μ] ℝ} (h_pos : 0 ≤ᵐ[μ] (to_simple_func f)) : integral f = ennreal.to_real (∫⁻ a, ennreal.of_real ((to_simple_func f) a) ∂μ) := by rw [integral, simple_func.integral_eq_lintegral (simple_func.integrable f) h_pos] lemma integral_eq_set_to_L1s (f : α →₁ₛ[μ] E) : integral f = set_to_L1s (weighted_smul μ) f := rfl lemma integral_congr {f g : α →₁ₛ[μ] E} (h : to_simple_func f =ᵐ[μ] to_simple_func g) : integral f = integral g := simple_func.integral_congr (simple_func.integrable f) h lemma integral_add (f g : α →₁ₛ[μ] E) : integral (f + g) = integral f + integral g := set_to_L1s_add _ (λ _ _, weighted_smul_null) weighted_smul_union _ _ lemma integral_smul [measurable_space 𝕜] [opens_measurable_space 𝕜] (c : 𝕜) (f : α →₁ₛ[μ] E) : integral (c • f) = c • integral f := set_to_L1s_smul _ (λ _ _, weighted_smul_null) weighted_smul_union weighted_smul_smul c f lemma norm_integral_le_norm (f : α →₁ₛ[μ] E) : ∥integral f∥ ≤ ∥f∥ := begin rw [integral, norm_eq_integral], exact (to_simple_func f).norm_integral_le_integral_norm (simple_func.integrable f) end variables {E' : Type*} [normed_group E'] [second_countable_topology E'] [measurable_space E'] [borel_space E'] [normed_space ℝ E'] [normed_space 𝕜 E'] [measurable_space 𝕜] [opens_measurable_space 𝕜] variables (α E μ 𝕜) /-- 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) /-- The Bochner integral over simple functions in L1 space as a continuous linear map over ℝ. -/ def integral_clm : (α →₁ₛ[μ] E) →L[ℝ] E := integral_clm' α E ℝ μ variables {α E μ 𝕜} 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 : α →₁ₛ[μ] ℝ) : to_simple_func (pos_part f) =ᵐ[μ] (to_simple_func f).pos_part := begin have eq : ∀ a, (to_simple_func f).pos_part a = max ((to_simple_func f) a) 0 := λa, rfl, have ae_eq : ∀ᵐ a ∂μ, to_simple_func (pos_part f) a = max ((to_simple_func f) a) 0, { filter_upwards [to_simple_func_eq_to_fun (pos_part f), Lp.coe_fn_pos_part (f : α →₁[μ] ℝ), to_simple_func_eq_to_fun f], assume a h₁ h₂ h₃, convert h₂ }, refine ae_eq.mono (assume a h, _), rw [h, eq] end lemma neg_part_to_simple_func (f : α →₁ₛ[μ] ℝ) : to_simple_func (neg_part f) =ᵐ[μ] (to_simple_func f).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], assume a h₁ h₂, rw h₁, show max _ _ = max _ _, rw h₂, refl end lemma integral_eq_norm_pos_part_sub (f : α →₁ₛ[μ] ℝ) : integral f = ∥pos_part f∥ - ∥neg_part f∥ := begin -- Convert things in `L¹` to their `simple_func` counterpart have ae_eq₁ : (to_simple_func f).pos_part =ᵐ[μ] (to_simple_func (pos_part f)).map norm, { filter_upwards [pos_part_to_simple_func f], 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₂ : (to_simple_func f).neg_part =ᵐ[μ] (to_simple_func (neg_part f)).map norm, { filter_upwards [neg_part_to_simple_func f], 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 ∂μ, (to_simple_func f).pos_part a - (to_simple_func f).neg_part a = (to_simple_func (pos_part f)).map norm a - (to_simple_func (neg_part f)).map norm a, { filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, rw [h₁, h₂] }, rw [integral, norm_eq_integral, norm_eq_integral, ← simple_func.integral_sub], { show (to_simple_func f).integral μ = ((to_simple_func (pos_part f)).map norm - (to_simple_func (neg_part f)).map norm).integral μ, apply measure_theory.simple_func.integral_congr (simple_func.integrable f), filter_upwards [ae_eq₁, ae_eq₂], assume a h₁ h₂, show _ = _ - _, rw [← h₁, ← h₂], have := (to_simple_func f).pos_part_sub_neg_part, conv_lhs {rw ← this}, refl }, { exact (simple_func.integrable f).max_zero.congr ae_eq₁ }, { exact (simple_func.integrable f).neg.max_zero.congr ae_eq₂ } end end pos_part end simple_func_integral end simple_func open simple_func local notation `Integral` := @integral_clm α E _ _ _ _ _ μ _ variables [normed_space ℝ E] [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] [normed_space ℝ F] [complete_space E] section integration_in_L1 local attribute [instance] simple_func.normed_space open continuous_linear_map variables (𝕜) [measurable_space 𝕜] [opens_measurable_space 𝕜] /-- The Bochner integral in L1 space as a continuous linear map. -/ def integral_clm' : (α →₁[μ] E) →L[𝕜] E := (integral_clm' α E 𝕜 μ).extend (coe_to_Lp α E 𝕜) (simple_func.dense_range one_ne_top) simple_func.uniform_inducing variables {𝕜} /-- The Bochner integral in L1 space as a continuous linear map over ℝ. -/ def integral_clm : (α →₁[μ] E) →L[ℝ] E := integral_clm' ℝ /-- 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 lemma integral_eq_set_to_L1 (f : α →₁[μ] E) : integral f = set_to_L1 (dominated_fin_meas_additive_weighted_smul μ) f := rfl @[norm_cast] lemma simple_func.integral_L1_eq_integral (f : α →₁ₛ[μ] E) : integral (f : α →₁[μ] E) = (simple_func.integral f) := set_to_L1_eq_set_to_L1s_clm (dominated_fin_meas_additive_weighted_smul μ) f 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 (c : 𝕜) (f : α →₁[μ] E) : integral (c • f) = c • integral f := map_smul (integral_clm' 𝕜) c 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 : ℝ≥0) * ∥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), integral f) := L1.integral_clm.continuous section pos_part local attribute [instance] fact_one_le_one_ennreal lemma integral_eq_norm_pos_part_sub (f : α →₁[μ] ℝ) : integral f = ∥Lp.pos_part f∥ - ∥Lp.neg_part f∥ := begin -- Use `is_closed_property` and `is_closed_eq` refine @is_closed_property _ _ _ (coe : (α →₁ₛ[μ] ℝ) → (α →₁[μ] ℝ)) (λ f : α →₁[μ] ℝ, integral f = ∥Lp.pos_part f∥ - ∥Lp.neg_part f∥) (simple_func.dense_range one_ne_top) (is_closed_eq _ _) _ f, { exact cont _ }, { refine continuous.sub (continuous_norm.comp Lp.continuous_pos_part) (continuous_norm.comp Lp.continuous_neg_part) }, -- Show that the property holds for all simple functions in the `L¹` space. { assume s, norm_cast, exact simple_func.integral_eq_norm_pos_part_sub _ } end end pos_part end integration_in_L1 end L1 /-! ### The Bochner integral on functions Define the Bochner integral on functions generally to be the `L1` Bochner integral, for integrable functions, and 0 otherwise; prove its basic properties. -/ variables [normed_group E] [second_countable_topology E] [normed_space ℝ E] [complete_space E] [measurable_space E] [borel_space E] [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 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 {m : measurable_space α} (μ : measure α) (f : α → E) : E := if hf : integrable f μ then L1.integral (hf.to_L1 f) 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} {m : measurable_space α} {μ : measure α} lemma integral_eq (f : α → E) (hf : integrable f μ) : ∫ a, f a ∂μ = L1.integral (hf.to_L1 f) := dif_pos hf lemma integral_eq_set_to_fun (f : α → E) : ∫ a, f a ∂μ = set_to_fun (dominated_fin_meas_additive_weighted_smul μ) f := rfl lemma L1.integral_eq_integral (f : α →₁[μ] E) : L1.integral f = ∫ a, f a ∂μ := (L1.set_to_fun_eq_set_to_L1 (dominated_fin_meas_additive_weighted_smul μ) f).symm lemma integral_undef (h : ¬ integrable f μ) : ∫ a, f a ∂μ = 0 := dif_neg h lemma integral_non_ae_measurable (h : ¬ ae_measurable f μ) : ∫ a, f a ∂μ = 0 := integral_undef $ not_and_of_not_left _ h variables (α E) lemma integral_zero : ∫ a : α, (0:E) ∂μ = 0 := set_to_fun_zero (dominated_fin_meas_additive_weighted_smul μ) @[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 ∂μ := set_to_fun_add (dominated_fin_meas_additive_weighted_smul μ) hf hg 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 ∂μ := set_to_fun_neg (dominated_fin_meas_additive_weighted_smul μ) f 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 ∂μ := set_to_fun_sub (dominated_fin_meas_additive_weighted_smul μ) hf hg 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 [measurable_space 𝕜] [opens_measurable_space 𝕜] (c : 𝕜) (f : α → E) : ∫ a, c • (f a) ∂μ = c • ∫ a, f a ∂μ := set_to_fun_smul (dominated_fin_meas_additive_weighted_smul μ) weighted_smul_smul c f 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 (h : f =ᵐ[μ] g) : ∫ a, f a ∂μ = ∫ a, g a ∂μ := set_to_fun_congr_ae (dominated_fin_meas_additive_weighted_smul μ) h @[simp] lemma L1.integral_of_fun_eq_integral {f : α → E} (hf : integrable f μ) : ∫ a, (hf.to_L1 f) a ∂μ = ∫ a, f a ∂μ := integral_congr_ae $ by simp [integrable.coe_fn_to_L1] @[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, ← integrable.norm_to_L1_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 ∂μ) : ℝ≥0∞) ≤ ∫⁻ 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 := by simp [integral_congr_ae hf, integral_zero] /-- If `f` has finite integral, then `∫ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma has_finite_integral.tendsto_set_integral_nhds_zero {ι} {f : α → E} (hf : has_finite_integral f μ) {l : filter ι} {s : ι → set α} (hs : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫ x in s i, f x ∂μ) l (𝓝 0) := begin rw [tendsto_zero_iff_norm_tendsto_zero], simp_rw [← coe_nnnorm, ← nnreal.coe_zero, nnreal.tendsto_coe, ← ennreal.tendsto_coe, ennreal.coe_zero], exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds (tendsto_set_lintegral_zero (ne_of_lt hf) hs) (λ i, zero_le _) (λ i, ennnorm_integral_le_lintegral_ennnorm _) end /-- If `f` is integrable, then `∫ x in s, f x ∂μ` is absolutely continuous in `s`: it tends to zero as `μ s` tends to zero. -/ lemma integrable.tendsto_set_integral_nhds_zero {ι} {f : α → E} (hf : integrable f μ) {l : filter ι} {s : ι → set α} (hs : tendsto (μ ∘ s) l (𝓝 0)) : tendsto (λ i, ∫ x in s i, f x ∂μ) l (𝓝 0) := hf.2.tendsto_set_integral_nhds_zero hs /-- 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, ∥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, ∥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], convert norm_integral_le_lintegral_norm (λ x, F i x - f x), ext1 x, exact coe_nnreal_eq _ end /-- Lebesgue dominated convergence theorem provides sufficient conditions under which almost everywhere convergence of a sequence of functions implies the convergence of their integrals. We could weaken the condition `bound_integrable` to require `has_finite_integral bound μ` instead (i.e. not requiring that `bound` is measurable), but in all applications proving integrability is easier. -/ theorem tendsto_integral_of_dominated_convergence {F : ℕ → α → E} {f : α → E} (bound : α → ℝ) (F_measurable : ∀ n, ae_measurable (F n) μ) (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 /- `f` is a.e.-measurable, since it is the a.e.-pointwise limit of a.e.-measurable functions. -/ have f_measurable : ae_measurable f μ := ae_measurable_of_tendsto_metric_ae F_measurable h_lim, /- 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 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 ι} [l.is_countably_generated] {F : ι → α → E} {f : α → E} (bound : α → ℝ) (hF_meas : ∀ᶠ n in l, ae_measurable (F n) μ) (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 tendsto_iff_seq_tendsto, intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem 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 bound _ bound_integrable _ _, { intro, refine (h _ _).1, apply self_le_add_left }, { intro, refine (h _ _).2, apply self_le_add_left }, { filter_upwards [h_lim], 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 variables {X : Type*} [topological_space X] [first_countable_topology X] lemma continuous_at_of_dominated {F : X → α → E} {x₀ : X} {bound : α → ℝ} (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) μ) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ a ∂μ, ∥F x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_cont : ∀ᵐ a ∂μ, continuous_at (λ x, F x a) x₀) : continuous_at (λ x, ∫ a, F x a ∂μ) x₀ := tendsto_integral_filter_of_dominated_convergence bound ‹_› ‹_› ‹_› ‹_› lemma continuous_of_dominated {F : X → α → E} {bound : α → ℝ} (hF_meas : ∀ x, ae_measurable (F x) μ) (h_bound : ∀ x, ∀ᵐ a ∂μ, ∥F x a∥ ≤ bound a) (bound_integrable : integrable bound μ) (h_cont : ∀ᵐ a ∂μ, continuous (λ x, F x a)) : continuous (λ x, ∫ a, F x a ∂μ) := continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated (eventually_of_forall hF_meas) (eventually_of_forall h_bound) ‹_› $ h_cont.mono $ λ _, continuous.continuous_at) /-- 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_pos_part_sub_lintegral_neg_part {f : α → ℝ} (hf : integrable f μ) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) - ennreal.to_real (∫⁻ a, (ennreal.of_real $ - f a) ∂μ) := let f₁ := hf.to_L1 f in -- Go to the `L¹` space have eq₁ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) = ∥Lp.pos_part f₁∥ := begin rw L1.norm_def, congr' 1, apply lintegral_congr_ae, filter_upwards [Lp.coe_fn_pos_part f₁, hf.coe_fn_to_L1], assume a h₁ h₂, rw [h₁, h₂, ennreal.of_real], congr' 1, apply nnreal.eq, simp [real.norm_of_nonneg, le_max_right, real.coe_to_nnreal] end, -- Go to the `L¹` space have eq₂ : ennreal.to_real (∫⁻ a, (ennreal.of_real $ - f a) ∂μ) = ∥Lp.neg_part f₁∥ := begin rw L1.norm_def, congr' 1, apply lintegral_congr_ae, filter_upwards [Lp.coe_fn_neg_part f₁, hf.coe_fn_to_L1], assume a h₁ h₂, rw [h₁, h₂, ennreal.of_real], congr' 1, apply nnreal.eq, simp only [real.norm_of_nonneg, min_le_right, neg_nonneg, real.coe_to_nnreal', subtype.coe_mk], rw [← max_neg_neg, coe_nnnorm, neg_zero, real.norm_of_nonneg (le_max_right (-f a) 0)] 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 : ae_measurable f μ) : ∫ a, f a ∂μ = ennreal.to_real (∫⁻ a, (ennreal.of_real $ f a) ∂μ) := begin by_cases hfi : integrable f μ, { rw integral_eq_lintegral_pos_part_sub_lintegral_neg_part hfi, have h_min : ∫⁻ a, ennreal.of_real (-f a) ∂μ = 0, { rw lintegral_eq_zero_iff', { refine hf.mono _, simp only [pi.zero_apply], assume a h, simp only [h, neg_nonpos, of_real_eq_zero], }, { exact measurable_of_real.comp_ae_measurable hfm.neg } }, rw [h_min, 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 of_real_integral_norm_eq_lintegral_nnnorm {G} [normed_group G] [measurable_space G] [opens_measurable_space G] {f : α → G} (hf : integrable f μ) : ennreal.of_real ∫ x, ∥f x∥ ∂μ = ∫⁻ x, ∥f x∥₊ ∂μ := begin rw integral_eq_lintegral_of_nonneg_ae _ hf.1.norm, { simp_rw [of_real_norm_eq_coe_nnnorm, ennreal.of_real_to_real (lt_top_iff_ne_top.mp hf.2)], }, { refine ae_of_all _ _, simp, }, end lemma integral_eq_integral_pos_part_sub_integral_neg_part {f : α → ℝ} (hf : integrable f μ) : ∫ a, f a ∂μ = (∫ a, real.to_nnreal (f a) ∂μ) - (∫ a, real.to_nnreal (-f a) ∂μ) := begin rw [← integral_sub hf.real_to_nnreal], { simp }, { exact hf.neg.real_to_nnreal } end lemma integral_nonneg_of_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a, f a ∂μ := begin by_cases hfm : ae_measurable f μ, { rw integral_eq_lintegral_of_nonneg_ae hf hfm, exact to_real_nonneg }, { rw integral_non_ae_measurable hfm } end lemma lintegral_coe_eq_integral (f : α → ℝ≥0) (hfi : integrable (λ x, (f x : ℝ)) μ) : ∫⁻ 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.ae_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 [nnreal.nnnorm_eq] end lemma integral_to_real {f : α → ℝ≥0∞} (hfm : ae_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.ennreal_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 lintegral_coe_le_coe_iff_integral_le {f : α → ℝ≥0} (hfi : integrable (λ x, (f x : ℝ)) μ) {b : ℝ≥0} : ∫⁻ a, f a ∂μ ≤ b ↔ ∫ a, (f a : ℝ) ∂μ ≤ b := by rw [lintegral_coe_eq_integral f hfi, ennreal.of_real, ennreal.coe_le_coe, real.to_nnreal_le_iff_le_coe] lemma integral_coe_le_of_lintegral_coe_le {f : α → ℝ≥0} {b : ℝ≥0} (h : ∫⁻ a, f a ∂μ ≤ b) : ∫ a, (f a : ℝ) ∂μ ≤ b := begin by_cases hf : integrable (λ a, (f a : ℝ)) μ, { exact (lintegral_coe_le_coe_iff_integral_le hf).1 h }, { rw integral_undef hf, exact b.2 } 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_ae_measurable 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, pos_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∥ ∂μ := begin simp only [snorm, snorm', ennreal.one_to_real, ennreal.rpow_one, Lp.norm_def, if_false, ennreal.one_ne_top, one_ne_zero, _root_.div_one], rw integral_eq_lintegral_of_nonneg_ae (eventually_of_forall (by simp [norm_nonneg])) (continuous_norm.measurable.comp_ae_measurable (Lp.ae_measurable f)), simp [of_real_norm_eq_coe_nnnorm] end lemma L1.norm_of_fun_eq_integral_norm {f : α → H} (hf : integrable f μ) : ∥hf.to_L1 f∥ = ∫ a, ∥f a∥ ∂μ := begin rw L1.norm_eq_integral_norm, refine integral_congr_ae _, apply hf.coe_fn_to_L1.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) @[mono] 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 : ae_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_ae_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 : ae_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 $ ae_measurable.norm h).symm ) ( λh : ¬ae_measurable f μ, begin rw [integral_non_ae_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.to_Lp_one_eq_to_L1, L1.simple_func.integral_L1_eq_integral, L1.simple_func.integral_eq_integral], exact simple_func.integral_congr hfi (Lp.simple_func.to_simple_func_to_Lp _ _).symm end lemma simple_func.integral_eq_sum (f : α →ₛ E) (hfi : integrable f μ) : ∫ x, f x ∂μ = ∑ x in f.range, (ennreal.to_real (μ (f ⁻¹' {x}))) • x := by { rw [← f.integral_eq_integral hfi, simple_func.integral, ← simple_func.integral_eq], refl, } @[simp] lemma integral_const (c : E) : ∫ x : α, c ∂μ = (μ univ).to_real • c := begin cases (@le_top _ _ _ (μ univ)).lt_or_eq with hμ hμ, { haveI : is_finite_measure μ := ⟨hμ⟩, calc ∫ x : α, c ∂μ = (simple_func.const α c).integral μ : ((simple_func.const α c).integral_eq_integral (integrable_const _)).symm ... = _ : simple_func.integral_const _ _ }, { by_cases hc : c = 0, { simp [hc, integral_zero] }, { have : ¬integrable (λ x : α, c) μ, { simp only [integrable_const_iff, not_or_distrib], exact ⟨hc, hμ.not_lt⟩ }, simp [integral_undef, *] } } end lemma norm_integral_le_of_norm_le_const [is_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_of_measurable {f : α → E} (fmeas : measurable f) (hf : integrable f μ) : tendsto (λ n, (simple_func.approx_on f fmeas univ 0 trivial n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ) := begin have : tendsto (λ n, ∫ x, simple_func.approx_on f fmeas univ 0 trivial n x ∂μ) at_top (𝓝 $ ∫ x, f x ∂μ) := tendsto_integral_of_L1 _ hf (eventually_of_forall $ simple_func.integrable_approx_on_univ fmeas hf) (simple_func.tendsto_approx_on_univ_L1_nnnorm fmeas hf), simpa only [simple_func.integral_eq_integral, simple_func.integrable_approx_on_univ fmeas hf] end variable {ν : measure α} private lemma integral_add_measure_of_measurable {f : α → E} (fmeas : measurable f) (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_of_measurable fmeas hfi) _, simpa only [simple_func.integral_add_measure _ (simple_func.integrable_approx_on_univ fmeas hfi _)] using (tendsto_integral_approx_on_univ_of_measurable fmeas hμ).add (tendsto_integral_approx_on_univ_of_measurable fmeas hν) end lemma integral_add_measure {f : α → E} (hμ : integrable f μ) (hν : integrable f ν) : ∫ x, f x ∂(μ + ν) = ∫ x, f x ∂μ + ∫ x, f x ∂ν := begin have h : ae_measurable f (μ + ν) := hμ.ae_measurable.add_measure hν.ae_measurable, let g := h.mk f, have A : f =ᵐ[μ + ν] g := h.ae_eq_mk, have B : f =ᵐ[μ] g := A.filter_mono (ae_mono (measure.le_add_right (le_refl μ))), have C : f =ᵐ[ν] g := A.filter_mono (ae_mono (measure.le_add_left (le_refl ν))), calc ∫ x, f x ∂(μ + ν) = ∫ x, g x ∂(μ + ν) : integral_congr_ae A ... = ∫ x, g x ∂μ + ∫ x, g x ∂ν : integral_add_measure_of_measurable h.measurable_mk ((integrable_congr B).1 hμ) ((integrable_congr C).1 hν) ... = ∫ x, f x ∂μ + ∫ x, f x ∂ν : by { congr' 1, { exact integral_congr_ae B.symm }, { exact integral_congr_ae C.symm } } end @[simp] lemma integral_zero_measure {m : measurable_space α} (f : α → E) : ∫ x, f x ∂(0 : measure α) = 0 := norm_le_zero_iff.1 $ le_trans (norm_integral_le_lintegral_norm f) $ by simp private lemma integral_smul_measure_aux {f : α → E} {c : ℝ≥0∞} (h0 : c ≠ 0) (hc : c ≠ ∞) (fmeas : measurable f) (hfi : integrable f μ) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin refine tendsto_nhds_unique _ (tendsto_const_nhds.smul (tendsto_integral_approx_on_univ_of_measurable fmeas hfi)), convert tendsto_integral_approx_on_univ_of_measurable fmeas (hfi.smul_measure hc), simp only [simple_func.integral_eq, measure.smul_apply, finset.smul_sum, smul_smul, ennreal.to_real_mul] end @[simp] lemma integral_smul_measure (f : α → E) (c : ℝ≥0∞) : ∫ x, f x ∂(c • μ) = c.to_real • ∫ x, f x ∂μ := begin -- First we consider “degenerate” cases: -- `c = 0` rcases eq_or_ne c 0 with rfl|h0, { simp }, -- `f` is not almost everywhere measurable by_cases hfm : ae_measurable f μ, swap, { have : ¬ (ae_measurable f (c • μ)), by simpa [h0] using hfm, simp [integral_non_ae_measurable, hfm, this] }, -- `c = ∞` rcases eq_or_ne c ∞ 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.smul_measure ∞), 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_ne_top.2 h0), rw [smul_smul, ennreal.inv_mul_cancel h0 hc, one_smul] }, -- Main case: `0 < c < ∞`, `f` is almost everywhere measurable and integrable let g := hfm.mk f, calc ∫ x, f x ∂(c • μ) = ∫ x, g x ∂(c • μ) : integral_congr_ae $ ae_smul_measure hfm.ae_eq_mk c ... = c.to_real • ∫ x, g x ∂μ : integral_smul_measure_aux h0 hc hfm.measurable_mk $ hfi.congr hfm.ae_eq_mk ... = c.to_real • ∫ x, f x ∂μ : by { congr' 1, exact integral_congr_ae (hfm.ae_eq_mk.symm) } end lemma integral_map_of_measurable {β} [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 hfm.ae_measurable hφ] }, refine tendsto_nhds_unique (tendsto_integral_approx_on_univ_of_measurable hfm hfi) _, convert tendsto_integral_approx_on_univ_of_measurable (hfm.comp hφ) ((integrable_map_measure hfm.ae_measurable hφ).1 hfi), ext1 i, simp only [simple_func.approx_on_comp, simple_func.integral_eq, measure.map_apply, hφ, simple_func.measurable_set_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_map {β} [measurable_space β] {φ : α → β} (hφ : measurable φ) {f : β → E} (hfm : ae_measurable f (measure.map φ μ)) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := let g := hfm.mk f in calc ∫ y, f y ∂(measure.map φ μ) = ∫ y, g y ∂(measure.map φ μ) : integral_congr_ae hfm.ae_eq_mk ... = ∫ x, g (φ x) ∂μ : integral_map_of_measurable hφ hfm.measurable_mk ... = ∫ x, f (φ x) ∂μ : integral_congr_ae $ ae_eq_comp hφ (hfm.ae_eq_mk).symm lemma _root_.measurable_embedding.integral_map {β} {_ : measurable_space β} {f : α → β} (hf : measurable_embedding f) (g : β → E) : ∫ y, g y ∂(measure.map f μ) = ∫ x, g (f x) ∂μ := begin by_cases hgm : ae_measurable g (measure.map f μ), { exact integral_map hf.measurable hgm }, { rw [integral_non_ae_measurable hgm, integral_non_ae_measurable], rwa ← hf.ae_measurable_map_iff } end lemma _root_.closed_embedding.integral_map {β} [topological_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] {φ : α → β} (hφ : closed_embedding φ) (f : β → E) : ∫ y, f y ∂(measure.map φ μ) = ∫ x, f (φ x) ∂μ := hφ.measurable_embedding.integral_map _ lemma integral_map_equiv {β} [measurable_space β] (e : α ≃ᵐ β) (f : β → E) : ∫ y, f y ∂(measure.map e μ) = ∫ x, f (e x) ∂μ := e.measurable_embedding.integral_map f @[simp] lemma integral_dirac' [measurable_space α] (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 $ ae_eq_dirac' hfm ... = f a : by simp [measure.dirac_apply_of_mem] @[simp] lemma integral_dirac [measurable_space α] [measurable_singleton_class α] (f : α → E) (a : α) : ∫ x, f x ∂(measure.dirac a) = f a := calc ∫ x, f x ∂(measure.dirac a) = ∫ x, f a ∂(measure.dirac a) : integral_congr_ae $ ae_eq_dirac f ... = f a : by simp [measure.dirac_apply_of_mem] end properties section group variables {G : Type*} [measurable_space G] [topological_space G] [group G] [has_continuous_mul G] [borel_space G] variables {μ : measure G} open measure /-- Translating a function by left-multiplication does not change its integral with respect to a left-invariant measure. -/ @[to_additive] lemma integral_mul_left_eq_self (hμ : is_mul_left_invariant μ) {f : G → E} (g : G) : ∫ x, f (g * x) ∂μ = ∫ x, f x ∂μ := begin have hgμ : measure.map (has_mul.mul g) μ = μ, { rw ← map_mul_left_eq_self at hμ, exact hμ g }, have h_mul : closed_embedding (λ x, g * x) := (homeomorph.mul_left g).closed_embedding, rw [← h_mul.integral_map, hgμ], apply_instance, end /-- Translating a function by right-multiplication does not change its integral with respect to a right-invariant measure. -/ @[to_additive] lemma integral_mul_right_eq_self (hμ : is_mul_right_invariant μ) {f : G → E} (g : G) : ∫ x, f (x * g) ∂μ = ∫ x, f x ∂μ := begin have hgμ : measure.map (λ x, x * g) μ = μ, { rw ← map_mul_right_eq_self at hμ, exact hμ g }, have h_mul : closed_embedding (λ x, x * g) := (homeomorph.mul_right g).closed_embedding, rw [← h_mul.integral_map, hgμ], apply_instance, end /-- If some left-translate of a function negates it, then the integral of the function with respect to a left-invariant measure is 0. -/ @[to_additive] lemma integral_zero_of_mul_left_eq_neg (hμ : is_mul_left_invariant μ) {f : G → E} {g : G} (hf' : ∀ x, f (g * x) = - f x) : ∫ x, f x ∂μ = 0 := begin refine eq_zero_of_eq_neg ℝ (eq.symm _), have : ∫ x, f (g * x) ∂μ = ∫ x, - f x ∂μ, { congr, ext x, exact hf' x }, convert integral_mul_left_eq_self hμ g using 1, rw [this, integral_neg] end /-- If some right-translate of a function negates it, then the integral of the function with respect to a right-invariant measure is 0. -/ @[to_additive] lemma integral_zero_of_mul_right_eq_neg (hμ : is_mul_right_invariant μ) {f : G → E} {g : G} (hf' : ∀ x, f (x * g) = - f x) : ∫ x, f x ∂μ = 0 := begin refine eq_zero_of_eq_neg ℝ (eq.symm _), have : ∫ x, f (x * g) ∂μ = ∫ x, - f x ∂μ, { congr, ext x, exact hf' x }, convert integral_mul_right_eq_self hμ g using 1, rw [this, integral_neg] end end group 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 section integral_trim variables {H β γ : Type*} [normed_group H] [measurable_space H] {m m0 : measurable_space β} {μ : measure β} /-- Simple function seen as simple function of a larger `measurable_space`. -/ def simple_func.to_larger_space (hm : m ≤ m0) (f : @simple_func β m γ) : simple_func β γ := ⟨@simple_func.to_fun β m γ f, λ x, hm _ (@simple_func.measurable_set_fiber β γ m f x), @simple_func.finite_range β γ m f⟩ lemma simple_func.coe_to_larger_space_eq (hm : m ≤ m0) (f : @simple_func β m γ) : ⇑(f.to_larger_space hm) = f := rfl lemma integral_simple_func_larger_space (hm : m ≤ m0) (f : @simple_func β m F) (hf_int : integrable f μ) : ∫ x, f x ∂μ = ∑ x in (@simple_func.range β F m f), (ennreal.to_real (μ (f ⁻¹' {x}))) • x := begin simp_rw ← f.coe_to_larger_space_eq hm, have hf_int : integrable (f.to_larger_space hm) μ, by rwa simple_func.coe_to_larger_space_eq, rw simple_func.integral_eq_sum _ hf_int, congr, end lemma integral_trim_simple_func (hm : m ≤ m0) (f : @simple_func β m F) (hf_int : integrable f μ) : ∫ x, f x ∂μ = ∫ x, f x ∂(μ.trim hm) := begin have hf : @measurable _ _ m _ f, from @simple_func.measurable β F m _ f, have hf_int_m := hf_int.trim hm hf, rw [integral_simple_func_larger_space le_rfl f hf_int_m, integral_simple_func_larger_space hm f hf_int], congr, ext1 x, congr, exact (trim_measurable_set_eq hm (@simple_func.measurable_set_fiber β F m f x)).symm, end lemma integral_trim (hm : m ≤ m0) {f : β → F} (hf : @measurable β F m _ f) : ∫ x, f x ∂μ = ∫ x, f x ∂(μ.trim hm) := begin by_cases hf_int : integrable f μ, swap, { have hf_int_m : ¬ integrable f (μ.trim hm), from λ hf_int_m, hf_int (integrable_of_integrable_trim hm hf_int_m), rw [integral_undef hf_int, integral_undef hf_int_m], }, let f_seq := @simple_func.approx_on F β _ _ _ m _ hf set.univ 0 (set.mem_univ 0) _, have hf_seq_meas : ∀ n, @measurable _ _ m _ (f_seq n), from λ n, @simple_func.measurable β F m _ (f_seq n), have hf_seq_int : ∀ n, integrable (f_seq n) μ, from simple_func.integrable_approx_on_univ (hf.mono hm le_rfl) hf_int, have hf_seq_int_m : ∀ n, integrable (f_seq n) (μ.trim hm), from λ n, (hf_seq_int n).trim hm (hf_seq_meas n) , have hf_seq_eq : ∀ n, ∫ x, f_seq n x ∂μ = ∫ x, f_seq n x ∂(μ.trim hm), from λ n, integral_trim_simple_func hm (f_seq n) (hf_seq_int n), have h_lim_1 : at_top.tendsto (λ n, ∫ x, f_seq n x ∂μ) (𝓝 (∫ x, f x ∂μ)), { refine tendsto_integral_of_L1 f hf_int (eventually_of_forall hf_seq_int) _, exact simple_func.tendsto_approx_on_univ_L1_nnnorm (hf.mono hm le_rfl) hf_int, }, have h_lim_2 : at_top.tendsto (λ n, ∫ x, f_seq n x ∂μ) (𝓝 (∫ x, f x ∂(μ.trim hm))), { simp_rw hf_seq_eq, refine @tendsto_integral_of_L1 β F _ _ _ _ _ _ m (μ.trim hm) _ f (hf_int.trim hm hf) _ _ (eventually_of_forall hf_seq_int_m) _, exact @simple_func.tendsto_approx_on_univ_L1_nnnorm β F m _ _ _ _ f _ hf (hf_int.trim hm hf), }, exact tendsto_nhds_unique h_lim_1 h_lim_2, end lemma integral_trim_ae (hm : m ≤ m0) {f : β → F} (hf : ae_measurable f (μ.trim hm)) : ∫ x, f x ∂μ = ∫ x, f x ∂(μ.trim hm) := begin rw [integral_congr_ae (ae_eq_of_ae_eq_trim hf.ae_eq_mk), integral_congr_ae hf.ae_eq_mk], exact integral_trim hm hf.measurable_mk, end lemma ae_eq_trim_of_measurable [measurable_space γ] [add_group γ] [measurable_singleton_class γ] [has_measurable_sub₂ γ] (hm : m ≤ m0) {f g : β → γ} (hf : @measurable _ _ m _ f) (hg : @measurable _ _ m _ g) (hfg : f =ᵐ[μ] g) : f =ᵐ[μ.trim hm] g := begin rwa [eventually_eq, ae_iff, trim_measurable_set_eq hm _], exact (@measurable_set.compl β _ m (@measurable_set_eq_fun β m γ _ _ _ _ _ _ hf hg)), end lemma ae_eq_trim_iff [measurable_space γ] [add_group γ] [measurable_singleton_class γ] [has_measurable_sub₂ γ] (hm : m ≤ m0) {f g : β → γ} (hf : @measurable _ _ m _ f) (hg : @measurable _ _ m _ g) : f =ᵐ[μ.trim hm] g ↔ f =ᵐ[μ] g := ⟨ae_eq_of_ae_eq_trim, ae_eq_trim_of_measurable hm hf hg⟩ end integral_trim end measure_theory
3fa1eaa36b0a7fc707f2868a5d2c4104c92ee08c
ce89339993655da64b6ccb555c837ce6c10f9ef4
/bluejam/chap5_exercise3.lean
36f33d7bc1c3583c08aa2ba9057c7efa8e3c662c
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
5,924
lean
open classical variables p q r s : Prop theorem t1 : p → q → p := begin intros hp hq, exact hp end theorem t2 (h₁ : q → r) (h₂ : p → q) : p → r := begin intro hp, apply h₁, apply h₂, exact hp end -- commutativity of ∧ and ∨ example : p ∧ q ↔ q ∧ p := begin apply iff.intro, intro h, cases h with hp hq, constructor, repeat { assumption }, intro h, cases h with hq hp, constructor, repeat { assumption } end example : p ∨ q ↔ q ∨ p := begin apply iff.intro, intro h, cases h with hp hq, right, exact hp, left, exact hq, intro h, cases h with hq hp, right, exact hq, left, exact hp end -- associativity of ∧ and ∨ example : (p ∧ q) ∧ r ↔ p ∧ (q ∧ r) := begin apply iff.intro, { intro h, cases h with hpq hr, cases hpq with hp hq, repeat { split; try { assumption } } }, intro h, cases h with hp hqr, cases hqr with hq hr, repeat { split; try { assumption } } end example : (p ∨ q) ∨ r ↔ p ∨ (q ∨ r) := begin apply iff.intro, { intro h, cases h with hpq hr, { cases hpq with hp hq, { apply or.intro_left, assumption}, apply or.intro_right, exact or.intro_left r hq }, apply or.intro_right, show q ∨ r, exact or.intro_right q hr }, intro h, cases h with hp hqr, { apply or.intro_left, exact or.intro_left q hp }, cases hqr with hq hr, { apply or.intro_left, exact or.intro_right p hq }, apply or.intro_right, assumption end -- distributivity example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := begin apply iff.intro, intro h, cases h with hp hqr, cases hqr with hq hr, apply or.intro_left, split, repeat { assumption }, apply or.intro_right, split, repeat { assumption }, intro h, cases h with hpq hpr, split, exact hpq.left, exact or.intro_left r hpq.right, split, exact hpr.left, exact or.intro_right q hpr.right end example : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (p ∨ r) := begin apply iff.intro, intro h, cases h with hp hqr, { split; apply or.intro_left; assumption }, cases hqr with hq hr, { split; apply or.intro_right; assumption }, intro h, cases h with hpq hpr, cases hpq with hp hq, apply or.intro_left, assumption, cases hpr with hp hr, apply or.intro_left, assumption, apply or.intro_right, split; assumption end -- other properties example : (p → (q → r)) ↔ (p ∧ q → r) := begin apply iff.intro, intros h hpq, exact h hpq.left hpq.right, intros h hp hq, exact h ⟨hp, hq⟩ end example : ((p ∨ q) → r) ↔ (p → r) ∧ (q → r) := begin apply iff.intro, intro h, split, intro, exact h (or.intro_left q a), intro, exact h (or.intro_right p a), intros h hpq, cases h with hpr hqr, cases hpq with hp hq, exact hpr hp, exact hqr hq end example : ¬(p ∨ q) ↔ ¬p ∧ ¬q := begin apply iff.intro, intro h, split, intro, exact absurd (or.intro_left q a) h, intro, exact absurd (or.intro_right p a) h, intros h hpq, cases hpq with hp hq, exact h.left hp, exact h.right hq end example : ¬p ∨ ¬q → ¬(p ∧ q) := begin intros h hnpq, cases h with hnp hnq, exact hnp hnpq.left, exact hnq hnpq.right end example : ¬(p ∧ ¬p) := begin intro h, exact h.right h.left end example : p ∧ ¬q → ¬(p → q) := begin intros h hpq, exact h.right (hpq h.left) end example : ¬p → (p → q) := begin intros, contradiction end example : (¬p ∨ q) → (p → q) := begin intros hpq hp, cases hpq, contradiction, assumption end example : p ∨ false ↔ p := begin apply iff.intro, intro, cases a, assumption, contradiction, intro, left, assumption end example : p ∧ false ↔ false := begin apply iff.intro, intro, exact a.right, intro, contradiction end example : ¬(p ↔ ¬p) := begin intro, cases a, have hnp: ¬ p, intros hp, have : ¬ p, apply a_mp, assumption, contradiction, have : p, apply a_mpr, assumption, contradiction end example : (p → q) → (¬q → ¬p) := begin intros hpq hnq hp, have : q, apply hpq, assumption, contradiction end -- these require classical reasoning example : (p → r ∨ s) → ((p → r) ∨ (p → s)) := begin intro h, apply by_cases, intro, left, assumption, intro hnpr, right, intro hp, cases h hp with hr hs, have hpr : p → r, intros, assumption, contradiction, assumption end example : ¬(p ∧ q) → ¬p ∨ ¬q := begin intro hnpq, apply by_cases, intro hp, right, intro hq, have : p ∧ q, split; assumption, contradiction, intro hnp, left, assumption end example : ¬(p → q) → p ∧ ¬q := begin intro h, split, apply by_cases, intro hp, assumption, intro hnp, have : p → q, intros, contradiction, contradiction, apply not.intro, intro hq, have : p → q, intros, assumption, contradiction end example : (p → q) → (¬p ∨ q) := begin intro, apply by_cases, intro hp, right, exact a hp, intro h, left, assumption end example : (¬q → ¬p) → (p → q) := begin intros, apply by_contradiction, intro hnq, have : ¬ p, apply a, assumption, contradiction end example : p ∨ ¬p := begin apply em end example : p ∨ ¬p := begin apply by_cases, intro hp, left, assumption, intro hnp, right, assumption end example : (((p → q) → p) → p) := begin intros, apply by_cases, intro, exact a a_1, intro, apply by_contradiction, intro, have h : p → q, intros, contradiction, contradiction end
07bc02e22ea6ecca276b2201211558e1820c19b6
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20170116_POPL/super/clauses.lean
0bc7b1fa9f50aa1ee88397e62a1ba11d986fcf2e
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
1,994
lean
import tools.super open super tactic monad meta def trivial_term_order (a b : expr) := ff -- most inferences in super require a term order -- Let's look at how clauses are handled in super. -- (I'm writing (¬¬q 4) instead of (q 4) here because otherwise super would pull -- some tricks to produce intuitionist proofs.) example (p q : ℕ → Prop) : p 3 → (∀x, p x → q (x+1)) → ¬¬q 4 := by do trace "refutation problem:", -- If we didn't already have a refutational problem, `as_refutation` would add -- the double negation. In addition it does `intros`. as_refutation, trace_state, trace "", trace "cnf:", -- This step only parses the formula into clauses. They can still contain -- propositional connectives--these are handled during preprocessing in the prover. c1 ← get_local `a >>= clause.of_classical_proof, c2 ← get_local `a_1 >>= clause.of_classical_proof, c3 ← get_local `a_2 >>= clause.of_classical_proof, trace [c1, c2, c3], -- Whenever super generates a new clause in an inference, it immediately -- generates a proof of it. To prevent the proof sizes from exploding -- exponentially, super then uses `assert` to store the derived clause in the -- local context, from then on we can refer to its proof via a local constant. -- Hence each clause needs to have a type, the type of its proof. This type is -- slightly ugly, but makes the implementation more uniform: trace "", trace "actual type of the proof of the second clause:", trace c2^.type, -- We can now do the required resolution inferences by hand. Internally, the -- `try_resolve` function instantiates the universal quantifiers with -- meta-variables and then unifies the specified literals. trace "", trace "two resolution inferences are required:", c4 ← try_resolve trivial_term_order c1 c2 0 0, trace c4, c5 ← try_resolve trivial_term_order c4 c3 0 0, trace c5, -- We now have a proof of false (the type of the empty clause) and are done. trace c5^.proof, trace c5^.type, exact c5^.proof
dbfb1e0bc19cfc27b07b6a81c12849e49f3849f2
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/tests/lean/run/doc_string3.lean
454422266d0013454d8027eb1dcb20510bf2f0bd
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
303
lean
/-! Documentation header for test module -/ /-- Documentation for x -/ def x := 10 namespace foo /-! Another block of documentation for this example. -/ /-- Documentation for y -/ def y := 20 end foo /-! Documentation footer testing -/ open tactic run_command module_doc_strings >>= trace
b6d5cedc899d4b3ec2c8a137fa052278275a5265
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Exception.lean
ff898eb1af0f46eb16afe6b6a700005714ad76a0
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
6,128
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Message import Lean.InternalExceptionId import Lean.Data.Options import Lean.Util.MonadCache namespace Lean /-- Exception type used in most Lean monads -/ inductive Exception where | /-- Error messages that are displayed to users. `ref` is used to provide position information. -/ error (ref : Syntax) (msg : MessageData) | /-- Internal exceptions that are not meant to be seen by users. Examples: "pospone elaboration", "stuck at universe constraint", etc -/ internal (id : InternalExceptionId) (extra : KVMap := {}) /-- Convert exception into a structured message. -/ def Exception.toMessageData : Exception → MessageData | .error _ msg => msg | .internal id _ => id.toString /-- Return syntax object providing position information for the exception. Recall that internal exceptions do not have position information. -/ def Exception.getRef : Exception → Syntax | .error ref _ => ref | .internal _ _ => Syntax.missing instance : Inhabited Exception := ⟨Exception.error default default⟩ /-- Similar to `AddMessageContext`, but for error messages. The default instance just uses `AddMessageContext`. In error messages, we may want to provide additional information (e.g., macro expansion stack), and refine the `(ref : Syntax)`. -/ class AddErrorMessageContext (m : Type → Type) where add : Syntax → MessageData → m (Syntax × MessageData) instance (m : Type → Type) [AddMessageContext m] [Monad m] : AddErrorMessageContext m where add ref msg := do let msg ← addMessageContext msg pure (ref, msg) class abbrev MonadError (m : Type → Type) := MonadExceptOf Exception m MonadRef m AddErrorMessageContext m section Methods /-- Throw an error exception using the given message data. The result of `getRef` is used as position information. Recall that `getRef` returns the current "reference" syntax. -/ protected def throwError [Monad m] [MonadError m] (msg : MessageData) : m α := do let ref ← getRef let (ref, msg) ← AddErrorMessageContext.add ref msg throw <| Exception.error ref msg /-- Thrown an unknown constant error message. -/ def throwUnknownConstant [Monad m] [MonadError m] (constName : Name) : m α := Lean.throwError m!"unknown constant '{mkConst constName}'" /-- Throw an error exception using the given message data and reference syntax. -/ protected def throwErrorAt [Monad m] [MonadError m] (ref : Syntax) (msg : MessageData) : m α := do withRef ref <| Lean.throwError msg /-- Convert an `Except` into a `m` monadic action, where `m` is any monad that implements `MonadError`. -/ def ofExcept [Monad m] [MonadError m] [ToString ε] (x : Except ε α) : m α := match x with | .ok a => return a | .error e => Lean.throwError <| toString e /-- Throw an error exception for the given kernel exception. -/ def throwKernelException [Monad m] [MonadError m] [MonadOptions m] (ex : KernelException) : m α := do Lean.throwError <| ex.toMessageData (← getOptions) end Methods class MonadRecDepth (m : Type → Type) where withRecDepth {α} : Nat → m α → m α getRecDepth : m Nat getMaxRecDepth : m Nat instance [Monad m] [MonadRecDepth m] : MonadRecDepth (ReaderT ρ m) where withRecDepth d x := fun ctx => MonadRecDepth.withRecDepth d (x ctx) getRecDepth := fun _ => MonadRecDepth.getRecDepth getMaxRecDepth := fun _ => MonadRecDepth.getMaxRecDepth instance [Monad m] [MonadRecDepth m] : MonadRecDepth (StateRefT' ω σ m) := inferInstanceAs (MonadRecDepth (ReaderT _ _)) instance [BEq α] [Hashable α] [Monad m] [STWorld ω m] [MonadRecDepth m] : MonadRecDepth (MonadCacheT α β m) := inferInstanceAs (MonadRecDepth (StateRefT' _ _ _)) /-- Throw a "maximum recursion depth has been reached" exception using the given reference syntax. -/ def throwMaxRecDepthAt [MonadError m] (ref : Syntax) : m α := throw <| .error ref (MessageData.ofFormat (Std.Format.text maxRecDepthErrorMessage)) /-- Return true if `ex` was generated by `throwMaxRecDepthAt`. This function is a bit hackish. The max rec depth exception should probably be an internal exception, but it is also produced by `MacroM` which implemented in the prelude, and internal exceptions have not been defined yet. -/ def Exception.isMaxRecDepth (ex : Exception) : Bool := match ex with | error _ (MessageData.ofFormat (Std.Format.text msg)) => msg == maxRecDepthErrorMessage | _ => false /-- Increment the current recursion depth and then execute `x`. Throw an exception if maximum recursion depth has been reached. We use this combinator to prevent stack overflows. -/ @[inline] def withIncRecDepth [Monad m] [MonadError m] [MonadRecDepth m] (x : m α) : m α := do let curr ← MonadRecDepth.getRecDepth let max ← MonadRecDepth.getMaxRecDepth if curr == max then throwMaxRecDepthAt (← getRef) else MonadRecDepth.withRecDepth (curr+1) x /-- Macro for throwing error exceptions. The argument can be an interpolated string. It is a convenient way of building `MessageData` objects. The result of `getRef` is used as position information. Recall that `getRef` returns the current "reference" syntax. -/ syntax "throwError " (interpolatedStr(term) <|> term) : term /-- Macro for throwing error exceptions. The argument can be an interpolated string. It is a convenient way of building `MessageData` objects. The first argument must be a `Syntax` that provides position information for the error message. `throwErrorAt ref msg` is equivalent to `withRef ref <| throwError msg` -/ syntax "throwErrorAt " term:max (interpolatedStr(term) <|> term) : term macro_rules | `(throwError $msg:interpolatedStr) => `(Lean.throwError (m! $msg)) | `(throwError $msg:term) => `(Lean.throwError $msg) macro_rules | `(throwErrorAt $ref $msg:interpolatedStr) => `(Lean.throwErrorAt $ref (m! $msg)) | `(throwErrorAt $ref $msg:term) => `(Lean.throwErrorAt $ref $msg) end Lean
e45d281171e48287cd1a74d51518c6016812c2fe
5d76f062116fa5bd22eda20d6fd74da58dba65bb
/src/general_lemmas/single_antidiagonal.lean
88f753c8be9f8aa950793c81c9f5b4c03ba1ea6d
[]
no_license
brando90/formal_baby_snark
59e4732dfb43f97776a3643f2731262f58d2bb81
4732da237784bd461ff949729cc011db83917907
refs/heads/master
1,682,650,246,414
1,621,103,975,000
1,621,103,975,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,785
lean
import data.finsupp.basic import data.finset.basic -- import ..vars section parameter {S : Type} parameter [decidable_eq S] /-- A general lemma about the anitdiagonal of a finsupp.single. -/ lemma single_antidiagonal_support (s : S) (n : ℕ) : (finsupp.single s n).antidiagonal.support = (finset.range (n+1)).image (λ i, (finsupp.single s (n-i), finsupp.single s (i))) := begin rw finset.ext_iff, intro a, rw finsupp.mem_antidiagonal_support, rw finset.mem_image, split, intro h, use a.snd s, split, rw finsupp.ext_iff at h, have h1 := h s, simp at h1, rw finset.mem_range, rw ←h1, apply @nat.lt_of_lt_of_le (a.snd s) (a.snd s + 1) _, exact lt_add_one ((a.snd) s), rw add_assoc, exact ((a.snd) s + 1).le_add_left ((a.fst) s), rw prod.ext_iff, simp, split, rw finsupp.ext_iff, intro a_1, rw finsupp.nat_sub_apply, rw finsupp.single_apply, rw finsupp.single_apply, by_cases h2 : a_1 = s, rw h2, simp, have h3 : (a.fst + a.snd) s = (finsupp.single s n) s, rw h, rw finsupp.add_apply at h3, rw finsupp.single_apply at h3, simp at h3, rw ←h3, simp, rw if_neg, rw if_neg, have h3 : (a.fst + a.snd) a_1 = (finsupp.single s n) a_1, rw h, rw finsupp.add_apply at h3, rw finsupp.single_apply at h3, simp at h3, rw if_neg at h3, rw add_eq_zero_iff at h3, rw h3.left, finish, finish, finish, rw finsupp.ext_iff, intro a_1, rw finsupp.single_apply, by_cases h2 : a_1 = s, rw h2, simp, rw if_neg, have h3 : (a.fst + a.snd) a_1 = (finsupp.single s n) a_1, rw h, rw finsupp.add_apply at h3, rw finsupp.single_apply at h3, simp at h3, rw if_neg at h3, rw add_eq_zero_iff at h3, rw h3.right, finish, finish, intro h, cases h, cases h_h, let h1 := prod.ext_iff.1 h_h_h, rw [←h1.left, ←h1.right], simp, rw [←finsupp.single_sub, ←finsupp.single_add], rw finset.mem_range at h_h_w, have h4 : n - h_w + h_w = n, rw nat.lt_succ_iff at h_h_w, exact nat.sub_add_cancel h_h_w, rw h4, end -- TODO make a lemma about how the antidiagonal of a sum of disjoint support finsupps is given by taking the product over the individual antidiagonals and summing. /-- A copy of the square_antidiagonal lemma, which relies on the more general single_antidiagonal_support rather than being self contained. -/ lemma single_2_antidiagonal_support (s : S) : (finsupp.single s 2).antidiagonal.support = { (finsupp.single s 0, finsupp.single s 2), (finsupp.single s 1, finsupp.single s 1), (finsupp.single s 2, finsupp.single s 0), } := begin rw single_antidiagonal_support s 2, rw finset.ext_iff, intro a, rw finset.range, rw finset.image, simp [-finsupp.single_sub], end end
e7080f8c90a54d20c7e0f8a8d37bba1c69b19b6a
367134ba5a65885e863bdc4507601606690974c1
/archive/imo/imo1988_q6.lean
b4fbd82c7a518de18a08d8af0467215f3a2b0671
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
13,855
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.nat.prime import data.rat.basic import order.well_founded import tactic.linarith import tactic.omega /-! # IMO 1988 Q6 and constant descent Vieta jumping Question 6 of IMO1988 is somewhat (in)famous. Several expert problem solvers could not tackle the question within the given time limit. The problem lead to the introduction of a new proof technique, so called “Vieta jumping”. In this file we formalise constant descent Vieta jumping, and apply this to prove Q6 of IMO1988. To illustrate the technique, we also prove a similar result. -/ -- open_locale classical local attribute [instance] classical.prop_decidable local attribute [simp] pow_two /-- Constant descent Vieta jumping. This proof technique allows one to prove an arbitrary proposition `claim`, by running a descent argument on a hyperbola `H` in the first quadrant of the plane, under the following conditions: * `h₀` : There exists an integral point `(x,y)` on the hyperbola `H`. * `H_symm` : The hyperbola has a symmetry along the diagonal in the plane. * `H_zero` : If an integral point `(x,0)` lies on the hyperbola `H`, then `claim` is true. * `H_diag` : If an integral point `(x,x)` lies on the hyperbola `H`, then `claim` is true. * `H_desc` : If `(x,y)` is an integral point on the hyperbola `H`, with `x < y` then there exists a “smaller” point on `H`: a point `(x',y')` with `x' < y' ≤ x`. For reasons of usability, the hyperbola `H` is implemented as an arbitrary predicate. (In question 6 of IMO1988, where this proof technique was first developped, the predicate `claim` would be `∃ (d : ℕ), d ^ 2 = k` for some natural number `k`, and the predicate `H` would be `λ a b, a * a + b * b = (a * b + 1) * k`.) To ensure that the predicate `H` actually describes a hyperbola, the user must provide arguments `B` and `C` that are used as coefficients for a quadratic equation. Finally, `H_quad` is the proof obligation that the quadratic equation `(y:ℤ) * y - B x * y + C x = 0` describes the same hyperbola as the predicate `H`. For extra flexibility, one must provide a predicate `base` on the integral points in the plane. In the descent step `H_desc` this will give the user the additional assumption that the point `(x,y)` does not lie in this base locus. The user must provide a proof that the proposition `claim` is true if there exists an integral point `(x,y)` on the hyperbola `H` that lies in the base locus. If such a base locus is not necessary, once can simply let it be `λ x y, false`. -/ lemma constant_descent_vieta_jumping (x y : ℕ) {claim : Prop} {H : ℕ → ℕ → Prop} (h₀ : H x y) (B : ℕ → ℤ) (C : ℕ → ℤ) (base : ℕ → ℕ → Prop) (H_quad : ∀ {x y}, H x y ↔ (y:ℤ) * y - B x * y + C x = 0) (H_symm : ∀ {x y}, H x y ↔ H y x) (H_zero : ∀ {x}, H x 0 → claim) (H_diag : ∀ {x}, H x x → claim) (H_desc : ∀ {x y}, 0 < x → x < y → ¬base x y → H x y → ∀ y', y' * y' - B x * y' + C x = 0 → y' = B x - y → y' * y = C x → 0 ≤ y' ∧ y' ≤ x) (H_base : ∀ {x y}, H x y → base x y → claim) : claim := begin -- First of all, we may assume that x ≤ y. -- We justify this using H_symm. wlog hxy : x ≤ y, swap, { rw H_symm at h₀, solve_by_elim }, -- In fact, we can easily deal with the case x = y. by_cases x_eq_y : x = y, {subst x_eq_y, exact H_diag h₀}, -- Hence we may assume that x < y. replace hxy : x < y := lt_of_le_of_ne hxy x_eq_y, clear x_eq_y, -- Consider the upper branch of the hyperbola defined by H. let upper_branch : set (ℕ × ℕ) := {p | H p.1 p.2 ∧ p.1 < p.2}, -- Note that the point p = (x,y) lies on the upper branch. let p : ℕ × ℕ := ⟨x,y⟩, have hp : p ∈ upper_branch := ⟨h₀, hxy⟩, -- We also consider the exceptional set of solutions (a,b) that satisfy -- a = 0 or a = b or B a = b or B a = b + a or that lie in the base locus. let exceptional : set (ℕ × ℕ) := {p | H p.1 p.2 ∧ (base p.1 p.2 ∨ p.1 = 0 ∨ p.1 = p.2 ∨ B p.1 = p.2 ∨ B p.1 = p.2 + p.1) }, -- Let S be the projection of the upper branch on to the y-axis -- after removing the exceptional locus. let S : set ℕ := prod.snd '' (upper_branch \ exceptional), -- The strategy is to show that the exceptional locus in nonempty -- by running a descent argument that starts with the given point p = (x,y). -- Our assumptions ensure that we can then prove the claim. suffices exc : exceptional.nonempty, { -- Suppose that there exists an element in the exceptional locus. simp [exceptional, -add_comm, set.nonempty] at exc, -- Let (a,b) be such an element, and consider all the possible cases. rcases exc with ⟨a, b, hH, hb⟩, rcases hb with _|rfl|rfl|hB|hB, -- The first three cases are rather easy to solve. { solve_by_elim }, { rw H_symm at hH, solve_by_elim }, { solve_by_elim }, -- The final two cases are very similar. all_goals { -- Consider the quadratic equation that (a,b) satisfies. rw H_quad at hH, -- We find the other root of the equation, and Vieta's formulas. rcases Vieta_formula_quadratic hH with ⟨c, h_root, hV₁, hV₂⟩, -- By substitutions we find that b = 0 or b = a. simp [hB] at hV₁, subst hV₁, rw [← int.coe_nat_zero] at *, rw ← H_quad at h_root, -- And hence we are done by H_zero and H_diag. solve_by_elim } }, -- To finish the main proof, we need to show that the exceptional locus is nonempty. -- So we assume that the exceptional locus is empty, and work towards dering a contradiction. rw ← set.ne_empty_iff_nonempty, assume exceptional_empty, -- Observe that S is nonempty. have S_nonempty : S.nonempty, { -- It contains the image of p. use p.2, apply set.mem_image_of_mem, -- After all, we assumed that the exceptional locus is empty. rwa [exceptional_empty, set.diff_empty], }, -- We are now set for an infinite descent argument. -- Let m be the smallest element of the nonempty set S. let m : ℕ := well_founded.min nat.lt_wf S S_nonempty, have m_mem : m ∈ S := well_founded.min_mem nat.lt_wf S S_nonempty, have m_min : ∀ k ∈ S, ¬ k < m := λ k hk, well_founded.not_lt_min nat.lt_wf S S_nonempty hk, -- It suffices to show that there is point (a,b) with b ∈ S and b < m. suffices hp' : ∃ p' : ℕ × ℕ, p'.2 ∈ S ∧ p'.2 < m, { rcases hp' with ⟨p', p'_mem, p'_small⟩, solve_by_elim }, -- Let (m_x, m_y) be a point on the upper branch that projects to m ∈ S -- and that does not lie in the exceptional locus. rcases m_mem with ⟨⟨mx, my⟩, ⟨⟨hHm, mx_lt_my⟩, h_base⟩, m_eq⟩, -- This means that m_y = m, -- and the conditions H(m_x, m_y) and m_x < m_y are satisfied. simp [exceptional, hHm] at mx_lt_my h_base m_eq, push_neg at h_base, -- Finally, it also means that (m_x, m_y) does not lie in the base locus, -- that m_x ≠ 0, m_x ≠ m_y, B(m_x) ≠ m_y, and B(m_x) ≠ m_x + m_y. rcases h_base with ⟨h_base, hmx, hm_diag, hm_B₁, hm_B₂⟩, replace hmx : 0 < mx := pos_iff_ne_zero.mpr hmx, -- Consider the quadratic equation that (m_x, m_y) satisfies. have h_quad := hHm, rw H_quad at h_quad, -- We find the other root of the equation, and Vieta's formulas. rcases Vieta_formula_quadratic h_quad with ⟨c, h_root, hV₁, hV₂⟩, -- No we rewrite Vietas formulas a bit, and apply the descent step. replace hV₁ : c = B mx - my := eq_sub_of_add_eq' hV₁, rw mul_comm at hV₂, have Hc := H_desc hmx mx_lt_my h_base hHm c h_root hV₁ hV₂, -- This means that we may assume that c ≥ 0 and c ≤ m_x. cases Hc with c_nonneg c_lt, -- In other words, c is a natural number. lift c to ℕ using c_nonneg, -- Recall that we are trying find a point (a,b) such that b ∈ S and b < m. -- We claim that p' = (c, m_x) does the job. let p' : ℕ × ℕ := ⟨c, mx⟩, use p', -- The second condition is rather easy to check, so we do that first. split, swap, { rwa m_eq at mx_lt_my }, -- Now we need to show that p' projects onto S. In other words, that c ∈ S. -- We do that, by showing that it lies in the upper branch -- (which is sufficient, because we assumed that the exceptional locus is empty). apply set.mem_image_of_mem, rw [exceptional_empty, set.diff_empty], -- Now we are ready to prove that p' = (c, m_x) lies on the upper branch. -- We need to check two conditions: H(c, m_x) and c < m_x. split; dsimp only, { -- The first condition is not so hard. After all, c is the other root of the quadratic equation. rw [H_symm, H_quad], simpa using h_root, }, { -- For the second condition, we note that it suffices to check that c ≠ m_x. suffices hc : c ≠ mx, { refine lt_of_le_of_ne _ hc, exact_mod_cast c_lt, }, -- However, recall that B(m_x) ≠ m_x + m_y. -- If c = m_x, we can prove B(m_x) = m_x + m_y. contrapose! hm_B₂, subst c, simp [hV₁], } -- Hence p' = (c, m_x) lies on the upper branch, and we are done. end /--Question 6 of IMO1988. If a and b are two natural numbers such that a*b+1 divides a^2 + b^2, show that their quotient is a perfect square.-/ lemma imo1988_q6 {a b : ℕ} (h : (a*b+1) ∣ a^2 + b^2) : ∃ d, d^2 = (a^2 + b^2)/(a*b + 1) := begin rcases h with ⟨k, hk⟩, rw [hk, nat.mul_div_cancel_left _ (nat.succ_pos (a*b))], simp only [pow_two] at hk, apply constant_descent_vieta_jumping a b hk (λ x, k * x) (λ x, x*x - k) (λ x y, false); clear hk a b, { -- We will now show that the fibers of the solution set are described by a quadratic equation. intros x y, dsimp only, rw [← int.coe_nat_inj', ← sub_eq_zero], apply eq_iff_eq_cancel_right.2, norm_cast, simp, ring, }, { -- Show that the solution set is symmetric in a and b. intros x y, simp [add_comm (x*x), mul_comm x], }, { -- Show that the claim is true if b = 0. suffices : ∀ a, a * a = k → ∃ d, d * d = k, by simpa, rintros x rfl, use x }, { -- Show that the claim is true if a = b. intros x hx, suffices : k ≤ 1, { rw [nat.le_add_one_iff, nat.le_zero_iff] at this, rcases this with rfl|rfl, { use 0, simp }, { use 1, simp } }, contrapose! hx with k_lt_one, apply ne_of_lt, calc x*x + x*x = x*x * 2 : by rw mul_two ... ≤ x*x * k : nat.mul_le_mul_left (x*x) k_lt_one ... < (x*x + 1) * k : by linarith }, { -- Show the descent step. intros x y hx x_lt_y hxky h z h_root hV₁ hV₀, split, { dsimp [-sub_eq_add_neg] at *, have hpos : z*z + x*x > 0, { apply add_pos_of_nonneg_of_pos, { apply mul_self_nonneg }, { apply mul_pos; exact_mod_cast hx }, }, have hzx : z*z + x*x = (z * x + 1) * k, { rw [← sub_eq_zero, ← h_root], ring, }, rw hzx at hpos, replace hpos : z * x + 1 > 0 := pos_of_mul_pos_right hpos (int.coe_zero_le k), replace hpos : z * x ≥ 0 := int.le_of_lt_add_one hpos, apply nonneg_of_mul_nonneg_right hpos (by exact_mod_cast hx), }, { contrapose! hV₀ with x_lt_z, apply ne_of_gt, calc z * y > x*x : by apply mul_lt_mul'; linarith ... ≥ x*x - k : sub_le_self _ (int.coe_zero_le k) }, }, { -- There is no base case in this application of Vieta jumping. simp }, end /- The following example illustrates the use of constant descent Vieta jumping in the presence of a non-trivial base case. -/ example {a b : ℕ} (h : a*b ∣ a^2 + b^2 + 1) : 3*a*b = a^2 + b^2 + 1 := begin rcases h with ⟨k, hk⟩, suffices : k = 3, { simp * at *, ring, }, simp only [pow_two] at hk, apply constant_descent_vieta_jumping a b hk (λ x, k * x) (λ x, x*x + 1) (λ x y, x ≤ 1); clear hk a b, { -- We will now show that the fibers of the solution set are described by a quadratic equation. intros x y, dsimp only, rw [← int.coe_nat_inj', ← sub_eq_zero], apply eq_iff_eq_cancel_right.2, simp, ring, }, { -- Show that the solution set is symmetric in a and b. cc }, { -- Show that the claim is true if b = 0. simp }, { -- Show that the claim is true if a = b. intros x hx, have x_sq_dvd : x*x ∣ x*x*k := dvd_mul_right (x*x) k, rw ← hx at x_sq_dvd, obtain ⟨y, hy⟩ : x * x ∣ 1 := by simpa only [nat.dvd_add_self_left, add_assoc] using x_sq_dvd, obtain ⟨rfl,rfl⟩ : x = 1 ∧ y = 1 := by simpa [nat.mul_eq_one_iff] using hy.symm, simpa using hx.symm, }, { -- Show the descent step. intros x y x_lt_y hx h_base h z h_root hV₁ hV₀, split, { have zy_pos : z * y ≥ 0, { rw hV₀, exact_mod_cast (nat.zero_le _) }, apply nonneg_of_mul_nonneg_right zy_pos, linarith }, { contrapose! hV₀ with x_lt_z, apply ne_of_gt, push_neg at h_base, calc z * y > x * y : by apply mul_lt_mul_of_pos_right; linarith ... ≥ x * (x + 1) : by apply mul_le_mul; linarith ... > x * x + 1 : begin rw [mul_add, mul_one], apply add_lt_add_left, assumption_mod_cast end, } }, { -- Show the base case. intros x y h h_base, obtain rfl|rfl : x = 0 ∨ x = 1 := by rwa [nat.le_add_one_iff, nat.le_zero_iff] at h_base, { simpa using h, }, { simp only [mul_one, one_mul, add_comm, zero_add] at h, have y_dvd : y ∣ y * k := dvd_mul_right y k, rw [← h, ← add_assoc, nat.dvd_add_left (dvd_mul_left y y)] at y_dvd, obtain rfl|rfl : y = 1 ∨ y = 2 := nat.prime_two.2 y y_dvd, all_goals { ring at h, omega } } } end
3a5eda6e05fa67641d182d0750d54631a3db0c31
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/meta/expr.lean
d8bd012322f83041db156226b3f3fab4a88b35ee
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
2,194
lean
/- Copyright (c) 2017 Simon Hudon All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Traversal for Lean expressions -/ universes u v section expr open expr variables {m : Type → Type u} [monad m] variables {elab elab' : bool} variables f : expr elab → m (expr elab') /- only traverses the direct descendents -/ meta def expr.traverse : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> mmap f es meta def expr.list_local_const (e : expr) : list expr := e.fold [] (λ e' _ es, if expr.is_local_constant e' ∧ ¬ e' ∈ es then e' :: es else es) end expr namespace tactic open expr binder_info meta def pis : list expr → expr → tactic expr | (e@(local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ pi pp info t (abstract_local f' uniq) | _ f := pure f meta def last_explicit_arg : expr → tactic expr | (app f e) := do t ← infer_type f >>= whnf, if t.binding_info = binder_info.default then pure e else last_explicit_arg f | e := pure e private meta def get_expl_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_expl_pi_arity_aux new_b, if bi = default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of the given (Pi-)type -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of the given function -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity end tactic
860daf4bdce4a4a45904122102d9e357f2564027
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/depElim1.lean
273d186476f84a336857887130550a46100b228e
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,602
lean
import Lean.Meta.Match open Lean open Lean.Meta open Lean.Meta.Match /- Infrastructure for testing -/ universes u v def check (x : Bool) : IO Unit := unless x $ throw $ IO.userError "check failed" def inaccessible {α : Sort u} (a : α) : α := a def val {α : Sort u} (a : α) : α := a def As {α : Sort u} (v a : α) : α := a inductive Pat {α : Sort u} (a : α) : Type u | mk : Pat inductive ArrayLit0 (α : Sort u) : Type u | mk : ArrayLit0 inductive ArrayLit1 {α : Sort u} (a : α) : Type u | mk : ArrayLit1 inductive ArrayLit2 {α : Sort u} (a b : α) : Type u | mk : ArrayLit2 inductive ArrayLit3 {α : Sort u} (a b c : α) : Type u | mk : ArrayLit3 inductive ArrayLit4 {α : Sort u} (a b c d : α) : Type u | mk : ArrayLit4 private def getConstructorVal (ctorName : Name) (fn : Expr) (args : Array Expr) : MetaM (Option (ConstructorVal × Expr × Array Expr)) := do env ← getEnv; match env.find? ctorName with | some (ConstantInfo.ctorInfo v) => if args.size == v.nparams + v.nfields then pure $ some (v, fn, args) else pure none | _ => pure none private def constructorApp? (e : Expr) : MetaM (Option (ConstructorVal × Expr × Array Expr)) := do env ← getEnv; match e with | Expr.lit (Literal.natVal n) _ => if n == 0 then getConstructorVal `Nat.zero (mkConst `Nat.zero) #[] else getConstructorVal `Nat.succ (mkConst `Nat.succ) #[mkNatLit (n-1)] | _ => let fn := e.getAppFn; match fn with | Expr.const n _ _ => getConstructorVal n fn e.getAppArgs | _ => pure none /- Convert expression using auxiliary hints `inaccessible` and `val` into a pattern -/ partial def mkPattern : Expr → MetaM Pattern | e => if e.isAppOfArity `val 2 then pure $ Pattern.val e.appArg! else if e.isAppOfArity `inaccessible 2 then pure $ Pattern.inaccessible e.appArg! else if e.isFVar then pure $ Pattern.var e.fvarId! else if e.isAppOfArity `As 3 && (e.getArg! 1).isFVar then do let v := e.getArg! 1; let p := e.getArg! 2; p ← mkPattern p; pure $ Pattern.as v.fvarId! p else if e.isAppOfArity `ArrayLit0 1 || e.isAppOfArity `ArrayLit1 2 || e.isAppOfArity `ArrayLit2 3 || e.isAppOfArity `ArrayLit3 4 || e.isAppOfArity `ArrayLit4 5 then do let args := e.getAppArgs; let type := args.get! 0; let ps := args.extract 1 args.size; ps ← ps.toList.mapM mkPattern; pure $ Pattern.arrayLit type ps else match e.arrayLit? with | some (_, es) => do pats ← es.mapM mkPattern; type ← inferType e; type ← whnfD type; let elemType := type.appArg!; pure $ Pattern.arrayLit elemType pats | none => do e ← whnfD e; r? ← constructorApp? e; match r? with | none => throwError "unexpected pattern" | some (cval, fn, args) => do let params := args.extract 0 cval.nparams; let fields := args.extract cval.nparams args.size; pats ← fields.toList.mapM mkPattern; pure $ Pattern.ctor cval.name fn.constLevels! params.toList pats partial def decodePats : Expr → MetaM (List Pattern) | e => match e.app2? `Pat with | some (_, pat) => do pat ← mkPattern pat; pure [pat] | none => match e.prod? with | none => throwError "unexpected pattern" | some (pat, pats) => do pat ← decodePats pat; pats ← decodePats pats; pure (pat ++ pats) partial def decodeAltLHS (e : Expr) : MetaM AltLHS := forallTelescopeReducing e fun args body => do decls ← args.toList.mapM (fun arg => getLocalDecl arg.fvarId!); pats ← decodePats body; pure { ref := Syntax.missing, fvarDecls := decls, patterns := pats } partial def decodeAltLHSs : Expr → MetaM (List AltLHS) | e => match e.app2? `LHS with | some (_, lhs) => do lhs ← decodeAltLHS lhs; pure [lhs] | none => match e.prod? with | none => throwError "unexpected LHS" | some (lhs, lhss) => do lhs ← decodeAltLHSs lhs; lhss ← decodeAltLHSs lhss; pure (lhs ++ lhss) def withDepElimFrom {α} (declName : Name) (numPats : Nat) (k : List FVarId → List AltLHS → MetaM α) : MetaM α := do cinfo ← getConstInfo declName; forallTelescopeReducing cinfo.type fun args body => if args.size < numPats then throwError "insufficient number of parameters" else do let xs := (args.extract (args.size - numPats) args.size).toList.map $ Expr.fvarId!; alts ← decodeAltLHSs body; k xs alts inductive LHS {α : Sort u} (a : α) : Type u | mk : LHS instance LHS.inhabited {α} (a : α) : Inhabited (LHS a) := ⟨LHS.mk⟩ -- set_option trace.Meta.debug true -- set_option trace.Meta.Tactic.cases true -- set_option trace.Meta.Tactic.subst true @[init] def register : IO Unit := registerTraceClass `Meta.mkElim /- Helper methods for testins mkElim -/ private def getUnusedLevelParam (majors : List Expr) (lhss : List AltLHS) : MetaM Level := do let s : CollectLevelParams.State := {}; s ← majors.foldlM (fun s major => do major ← instantiateMVars major; majorType ← inferType major; majorType ← instantiateMVars majorType; let s := collectLevelParams s major; pure $ collectLevelParams s majorType) s; pure s.getUnusedLevelParam /- Return `Prop` if `inProf == true` and `Sort u` otherwise, where `u` is a fresh universe level parameter. -/ private def mkElimSort (majors : List Expr) (lhss : List AltLHS) (inProp : Bool) : MetaM Expr := if inProp then pure $ mkSort $ levelZero else do v ← getUnusedLevelParam majors lhss; pure $ mkSort $ v def mkTester (elimName : Name) (majors : List Expr) (lhss : List AltLHS) (inProp : Bool := false) : MetaM MatcherResult := do sortv ← mkElimSort majors lhss inProp; generalizeTelescope majors.toArray `_d fun majors => do motiveType ← mkForallFVars majors sortv; Match.mkMatcher elimName motiveType majors.size lhss def test (ex : Name) (numPats : Nat) (elimName : Name) (inProp : Bool := false) : MetaM Unit := withDepElimFrom ex numPats fun majors alts => do let majors := majors.map mkFVar; trace! `Meta.debug ("majors: " ++ majors.toArray); r ← mkTester elimName majors alts inProp; unless r.counterExamples.isEmpty $ throwError ("missing cases:" ++ Format.line ++ counterExamplesToMessageData r.counterExamples); unless r.unusedAltIdxs.isEmpty $ throwError ("unused alternatives: " ++ toString (r.unusedAltIdxs.map fun idx => "#" ++ toString (idx+1))); pure () def testFailure (ex : Name) (numPats : Nat) (elimName : Name) (inProp : Bool := false) : MetaM Unit := do worked ← catch (do test ex numPats elimName inProp; pure true) (fun ex => pure false); when worked $ throwError "unexpected success" def ex0 (x : Nat) : LHS (forall (y : Nat), Pat y) := arbitrary _ #eval test `ex0 1 `elimTest0 #print elimTest0 def ex1 (α : Type u) (β : Type v) (n : Nat) (x : List α) (y : List β) : LHS (Pat ([] : List α) × Pat ([] : List β)) × LHS (forall (a : α) (as : List α) (b : β) (bs : List β), Pat (a::as) × Pat (b::bs)) × LHS (forall (a : α) (as : List α), Pat (a::as) × Pat ([] : List β)) × LHS (forall (b : β) (bs : List β), Pat ([] : List α) × Pat (b::bs)) := arbitrary _ #eval test `ex1 2 `elimTest1 #print elimTest1 inductive Vec (α : Type u) : Nat → Type u | nil : Vec 0 | cons {n : Nat} : α → Vec n → Vec (n+1) def ex2 (α : Type u) (n : Nat) (xs : Vec α n) (ys : Vec α n) : LHS (Pat (inaccessible 0) × Pat (Vec.nil : Vec α 0) × Pat (Vec.nil : Vec α 0)) × LHS (forall (n : Nat) (x : α) (xs : Vec α n) (y : α) (ys : Vec α n), Pat (inaccessible (n+1)) × Pat (Vec.cons x xs) × Pat (Vec.cons y ys)) := arbitrary _ #eval test `ex2 3 `elimTest2 #print elimTest2 def ex3 (α : Type u) (β : Type v) (n : Nat) (x : List α) (y : List β) : LHS (Pat ([] : List α) × Pat ([] : List β)) × LHS (forall (a : α) (b : β), Pat [a] × Pat [b]) × LHS (forall (a₁ a₂ : α) (as : List α) (b₁ b₂ : β) (bs : List β), Pat (a₁::a₂::as) × Pat (b₁::b₂::bs)) × LHS (forall (as : List α) (bs : List β), Pat as × Pat bs) := arbitrary _ -- set_option trace.Meta.EqnCompiler.match true -- set_option trace.Meta.EqnCompiler.matchDebug true #eval test `ex3 2 `elimTest3 #print elimTest3 def ex4 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (Pat (inaccessible 0) × Pat (Vec.nil : Vec α 0)) × LHS (forall (n : Nat) (xs : Vec α (n+1)), Pat (inaccessible (n+1)) × Pat xs) := arbitrary _ #eval test `ex4 2 `elimTest4 #print elimTest4 def ex5 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (Pat Nat.zero × Pat (Vec.nil : Vec α 0)) × LHS (forall (n : Nat) (xs : Vec α (n+1)), Pat (Nat.succ n) × Pat xs) := arbitrary _ #eval test `ex5 2 `elimTest5 #print elimTest5 def ex6 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (Pat (inaccessible Nat.zero) × Pat (Vec.nil : Vec α 0)) × LHS (forall (N : Nat) (XS : Vec α N), Pat (inaccessible N) × Pat XS) := arbitrary _ set_option trace.Meta.Match.match true set_option trace.Meta.Match.debug true #eval test `ex6 2 `elimTest6 #print elimTest6 def ex7 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (forall (a : α), Pat (inaccessible 1) × Pat (Vec.cons a Vec.nil)) × LHS (forall (N : Nat) (XS : Vec α N), Pat (inaccessible N) × Pat XS) := arbitrary _ #eval test `ex7 2 `elimTest7 #check elimTest7 def isSizeOne {n : Nat} (xs : Vec Nat n) : Bool := elimTest7 _ (fun _ _ => Bool) n xs (fun _ => true) (fun _ _ => false) #eval isSizeOne Vec.nil #eval isSizeOne (Vec.cons 1 Vec.nil) #eval isSizeOne (Vec.cons 2 (Vec.cons 1 Vec.nil)) def singleton? {n : Nat} (xs : Vec Nat n) : Option Nat := elimTest7 _ (fun _ _ => Option Nat) n xs (fun a => some a) (fun _ _ => none) #eval singleton? Vec.nil #eval singleton? (Vec.cons 10 Vec.nil) #eval singleton? (Vec.cons 20 (Vec.cons 10 Vec.nil)) def ex8 (α : Type u) (n : Nat) (xs : Vec α n) : LHS (forall (a b : α), Pat (inaccessible 2) × Pat (Vec.cons a (Vec.cons b Vec.nil))) × LHS (forall (N : Nat) (XS : Vec α N), Pat (inaccessible N) × Pat XS) := arbitrary _ #eval test `ex8 2 `elimTest8 #print elimTest8 def pair? {n : Nat} (xs : Vec Nat n) : Option (Nat × Nat) := elimTest8 _ (fun _ _ => Option (Nat × Nat)) n xs (fun a b => some (a, b)) (fun _ _ => none) #eval pair? Vec.nil #eval pair? (Vec.cons 10 Vec.nil) #eval pair? (Vec.cons 20 (Vec.cons 10 Vec.nil)) inductive Op : Nat → Nat → Type | mk : ∀ n, Op n n structure Node : Type := (id₁ id₂ : Nat) (o : Op id₁ id₂) def ex9 (xs : List Node) : LHS (forall (h : Node) (t : List Node), Pat (h :: Node.mk 1 1 (Op.mk 1) :: t)) × LHS (forall (ys : List Node), Pat ys) := arbitrary _ #eval test `ex9 1 `elimTest9 #print elimTest9 def f (xs : List Node) : Bool := elimTest9 (fun _ => Bool) xs (fun _ _ => true) (fun _ => false) #eval check (f [] == false) #eval check (f [⟨0, 0, Op.mk 0⟩] == false) #eval check (f [⟨0, 0, Op.mk 0⟩, ⟨1, 1, Op.mk 1⟩]) #eval check (f [⟨0, 0, Op.mk 0⟩, ⟨2, 2, Op.mk 2⟩] == false) inductive Foo : Bool → Prop | bar : Foo false | baz : Foo false def ex10 (x : Bool) (y : Foo x) : LHS (Pat (inaccessible false) × Pat Foo.bar) × LHS (forall (x : Bool) (y : Foo x), Pat (inaccessible x) × Pat y) := arbitrary _ #eval test `ex10 2 `elimTest10 true def ex11 (xs : List Node) : LHS (forall (h : Node) (t : List Node), Pat (h :: Node.mk 1 1 (Op.mk 1) :: t)) × LHS (Pat ([] : List Node)) := arbitrary _ #eval testFailure `ex11 1 `elimTest11 -- should produce error message def ex12 (x y z : Bool) : LHS (forall (x y : Bool), Pat x × Pat y × Pat true) × LHS (forall (x z : Bool), Pat false × Pat true × Pat z) × LHS (forall (y z : Bool), Pat true × Pat false × Pat z) := arbitrary _ #eval testFailure `ex12 3 `elimTest12 -- should produce error message def ex13 (xs : List Node) : LHS (forall (h : Node) (t : List Node), Pat (h :: Node.mk 1 1 (Op.mk 1) :: t)) × LHS (forall (ys : List Node), Pat ys) × LHS (forall (ys : List Node), Pat ys) := arbitrary _ #eval testFailure `ex13 1 `elimTest13 -- should produce error message def ex14 (x y : Nat) : LHS (Pat (val 1) × Pat (val 2)) × LHS (Pat (val 2) × Pat (val 3)) × LHS (forall (x y : Nat), Pat x × Pat y) := arbitrary _ set_option trace.Meta.Match true #eval test `ex14 2 `elimTest14 #print elimTest14 def h2 (x y : Nat) : Nat := elimTest14 (fun _ _ => Nat) x y (fun _ => 0) (fun _ => 1) (fun x y => x + y) #eval check (h2 1 2 == 0) #eval check (h2 1 4 == 5) #eval check (h2 2 3 == 1) #eval check (h2 2 4 == 6) #eval check (h2 3 4 == 7) def ex15 (xs : Array (List Nat)) : LHS (forall (a : Nat), Pat (ArrayLit1 [a])) × LHS (forall (a b : Nat), Pat (ArrayLit2 [a] [b])) × LHS (forall (ys : Array (List Nat)), Pat ys) := arbitrary _ #eval test `ex15 1 `elimTest15 #check elimTest15 def h3 (xs : Array (List Nat)) : Nat := elimTest15 (fun _ => Nat) xs (fun a => a + 1) (fun a b => a + b) (fun ys => ys.size) #eval check (h3 #[[1]] == 2) #eval check (h3 #[[3], [2]] == 5) #eval check (h3 #[[1, 2]] == 1) #eval check (h3 #[[1, 2], [2, 3], [3]] == 3) def ex16 (xs : List Nat) : LHS (forall (a : Nat) (xs : List Nat) (b : Nat) (as : List Nat), Pat (a :: As xs (b :: as))) × LHS (forall (a : Nat), Pat ([a])) × LHS (Pat ([] : List Nat)) := arbitrary _ #eval test `ex16 1 `elimTest16 #check elimTest16 #print elimTest16 def h4 (xs : List Nat) : List Nat := elimTest16 (fun _ => List Nat) xs (fun a xs b ys => xs) (fun a => []) (fun _ => [1]) #eval check (h4 [1, 2, 3] == [2, 3]) #eval check (h4 [1] == []) #eval check (h4 [] == [1])
576b153ee6e11074d431e5fc3719e249945f2a7e
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Server/Watchdog.lean
2b9cb98407a8150387169ff7e0b3ee861c4cdf0c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
26,347
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.System.IO import Init.Data.ByteArray import Std.Data.RBMap import Lean.Elab.Import import Lean.Data.Lsp import Lean.Server.Utils import Lean.Server.Requests /-! For general server architecture, see `README.md`. This module implements the watchdog process. ## Watchdog state Most LSP clients only send us file diffs, so to facilitate sending entire file contents to freshly restarted workers, the watchdog needs to maintain the current state of each file. It can also use this state to detect changes to the header and thus restart the corresponding worker, freeing its imports. TODO(WN): We may eventually want to keep track of approximately (since this isn't knowable exactly) where in the file a worker crashed. Then on restart, we tell said worker to only parse up to that point and query the user about how to proceed (continue OR allow the user to fix the bug and then continue OR ..). Without this, if the crash is deterministic, users may be confused about why the server seemingly stopped working for a single file. ## Watchdog <-> worker communication The watchdog process and its file worker processes communicate via LSP. If the necessity arises, we might add non-standard commands similarly based on JSON-RPC. Most requests and notifications are forwarded to the corresponding file worker process, with the exception of these notifications: - textDocument/didOpen: Launch the file worker, create the associated watchdog state and launch a task to asynchronously receive LSP packets from the worker (e.g. request responses). - textDocument/didChange: Update the local file state. If the header was mutated, signal a shutdown to the file worker by closing the I/O channels. Then restart the file worker. Otherwise, forward the `didChange` notification. - textDocument/didClose: Signal a shutdown to the file worker and remove the associated watchdog state. Moreover, we don't implement the full protocol at this level: - Upon starting, the `initialize` request is forwarded to the worker, but it must not respond with its server capabilities. Consequently, the watchdog will not send an `initialized` notification to the worker. - After `initialize`, the watchdog sends the corresponding `didOpen` notification with the full current state of the file. No additional `didOpen` notifications will be forwarded to the worker process. - `$/cancelRequest` notifications are forwarded to all file workers. - File workers are always terminated with an `exit` notification, without previously receiving a `shutdown` request. Similarly, they never receive a `didClose` notification. ## Watchdog <-> client communication The watchdog itself should implement the LSP standard as closely as possible. However we reserve the right to add non-standard extensions in case they're needed, for example to communicate tactic state. -/ namespace Lean.Server.Watchdog open IO open Std (RBMap RBMap.empty) open Lsp open JsonRpc section Utils structure OpenDocument where meta : DocumentMeta headerAst : Syntax def workerCfg : Process.StdioConfig := { stdin := Process.Stdio.piped stdout := Process.Stdio.piped -- We pass workers' stderr through to the editor. stderr := Process.Stdio.inherit } /-- Events that worker-specific tasks signal to the main thread. -/ inductive WorkerEvent where /- A synthetic event signalling that the grouped edits should be processed. -/ | processGroupedEdits | terminated | crashed (e : IO.Error) | ioError (e : IO.Error) inductive WorkerState where /- The watchdog can detect a crashed file worker in two places: When trying to send a message to the file worker and when reading a request reply. In the latter case, the forwarding task terminates and delegates a `crashed` event to the main task. Then, in both cases, the file worker has its state set to `crashed` and requests that are in-flight are errored. Upon receiving the next packet for that file worker, the file worker is restarted and the packet is forwarded to it. If the crash was detected while writing a packet, we queue that packet until the next packet for the file worker arrives. -/ | crashed (queuedMsgs : Array JsonRpc.Message) | running abbrev PendingRequestMap := RBMap RequestID JsonRpc.Message compare private def parseHeaderAst (input : String) : IO Syntax := do let inputCtx := Parser.mkInputContext input "<input>" let (stx, _, _) ← Parser.parseHeader inputCtx return stx end Utils section FileWorker /-- A group of edits which will be processed at a future instant. -/ structure GroupedEdits where /-- When to process the edits. -/ applyTime : Nat params : DidChangeTextDocumentParams /-- Signals when `applyTime` has been reached. -/ signalTask : Task WorkerEvent /-- We should not reorder messages when delaying edits, so we queue other messages since the last request here. -/ queuedMsgs : Array JsonRpc.Message structure FileWorker where doc : OpenDocument proc : Process.Child workerCfg commTask : Task WorkerEvent state : WorkerState -- This should not be mutated outside of namespace FileWorker, as it is used as shared mutable state /-- The pending requests map contains all requests that have been received from the LSP client, but were not answered yet. This includes the queued messages in the grouped edits. -/ pendingRequestsRef : IO.Ref PendingRequestMap groupedEditsRef : IO.Ref (Option GroupedEdits) namespace FileWorker def stdin (fw : FileWorker) : FS.Stream := FS.Stream.ofHandle fw.proc.stdin def stdout (fw : FileWorker) : FS.Stream := FS.Stream.ofHandle fw.proc.stdout def erasePendingRequest (fw : FileWorker) (id : RequestID) : IO Unit := fw.pendingRequestsRef.modify fun pendingRequests => pendingRequests.erase id def errorPendingRequests (fw : FileWorker) (hError : FS.Stream) (code : ErrorCode) (msg : String) : IO Unit := do let pendingRequests ← fw.pendingRequestsRef.modifyGet (fun pendingRequests => (pendingRequests, RBMap.empty)) for ⟨id, _⟩ in pendingRequests do hError.writeLspResponseError { id := id, code := code, message := msg } partial def runEditsSignalTask (fw : FileWorker) : IO (Task WorkerEvent) := do -- check `applyTime` in a loop since it might have been postponed by a subsequent edit notification let rec loopAction : IO WorkerEvent := do let now ← monoMsNow let some ge ← fw.groupedEditsRef.get | throwServerError "Internal error: empty grouped edits reference in signal task" if ge.applyTime ≤ now then return WorkerEvent.processGroupedEdits else IO.sleep <| UInt32.ofNat <| ge.applyTime - now loopAction let t ← IO.asTask loopAction return t.map fun | Except.ok ev => ev | Except.error e => WorkerEvent.ioError e end FileWorker end FileWorker section ServerM abbrev FileWorkerMap := RBMap DocumentUri FileWorker compare structure ServerContext where hIn : FS.Stream hOut : FS.Stream hLog : FS.Stream /-- Command line arguments. -/ args : List String fileWorkersRef : IO.Ref FileWorkerMap /-- We store these to pass them to workers. -/ initParams : InitializeParams editDelay : Nat workerPath : System.FilePath abbrev ServerM := ReaderT ServerContext IO def updateFileWorkers (val : FileWorker) : ServerM Unit := do (←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.insert val.doc.meta.uri val) def findFileWorker? (uri : DocumentUri) : ServerM (Option FileWorker) := do (←(←read).fileWorkersRef.get).find? uri def findFileWorker! (uri : DocumentUri) : ServerM FileWorker := do let some fw ← findFileWorker? uri | throwServerError s!"cannot find open document '{uri}'" return fw def eraseFileWorker (uri : DocumentUri) : ServerM Unit := do (←read).fileWorkersRef.modify (fun fileWorkers => fileWorkers.erase uri) def log (msg : String) : ServerM Unit := do let st ← read st.hLog.putStrLn msg st.hLog.flush /-- Creates a Task which forwards a worker's messages into the output stream until an event which must be handled in the main watchdog thread (e.g. an I/O error) happens. -/ private partial def forwardMessages (fw : FileWorker) : ServerM (Task WorkerEvent) := do let o := (←read).hOut let rec loop : ServerM WorkerEvent := do try let msg ← fw.stdout.readLspMessage if let Message.response id _ := msg then fw.erasePendingRequest id if let Message.responseError id _ _ _ := msg then fw.erasePendingRequest id -- Writes to Lean I/O channels are atomic, so these won't trample on each other. o.writeLspMessage msg catch err => -- If writeLspMessage from above errors we will block here, but the main task will -- quit eventually anyways if that happens let exitCode ← fw.proc.wait if exitCode = 0 then -- Worker was terminated fw.errorPendingRequests o ErrorCode.contentModified ("The file worker has been terminated. Either the header has changed," ++ " or the file was closed, or the server is shutting down.") return WorkerEvent.terminated else -- Worker crashed fw.errorPendingRequests o ErrorCode.internalError s!"Server process for {fw.doc.meta.uri} crashed, {if exitCode = 1 then "see stderr for exception" else "likely due to a stack overflow in user code"}." return WorkerEvent.crashed err loop let task ← IO.asTask (loop $ ←read) Task.Priority.dedicated task.map $ fun | Except.ok ev => ev | Except.error e => WorkerEvent.ioError e def startFileWorker (m : DocumentMeta) : ServerM Unit := do publishProgressAtPos m 0 (← read).hOut let st ← read let headerAst ← parseHeaderAst m.text.source let workerProc ← Process.spawn { toStdioConfig := workerCfg cmd := st.workerPath.toString args := #["--worker"] ++ st.args.toArray } let pendingRequestsRef ← IO.mkRef (RBMap.empty : PendingRequestMap) -- The task will never access itself, so this is fine let fw : FileWorker := { doc := ⟨m, headerAst⟩ proc := workerProc commTask := Task.pure WorkerEvent.terminated state := WorkerState.running pendingRequestsRef := pendingRequestsRef groupedEditsRef := ← IO.mkRef none } let commTask ← forwardMessages fw let fw : FileWorker := { fw with commTask := commTask } fw.stdin.writeLspRequest ⟨0, "initialize", st.initParams⟩ fw.stdin.writeLspNotification { method := "textDocument/didOpen" param := { textDocument := { uri := m.uri languageId := "lean" version := m.version text := m.text.source } : DidOpenTextDocumentParams } } updateFileWorkers fw def terminateFileWorker (uri : DocumentUri) : ServerM Unit := do let fw ← findFileWorker! uri try fw.stdin.writeLspMessage (Message.notification "exit" none) catch _ => /- The file worker must have crashed just when we were about to terminate it! That's fine - just forget about it then. (on didClose we won't need the crashed file worker anymore, when the header changed we'll start a new one right after anyways and when we're shutting down the server it's over either way.) -/ return eraseFileWorker uri def handleCrash (uri : DocumentUri) (queuedMsgs : Array JsonRpc.Message) : ServerM Unit := do updateFileWorkers { ←findFileWorker! uri with state := WorkerState.crashed queuedMsgs } /-- Tries to write a message, sets the state of the FileWorker to `crashed` if it does not succeed and restarts the file worker if the `crashed` flag was already set. Just logs an error if there is no FileWorker at this `uri`. Messages that couldn't be sent can be queued up via the queueFailedMessage flag and will be discharged after the FileWorker is restarted. -/ def tryWriteMessage (uri : DocumentUri) (msg : JsonRpc.Message) (queueFailedMessage := true) (restartCrashedWorker := false) : ServerM Unit := do let some fw ← findFileWorker? uri | do (←read).hLog.putStrLn s!"Cannot send message to unknown document '{uri}':\n{(toJson msg).compress}" return let pendingEdit ← fw.groupedEditsRef.modifyGet fun | some ge => (true, some { ge with queuedMsgs := ge.queuedMsgs.push msg }) | none => (false, none) if pendingEdit then return match fw.state with | WorkerState.crashed queuedMsgs => let mut queuedMsgs := queuedMsgs if queueFailedMessage then queuedMsgs := queuedMsgs.push msg if !restartCrashedWorker then return -- restart the crashed FileWorker eraseFileWorker uri startFileWorker fw.doc.meta let newFw ← findFileWorker! uri let mut crashedMsgs := #[] -- try to discharge all queued msgs, tracking the ones that we can't discharge for msg in queuedMsgs do try newFw.stdin.writeLspMessage msg catch _ => crashedMsgs := crashedMsgs.push msg if ¬ crashedMsgs.isEmpty then handleCrash uri crashedMsgs | WorkerState.running => let initialQueuedMsgs := if queueFailedMessage then #[msg] else #[] try fw.stdin.writeLspMessage msg catch _ => handleCrash uri initialQueuedMsgs end ServerM section NotificationHandling def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit := let doc := p.textDocument /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ startFileWorker ⟨doc.uri, doc.version, doc.text.toFileMap⟩ def handleEdits (fw : FileWorker) : ServerM Unit := do let some ge ← fw.groupedEditsRef.modifyGet (·, none) | throwServerError "Internal error: empty grouped edits reference" let doc := ge.params.textDocument let changes := ge.params.contentChanges let oldDoc := fw.doc let some newVersion ← pure doc.version? | throwServerError "Expected version number" if newVersion <= oldDoc.meta.version then throwServerError "Got outdated version number" if changes.isEmpty then return let newDocText := foldDocumentChanges changes oldDoc.meta.text let newMeta : DocumentMeta := ⟨doc.uri, newVersion, newDocText⟩ let newHeaderAst ← parseHeaderAst newDocText.source if newHeaderAst != oldDoc.headerAst then terminateFileWorker doc.uri startFileWorker newMeta else let newDoc : OpenDocument := ⟨newMeta, oldDoc.headerAst⟩ updateFileWorkers { fw with doc := newDoc } tryWriteMessage doc.uri (Notification.mk "textDocument/didChange" ge.params) (restartCrashedWorker := true) for msg in ge.queuedMsgs do tryWriteMessage doc.uri msg def handleDidClose (p : DidCloseTextDocumentParams) : ServerM Unit := terminateFileWorker p.textDocument.uri def handleCancelRequest (p : CancelParams) : ServerM Unit := do let fileWorkers ← (←read).fileWorkersRef.get for ⟨uri, fw⟩ in fileWorkers do -- Cancelled requests still require a response, so they can't be removed -- from the pending requests map. if (← fw.pendingRequestsRef.get).contains p.id then tryWriteMessage uri (Notification.mk "$/cancelRequest" p) (queueFailedMessage := false) def forwardNotification {α : Type} [ToJson α] [FileSource α] (method : String) (params : α) : ServerM Unit := tryWriteMessage (fileSource params) (Notification.mk method params) (queueFailedMessage := true) end NotificationHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType := match fromJson? params with | Except.ok parsed => pure parsed | Except.error inner => throwServerError s!"Got param with wrong structure: {params.compress}\n{inner}" def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do let uri: DocumentUri ← -- This request is handled specially. if method == "$/lean/rpc/connect" then let ps ← parseParams Lsp.RpcConnectParams params fileSource ps else match (← routeLspRequest method params) with | Except.error e => (←read).hOut.writeLspResponseError <| e.toLspResponseError id return | Except.ok uri => uri let some fw ← findFileWorker? uri /- Clients may send requests to closed files, which we respond to with an error. For example, VSCode sometimes sends requests just after closing a file, and RPC clients may also do so, e.g. due to remaining timers. -/ | do (←read).hOut.writeLspResponseError { id := id /- Some clients (VSCode) also send requests *before* opening a file. We reply with `contentModified` as that does not display a "request failed" popup. -/ code := ErrorCode.contentModified message := s!"Cannot process request to closed file '{uri}'" } return let r := Request.mk id method params fw.pendingRequestsRef.modify (·.insert id r) tryWriteMessage uri r def handleNotification (method : String) (params : Json) : ServerM Unit := do let handle := (fun α [FromJson α] (handler : α → ServerM Unit) => parseParams α params >>= handler) match method with | "textDocument/didOpen" => handle DidOpenTextDocumentParams handleDidOpen /- NOTE: textDocument/didChange is handled in the main loop. -/ | "textDocument/didClose" => handle DidCloseTextDocumentParams handleDidClose | "$/cancelRequest" => handle CancelParams handleCancelRequest | "$/lean/rpc/connect" => handle RpcConnectParams (forwardNotification method) | "$/lean/rpc/release" => handle RpcReleaseParams (forwardNotification method) | "$/lean/rpc/keepAlive" => handle RpcKeepAliveParams (forwardNotification method) | _ => if !"$/".isPrefixOf method then -- implementation-dependent notifications can be safely ignored (←read).hLog.putStrLn s!"Got unsupported notification: {method}" end MessageHandling section MainLoop def shutdown : ServerM Unit := do let fileWorkers ← (←read).fileWorkersRef.get for ⟨uri, _⟩ in fileWorkers do terminateFileWorker uri for ⟨_, fw⟩ in fileWorkers do discard <| IO.wait fw.commTask inductive ServerEvent where | workerEvent (fw : FileWorker) (ev : WorkerEvent) | clientMsg (msg : JsonRpc.Message) | clientError (e : IO.Error) def runClientTask : ServerM (Task ServerEvent) := do let st ← read let readMsgAction : IO ServerEvent := do /- Runs asynchronously. -/ let msg ← st.hIn.readLspMessage ServerEvent.clientMsg msg let clientTask := (←IO.asTask readMsgAction).map $ fun | Except.ok ev => ev | Except.error e => ServerEvent.clientError e return clientTask partial def mainLoop (clientTask : Task ServerEvent) : ServerM Unit := do let st ← read let workers ← st.fileWorkersRef.get let mut workerTasks := #[] for (_, fw) in workers do if let WorkerState.running := fw.state then workerTasks := workerTasks.push <| fw.commTask.map (ServerEvent.workerEvent fw) if let some ge ← fw.groupedEditsRef.get then workerTasks := workerTasks.push <| ge.signalTask.map (ServerEvent.workerEvent fw) let ev ← IO.waitAny (workerTasks.push clientTask |>.toList) match ev with | ServerEvent.clientMsg msg => match msg with | Message.request id "shutdown" _ => shutdown st.hOut.writeLspResponse ⟨id, Json.null⟩ | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop (←runClientTask) | Message.notification "textDocument/didChange" (some params) => let p ← parseParams DidChangeTextDocumentParams (toJson params) let fw ← findFileWorker! p.textDocument.uri let now ← monoMsNow /- We wait `editDelay`ms since last edit before applying the changes. -/ let applyTime := now + st.editDelay let queuedMsgs? ← fw.groupedEditsRef.modifyGet fun | some ge => (some ge.queuedMsgs, some { ge with applyTime := applyTime params.textDocument := p.textDocument params.contentChanges := ge.params.contentChanges ++ p.contentChanges -- drain now-outdated messages and respond with `contentModified` below queuedMsgs := #[] }) | none => (none, some { applyTime := applyTime params := p /- This is overwritten just below. -/ signalTask := Task.pure WorkerEvent.processGroupedEdits queuedMsgs := #[] }) match queuedMsgs? with | some queuedMsgs => for msg in queuedMsgs do match msg with | JsonRpc.Message.request id _ _ => fw.erasePendingRequest id (← read).hOut.writeLspResponseError { id := id code := ErrorCode.contentModified message := "File changed." } | _ => () -- notifications do not need to be cancelled | _ => let t ← fw.runEditsSignalTask fw.groupedEditsRef.modify (Option.map fun ge => { ge with signalTask := t } ) mainLoop (←runClientTask) | Message.notification method (some params) => handleNotification method (toJson params) mainLoop (←runClientTask) | _ => throwServerError "Got invalid JSON-RPC message" | ServerEvent.clientError e => throw e | ServerEvent.workerEvent fw ev => match ev with | WorkerEvent.processGroupedEdits => handleEdits fw mainLoop clientTask | WorkerEvent.ioError e => throwServerError s!"IO error while processing events for {fw.doc.meta.uri}: {e}" | WorkerEvent.crashed e => handleCrash fw.doc.meta.uri #[] mainLoop clientTask | WorkerEvent.terminated => throwServerError "Internal server error: got termination event for worker that should have been removed" end MainLoop def mkLeanServerCapabilities : ServerCapabilities := { textDocumentSync? := some { openClose := true change := TextDocumentSyncKind.incremental willSave := false willSaveWaitUntil := false save? := none } -- refine completionProvider? := some { triggerCharacters? := some #["."] } hoverProvider := true declarationProvider := true definitionProvider := true typeDefinitionProvider := true referencesProvider := true documentHighlightProvider := true documentSymbolProvider := true semanticTokensProvider? := some { legend := { tokenTypes := SemanticTokenType.names tokenModifiers := #[] } full := true range := true } } def initAndRunWatchdogAux : ServerM Unit := do let st ← read try discard $ st.hIn.readLspNotificationAs "initialized" InitializedParams let clientTask ← runClientTask mainLoop clientTask catch err => shutdown throw err /- NOTE(WN): It looks like instead of sending the `exit` notification, VSCode just closes the stream. In that case, pretend we got an `exit`. -/ let Message.notification "exit" none ← try st.hIn.readLspMessage catch _ => pure (Message.notification "exit" none) | throwServerError "Got `shutdown` request, expected an `exit` notification" def initAndRunWatchdog (args : List String) (i o e : FS.Stream) : IO Unit := do let mut workerPath ← IO.appPath if let some path := (←IO.getEnv "LEAN_SYSROOT") then workerPath := System.FilePath.mk path / "bin" / "lean" |>.withExtension System.FilePath.exeExtension if let some path := (←IO.getEnv "LEAN_WORKER_PATH") then workerPath := System.FilePath.mk path let fileWorkersRef ← IO.mkRef (RBMap.empty : FileWorkerMap) let i ← maybeTee "wdIn.txt" false i let o ← maybeTee "wdOut.txt" true o let e ← maybeTee "wdErr.txt" true e let initRequest ← i.readLspRequestAs "initialize" InitializeParams o.writeLspResponse { id := initRequest.id result := { capabilities := mkLeanServerCapabilities serverInfo? := some { name := "Lean 4 Server" version? := "0.1.1" } : InitializeResult } } ReaderT.run initAndRunWatchdogAux { hIn := i hOut := o hLog := e args := args fileWorkersRef := fileWorkersRef initParams := initRequest.param editDelay := initRequest.param.initializationOptions? |>.bind InitializationOptions.editDelay? |>.getD 200 workerPath := workerPath : ServerContext } @[export lean_server_watchdog_main] def watchdogMain (args : List String) : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try initAndRunWatchdog args i o e return 0 catch err => e.putStrLn s!"Watchdog error: {err}" return 1 end Lean.Server.Watchdog
2229a32ab1aab89008c8c40c8b8c94816eaeec80
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/iterate_hom.lean
4e39f04e998975c8e64eb798b6ee8b4f1db7a145
[ "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
5,927
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import algebra.group_power.basic import logic.function.iterate import group_theory.perm.basic /-! # Iterates of monoid and ring homomorphisms Iterate of a monoid/ring homomorphism is a monoid/ring homomorphism but it has a wrong type, so Lean can't apply lemmas like `monoid_hom.map_one` to `f^[n] 1`. Though it is possible to define a monoid structure on the endomorphisms, quite often we do not want to convert from `M →* M` to (not yet defined) `monoid.End M` and from `f^[n]` to `f^n` just to apply a simple lemma. So, we restate standard `*_hom.map_*` lemmas under names `*_hom.iterate_map_*`. We also prove formulas for iterates of add/mul left/right. ## Tags homomorphism, iterate -/ open function variables {M : Type*} {N : Type*} {G : Type*} {H : Type*} /-- An auxiliary lemma that can be used to prove `⇑(f ^ n) = (⇑f^[n])`. -/ lemma hom_coe_pow {F : Type*} [monoid F] (c : F → M → M) (h1 : c 1 = id) (hmul : ∀ f g, c (f * g) = c f ∘ c g) (f : F) : ∀ n, c (f ^ n) = (c f^[n]) | 0 := by { rw [pow_zero, h1], refl } | (n + 1) := by rw [pow_succ, iterate_succ', hmul, hom_coe_pow] namespace monoid_hom section variables [mul_one_class M] [mul_one_class N] @[simp, to_additive] theorem iterate_map_one (f : M →* M) (n : ℕ) : f^[n] 1 = 1 := iterate_fixed f.map_one n @[simp, to_additive] theorem iterate_map_mul (f : M →* M) (n : ℕ) (x y) : f^[n] (x * y) = (f^[n] x) * (f^[n] y) := semiconj₂.iterate f.map_mul n x y end variables [monoid M] [monoid N] [group G] [group H] @[simp, to_additive] theorem iterate_map_inv (f : G →* G) (n : ℕ) (x) : f^[n] (x⁻¹) = (f^[n] x)⁻¹ := commute.iterate_left f.map_inv n x theorem iterate_map_pow (f : M →* M) (a) (n m : ℕ) : f^[n] (a^m) = (f^[n] a)^m := commute.iterate_left (λ x, f.map_pow x m) n a theorem iterate_map_gpow (f : G →* G) (a) (n : ℕ) (m : ℤ) : f^[n] (a^m) = (f^[n] a)^m := commute.iterate_left (λ x, f.map_gpow x m) n a lemma coe_pow {M} [comm_monoid M] (f : monoid.End M) (n : ℕ) : ⇑(f^n) = (f^[n]) := hom_coe_pow _ rfl (λ f g, rfl) _ _ end monoid_hom namespace add_monoid_hom variables [add_monoid M] [add_monoid N] [add_group G] [add_group H] @[simp] theorem iterate_map_sub (f : G →+ G) (n : ℕ) (x y) : f^[n] (x - y) = (f^[n] x) - (f^[n] y) := semiconj₂.iterate f.map_sub n x y theorem iterate_map_smul (f : M →+ M) (n m : ℕ) (x : M) : f^[n] (m • x) = m • (f^[n] x) := f.to_multiplicative.iterate_map_pow x n m theorem iterate_map_gsmul (f : G →+ G) (n : ℕ) (m : ℤ) (x : G) : f^[n] (m • x) = m • (f^[n] x) := f.to_multiplicative.iterate_map_gpow x n m end add_monoid_hom namespace ring_hom section semiring variables {R : Type*} [semiring R] (f : R →+* R) (n : ℕ) (x y : R) lemma coe_pow (n : ℕ) : ⇑(f^n) = (f^[n]) := hom_coe_pow _ rfl (λ f g, rfl) f n theorem iterate_map_one : f^[n] 1 = 1 := f.to_monoid_hom.iterate_map_one n theorem iterate_map_zero : f^[n] 0 = 0 := f.to_add_monoid_hom.iterate_map_zero n theorem iterate_map_add : f^[n] (x + y) = (f^[n] x) + (f^[n] y) := f.to_add_monoid_hom.iterate_map_add n x y theorem iterate_map_mul : f^[n] (x * y) = (f^[n] x) * (f^[n] y) := f.to_monoid_hom.iterate_map_mul n x y theorem iterate_map_pow (a) (n m : ℕ) : f^[n] (a^m) = (f^[n] a)^m := f.to_monoid_hom.iterate_map_pow a n m theorem iterate_map_smul (n m : ℕ) (x : R) : f^[n] (m • x) = m • (f^[n] x) := f.to_add_monoid_hom.iterate_map_smul n m x end semiring variables {R : Type*} [ring R] (f : R →+* R) (n : ℕ) (x y : R) theorem iterate_map_sub : f^[n] (x - y) = (f^[n] x) - (f^[n] y) := f.to_add_monoid_hom.iterate_map_sub n x y theorem iterate_map_neg : f^[n] (-x) = -(f^[n] x) := f.to_add_monoid_hom.iterate_map_neg n x theorem iterate_map_gsmul (n : ℕ) (m : ℤ) (x : R) : f^[n] (m • x) = m • (f^[n] x) := f.to_add_monoid_hom.iterate_map_gsmul n m x end ring_hom lemma equiv.perm.coe_pow {α : Type*} (f : equiv.perm α) (n : ℕ) : ⇑(f ^ n) = (f^[n]) := hom_coe_pow _ rfl (λ _ _, rfl) _ _ --what should be the namespace for this section? section monoid variables [monoid G] (a : G) (n : ℕ) @[simp] lemma mul_left_iterate : ((*) a)^[n] = (*) (a^n) := nat.rec_on n (funext $ λ x, by simp) $ λ n ihn, funext $ λ x, by simp [iterate_succ, ihn, pow_succ', mul_assoc] @[simp] lemma mul_right_iterate : (* a)^[n] = (* a ^ n) := begin induction n with d hd, { simpa }, { simp [← pow_succ, hd] } end lemma mul_right_iterate_apply_one : (* a)^[n] 1 = a ^ n := by simp [mul_right_iterate] end monoid section semigroup variables [semigroup G] {a b c : G} @[to_additive] lemma semiconj_by.function_semiconj_mul_left (h : semiconj_by a b c) : function.semiconj ((*)a) ((*)b) ((*)c) := λ j, by rw [← mul_assoc, h.eq, mul_assoc] @[to_additive] lemma commute.function_commute_mul_left (h : commute a b) : function.commute ((*)a) ((*)b) := semiconj_by.function_semiconj_mul_left h @[to_additive] lemma semiconj_by.function_semiconj_mul_right_swap (h : semiconj_by a b c) : function.semiconj (*a) (*c) (*b) := λ j, by simp_rw [mul_assoc, ← h.eq] @[to_additive] lemma commute.function_commute_mul_right (h : commute a b) : function.commute (*a) (*b) := semiconj_by.function_semiconj_mul_right_swap h end semigroup --what should be the namespace for this section? section add_monoid variables [add_monoid M] (a : M) (n : ℕ) @[simp] lemma add_left_iterate : ((+) a)^[n] = (+) (n • a) := @mul_left_iterate (multiplicative M) _ a n @[simp] lemma add_right_iterate : (+ a)^[n] = (+ n • a) := begin induction n with d hd, { simp [zero_nsmul, id_def] }, { simp [hd, add_assoc, succ_nsmul] } end lemma add_right_iterate_apply_zero : (+ a)^[n] 0 = n • a := by simp [add_right_iterate] end add_monoid
e5bee588171a5d8e1e616243fbb98e401ca449c2
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/matrix.lean
325ffc9467f232cafbf7f80fd8bd4da03ce172e8
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,998
lean
/- Helper classes for Lean 3 users -/ class One (α : Type u) where one : α instance [OfNat α (nat_lit 1)] : One α where one := 1 instance [One α] : OfNat α (nat_lit 1) where ofNat := One.one class Zero (α : Type u) where zero : α instance [OfNat α (nat_lit 0)] : Zero α where zero := 0 instance [Zero α] : OfNat α (nat_lit 0) where ofNat := Zero.zero /- Simple Matrix -/ def Matrix (m n : Nat) (α : Type u) : Type u := Fin m → Fin n → α namespace Matrix /- Scoped notation for accessing values stored in matrices. -/ scoped syntax:max term noWs "[" term ", " term "]" : term macro_rules | `($x[$i, $j]) => `($x $i $j) def dotProduct [Mul α] [Add α] [Zero α] (u v : Fin m → α) : α := loop m (Nat.leRefl ..) Zero.zero where loop (i : Nat) (h : i ≤ m) (acc : α) : α := match i, h with | 0, h => acc | i+1, h => have : i < m := Nat.ltOfLtOfLe (Nat.ltSuccSelf _) h loop i (Nat.leOfLt this) (acc + u ⟨i, this⟩ * v ⟨i, this⟩) instance [Zero α] : Zero (Matrix m n α) where zero _ _ := 0 instance [Add α] : Add (Matrix m n α) where add x y i j := x[i, j] + y[i, j] instance [Mul α] [Add α] [Zero α] : HMul (Matrix m n α) (Matrix n p α) (Matrix m p α) where hMul x y i j := dotProduct (x[i, ·]) (y[·, j]) instance [Mul α] : HMul α (Matrix m n α) (Matrix m n α) where hMul c x i j := c * x[i, j] end Matrix def m1 : Matrix 2 2 Int := fun i j => #[#[1, 2], #[3, 4]][i][j] def m2 : Matrix 2 2 Int := fun i j => #[#[5, 6], #[7, 8]][i][j] open Matrix -- activate .[.,.] notation #eval (m1*m2)[0, 0] -- 19 #eval (m1*m2)[0, 1] -- 22 #eval (m1*m2)[1, 0] -- 43 #eval (m1*m2)[1, 1] -- 50 def v := -2 #eval (v*m1*m2)[0, 0] -- -38 def ex1 (a b : Nat) (x : Matrix 10 20 Nat) (y : Matrix 20 10 Nat) (z : Matrix 10 10 Nat) : Matrix 10 10 Nat := a * x * y + b * z def ex2 (a b : Nat) (x : Matrix m n Nat) (y : Matrix n m Nat) (z : Matrix m m Nat) : Matrix m m Nat := a * x * y + b * z
8fa2916704b50397489f753ded164907fa85f5ff
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/group/with_one/defs.lean
3fc88f27803a39d6c0b2ce714e875a083447870c
[ "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
12,144
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johan Commelin -/ import order.with_bot import algebra.ring.defs /-! # Adjoining a zero/one to semigroups and related algebraic structures This file contains different results about adjoining an element to an algebraic structure which then behaves like a zero or a one. An example is adjoining a one to a semigroup to obtain a monoid. That this provides an example of an adjunction is proved in `algebra.category.Mon.adjunctions`. Another result says that adjoining to a group an element `zero` gives a `group_with_zero`. For more information about these structures (which are not that standard in informal mathematics, see `algebra.group_with_zero.basic`) -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Add an extra element `1` to a type -/ @[to_additive "Add an extra element `0` to a type"] def with_one (α) := option α namespace with_one instance [has_repr α] : has_repr (with_zero α) := ⟨λ o, match o with | none := "0" | (some a) := "↑" ++ repr a end⟩ @[to_additive] instance [has_repr α] : has_repr (with_one α) := ⟨λ o, match o with | none := "1" | (some a) := "↑" ++ repr a end⟩ @[to_additive] instance : monad with_one := option.monad @[to_additive] instance : has_one (with_one α) := ⟨none⟩ @[to_additive] instance [has_mul α] : has_mul (with_one α) := ⟨option.lift_or_get (*)⟩ @[to_additive] instance [has_inv α] : has_inv (with_one α) := ⟨λ a, option.map has_inv.inv a⟩ @[to_additive] instance [has_involutive_inv α] : has_involutive_inv (with_one α) := { inv_inv := λ a, (option.map_map _ _ _).trans $ by simp_rw [inv_comp_inv, option.map_id, id], ..with_one.has_inv } @[to_additive] instance [has_inv α] : inv_one_class (with_one α) := { inv_one := rfl, ..with_one.has_one, ..with_one.has_inv } @[to_additive] instance : inhabited (with_one α) := ⟨1⟩ @[to_additive] instance [nonempty α] : nontrivial (with_one α) := option.nontrivial @[to_additive] instance : has_coe_t α (with_one α) := ⟨some⟩ /-- Recursor for `with_one` using the preferred forms `1` and `↑a`. -/ @[elab_as_eliminator, to_additive "Recursor for `with_zero` using the preferred forms `0` and `↑a`."] def rec_one_coe {C : with_one α → Sort*} (h₁ : C 1) (h₂ : Π (a : α), C a) : Π (n : with_one α), C n := option.rec h₁ h₂ /-- Deconstruct a `x : with_one α` to the underlying value in `α`, given a proof that `x ≠ 1`. -/ @[to_additive unzero "Deconstruct a `x : with_zero α` to the underlying value in `α`, given a proof that `x ≠ 0`."] def unone {x : with_one α} (hx : x ≠ 1) : α := with_bot.unbot x hx @[simp, to_additive unzero_coe] lemma unone_coe {x : α} (hx : (x : with_one α) ≠ 1) : unone hx = x := rfl @[simp, to_additive coe_unzero] lemma coe_unone {x : with_one α} (hx : x ≠ 1) : ↑(unone hx) = x := with_bot.coe_unbot x hx @[to_additive] lemma some_eq_coe {a : α} : (some a : with_one α) = ↑a := rfl @[simp, to_additive] lemma coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) := option.some_ne_none a @[simp, to_additive] lemma one_ne_coe {a : α} : (1 : with_one α) ≠ a := coe_ne_one.symm @[to_additive] lemma ne_one_iff_exists {x : with_one α} : x ≠ 1 ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists @[to_additive] instance can_lift : can_lift (with_one α) α coe (λ a, a ≠ 1) := { prf := λ a, ne_one_iff_exists.1 } @[simp, norm_cast, to_additive] lemma coe_inj {a b : α} : (a : with_one α) = b ↔ a = b := option.some_inj @[elab_as_eliminator, to_additive] protected lemma cases_on {P : with_one α → Prop} : ∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x := option.cases_on -- the `show` statements in the proofs are important, because otherwise the generated lemmas -- `with_one.mul_one_class._proof_{1,2}` have an ill-typed statement after `with_one` is made -- irreducible. @[to_additive] instance [has_mul α] : mul_one_class (with_one α) := { mul := (*), one := (1), one_mul := show ∀ x : with_one α, 1 * x = x, from (option.lift_or_get_is_left_id _).1, mul_one := show ∀ x : with_one α, x * 1 = x, from (option.lift_or_get_is_right_id _).1 } @[to_additive] instance [semigroup α] : monoid (with_one α) := { mul_assoc := (option.lift_or_get_assoc _).1, ..with_one.mul_one_class } example [semigroup α] : @monoid.to_mul_one_class _ (@with_one.monoid α _) = @with_one.mul_one_class α _ := rfl @[to_additive] instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } attribute [irreducible] with_one @[simp, norm_cast, to_additive] lemma coe_mul [has_mul α] (a b : α) : ((a * b : α) : with_one α) = a * b := rfl @[simp, norm_cast, to_additive] lemma coe_inv [has_inv α] (a : α) : ((a⁻¹ : α) : with_one α) = a⁻¹ := rfl end with_one namespace with_zero instance [one : has_one α] : has_one (with_zero α) := { ..one } @[simp, norm_cast] lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a * b) o₂), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.has_zero } @[simp, norm_cast] lemma coe_mul {α : Type u} [has_mul α] {a b : α} : ((a * b : α) : with_zero α) = a * b := rfl @[simp] lemma zero_mul {α : Type u} [has_mul α] (a : with_zero α) : 0 * a = 0 := rfl @[simp] lemma mul_zero {α : Type u} [has_mul α] (a : with_zero α) : a * 0 = 0 := by cases a; refl instance [has_mul α] : no_zero_divisors (with_zero α) := ⟨by { rintro (a|a) (b|b) h, exacts [or.inl rfl, or.inl rfl, or.inr rfl, option.no_confusion h] }⟩ instance [semigroup α] : semigroup_with_zero (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup_with_zero } instance [mul_one_class α] : mul_zero_one_class (with_zero α) := { one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.mul_zero_class, ..with_zero.has_one } instance [has_one α] [has_pow α ℕ] : has_pow (with_zero α) ℕ := ⟨λ x n, match x, n with | none, 0 := 1 | none, n + 1 := 0 | some x, n := ↑(x ^ n) end⟩ @[simp, norm_cast] lemma coe_pow [has_one α] [has_pow α ℕ] {a : α} (n : ℕ) : ↑(a ^ n : α) = (↑a ^ n : with_zero α) := rfl instance [monoid α] : monoid_with_zero (with_zero α) := { npow := λ n x, x ^ n, npow_zero' := λ x, match x with | none := rfl | some x := congr_arg some $ pow_zero _ end, npow_succ' := λ n x, match x with | none := rfl | some x := congr_arg some $ pow_succ _ _ end, .. with_zero.mul_zero_one_class, .. with_zero.semigroup_with_zero } instance [comm_monoid α] : comm_monoid_with_zero (with_zero α) := { ..with_zero.monoid_with_zero, ..with_zero.comm_semigroup } /-- Given an inverse operation on `α` there is an inverse operation on `with_zero α` sending `0` to `0`-/ instance [has_inv α] : has_inv (with_zero α) := ⟨λ a, option.map has_inv.inv a⟩ @[simp, norm_cast] lemma coe_inv [has_inv α] (a : α) : ((a⁻¹ : α) : with_zero α) = a⁻¹ := rfl @[simp] lemma inv_zero [has_inv α] : (0 : with_zero α)⁻¹ = 0 := rfl instance [has_involutive_inv α] : has_involutive_inv (with_zero α) := { inv_inv := λ a, (option.map_map _ _ _).trans $ by simp_rw [inv_comp_inv, option.map_id, id], ..with_zero.has_inv } instance [inv_one_class α] : inv_one_class (with_zero α) := { inv_one := show ((1⁻¹ : α) : with_zero α) = 1, by simp, ..with_zero.has_one, ..with_zero.has_inv } instance [has_div α] : has_div (with_zero α) := ⟨λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a / b) o₂)⟩ @[norm_cast] lemma coe_div [has_div α] (a b : α) : ↑(a / b : α) = (a / b : with_zero α) := rfl instance [has_one α] [has_pow α ℤ] : has_pow (with_zero α) ℤ := ⟨λ x n, match x, n with | none, int.of_nat 0 := 1 | none, int.of_nat (nat.succ n) := 0 | none, int.neg_succ_of_nat n := 0 | some x, n := ↑(x ^ n) end⟩ @[simp, norm_cast] lemma coe_zpow [div_inv_monoid α] {a : α} (n : ℤ) : ↑(a ^ n : α) = (↑a ^ n : with_zero α) := rfl instance [div_inv_monoid α] : div_inv_monoid (with_zero α) := { div_eq_mul_inv := λ a b, match a, b with | none, _ := rfl | some a, none := rfl | some a, some b := congr_arg some (div_eq_mul_inv _ _) end, zpow := λ n x, x ^ n, zpow_zero' := λ x, match x with | none := rfl | some x := congr_arg some $ zpow_zero _ end, zpow_succ' := λ n x, match x with | none := rfl | some x := congr_arg some $ div_inv_monoid.zpow_succ' _ _ end, zpow_neg' := λ n x, match x with | none := rfl | some x := congr_arg some $ div_inv_monoid.zpow_neg' _ _ end, .. with_zero.has_div, .. with_zero.has_inv, .. with_zero.monoid_with_zero, } instance [div_inv_one_monoid α] : div_inv_one_monoid (with_zero α) := { ..with_zero.div_inv_monoid, ..with_zero.inv_one_class } instance [division_monoid α] : division_monoid (with_zero α) := { mul_inv_rev := λ a b, match a, b with | none, none := rfl | none, some b := rfl | some a, none := rfl | some a, some b := congr_arg some $ mul_inv_rev _ _ end, inv_eq_of_mul := λ a b, match a, b with | none, none := λ _, rfl | none, some b := by contradiction | some a, none := by contradiction | some a, some b := λ h, congr_arg some $ inv_eq_of_mul_eq_one_right $ option.some_injective _ h end, .. with_zero.div_inv_monoid, .. with_zero.has_involutive_inv } instance [division_comm_monoid α] : division_comm_monoid (with_zero α) := { .. with_zero.division_monoid, .. with_zero.comm_semigroup } section group variables [group α] /-- if `G` is a group then `with_zero G` is a group with zero. -/ instance : group_with_zero (with_zero α) := { inv_zero := inv_zero, mul_inv_cancel := λ a ha, by { lift a to α using ha, norm_cast, apply mul_right_inv }, .. with_zero.monoid_with_zero, .. with_zero.div_inv_monoid, .. with_zero.nontrivial } end group instance [comm_group α] : comm_group_with_zero (with_zero α) := { .. with_zero.group_with_zero, .. with_zero.comm_monoid_with_zero } instance [add_monoid_with_one α] : add_monoid_with_one (with_zero α) := { nat_cast := λ n, if n = 0 then 0 else (n.cast : α), nat_cast_zero := rfl, nat_cast_succ := λ n, begin cases n, show (((1 : ℕ) : α) : with_zero α) = 0 + 1, by rw [nat.cast_one, coe_one, zero_add], show (((n + 2 : ℕ) : α) : with_zero α) = ((n + 1 : ℕ) : α) + 1, by rw [nat.cast_succ, coe_add, coe_one], end, .. with_zero.add_monoid, ..with_zero.has_one } instance [semiring α] : semiring (with_zero α) := { left_distrib := λ a b c, begin cases a with a, {refl}, cases b with b; cases c with c; try {refl}, exact congr_arg some (left_distrib _ _ _) end, right_distrib := λ a b c, begin cases c with c, { change (a + b) * 0 = a * 0 + b * 0, simp }, cases a with a; cases b with b; try {refl}, exact congr_arg some (right_distrib _ _ _) end, ..with_zero.add_monoid_with_one, ..with_zero.add_comm_monoid, ..with_zero.mul_zero_class, ..with_zero.monoid_with_zero } attribute [irreducible] with_zero end with_zero
5ae02dc8882fe0a57e5da49ec787fdef2551eccd
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world8/level8.lean
c007a90676bbc0cb21dd74984c4ae1c5725ebaee
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
508
lean
import game.world8.level7 -- hide namespace mynat -- hide /- # Advanced Addition World ## Level 8: `eq_zero_of_add_right_eq_self` The lemma you're about to prove will be useful when we want to prove that $\leq$ is antisymmetric. There are some wrong paths that you can take with this one. -/ /- Lemma If $a$ and $b$ are natural numbers such that $$ a + b = a, $$ then $b = 0$. -/ lemma eq_zero_of_add_right_eq_self (a b : mynat) : a + b = a → b = 0 := begin [nat_num_game] end end mynat -- hide
7cbe20aa5a083f3fdd6ac952770015f02fd1dd63
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/finsupp/antidiagonal.lean
53bef39b2863528a23ee958fd28de6741c885f49
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,503
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import data.finsupp.basic import data.multiset.antidiagonal /-! # The `finsupp` counterpart of `multiset.antidiagonal`. The antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. -/ noncomputable theory open_locale classical big_operators namespace finsupp open finset variables {α : Type*} /-- The `finsupp` counterpart of `multiset.antidiagonal`: the antidiagonal of `s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/ def antidiagonal' (f : α →₀ ℕ) : ((α →₀ ℕ) × (α →₀ ℕ)) →₀ ℕ := (f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp /-- The antidiagonal of `s : α →₀ ℕ` is the finset of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`. -/ def antidiagonal (f : α →₀ ℕ) : finset ((α →₀ ℕ) × (α →₀ ℕ)) := f.antidiagonal'.support @[simp] lemma mem_antidiagonal {f : α →₀ ℕ} {p : (α →₀ ℕ) × (α →₀ ℕ)} : p ∈ antidiagonal f ↔ p.1 + p.2 = f := begin rcases p with ⟨p₁, p₂⟩, simp [antidiagonal, antidiagonal', ← and.assoc, ← finsupp.to_multiset.apply_eq_iff_eq] end lemma swap_mem_antidiagonal {n : α →₀ ℕ} {f : (α →₀ ℕ) × (α →₀ ℕ)} : f.swap ∈ antidiagonal n ↔ f ∈ antidiagonal n := by simp only [mem_antidiagonal, add_comm, prod.swap] lemma antidiagonal_filter_fst_eq (f g : α →₀ ℕ) [D : Π (p : (α →₀ ℕ) × (α →₀ ℕ)), decidable (p.1 = g)] : (antidiagonal f).filter (λ p, p.1 = g) = if g ≤ f then {(g, f - g)} else ∅ := begin ext ⟨a, b⟩, suffices : a = g → (a + b = f ↔ g ≤ f ∧ b = f - g), { simpa [apply_ite ((∈) (a, b)), ← and.assoc, @and.right_comm _ (a = _), and.congr_left_iff] }, unfreezingI {rintro rfl}, split, { rintro rfl, exact ⟨le_add_right le_rfl, (add_tsub_cancel_left _ _).symm⟩ }, { rintro ⟨h, rfl⟩, exact add_tsub_cancel_of_le h } end lemma antidiagonal_filter_snd_eq (f g : α →₀ ℕ) [D : Π (p : (α →₀ ℕ) × (α →₀ ℕ)), decidable (p.2 = g)] : (antidiagonal f).filter (λ p, p.2 = g) = if g ≤ f then {(f - g, g)} else ∅ := begin ext ⟨a, b⟩, suffices : b = g → (a + b = f ↔ g ≤ f ∧ a = f - g), { simpa [apply_ite ((∈) (a, b)), ← and.assoc, and.congr_left_iff] }, unfreezingI {rintro rfl}, split, { rintro rfl, exact ⟨le_add_left le_rfl, (add_tsub_cancel_right _ _).symm⟩ }, { rintro ⟨h, rfl⟩, exact tsub_add_cancel_of_le h } end @[simp] lemma antidiagonal_zero : antidiagonal (0 : α →₀ ℕ) = singleton (0,0) := by rw [antidiagonal, antidiagonal', multiset.to_finsupp_support]; refl @[to_additive] lemma prod_antidiagonal_swap {M : Type*} [comm_monoid M] (n : α →₀ ℕ) (f : (α →₀ ℕ) → (α →₀ ℕ) → M) : ∏ p in antidiagonal n, f p.1 p.2 = ∏ p in antidiagonal n, f p.2 p.1 := finset.prod_bij (λ p hp, p.swap) (λ p, swap_mem_antidiagonal.2) (λ p hp, rfl) (λ p₁ p₂ _ _ h, prod.swap_injective h) (λ p hp, ⟨p.swap, swap_mem_antidiagonal.2 hp, p.swap_swap.symm⟩) /-- The set `{m : α →₀ ℕ | m ≤ n}` as a `finset`. -/ def Iic_finset (n : α →₀ ℕ) : finset (α →₀ ℕ) := (antidiagonal n).image prod.fst @[simp] lemma mem_Iic_finset {m n : α →₀ ℕ} : m ∈ Iic_finset n ↔ m ≤ n := by simp [Iic_finset, le_iff_exists_add, eq_comm] @[simp] lemma coe_Iic_finset (n : α →₀ ℕ) : ↑(Iic_finset n) = set.Iic n := by { ext, simp } /-- Let `n : α →₀ ℕ` be a finitely supported function. The set of `m : α →₀ ℕ` that are coordinatewise less than or equal to `n`, is a finite set. -/ lemma finite_le_nat (n : α →₀ ℕ) : set.finite {m | m ≤ n} := by simpa using (Iic_finset n).finite_to_set /-- Let `n : α →₀ ℕ` be a finitely supported function. The set of `m : α →₀ ℕ` that are coordinatewise less than or equal to `n`, but not equal to `n` everywhere, is a finite set. -/ lemma finite_lt_nat (n : α →₀ ℕ) : set.finite {m | m < n} := (finite_le_nat n).subset $ λ m, le_of_lt end finsupp
4c601f070a3ee8fd8d62e0f908ee013e75d27889
4fa118f6209450d4e8d058790e2967337811b2b5
/src/for_mathlib/with_zero.lean
e7d60e52119898bd50751dcb21d51230b691f24e
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
5,476
lean
import data.equiv.basic import group_theory.subgroup universes u v section open tactic interactive (parse loc.wildcard) interactive.types (location) lean.parser (many ident) run_cmd mk_simp_attr `with_zero_simp meta def tactic.with_zero_cases : list expr → tactic unit | (h::t) := seq (induction h [] (some `with_zero.cases_on) >> skip) $ tactic.with_zero_cases t | [] := do try (interactive.norm_cast loc.wildcard), try (tactic.interactive.simp_core {} assumption ff [] [`with_zero_simp] loc.wildcard), try (do exfalso, assumption) /-- Case bashing for with_zero. If `x₁, ... x_n` have type `with_zero α` then `with_zero cases x₁ ... x_n` will split according to whether each `x_i` is zero or coerced from `α` then run `norm_cast at *`, try to simplify using the simp rules `with_zero_simp`, and try to get a contradiction. -/ meta def tactic.interactive.with_zero_cases (l : parse $ many ident) := l.mmap tactic.get_local >>= tactic.with_zero_cases end namespace with_zero variables {α : Type u} {β : Type v} @[simp, with_zero_simp] lemma zero_le [preorder α] {x : with_zero α} : 0 ≤ x := by { intros y hy, cases hy } @[simp, with_zero_simp] lemma zero_lt_coe [preorder α] {a : α} : (0 : with_zero α) < a := ⟨a, rfl, λ y hy, by cases hy⟩ @[simp, with_zero_simp] lemma not_coe_eq_zero [preorder α] {x : α} : ¬ (x : with_zero α) = 0 := λ h, option.no_confusion h @[elim_cast] lemma coe_le_coe [preorder α] {x y : α} : (x : with_zero α) ≤ (y : with_zero α) ↔ x ≤ y := ⟨λ h, by rcases (h x rfl) with ⟨z, ⟨h2⟩, h3⟩; exact h3, λ _ _ h, ⟨y, rfl, by cases h ; assumption⟩⟩ @[elim_cast] lemma coe_lt_coe [preorder α] {x y : α} : (x : with_zero α) < (y : with_zero α) ↔ x < y := by repeat { rw [lt_iff_le_not_le, coe_le_coe] } -- TODO: replace `coe_one` in mathlib by this one, which seems to be stated as needed by norm_cast. -- Same remark applies to the next two lemmas. @[elim_cast] lemma coe_one' [has_one α] : (1 : with_zero α) = ((1 : α) : with_zero α) := rfl @[move_cast] lemma inv_coe' {α : Type*} [has_inv α] (a : α) : ((a⁻¹ : α) : with_zero α) = (a : with_zero α)⁻¹ := rfl @[move_cast] lemma mul_coe' {α : Type*} [has_mul α] (a b : α) : ((a * b : α) : with_zero α) = (a : with_zero α) * b := rfl attribute [elim_cast] coe_inj @[simp] lemma le_zero_iff_eq_zero [preorder α] {x : with_zero α} : x ≤ 0 ↔ x = 0 := begin with_zero_cases x, intro h, rcases h x rfl with ⟨_, h, _⟩, exact option.no_confusion h, end @[simp] lemma not_coe_le_zero [preorder α] (x : α) : ¬ (x : with_zero α) ≤ 0 := begin intro h, rw le_zero_iff_eq_zero at h, exact not_coe_eq_zero h, end @[simp] lemma not_lt_zero [preorder α] (x : with_zero α) : ¬ x < 0 := begin intro h, with_zero_cases x, exact lt_irrefl _ h, exact not_coe_le_zero x (le_of_lt h), end @[simp] lemma map_zero {f : α → β} : map f 0 = 0 := option.map_none' @[simp, elim_cast] lemma map_coe {f : α → β} {a : α} : map f (a : with_zero α) = f a := option.map_some' @[simp] lemma map_id {α : Type*} : map (id : α → α) = id := option.map_id lemma map_comp {α β γ : Type*} (f : α → β) (g : β → γ) (r : with_zero α) : map (g ∘ f) r = map g (map f r) := by cases r; refl @[simp] lemma map_eq_zero_iff {f : α → β} {a : with_zero α} : map f a = 0 ↔ a = 0 := ⟨λ h, by with_zero_cases a, λ h, by simp [h]⟩ lemma injective_map {f : α → β} (H : function.injective f) : function.injective (map f) := option.injective_map H lemma map_monotone [preorder α] [preorder β] {f : α → β} (H : monotone f) : monotone (map f) := λ x y, by { with_zero_cases x y, exact λ h, H h } lemma map_strict_mono [linear_order α] [partial_order β] {f : α → β} (H : ∀ a b, a < b → f a < f b) : strict_mono (map f) := λ x y, by { with_zero_cases x y, exact λ h, H _ _ h } lemma map_le [preorder α] [preorder β] {f : α → β} (H : ∀ a b : α, a ≤ b ↔ f a ≤ f b) (x y : with_zero α) : x ≤ y ↔ map f x ≤ map f y := by { with_zero_cases x y, exact H x y } @[move_cast] lemma coe_min (x y : α) [decidable_linear_order α] : ((min x y : α) : with_zero α) = min x y := begin by_cases h: x ≤ y, { simp [min_eq_left, h] }, { simp [min_eq_right, le_of_not_le h] } end section group variables [group α] lemma mul_left_cancel : ∀ {x : with_zero α} (h : x ≠ 0) {y z : with_zero α}, x * y = x * z → y = z | 0 h := false.elim $ h rfl | (a : α) h := λ y z h2, begin have h3 : (a⁻¹ : with_zero α) * (a * y) = a⁻¹ * (a * z) := by rw h2, rwa [←mul_assoc, ←mul_assoc, mul_left_inv _ h, one_mul, one_mul] at h3, end lemma mul_right_cancel : ∀ {x : with_zero α} (h : x ≠ 0) {y z : with_zero α}, y * x = z * x → y = z | 0 h := false.elim $ h rfl | (a : α) h := λ y z h2, begin have h3 : (y * a) * a⁻¹ = (z * a) * a⁻¹ := by rw h2, rwa [mul_assoc, mul_assoc, mul_right_inv _ h, mul_one, mul_one] at h3, end lemma mul_inv_eq_of_eq_mul : ∀ {x : with_zero α} (h : x ≠ 0) {y z : with_zero α}, y = z * x → y * x⁻¹ = z | 0 h := false.elim $ h rfl | (x : α) h := λ _ _ _, mul_right_cancel h (by rwa [mul_assoc, mul_left_inv _ h, mul_one]) lemma eq_mul_inv_of_mul_eq {x : with_zero α} (h : x ≠ 0) {y z : with_zero α} (h2 : z * x = y) : z = y * x⁻¹ := eq.symm $ mul_inv_eq_of_eq_mul h h2.symm end group end with_zero
d1aacf7e4629123435e38d6fdea5c588ff652946
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/topology/maps.lean
de55ec636a42d613e775fe5c43fff264b5a89c93
[ "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
14,813
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 Specific classes of maps between topological spaces: embeddings, open maps, quotient maps. -/ import topology.order open set filter lattice variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section inducing structure inducing [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := (induced : tα = tβ.induced f) variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma inducing_id : inducing (@id α) := ⟨induced_id.symm⟩ lemma inducing.comp {f : α → β} {g : β → γ} (hg : inducing g) (hf : inducing f) : inducing (g ∘ f) := ⟨by rw [hf.induced, hg.induced, induced_compose]⟩ 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 inducing_of_inducing_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : inducing (g ∘ f)) : inducing f := ⟨le_antisymm (by rwa ← continuous_iff_le_induced) (by { rw [hgf.induced, ← continuous_iff_le_induced], apply hg.comp continuous_induced_dom })⟩ lemma inducing_open {f : α → β} {s : set α} (hf : inducing f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.induced] at hs; exact hs in have is_open (t ∩ range f), from is_open_inter ht h, h_eq ▸ by rwa [image_preimage_eq_inter_range] lemma inducing_is_closed {f : α → β} {s : set α} (hf : inducing f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := let ⟨t, ht, h_eq⟩ := by rw [hf.induced, is_closed_induced_iff] at hs; exact hs in have is_closed (t ∩ range f), from is_closed_inter ht h, h_eq.symm ▸ by rwa [image_preimage_eq_inter_range] lemma inducing.nhds_eq_comap {f : α → β} (hf : inducing f) : ∀ (a : α), nhds a = comap f (nhds $ f a) := (induced_iff_nhds_eq f).1 hf.induced lemma inducing.map_nhds_eq {f : α → β} (hf : inducing f) (a : α) (h : range f ∈ nhds (f a)) : (nhds a).map f = nhds (f a) := hf.induced.symm ▸ map_nhds_induced_eq h lemma inducing.tendsto_nhds_iff {ι : Type*} {f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : inducing g) : tendsto f a (nhds b) ↔ tendsto (g ∘ f) a (nhds (g b)) := by rw [tendsto, tendsto, hg.induced, nhds_induced, ← map_le_iff_le_comap, filter.map_map] lemma inducing.continuous_iff {f : α → β} {g : β → γ} (hg : inducing g) : continuous f ↔ continuous (g ∘ f) := by simp [continuous_iff_continuous_at, continuous_at, inducing.tendsto_nhds_iff hg] lemma inducing.continuous {f : α → β} (hf : inducing f) : continuous f := hf.continuous_iff.mp continuous_id end inducing section embedding /-- A function between topological spaces is an embedding if it is injective, and for all `s : set α`, `s` is open iff it is the preimage of an open set. -/ structure embedding [tα : topological_space α] [tβ : topological_space β] (f : α → β) extends inducing f : Prop := (inj : function.injective f) variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma embedding.mk' (f : α → β) (inj : function.injective f) (induced : ∀a, comap f (nhds (f a)) = nhds a) : embedding f := ⟨⟨(induced_iff_nhds_eq f).2 (λ a, (induced a).symm)⟩, inj⟩ lemma embedding_id : embedding (@id α) := ⟨inducing_id, assume a₁ a₂ h, h⟩ lemma embedding.comp {f : α → β} {g : β → γ} (hg : embedding g) (hf : embedding f) : embedding (g ∘ f) := { inj:= assume a₁ a₂ h, hf.inj $ hg.inj h, ..hg.to_inducing.comp hf.to_inducing } 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 } lemma embedding_of_embedding_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : embedding (g ∘ f)) : embedding f := { induced := (inducing_of_inducing_compose hf hg hgf.to_inducing).induced, inj := assume a₁ a₂ h, hgf.inj $ by simp [h, (∘)] } lemma embedding_open {f : α → β} {s : set α} (hf : embedding f) (h : is_open (range f)) (hs : is_open s) : is_open (f '' s) := inducing_open hf.1 h hs lemma embedding_is_closed {f : α → β} {s : set α} (hf : embedding f) (h : is_closed (range f)) (hs : is_closed s) : is_closed (f '' s) := inducing_is_closed hf.1 h hs lemma embedding.map_nhds_eq {f : α → β} (hf : embedding f) (a : α) (h : range f ∈ nhds (f a)) : (nhds a).map f = nhds (f a) := inducing.map_nhds_eq hf.1 a h lemma embedding.tendsto_nhds_iff {ι : Type*} {f : ι → β} {g : β → γ} {a : filter ι} {b : β} (hg : embedding g) : tendsto f a (nhds b) ↔ tendsto (g ∘ f) a (nhds (g b)) := by rw [tendsto, tendsto, hg.induced, nhds_induced, ← map_le_iff_le_comap, filter.map_map] lemma embedding.continuous_iff {f : α → β} {g : β → γ} (hg : embedding g) : continuous f ↔ continuous (g ∘ f) := inducing.continuous_iff hg.1 lemma embedding.continuous {f : α → β} (hf : embedding f) : continuous f := inducing.continuous hf.1 lemma embedding.closure_eq_preimage_closure_image {e : α → β} (he : embedding e) (s : set α) : closure s = e ⁻¹' closure (e '' s) := by { ext x, rw [set.mem_preimage, ← closure_induced he.inj, he.induced] } end embedding /-- A function between topological spaces is a quotient map if it is surjective, and for all `s : set β`, `s` is open iff its preimage is an open set. -/ def quotient_map {α : Type*} {β : Type*} [tα : topological_space α] [tβ : topological_space β] (f : α → β) : Prop := function.surjective f ∧ tβ = tα.coinduced f namespace quotient_map variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] protected lemma id : quotient_map (@id α) := ⟨assume a, ⟨a, rfl⟩, coinduced_id.symm⟩ protected lemma comp {f : α → β} {g : β → γ} (hf : quotient_map f) (hg : quotient_map g) : quotient_map (g ∘ f) := ⟨function.surjective_comp hg.left hf.left, by rw [hg.right, hf.right, coinduced_compose]⟩ protected lemma of_quotient_map_compose {f : α → β} {g : β → γ} (hf : continuous f) (hg : continuous g) (hgf : quotient_map (g ∘ f)) : quotient_map g := ⟨assume b, let ⟨a, h⟩ := hgf.left b in ⟨f a, h⟩, le_antisymm (by rw [hgf.right, ← continuous_iff_coinduced_le]; apply continuous_coinduced_rng.comp hf) (by rwa ← continuous_iff_coinduced_le)⟩ protected lemma continuous_iff {f : α → β} {g : β → γ} (hf : quotient_map f) : continuous g ↔ continuous (g ∘ f) := by rw [continuous_iff_coinduced_le, continuous_iff_coinduced_le, hf.right, coinduced_compose] protected lemma continuous {f : α → β} (hf : quotient_map f) : continuous f := hf.continuous_iff.mp continuous_id end quotient_map section is_open_map variables [topological_space α] [topological_space β] def is_open_map (f : α → β) := ∀ U : set α, is_open U → is_open (f '' U) lemma is_open_map_iff_nhds_le (f : α → β) : is_open_map f ↔ ∀(a:α), nhds (f a) ≤ (nhds a).map f := begin split, { assume h a s hs, rcases mem_nhds_sets_iff.1 hs with ⟨t, hts, ht, hat⟩, exact filter.mem_sets_of_superset (mem_nhds_sets (h t ht) (mem_image_of_mem _ hat)) (image_subset_iff.2 hts) }, { refine assume h s hs, is_open_iff_mem_nhds.2 _, rintros b ⟨a, ha, rfl⟩, exact h _ (filter.image_mem_map $ mem_nhds_sets hs ha) } end end is_open_map namespace is_open_map variables [topological_space α] [topological_space β] [topological_space γ] open function protected lemma id : is_open_map (@id α) := assume s hs, by rwa [image_id] protected lemma comp {f : α → β} {g : β → γ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (g ∘ f) := by intros s hs; rw [image_comp]; exact hg _ (hf _ hs) lemma of_inverse {f : α → β} {f' : β → α} (h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') : is_open_map f := assume s hs, have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv], this ▸ h s hs lemma to_quotient_map {f : α → β} (open_map : is_open_map f) (cont : continuous f) (surj : function.surjective f) : quotient_map f := ⟨ surj, begin ext s, show is_open s ↔ is_open (f ⁻¹' s), split, { exact cont s }, { assume h, rw ← @image_preimage_eq _ _ _ s surj, exact open_map _ h } end⟩ end is_open_map section is_closed_map variables [topological_space α] [topological_space β] def is_closed_map (f : α → β) := ∀ U : set α, is_closed U → is_closed (f '' U) end is_closed_map namespace is_closed_map variables [topological_space α] [topological_space β] [topological_space γ] open function protected lemma id : is_closed_map (@id α) := assume s hs, by rwa image_id protected lemma comp {f : α → β} {g : β → γ} (hf : is_closed_map f) (hg : is_closed_map g) : is_closed_map (g ∘ f) := by { intros s hs, rw image_comp, exact hg _ (hf _ hs) } lemma of_inverse {f : α → β} {f' : β → α} (h : continuous f') (l_inv : left_inverse f f') (r_inv : right_inverse f f') : is_closed_map f := assume s hs, have f' ⁻¹' s = f '' s, by ext x; simp [mem_image_iff_of_inverse r_inv l_inv], this ▸ continuous_iff_is_closed.mp h s hs end is_closed_map section open_embedding variables [topological_space α] [topological_space β] [topological_space γ] /-- An open embedding is an embedding with open image. -/ structure open_embedding (f : α → β) extends embedding f : Prop := (open_range : is_open $ range f) lemma open_embedding.open_iff_image_open {f : α → β} (hf : open_embedding f) {s : set α} : is_open s ↔ is_open (f '' s) := ⟨embedding_open hf.to_embedding hf.open_range, λ h, begin convert ←hf.to_embedding.continuous _ h, apply preimage_image_eq _ hf.inj end⟩ lemma open_embedding.is_open_map {f : α → β} (hf : open_embedding f) : is_open_map f := λ s, hf.open_iff_image_open.mp lemma open_embedding.continuous {f : α → β} (hf : open_embedding f) : continuous f := hf.to_embedding.continuous lemma open_embedding.open_iff_preimage_open {f : α → β} (hf : open_embedding f) {s : set β} (hs : s ⊆ range f) : is_open s ↔ is_open (f ⁻¹' s) := begin convert ←hf.open_iff_image_open.symm, rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left] end lemma open_embedding_of_embedding_open {f : α → β} (h₁ : embedding f) (h₂ : is_open_map f) : open_embedding f := ⟨h₁, by convert h₂ univ is_open_univ; simp⟩ lemma open_embedding_of_continuous_injective_open {f : α → β} (h₁ : continuous f) (h₂ : function.injective f) (h₃ : is_open_map f) : open_embedding f := begin refine open_embedding_of_embedding_open ⟨⟨_⟩, h₂⟩ h₃, apply le_antisymm (continuous_iff_le_induced.mp h₁) _, intro s, change is_open _ ≤ is_open _, rw is_open_induced_iff, refine λ hs, ⟨f '' s, h₃ s hs, _⟩, rw preimage_image_eq _ h₂ end lemma open_embedding_id : open_embedding (@id α) := ⟨embedding_id, by convert is_open_univ; apply range_id⟩ lemma open_embedding.comp {f : α → β} {g : β → γ} (hg : open_embedding g) (hf : open_embedding f) : open_embedding (g ∘ f) := ⟨hg.1.comp hf.1, show is_open (range (g ∘ f)), by rw [range_comp, ←hg.open_iff_image_open]; exact hf.2⟩ lemma subtype_val.open_embedding {s : set α} (hs : is_open s) : open_embedding (subtype.val : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.val_injective, open_range := (subtype.val_range : range subtype.val = s).symm ▸ hs } end open_embedding section closed_embedding variables [topological_space α] [topological_space β] [topological_space γ] /-- A closed embedding is an embedding with closed image. -/ structure closed_embedding (f : α → β) extends embedding f : Prop := (closed_range : is_closed $ range f) variables {f : α → β} lemma closed_embedding.continuous (hf : closed_embedding f) : continuous f := hf.to_embedding.continuous lemma closed_embedding.closed_iff_image_closed (hf : closed_embedding f) {s : set α} : is_closed s ↔ is_closed (f '' s) := ⟨embedding_is_closed hf.to_embedding hf.closed_range, λ h, begin convert ←continuous_iff_is_closed.mp hf.continuous _ h, apply preimage_image_eq _ hf.inj end⟩ lemma closed_embedding.is_closed_map (hf : closed_embedding f) : is_closed_map f := λ s, hf.closed_iff_image_closed.mp lemma closed_embedding.closed_iff_preimage_closed (hf : closed_embedding f) {s : set β} (hs : s ⊆ range f) : is_closed s ↔ is_closed (f ⁻¹' s) := begin convert ←hf.closed_iff_image_closed.symm, rwa [image_preimage_eq_inter_range, inter_eq_self_of_subset_left] end lemma closed_embedding_of_embedding_closed (h₁ : embedding f) (h₂ : is_closed_map f) : closed_embedding f := ⟨h₁, by convert h₂ univ is_closed_univ; simp⟩ lemma closed_embedding_of_continuous_injective_closed (h₁ : continuous f) (h₂ : function.injective f) (h₃ : is_closed_map f) : closed_embedding f := begin refine closed_embedding_of_embedding_closed ⟨⟨_⟩, h₂⟩ h₃, apply le_antisymm (continuous_iff_le_induced.mp h₁) _, intro s', change is_open _ ≤ is_open _, rw [←is_closed_compl_iff, ←is_closed_compl_iff], generalize : -s' = s, rw is_closed_induced_iff, refine λ hs, ⟨f '' s, h₃ s hs, _⟩, rw preimage_image_eq _ h₂ end lemma closed_embedding_id : closed_embedding (@id α) := ⟨embedding_id, by convert is_closed_univ; apply range_id⟩ lemma closed_embedding.comp {f : α → β} {g : β → γ} (hg : closed_embedding g) (hf : closed_embedding f) : closed_embedding (g ∘ f) := ⟨hg.to_embedding.comp hf.to_embedding, show is_closed (range (g ∘ f)), by rw [range_comp, ←hg.closed_iff_image_closed]; exact hf.closed_range⟩ lemma subtype_val.closed_embedding {s : set α} (hs : is_closed s) : closed_embedding (subtype.val : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.val_injective, closed_range := (subtype.val_range : range subtype.val = s).symm ▸ hs } end closed_embedding
b228dd8778babd46e36a1b727b9ef035cb01b913
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/stage0/src/Lean/Util/MonadCache.lean
adde4a47f91746f7e1474c1bcb20025355ed9c44
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,482
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.HashMap namespace Lean /-- Interface for caching results. -/ class MonadCache (α β : Type) (m : Type → Type) := (findCached? : α → m (Option β)) (cache : α → β → m Unit) /-- If entry `a := b` is already in the cache, then return `b`. Otherwise, execute `b ← f a`, store `a := b` in the cache and return `b`. -/ @[inline] def checkCache {α β : Type} {m : Type → Type} [MonadCache α β m] [Monad m] (a : α) (f : α → m β) : m β := do match (← MonadCache.findCached? a) with | some b => pure b | none => do let b ← f a MonadCache.cache a b pure b instance {α β ρ : Type} {m : Type → Type} [MonadCache α β m] : MonadCache α β (ReaderT ρ m) := { findCached? := fun a r => MonadCache.findCached? a, cache := fun a b r => MonadCache.cache a b } instance {α β ε : Type} {m : Type → Type} [MonadCache α β m] [Monad m] : MonadCache α β (ExceptT ε m) := { findCached? := fun a => ExceptT.lift $ MonadCache.findCached? a, cache := fun a b => ExceptT.lift $ MonadCache.cache a b } open Std (HashMap) /-- Adapter for implementing `MonadCache` interface using `HashMap`s. We just have to specify how to extract/modify the `HashMap`. -/ class MonadHashMapCacheAdapter (α β : Type) (m : Type → Type) [BEq α] [Hashable α] := (getCache : m (HashMap α β)) (modifyCache : (HashMap α β → HashMap α β) → m Unit) namespace MonadHashMapCacheAdapter @[inline] def findCached? {α β : Type} {m : Type → Type} [BEq α] [Hashable α] [Monad m] [MonadHashMapCacheAdapter α β m] (a : α) : m (Option β) := do let c ← getCache pure (c.find? a) @[inline] def cache {α β : Type} {m : Type → Type} [BEq α] [Hashable α] [MonadHashMapCacheAdapter α β m] (a : α) (b : β) : m Unit := modifyCache fun s => s.insert a b instance {α β : Type} {m : Type → Type} [BEq α] [Hashable α] [Monad m] [MonadHashMapCacheAdapter α β m] : MonadCache α β m := { findCached? := MonadHashMapCacheAdapter.findCached?, cache := MonadHashMapCacheAdapter.cache } end MonadHashMapCacheAdapter def MonadCacheT {ω} (α β : Type) (m : Type → Type) [STWorld ω m] [BEq α] [Hashable α] := StateRefT (HashMap α β) m namespace MonadCacheT variables {ω α β : Type} {m : Type → Type} [STWorld ω m] [BEq α] [Hashable α] [MonadLiftT (ST ω) m] [Monad m] instance : MonadHashMapCacheAdapter α β (MonadCacheT α β m) := { getCache := (get : StateRefT' ..), modifyCache := fun f => (modify f : StateRefT' ..) } @[inline] def run {σ} (x : MonadCacheT α β m σ) : m σ := x.run' Std.mkHashMap instance : Monad (MonadCacheT α β m) := inferInstanceAs (Monad (StateRefT' _ _ _)) instance : MonadLift m (MonadCacheT α β m) := inferInstanceAs (MonadLift m (StateRefT' _ _ _)) instance [MonadIO m] : MonadIO (MonadCacheT α β m) := inferInstanceAs (MonadIO (StateRefT' _ _ _)) instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (MonadCacheT α β m) := inferInstanceAs (MonadExceptOf ε (StateRefT' _ _ _)) instance : MonadControl m (MonadCacheT α β m) := inferInstanceAs (MonadControl m (StateRefT' _ _ _)) instance [MonadFinally m] : MonadFinally (MonadCacheT α β m) := inferInstanceAs (MonadFinally (StateRefT' _ _ _)) end MonadCacheT end Lean
e73e900854fd0fc7d97cc8b8c107b56bba600377
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Util/PPGoal.lean
385b88df95b8f49cb40afa445c13549c17c2ec08
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,175
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 -/ import Lean.Util.PPExt namespace Lean def ppAuxDeclsDefault := false builtin_initialize registerOption `pp.auxDecls { defValue := ppAuxDeclsDefault, group := "pp", descr := "display auxiliary declarations used to compile recursive functions" } def getAuxDeclsOption (o : Options) : Bool := o.get `pp.auxDecls ppAuxDeclsDefault def ppGoal (ppCtx : PPContext) (mvarId : MVarId) : IO Format := let env := ppCtx.env let mctx := ppCtx.mctx let opts := ppCtx.opts match mctx.findDecl? mvarId with | none => pure "unknown goal" | some mvarDecl => do let indent := 2 -- Use option let ppAuxDecls := getAuxDeclsOption opts let lctx := mvarDecl.lctx let lctx := lctx.sanitizeNames.run' { options := opts } let ppCtx := { ppCtx with lctx := lctx } let pp (e : Expr) : IO Format := ppExpr ppCtx e let instMVars (e : Expr) : Expr := mctx.instantiateMVars e $.1 let addLine (fmt : Format) : Format := if fmt.isNil then fmt else fmt ++ Format.line let pushPending (ids : List Name) (type? : Option Expr) (fmt : Format) : IO Format := if ids.isEmpty then pure fmt else let fmt := addLine fmt match ids, type? with | [], _ => pure fmt | _, none => pure fmt | _, some type => do let typeFmt ← pp type pure $ fmt ++ (Format.joinSep ids.reverse " " ++ " :" ++ Format.nest indent (Format.line ++ typeFmt)).group let (varNames, type?, fmt) ← lctx.foldlM (fun (acc : List Name × Option Expr × Format) (localDecl : LocalDecl) => if !ppAuxDecls && localDecl.isAuxDecl then pure acc else let (varNames, prevType?, fmt) := acc match localDecl with | LocalDecl.cdecl _ _ varName type _ => let varName := varName.simpMacroScopes let type := instMVars type if prevType? == none || prevType? == some type then pure (varName :: varNames, some type, fmt) else do let fmt ← pushPending varNames prevType? fmt pure ([varName], some type, fmt) | LocalDecl.ldecl _ _ varName type val _ => do let varName := varName.simpMacroScopes let fmt ← pushPending varNames prevType? fmt let fmt := addLine fmt let type := instMVars type let val := instMVars val let typeFmt ← pp type let valFmt ← pp val let fmt := fmt ++ (format varName ++ " : " ++ typeFmt ++ " :=" ++ Format.nest indent (Format.line ++ valFmt)).group pure ([], none, fmt)) ([], none, Format.nil) let fmt ← pushPending varNames type? fmt let fmt := addLine fmt let typeFmt ← pp mvarDecl.type let fmt := fmt ++ "⊢" ++ " " ++ Format.nest indent typeFmt match mvarDecl.userName with | Name.anonymous => pure fmt | name => pure $ "case " ++ format name.eraseMacroScopes ++ Format.line ++ fmt end Lean
8b8703069a1faa5e2a1283b394a9fe5057a665ee
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/order/filter/basic.lean
6df2eb929af5cffc640d635a3affe553edafb217
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
98,948
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad -/ import order.galois_connection order.zorn order.copy import data.set.finite /-! # Theory of filters on sets ## Main definitions * `filter` : filter on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `join` : operations on filters; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`. * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`. -/ open set universes u v w x y open_locale classical section order variables {α : Type u} (r : α → α → Prop) local infix ` ≼ ` : 50 := r lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊆) f) (h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) := by simp only [directed_on, exists_prop, mem_Union, exists_imp_distrib]; exact assume a₁ b₁ fb₁ a₂ b₂ fb₂, let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂, ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) in ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ end order theorem directed_of_chain {α β r} [is_refl β r] {f : α → β} {c : set α} (h : zorn.chain (f ⁻¹'o r) c) : directed r (λx:{a:α // a ∈ c}, f (x.val)) := assume ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases (assume : a = b, by simp only [this, exists_prop, and_self, subtype.exists]; exact ⟨b, hb, refl _⟩) (assume : a ≠ b, (h a ha b hb this).elim (λ h : r (f a) (f b), ⟨⟨b, hb⟩, h, refl _⟩) (λ h : r (f b) (f a), ⟨⟨a, ha⟩, refl _, h⟩)) /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection, -/ structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ @[reducible] instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by rw [filter_eq_iff, ext_iff] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets lemma univ_mem_sets' (h : ∀ a, a ∈ s) : s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ lemma Inter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (∀i∈is, s i ∈ f) → (⋂i∈is, s i) ∈ f := finite.induction_on hf (assume hs, by simp only [univ_mem_sets, mem_empty_eq, Inter_neg, Inter_univ, not_false_iff]) (assume i is _ hf hi hs, have h₁ : s i ∈ f, from hs i (by simp), have h₂ : (⋂x∈is, s x) ∈ f, from hi $ assume a ha, hs _ $ by simp only [ha, mem_insert_iff, or_true], by simp [inter_mem_sets h₁ h₂]) lemma Inter_mem_sets_of_fintype {β : Type v} {s : β → set α} [fintype β] (h : ∀i, s i ∈ f) : (⋂i, s i) ∈ f := by simpa using Inter_mem_sets finite_univ (λi hi, h i) lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', match e' with | some e := interactive.exact e | none := skip end end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } instance : inhabited (filter α) := ⟨principal ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ principal t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ principal s := subset.refl _ end principal section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [univ_mem_sets, mem_set_of_eq]; exact univ_mem_sets, sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ {} : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s), sets_of_superset := assume x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := assume x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u h, generate_sets.basic h, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃t₁∈f, ∃t₂∈g, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) := iff.rfl @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.has_top).1 (top_unique $ assume s hs, by have := univ_mem_sets ; finish) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ principal) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [supr_sets_eq, iff_self, mem_Inter] @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] lemma monotone_principal : monotone (principal : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s := rfl /-! ### Lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma nonempty_of_mem_sets {f : filter α} (hf : f ≠ ⊥) {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_in_sets_eq_bot.mp hf)) id lemma nonempty_of_ne_bot {f : filter α} (hf : f ≠ ⊥) : nonempty α := nonempty_of_exists $ nonempty_of_mem_sets hf univ_mem_sets lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) lemma forall_sets_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ f ≠ ⊥ := ⟨λ h hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot_sets), nonempty_of_mem_sets⟩ lemma mem_sets_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f := have ∅ ∈ f ⊓ principal (- s), from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma eq_Inf_of_mem_sets_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_sets_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_sets_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_sets_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_sets_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_sets_iff_exists_mem (λ s, by simp only [mem_Union]), congr_arg filter.sets this.symm lemma mem_infi {f : ι → filter α} (h : directed (≥) f) (ne : nonempty ι) (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [infi_sets_eq h ne, mem_Union] @[nolint ge_or_gt] -- Intentional use of `≥` lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := let ⟨i, hi⟩ := ne in calc (⨅ i ∈ s, f i).sets = (⨅ t : {t // t ∈ s}, (f t.val)).sets : by rw [infi_subtype]; refl ... = (⨆ t : {t // t ∈ s}, (f t.val).sets) : infi_sets_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨆ t ∈ {t | t ∈ s}, (f t).sets) : by rw [supr_subtype]; refl @[nolint ge_or_gt] -- Intentional use of `≥` lemma mem_binfi {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i∈s, f i) ↔ ∃ i ∈ s, t ∈ f i := by simp only [binfi_sets_eq h ne, mem_bUnion_iff] lemma infi_sets_eq_finite (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h), apply_instance end lemma mem_infi_finite {f : ι → filter α} (s) : s ∈ infi f ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets := show s ∈ (infi f).sets ↔ s ∈ ⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets, by rw infi_sets_eq_finite @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, mem_sup_sets, iff_self, mem_set_of_eq] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, join, iff_self, mem_Inter, mem_set_of_eq] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_eq {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup (le_refl f) $ infi_le _ _), rintros t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_right_of_le le_top }, { rintros ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this _ _, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, assume p hpa hp ht, exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem_sets @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem_sets lemma eventually_of_forall {p : α → Prop} (f : filter α) (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem_sets' hp lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_in_sets_eq_bot lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_sets hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (f.eventually_of_forall hq) lemma eventually.congr {f : filter α} {β : Type*} {u v : α → β} {p : β → Prop} (h : ∀ᶠ a in f, u a = v a) (h' : ∀ᶠ a in f, p (u a)) : ∀ᶠ a in f, p (v a) := h'.mp (h.mono (by simp {contextual := tt})) lemma eventually.congr_iff {f : filter α} {β : Type*} {u v : α → β} (h : ∀ᶠ a in f, u a = v a) (p : β → Prop) : (∀ᶠ a in f, p (u a)) ↔ (∀ᶠ a in f, p (v a)) := ⟨h.congr, eventually.congr (h.mp (by simp {contextual := tt}))⟩ @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr_sets @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in principal a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} (hf : f ≠ ⊥) {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := begin assume h', have := h.and h', simp only [and_not_self, eventually_false_iff_eq_bot] at this, exact hf this end lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (f.eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, assume x hpq hq hp, exact hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from f.eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hf : f ≠ ⊥) : ∃ x, p x := (hp.frequently hf).exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨assume hp q hq, (hp.and_eventually hq).exists, assume H hp, by simpa only [and_not_self, exists_false] using H hp⟩ @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ f ≠ ⊥ := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in principal a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) := filter_eq $ set.ext $ by simp only [union_subset_iff, union_subset_iff, mem_sup_sets, forall_const, iff_self, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) := filter_eq $ set.ext $ assume x, by simp only [supr_sets_eq, mem_principal_sets, mem_Inter]; exact (@supr_le_iff (set α) _ _ _ _).symm lemma principal_univ : principal (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] lemma principal_empty : principal (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ @[simp] lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ := empty_in_sets_eq_bot.symm.trans $ mem_principal_sets.trans subset_empty_iff lemma principal_ne_bot_iff {s : set α} : principal s ≠ ⊥ ↔ s.nonempty := (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma inf_principal_eq_bot {f : filter α} {s : set α} (hs : -s ∈ f) : f ⊓ principal s = ⊥ := empty_in_sets_eq_bot.mp ⟨_, hs, s, mem_principal_self s, assume x ⟨h₁, h₂⟩, h₁ h₂⟩ theorem mem_inf_principal (f : filter α) (s t : set α) : s ∈ f ⊓ principal t ↔ { x | x ∈ t → x ∈ s } ∈ f := begin simp only [mem_inf_sets, mem_principal_sets, exists_prop], split, { rintros ⟨u, ul, v, tsubv, uvinter⟩, apply filter.mem_sets_of_superset ul, intros x xu xt, exact uvinter ⟨xu, tsubv xt⟩ }, intro h, refine ⟨_, h, t, set.subset.refl t, _⟩, rintros x ⟨hx, xt⟩, exact hx xt end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅i∈s, principal (f i)) = principal (⋂i∈s, f i) := begin ext t, simp [mem_infi_sets_finset], split, { rintros ⟨p, hp, ht⟩, calc (⋂ (i : ι) (H : i ∈ s), f i) ≤ (⋂ (i : ι) (H : i ∈ s), p i) : infi_le_infi (λi, infi_le_infi (λhi, mem_principal_sets.1 (hp i hi))) ... ≤ t : ht }, { assume h, exact ⟨f, λi hi, subset.refl _, h⟩ } end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅i, principal (f i)) = principal (⋂i, f i) := by simpa using infi_principal_finset finset.univ f end lattice section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (principal s) = principal (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) := iff.intro (assume ht, ⟨set.preimage m t, ht, image_preimage_subset _ _⟩) (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht) @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } end comap /-- The cofinite filter is the filter of subsets whose complements are finite. -/ def cofinite : filter α := { sets := {s | finite (- s)}, univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq], sets_of_superset := assume s t (hs : finite (-s)) (st: s ⊆ t), finite_subset hs $ compl_subset_compl.2 st, inter_sets := assume s t (hs : finite (-s)) (ht : finite (-t)), by simp only [compl_inter, finite_union, ht, hs, mem_set_of_eq] } @[simp] lemma mem_cofinite {s : set α} : s ∈ (@cofinite α) ↔ finite (-s) := iff.rfl lemma cofinite_ne_bot [infinite α] : @cofinite α ≠ ⊥ := mt empty_in_sets_eq_bot.mpr $ by { simp only [mem_cofinite, compl_empty], exact infinite_univ } lemma frequently_cofinite_iff_infinite {p : α → Prop} : (∃ᶠ x in cofinite, p x) ↔ set.infinite {x | p x} := by simp only [filter.frequently, filter.eventually, mem_cofinite, compl_set_of, not_not, set.infinite] /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩, assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁, assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `principal {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl lemma pure_eq_principal (a : α) : (pure a : filter α) = principal {a} := filter.ext $ λ s, by simp only [mem_pure_sets, mem_principal_sets, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := filter.ext $ λ s, iff.rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β, pure_bind, bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map, mem_join_sets, mem_set_of_eq, function.comp, mem_pure_sets] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /- map and comap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.refl _⟩ lemma comap_id : comap id f = f := le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma comap_comap_comp {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) @[simp] theorem comap_principal {t : set β} : comap m (principal t) = principal (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := assume f g, map_le_iff_le_comap lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ assume s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆i, comap m (f i)) := le_antisymm (assume s hs, have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], assume i, exact (ht i).2 end⟩) (supr_le $ assume i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨g₁.sets_of_superset ht₁ (subset_union_left _ _), g₂.sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) ((@comap_mono _ _ m).le_map_sup _ _) lemma map_comap {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := le_antisymm map_comap_le (assume t' ⟨t, ht, sub⟩, by filter_upwards [ht, hf]; rintros x hxt ⟨y, rfl⟩; exact sub hxt) lemma comap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) : comap m (map m f) = f := have ∀s, preimage m (image m s) = s, from assume s, preimage_image_eq s h, le_antisymm (assume s hs, ⟨ image m s, f.sets_of_superset hs $ by simp only [this, subset.refl], by simp only [this, subset.refl]⟩) le_comap_map lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : ∀ x y, m x = m y → x = y) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this theorem le_map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : l ≤ map f (comap f l) := assume s ⟨t, tl, ht⟩, have t ∩ u ⊆ s, from assume x ⟨xt, xu⟩, exists.elim (hf x xu) $ λ a faeq, by { rw ←faeq, apply ht, change f a ∈ t, rw faeq, exact xt }, mem_sets_of_superset (inter_mem_sets tl ul) this theorem map_comap_of_surjective' {f : α → β} {l : filter β} {u : set β} (ul : u ∈ l) (hf : ∀ y ∈ u, ∃ x, f x = y) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective' ul hf) theorem le_map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : l ≤ map f (comap f l) := le_map_comap_of_surjective' univ_mem_sets (λ y _, hf y) theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := le_antisymm map_comap_le (le_map_comap_of_surjective hf l) lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀t∈ f, ∃a, m a ∈ t) : comap m f ≠ ⊥ := forall_sets_nonempty_iff_ne_bot.mp $ assume s ⟨t, ht, t_s⟩, set.nonempty.mono t_s (hm t ht) lemma comap_ne_bot_of_range_mem {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : range m ∈ f) : comap m f ≠ ⊥ := comap_ne_bot $ assume t ht, let ⟨_, ha, a, rfl⟩ := nonempty_of_mem_sets hf (inter_mem_sets ht hm) in ⟨a, ha⟩ lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : f ≠ ⊥) {s : set α} (hs : m '' s ∈ f) : (comap m f ⊓ principal s) ≠ ⊥ := begin refine compl_compl s ▸ mt mem_sets_of_eq_bot _, rintros ⟨t, ht, hts⟩, rcases nonempty_of_mem_sets hf (inter_mem_sets hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma comap_ne_bot_of_surj {f : filter β} {m : α → β} (hf : f ≠ ⊥) (hm : function.surjective m) : comap m f ≠ ⊥ := comap_ne_bot_of_range_mem hf $ univ_mem_sets' hm lemma comap_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : f ≠ ⊥) {s : set α} (hs : m '' s ∈ f) : comap m f ≠ ⊥ := ne_bot_of_le_ne_bot (comap_inf_principal_ne_bot_of_image_mem hf hs) inf_le_left @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot (hf : f ≠ ⊥) : map m f ≠ ⊥ := assume h, hf $ by rwa [map_eq_bot_iff] at h lemma map_ne_bot_iff (f : α → β) {F : filter α} : map f F ≠ ⊥ ↔ F ≠ ⊥ := by rw [not_iff_not, map_eq_bot_iff] lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀(comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, iff_self, mem_Inter, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map lemma map_cong {m₁ m₂ : α → β} {f : filter α} (h : {x | m₁ x = m₂ x} ∈ f) : map m₁ f = map m₂ f := have ∀(m₁ m₂ : α → β) (h : {x | m₁ x = m₂ x} ∈ f), map m₁ f ≤ map m₂ f, begin intros m₁ m₂ h s hs, show {x | m₁ x ∈ s} ∈ f, filter_upwards [h, hs], simp only [subset_def, mem_preimage, mem_set_of_eq, forall_true_iff] {contextual := tt} end, le_antisymm (this m₁ m₂ h) (this m₂ m₁ $ mem_sets_of_superset h $ assume x, eq.symm) -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) (hι : nonempty ι) : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ infi f), have ∃i, preimage m s ∈ f i, by simp only [infi_sets_eq hf hι, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ principal s, from infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption, by simp only [filter.le_principal_iff] at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := let ⟨i, hi⟩ := ne in calc map m (⨅i (h : p i), f i) = map m (⨅i:subtype p, f i.val) : by simp only [infi_subtype, eq_self_iff_true] ... = (⨅i:subtype p, map m (f i.val)) : map_infi_eq (assume ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end) ⟨⟨i, hi⟩⟩ ... = (⨅i (h : p i), map m (f i)) : by simp only [infi_subtype, eq_self_iff_true] lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (assume s hs, _), simp only [map, mem_inf_sets, exists_prop, mem_map, mem_preimage, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀s∈ f, m '' s ∈ g) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_right (map f F) map_comap_le }, { rintros U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, rw ← image_subset_iff at h, use [f '' V, image_mem_map V_in, Z, Z_in], refine subset.trans _ h, have : f '' (V ∩ f ⁻¹' Z) ⊆ f '' (V ∩ W), from image_subset _ (inter_subset_inter_right _ ‹_›), rwa set.push_pull at this } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_inj : function.injective (pure : α → filter α) := assume a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl @[simp] lemma pure_ne_bot {α : Type u} {a : α} : pure a ≠ (⊥ : filter α) := mt empty_in_sets_eq_bot.2 $ not_mem_empty a @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure_sets, λ h s hs, mem_sets_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) := iff.intro (assume ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, assume a, hts _⟩) (assume ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, assume f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $ assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq_sets _ hs, exact singleton_mem_pure_sets }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq_sets hs singleton_mem_pure_sets }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)), rw ← set.seq_seq, exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) }, { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht), rw set.seq_seq, exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw ← set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu }, { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := assume α f, map_id, comp_map := assume α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := assume α β, pure_seq_eq_map, map_pure := assume α β, map_pure, seq_pure := assume α β, seq_pure, seq_assoc := assume α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨assume α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /- bind equations -/ section bind @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : by simp only [bind, mem_map, iff_self, mem_join_sets, mem_set_of_eq] ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.rfl lemma bind_mono {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f) : bind f g ≤ bind f h := assume x h₂, show (_ ∈ f), by filter_upwards [h₁, h₂] assume s gh' h', gh' h' lemma bind_sup {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma bind_mono2 {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) : bind f h ≤ bind g h := assume s h', h₁ h' lemma principal_bind {s : set α} {f : α → filter β} : (bind (principal s) f) = (⨆x ∈ s, f x) := show join (map f (principal s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind /-- If `f : ι → filter α` is derected, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} (hn : nonempty ι) (hd : directed (≥) f) (hb : ∀i, f i ≠ ⊥) : (infi f) ≠ ⊥ := begin intro h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃i, ∅ ∈ f i, from (mem_infi hd hn ∅).1 he, exact hb i (empty_in_sets_eq_bot.1 hi) end /-- If `f : ι → filter α` is derected, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≥) f) (hb : ∀i, f i ≠ ⊥) : (infi f) ≠ ⊥ := if hι : nonempty ι then infi_ne_bot_of_directed' hι hd hb else assume h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x) lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} (hn : nonempty ι) (hd : directed (≥) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) := ⟨assume ne_bot i, ne_bot_of_le_ne_bot ne_bot (infi_le _ i), infi_ne_bot_of_directed' hn hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} (hn : nonempty α) (hd : directed (≥) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) := ⟨assume ne_bot i, ne_bot_of_le_ne_bot ne_bot (infi_le _ i), infi_ne_bot_of_directed hn hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_finite] at hs, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { assume s hs, rwa [mem_top_sets.1 hs] }, { rintros ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_sets] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, exact upw hs (ins hs₁ (ih hs₂)) } end /- tendsto -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : {x | f₁ x = f₂ x} ∈ l₁) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_cong hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : {x | f₁ x = f₂ x} ∈ l₁) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem_sets' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto_le_left {f : α → β} {x y : filter α} {z : filter β} (h : y ≤ x) : tendsto f x z → tendsto f y z := le_trans (map_mono h) lemma tendsto_le_right {f : α → β} {x : filter α} {y z : filter β} (h₁ : y ≤ z) (h₂ : tendsto f x y) : tendsto f x z := le_trans h₂ h₁ lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) (hx : x ≠ ⊥) : y ≠ ⊥ := ne_bot_of_le_ne_bot (map_ne_bot hx) h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, tendsto_comap.comp h, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by rw [tendsto, ← map_compose]; simp only [(∘), map_comap h, tendsto] lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ), rw [comap_comap_comp, eq, comap_id], exact le_refl _ end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_refl _ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp only [tendsto, iff_self, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) : tendsto f (x i) y → tendsto f (⨅i, x i) y := tendsto_le_left (infi_le _ _) lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (principal s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map, iff_self, filter.eventually] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (principal s) (principal t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto, image_subset_iff, le_principal_iff, map_principal, mem_principal_sets]; refl lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ {x | f x = b} ∈ a := by simp only [tendsto, le_pure_iff, mem_map, mem_singleton_iff] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λx, b) a (pure b) := tendsto_pure.2 $ univ_mem_sets' $ λ _, rfl lemma tendsto_if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [decidable_pred p] (h₀ : tendsto f (l₁ ⊓ principal p) l₂) (h₁ : tendsto g (l₁ ⊓ principal { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin revert h₀ h₁, simp only [tendsto_def, mem_inf_principal], intros h₀ h₁ s hs, apply mem_sets_of_superset (inter_mem_sets (h₀ s hs) (h₁ s hs)), rintros x ⟨hp₀, hp₁⟩, simp only [mem_preimage], by_cases h : p x, { rw if_pos h, exact hp₀ h }, rw if_neg h, exact hp₁ h end section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ f ×ᶠ g := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (f ×ᶠ g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma prod_infi_left {f : ι → filter α} {g : filter β} (i : ι) : (⨅i, f i) ×ᶠ g = (⨅i, (f i) ×ᶠ g) := by rw [filter.prod, comap_infi, infi_inf i]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right {f : filter α} {g : ι → filter β} (i : ι) : f ×ᶠ (⨅i, g i) = (⨅i, f ×ᶠ (g i)) := by rw [filter.prod, comap_infi, inf_infi i]; simp only [filter.prod, eq_self_iff_true] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ f₂ ×ᶠ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap_comp, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap_comp, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λp:β×α, (p.2, p.1)) (g ×ᶠ f) := by rw [prod_comm', ← map_swap_eq_comap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp (le_refl _) tendsto_fst).prod_mk (tendsto.comp (le_refl _) tendsto_snd)) lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f.prod g) = (f.map (λa b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], assume s, split, exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f.prod g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (principal s) ×ᶠ (principal t) = principal (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma prod_pure_pure {a : α} {b : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp [pure_eq_principal] lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : f ×ᶠ g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) := by rw [(≠), prod_eq_bot, not_or_distrib] lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod /- at_top and at_bot -/ /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, principal {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, principal {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ @[simp] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : (at_top : filter α) ≠ ⊥ := infi_ne_bot_of_directed (by apply_instance) (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of, mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩) (assume a, principal_ne_bot_iff.2 nonempty_Ici) @[simp, nolint ge_or_gt] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := let ⟨a⟩ := ‹nonempty α› in iff.intro (assume h, infi_sets_induct h ⟨a, by simp only [forall_const, mem_univ, forall_true_iff]⟩ (assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b, assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩) (assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩)) (assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x) @[nolint ge_or_gt] lemma eventually_at_top {α} [semilattice_sup α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) := by simp only [filter.eventually, filter.mem_at_top_sets, mem_set_of_eq] @[nolint ge_or_gt] lemma eventually.exists_forall_of_at_top {α} [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b := eventually_at_top.mp h @[nolint ge_or_gt] lemma frequently_at_top {α} [semilattice_sup α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) := by simp only [filter.frequently, eventually_at_top, not_exists, not_forall, not_not] @[nolint ge_or_gt] lemma frequently.forall_exists_of_at_top {α} [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b := frequently_at_top.mp h lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, principal $ f '' {a' | a ≤ a'}) := calc map f (⨅a, principal {a' | a ≤ a'}) = (⨅a, map f $ principal {a' | a ≤ a'}) : map_infi_eq (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of, mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩) (by apply_instance) ... = (⨅a, principal $ f '' {a' | a ≤ a'}) : by simp only [map_principal, eq_self_iff_true] lemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) : tendsto m f at_top ↔ (∀b, {a | b ≤ m a} ∈ f) := by simp only [at_top, tendsto_infi, tendsto_principal]; refl lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : {x | f₁ x ≤ f₂ x} ∈ l) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, (tendsto_at_top _ _).2 $ λ b, mp_sets ((tendsto_at_top _ _).1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_top_mono [preorder β] (l : filter α) : monotone (λ f : α → β, tendsto f l at_top) := λ f₁ f₂ h, tendsto_at_top_mono' l $ univ_mem_sets' h section ordered_monoid variables [ordered_cancel_comm_monoid β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : {x | 0 ≤ f x} ∈ l) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_left) hf) hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' l (univ_mem_sets' hf) hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : {x | 0 ≤ g x} ∈ l) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' l hf (univ_mem_sets' hg) lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, monotone_mem_sets (λ x, le_of_add_le_add_left) ((tendsto_at_top _ _).1 hf (C + b)) lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, monotone_mem_sets (λ x, le_of_add_le_add_right) ((tendsto_at_top _ _).1 hf (b + C)) lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : {x | f x ≤ C} ∈ l) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left l C (tendsto_at_top_mono' l (monotone_mem_sets (λ x (hx : f x ≤ C), add_le_add_right hx (g x)) hC) h) lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' l C (univ_mem_sets' hC) lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : {x | g x ≤ C} ∈ l) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right l C (tendsto_at_top_mono' l (monotone_mem_sets (λ x (hx : g x ≤ C), add_le_add_left hx (f x)) hC) h) lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' l C (univ_mem_sets' hC) end ordered_monoid section ordered_group variables [ordered_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : {x | C ≤ f x} ∈ l) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simp [hf]) (by simp [hg]) lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : {x | C ≤ g x} ∈ l) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) end ordered_group open_locale filter @[nolint ge_or_gt] lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl @[nolint ge_or_gt] theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (principal s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl /-- A function `f` grows to infinity independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_embedding {α β γ : Type*} [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin rw [tendsto_at_top, tendsto_at_top], split, { assume hc b, filter_upwards [hc (e b)] assume a, (hm b (f a)).1 }, { assume hb c, rcases hu c with ⟨b, hc⟩, filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) } end lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal @[nolint ge_or_gt] lemma tendsto_at_top_at_bot [nonempty α] [decidable_linear_order α] [preorder β] (f : α → β) : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → b ≥ f a := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := (tendsto_at_top_at_top f).trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top.2 finset.exists_nat_subset_range lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : ∀x, j (i x) = x) : tendsto (finset.image j) at_top at_top := have j ∘ i = id, from funext h, (finset.image_mono j).tendsto_at_top_at_top.2 $ assume s, ⟨s.image i, by simp only [finset.image_image, this, finset.image_id, le_refl]⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [nonempty β₁] [nonempty β₂] [semilattice_sup β₁] [semilattice_sup β₂] : (@at_top β₁ _) ×ᶠ (@at_top β₂ _) = @at_top (β₁ × β₂) _ := by inhabit β₁; inhabit β₂; simp [at_top, prod_infi_left (default β₁), prod_infi_right (default β₂), infi_prod]; exact infi_comm lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [nonempty β₁] [nonempty β₂] [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β)(hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin rw [@map_at_top_eq α _ ⟨g b'⟩], refine le_antisymm (le_infi $ assume b, infi_le_of_le (g (b ⊔ b')) $ principal_mono.2 $ image_subset_iff.2 _) (le_infi $ assume a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 _), { assume a ha, exact (le_trans le_sup_left $ le_trans (hgi _ le_sup_right) $ hf ha) }, { assume b hb, have hb' : b' ≤ b := le_trans le_sup_right hb, exact ⟨g b, (gc _ _ hb').1 (le_trans le_sup_left hb), le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')⟩ } end lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendso_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendso_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : k > 0) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /- ultrafilter -/ section ultrafilter open zorn variables {f g : filter α} /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ def is_ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g lemma ultrafilter_unique (hg : is_ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g := le_antisymm h (hg.right _ hf h) lemma le_of_ultrafilter {g : filter α} (hf : is_ultrafilter f) (h : f ⊓ g ≠ ⊥) : f ≤ g := le_of_inf_eq $ ultrafilter_unique hf h inf_le_left /-- Equivalent characterization of ultrafilters: A filter f is an ultrafilter if and only if for each set s, -s belongs to f if and only if s does not belong to f. -/ lemma ultrafilter_iff_compl_mem_iff_not_mem : is_ultrafilter f ↔ (∀ s, -s ∈ f ↔ s ∉ f) := ⟨assume hf s, ⟨assume hns hs, hf.1 $ empty_in_sets_eq_bot.mp $ by convert f.inter_sets hs hns; rw [inter_compl_self], assume hs, have f ≤ principal (-s), from le_of_ultrafilter hf $ assume h, hs $ mem_sets_of_eq_bot $ by simp only [h, eq_self_iff_true, compl_compl], by simp only [le_principal_iff] at this; assumption⟩, assume hf, ⟨mt empty_in_sets_eq_bot.mpr ((hf ∅).mp (by convert f.univ_sets; rw [compl_empty])), assume g hg g_le s hs, classical.by_contradiction $ mt (hf s).mpr $ assume : - s ∈ f, have s ∩ -s ∈ g, from inter_mem_sets hs (g_le this), by simp only [empty_in_sets_eq_bot, hg, inter_compl_self] at this; contradiction⟩⟩ lemma mem_or_compl_mem_of_ultrafilter (hf : is_ultrafilter f) (s : set α) : s ∈ f ∨ - s ∈ f := classical.or_iff_not_imp_left.2 (ultrafilter_iff_compl_mem_iff_not_mem.mp hf s).mpr lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : is_ultrafilter f) (h : s ∪ t ∈ f) : s ∈ f ∨ t ∈ f := (mem_or_compl_mem_of_ultrafilter hf s).imp_right (assume : -s ∈ f, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx) lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : is_ultrafilter f) (hs : finite s) : ⋃₀ s ∈ f → ∃t∈s, t ∈ f := finite.induction_on hs (by simp only [empty_in_sets_eq_bot, hf.left, mem_empty_eq, sUnion_empty, forall_prop_of_false, exists_false, not_false_iff, exists_prop_of_false]) $ λ t s' ht' hs' ih, by simp only [exists_prop, mem_insert_iff, set.sUnion_insert]; exact assume h, (mem_or_mem_of_ultrafilter hf h).elim (assume : t ∈ f, ⟨t, or.inl rfl, this⟩) (assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩) lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α} (hf : is_ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f) : ∃i∈is, s i ∈ f := have his : finite (image s is), from finite_image s his, have h : (⋃₀ image s is) ∈ f, from by simp only [sUnion_image, set.sUnion_image]; assumption, let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in ⟨i, hi, h_eq.symm ▸ ht⟩ lemma ultrafilter_map {f : filter α} {m : α → β} (h : is_ultrafilter f) : is_ultrafilter (map m f) := by rw ultrafilter_iff_compl_mem_iff_not_mem at ⊢ h; exact assume s, h (m ⁻¹' s) lemma ultrafilter_pure {a : α} : is_ultrafilter (pure a) := begin rw ultrafilter_iff_compl_mem_iff_not_mem, intro s, rw [mem_pure_sets, mem_pure_sets], exact iff.rfl end lemma ultrafilter_bind {f : filter α} (hf : is_ultrafilter f) {m : α → filter β} (hm : ∀ a, is_ultrafilter (m a)) : is_ultrafilter (f.bind m) := begin simp only [ultrafilter_iff_compl_mem_iff_not_mem] at ⊢ hf hm, intro s, dsimp [bind, join, map, preimage], simp only [hm], apply hf end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ is_ultrafilter u := let τ := {f' // f' ≠ ⊥ ∧ f' ≤ f}, r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, ⟨a, ha⟩ := nonempty_of_mem_sets h univ_mem_sets, top : τ := ⟨f, h, le_refl f⟩, sup : Π(c:set τ), chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val, infi_ne_bot_of_directed ⟨a⟩ (directed_of_chain $ chain_insert hc $ assume ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩ in have ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _), have (∃ (u : τ), ∀ (a : τ), r u a → r a u), from exists_maximal_of_chains_bounded (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), let ⟨uτ, hmin⟩ := this in ⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩ /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def ultrafilter_of (f : filter α) : filter α := if h : f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ is_ultrafilter u) lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ is_ultrafilter (ultrafilter_of f) := begin have h' := classical.epsilon_spec (exists_ultrafilter h), simp only [ultrafilter_of, dif_neg, h, dif_neg, not_false_iff], simp only at h', assumption end lemma ultrafilter_of_le : ultrafilter_of f ≤ f := if h : f = ⊥ then by simp only [ultrafilter_of, dif_pos, h, dif_pos, eq_self_iff_true, le_bot_iff]; exact le_refl _ else (ultrafilter_of_spec h).left lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : is_ultrafilter (ultrafilter_of f) := (ultrafilter_of_spec h).right lemma ultrafilter_of_ultrafilter (h : is_ultrafilter f) : ultrafilter_of f = f := ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma sup_of_ultrafilters (f : filter α) : f = ⨆ (g) (u : is_ultrafilter g) (H : g ≤ f), g := begin refine le_antisymm _ (supr_le $ λ g, supr_le $ λ u, supr_le $ λ H, H), intros s hs, -- If s ∉ f.sets, we'll apply the ultrafilter lemma to the restriction of f to -s. by_contradiction hs', let j : (-s) → α := subtype.val, have j_inv_s : j ⁻¹' s = ∅, by erw [←preimage_inter_range, subtype.val_range, inter_compl_self, preimage_empty], let f' := comap j f, have : f' ≠ ⊥, { apply mt empty_in_sets_eq_bot.mpr, rintro ⟨t, htf, ht⟩, suffices : t ⊆ s, from absurd (f.sets_of_superset htf this) hs', rw [subset_empty_iff] at ht, have : j '' (j ⁻¹' t) = ∅, by rw [ht, image_empty], erw [image_preimage_eq_inter_range, subtype.val_range, ←subset_compl_iff_disjoint, set.compl_compl] at this, exact this }, rcases exists_ultrafilter this with ⟨g', g'f', u'⟩, simp only [supr_sets_eq, mem_Inter] at hs, have := hs (g'.map subtype.val) (ultrafilter_map u') (map_le_iff_le_comap.mpr g'f'), rw [←le_principal_iff, map_le_iff_le_comap, comap_principal, j_inv_s, principal_empty, le_bot_iff] at this, exact absurd this u'.1 end /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g, is_ultrafilter g → g ≤ l₁ → g.map f ≤ l₂ := ⟨assume h g u gx, le_trans (map_mono gx) h, assume h, by rw [sup_of_ultrafilters l₁]; simpa only [tendsto, map_supr, supr_le_iff]⟩ /-- The ultrafilter monad. The monad structure on ultrafilters is the restriction of the one on filters. -/ def ultrafilter (α : Type u) : Type u := {f : filter α // is_ultrafilter f} /-- Push-forward for ultra-filters. -/ def ultrafilter.map (m : α → β) (u : ultrafilter α) : ultrafilter β := ⟨u.val.map m, ultrafilter_map u.property⟩ /-- The principal ultra-filter associated to a point `x`. -/ def ultrafilter.pure (x : α) : ultrafilter α := ⟨pure x, ultrafilter_pure⟩ /-- Monadic bind for ultra-filters, coming from the one on filters defined in terms of map and join.-/ def ultrafilter.bind (u : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := ⟨u.val.bind (λ a, (m a).val), ultrafilter_bind u.property (λ a, (m a).property)⟩ instance ultrafilter.has_pure : has_pure ultrafilter := ⟨@ultrafilter.pure⟩ instance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map } instance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map } instance ultrafilter.inhabited [inhabited α] : inhabited (ultrafilter α) := ⟨pure (default _)⟩ /-- The ultra-filter extending the cofinite filter. -/ noncomputable def hyperfilter : filter α := ultrafilter_of cofinite lemma hyperfilter_le_cofinite : @hyperfilter α ≤ cofinite := ultrafilter_of_le lemma is_ultrafilter_hyperfilter [infinite α] : is_ultrafilter (@hyperfilter α) := (ultrafilter_of_spec cofinite_ne_bot).2 theorem nmem_hyperfilter_of_finite [infinite α] {s : set α} (hf : s.finite) : s ∉ @hyperfilter α := λ hy, have hx : -s ∉ hyperfilter := λ hs, (ultrafilter_iff_compl_mem_iff_not_mem.mp is_ultrafilter_hyperfilter s).mp hs hy, have ht : -s ∈ cofinite.sets := by show -s ∈ {s | _}; rwa [set.mem_set_of_eq, compl_compl], hx $ hyperfilter_le_cofinite ht theorem compl_mem_hyperfilter_of_finite [infinite α] {s : set α} (hf : set.finite s) : -s ∈ @hyperfilter α := (ultrafilter_iff_compl_mem_iff_not_mem.mp is_ultrafilter_hyperfilter s).mpr $ nmem_hyperfilter_of_finite hf theorem mem_hyperfilter_of_finite_compl [infinite α] {s : set α} (hf : set.finite (-s)) : s ∈ @hyperfilter α := s.compl_compl ▸ compl_mem_hyperfilter_of_finite hf section local attribute [instance] filter.monad filter.is_lawful_monad instance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, subtype.eq (id_map f.val), pure_bind := assume α β a f, subtype.eq (pure_bind a (subtype.val ∘ f)), bind_assoc := assume α β γ f m₁ m₂, subtype.eq (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, subtype.eq (bind_pure_comp_eq_map _ f x.val) } end lemma ultrafilter.eq_iff_val_le_val {u v : ultrafilter α} : u = v ↔ u.val ≤ v.val := ⟨assume h, by rw h; exact le_refl _, assume h, by rw subtype.ext; apply ultrafilter_unique v.property u.property.1 h⟩ lemma exists_ultrafilter_iff (f : filter α) : (∃ (u : ultrafilter α), u.val ≤ f) ↔ f ≠ ⊥ := ⟨assume ⟨u, uf⟩, ne_bot_of_le_ne_bot u.property.1 uf, assume h, let ⟨u, uf, hu⟩ := exists_ultrafilter h in ⟨⟨u, hu⟩, uf⟩⟩ end ultrafilter end filter namespace filter variables {α β γ : Type u} {f : β → filter α} {s : γ → set α} open list lemma mem_traverse_sets : ∀(fs : list β) (us : list γ), forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _ | (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs) lemma mem_traverse_sets_iff (fs : list β) (t : set (list α)) : t ∈ traverse f fs ↔ (∃us:list (set α), forall₂ (λb (s : set α), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure_sets, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { assume ht, rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } }, { rintros ⟨us, hus, hs⟩, exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs } end lemma sequence_mono : ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_refl _ | (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) end filter open filter lemma set.infinite_iff_frequently_cofinite {α : Type u} {s : set α} : set.infinite s ↔ (∃ᶠ x in cofinite, x ∈ s) := frequently_cofinite_iff_infinite.symm /-- For natural numbers the filters `cofinite` and `at_top` coincide. -/ lemma nat.cofinite_eq_at_top : @cofinite ℕ = at_top := begin ext s, simp only [mem_cofinite, mem_at_top_sets], split, { assume hs, use (hs.to_finset.sup id) + 1, assume b hb, by_contradiction hbs, have := hs.to_finset.subset_range_sup_succ (finite.mem_to_finset.2 hbs), exact not_lt_of_le hb (finset.mem_range.1 this) }, { rintros ⟨N, hN⟩, apply finite_subset (finite_lt_nat N), assume n hn, change n < N, exact lt_of_not_ge (λ hn', hn $ hN n hn') } end
6fba96f446c12fed8940b5fce15108e7f643718e
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/lean/bytearray.lean
4baad04f2032ae431e67fc78ecc9e1f2d82b7624
[ "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
487
lean
def tst : IO Unit := do let bs := [1, 2, 3].toByteArray; IO.println bs; let bs := bs.push 4; let bs := bs.set! 1 20; IO.println bs; let bs₁ := bs.set! 2 30; IO.println bs₁; IO.println bs; IO.println bs.size; IO.println (bs ++ bs); IO.println (bs.extract 1 3); pure () #eval tst #eval [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88].toByteArray.toUInt64LE! == 0x1122334455667788 #eval [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88].toByteArray.toUInt64BE! == 0x8877665544332211
0ff9244002ae40fa59443f828843a236e16b6c94
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/topologie-espaces-normés/cpge_ten_05a.lean
9b3dc7c80dfa734727a8b4daf77c91aa5d12734f
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
513
lean
import data.set.basic import topology.basic import algebra.module.basic import algebra.module.submodule import order.complete_lattice import analysis.normed_space.basic -- Soit E une espace vectoriel normé. -- (a) Soient F une partie fermée non vide de E et x ∈ E . Montrer -- d(x, F ) = 0 ⇐⇒ x ∈ F . theorem a {R E: Type*} [normed_field R] [normed_group E] [normed_space R E] : forall (F: set E) (x: E), (is_closed F) -> (set.nonempty F) -> set.mem x F <-> infi (dist x) = 0 := sorry
b1d606c9947072b47b97ac9263da292d7038c8a4
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/quandle.lean
15733942a6dfc6ead879da8933849c5e892eea4f
[ "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
23,968
lean
/- Copyright (c) 2020 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import data.zmod.basic import data.equiv.mul_add import tactic.group /-! # Racks and Quandles This file defines racks and quandles, algebraic structures for sets that bijectively act on themselves with a self-distributivity property. If `R` is a rack and `act : R → (R ≃ R)` is the self-action, then the self-distributivity is, equivalently, that ``` act (act x y) = act x * act y * (act x)⁻¹ ``` where multiplication is composition in `R ≃ R` as a group. Quandles are racks such that `act x x = x` for all `x`. One example of a quandle (not yet in mathlib) is the action of a Lie algebra on itself, defined by `act x y = Ad (exp x) y`. Quandles and racks were independently developed by multiple mathematicians. David Joyce introduced quandles in his thesis [Joyce1982] to define an algebraic invariant of knot and link complements that is analogous to the fundamental group of the exterior, and he showed that the quandle associated to an oriented knot is invariant up to orientation-reversed mirror image. Racks were used by Fenn and Rourke for framed codimension-2 knots and links.[FennRourke1992] The name "rack" came from wordplay by Conway and Wraith for the "wrack and ruin" of forgetting everything but the conjugation operation for a group. ## Main definitions * `shelf` is a type with a self-distributive action * `rack` is a shelf whose action for each element is invertible * `quandle` is a rack whose action for an element fixes that element * `quandle.conj` defines a quandle of a group acting on itself by conjugation. * `shelf_hom` is homomorphisms of shelves, racks, and quandles. * `rack.envel_group` gives the universal group the rack maps to as a conjugation quandle. * `rack.opp` gives the rack with the action replaced by its inverse. ## Main statements * `rack.envel_group` is universal (`to_envel_group.univ` and `to_envel_group.univ_uniq`) ## Notation The following notation is localized in `quandles`: * `x ◃ y` is `shelf.act x y` * `x ◃⁻¹ y` is `rack.inv_act x y` * `S →◃ S'` is `shelf_hom S S'` Use `open_locale quandles` to use these. ## Todo * If g is the Lie algebra of a Lie group G, then (x ◃ y) = Ad (exp x) x forms a quandle * If X is a symmetric space, then each point has a corresponding involution that acts on X, forming a quandle. * Alexander quandle with `a ◃ b = t * b + (1 - t) * b`, with `a` and `b` elements of a module over Z[t,t⁻¹]. * If G is a group, H a subgroup, and z in H, then there is a quandle `(G/H;z)` defined by `yH ◃ xH = yzy⁻¹xH`. Every homogeneous quandle (i.e., a quandle Q whose automorphism group acts transitively on Q as a set) is isomorphic to such a quandle. There is a generalization to this arbitrary quandles in [Joyce's paper (Theorem 7.2)][Joyce1982]. ## Tags rack, quandle -/ open opposite universes u v /-- A *shelf* is a structure with a self-distributive binary operation. The binary operation is regarded as a left action of the type on itself. -/ class shelf (α : Type u) := (act : α → α → α) (self_distrib : ∀ {x y z : α}, act x (act y z) = act (act x y) (act x z)) /-- The type of homomorphisms between shelves. This is also the notion of rack and quandle homomorphisms. -/ @[ext] structure shelf_hom (S₁ : Type*) (S₂ : Type*) [shelf S₁] [shelf S₂] := (to_fun : S₁ → S₂) (map_act' : ∀ {x y : S₁}, to_fun (shelf.act x y) = shelf.act (to_fun x) (to_fun y)) /-- A *rack* is an automorphic set (a set with an action on itself by bijections) that is self-distributive. It is a shelf such that each element's action is invertible. The notations `x ◃ y` and `x ◃⁻¹ y` denote the action and the inverse action, respectively, and they are right associative. -/ class rack (α : Type u) extends shelf α := (inv_act : α → α → α) (left_inv : ∀ x, function.left_inverse (inv_act x) (act x)) (right_inv : ∀ x, function.right_inverse (inv_act x) (act x)) localized "infixr ` ◃ `:65 := shelf.act" in quandles localized "infixr ` ◃⁻¹ `:65 := rack.inv_act" in quandles localized "infixr ` →◃ `:25 := shelf_hom" in quandles open_locale quandles namespace rack variables {R : Type*} [rack R] lemma self_distrib {x y z : R} : x ◃ (y ◃ z) = (x ◃ y) ◃ (x ◃ z) := shelf.self_distrib /-- A rack acts on itself by equivalences. -/ def act (x : R) : R ≃ R := { to_fun := shelf.act x, inv_fun := inv_act x, left_inv := left_inv x, right_inv := right_inv x } @[simp] lemma act_apply (x y : R) : act x y = x ◃ y := rfl @[simp] lemma act_symm_apply (x y : R) : (act x).symm y = x ◃⁻¹ y := rfl @[simp] lemma inv_act_apply (x y : R) : (act x)⁻¹ y = x ◃⁻¹ y := rfl @[simp] lemma inv_act_act_eq (x y : R) : x ◃⁻¹ x ◃ y = y := left_inv x y @[simp] lemma act_inv_act_eq (x y : R) : x ◃ x ◃⁻¹ y = y := right_inv x y lemma left_cancel (x : R) {y y' : R} : x ◃ y = x ◃ y' ↔ y = y' := by { split, apply (act x).injective, rintro rfl, refl } lemma left_cancel_inv (x : R) {y y' : R} : x ◃⁻¹ y = x ◃⁻¹ y' ↔ y = y' := by { split, apply (act x).symm.injective, rintro rfl, refl } lemma self_distrib_inv {x y z : R} : x ◃⁻¹ y ◃⁻¹ z = (x ◃⁻¹ y) ◃⁻¹ (x ◃⁻¹ z) := begin rw [←left_cancel (x ◃⁻¹ y), right_inv, ←left_cancel x, right_inv, self_distrib], repeat {rw right_inv }, end /-- The *adjoint action* of a rack on itself is `op'`, and the adjoint action of `x ◃ y` is the conjugate of the action of `y` by the action of `x`. It is another way to understand the self-distributivity axiom. This is used in the natural rack homomorphism `to_conj` from `R` to `conj (R ≃ R)` defined by `op'`. -/ lemma ad_conj {R : Type*} [rack R] (x y : R) : act (x ◃ y) = act x * act y * (act x)⁻¹ := begin apply @mul_right_cancel _ _ _ (act x), ext z, simp only [inv_mul_cancel_right], apply self_distrib.symm, end /-- The opposite rack, swapping the roles of `◃` and `◃⁻¹`. -/ instance opposite_rack : rack Rᵒᵖ := { act := λ x y, op (inv_act (unop x) (unop y)), self_distrib := λ (x y z : Rᵒᵖ), begin op_induction x, op_induction y, op_induction z, simp only [unop_op, op_inj_iff], exact self_distrib_inv, end, inv_act := λ x y, op (shelf.act (unop x) (unop y)), left_inv := λ x y, begin op_induction x, op_induction y, simp, end, right_inv := λ x y, begin op_induction x, op_induction y, simp, end } @[simp] lemma op_act_op_eq {x y : R} : (op x) ◃ (op y) = op (x ◃⁻¹ y) := rfl @[simp] lemma op_inv_act_op_eq {x y : R} : (op x) ◃⁻¹ (op y) = op (x ◃ y) := rfl @[simp] lemma self_act_act_eq {x y : R} : (x ◃ x) ◃ y = x ◃ y := by { rw [←right_inv x y, ←self_distrib] } @[simp] lemma self_inv_act_inv_act_eq {x y : R} : (x ◃⁻¹ x) ◃⁻¹ y = x ◃⁻¹ y := by { have h := @self_act_act_eq _ _ (op x) (op y), simpa using h } @[simp] lemma self_act_inv_act_eq {x y : R} : (x ◃ x) ◃⁻¹ y = x ◃⁻¹ y := by { rw ←left_cancel (x ◃ x), rw right_inv, rw self_act_act_eq, rw right_inv } @[simp] lemma self_inv_act_act_eq {x y : R} : (x ◃⁻¹ x) ◃ y = x ◃ y := by { have h := @self_act_inv_act_eq _ _ (op x) (op y), simpa using h } lemma self_act_eq_iff_eq {x y : R} : x ◃ x = y ◃ y ↔ x = y := begin split, swap, rintro rfl, refl, intro h, transitivity (x ◃ x) ◃⁻¹ (x ◃ x), rw [←left_cancel (x ◃ x), right_inv, self_act_act_eq], rw [h, ←left_cancel (y ◃ y), right_inv, self_act_act_eq], end lemma self_inv_act_eq_iff_eq {x y : R} : x ◃⁻¹ x = y ◃⁻¹ y ↔ x = y := by { have h := @self_act_eq_iff_eq _ _ (op x) (op y), simpa using h } /-- The map `x ↦ x ◃ x` is a bijection. (This has applications for the regular isotopy version of the Reidemeister I move for knot diagrams.) -/ def self_apply_equiv (R : Type*) [rack R] : R ≃ R := { to_fun := λ x, x ◃ x, inv_fun := λ x, x ◃⁻¹ x, left_inv := λ x, by simp, right_inv := λ x, by simp } /-- An involutory rack is one for which `rack.op R x` is an involution for every x. -/ def is_involutory (R : Type*) [rack R] : Prop := ∀ x : R, function.involutive (shelf.act x) lemma involutory_inv_act_eq_act {R : Type*} [rack R] (h : is_involutory R) (x y : R) : x ◃⁻¹ y = x ◃ y := begin rw [←left_cancel x, right_inv], exact ((h x).left_inverse y).symm, end /-- An abelian rack is one for which the mediality axiom holds. -/ def is_abelian (R : Type*) [rack R] : Prop := ∀ (x y z w : R), (x ◃ y) ◃ (z ◃ w) = (x ◃ z) ◃ (y ◃ w) /-- Associative racks are uninteresting. -/ lemma assoc_iff_id {R : Type*} [rack R] {x y z : R} : x ◃ y ◃ z = (x ◃ y) ◃ z ↔ x ◃ z = z := by { rw self_distrib, rw left_cancel } end rack namespace shelf_hom variables {S₁ : Type*} {S₂ : Type*} {S₃ : Type*} [shelf S₁] [shelf S₂] [shelf S₃] instance : has_coe_to_fun (S₁ →◃ S₂) := ⟨_, shelf_hom.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : S₁ →◃ S₂) : f.to_fun = f := rfl @[simp] lemma map_act (f : S₁ →◃ S₂) {x y : S₁} : f (x ◃ y) = f x ◃ f y := map_act' f /-- The identity homomorphism -/ def id (S : Type*) [shelf S] : S →◃ S := { to_fun := id, map_act' := by simp } instance inhabited (S : Type*) [shelf S] : inhabited (S →◃ S) := ⟨id S⟩ /-- The composition of shelf homomorphisms -/ def comp (g : S₂ →◃ S₃) (f : S₁ →◃ S₂) : S₁ →◃ S₃ := { to_fun := g.to_fun ∘ f.to_fun, map_act' := by simp } @[simp] lemma comp_apply (g : S₂ →◃ S₃) (f : S₁ →◃ S₂) (x : S₁) : (g.comp f) x = g (f x) := rfl end shelf_hom /-- A quandle is a rack such that each automorphism fixes its corresponding element. -/ class quandle (α : Type*) extends rack α := (fix : ∀ {x : α}, act x x = x) namespace quandle open rack variables {Q : Type*} [quandle Q] attribute [simp] fix @[simp] lemma fix_inv {x : Q} : x ◃⁻¹ x = x := by { rw ←left_cancel x, simp } instance opposite_quandle : quandle Qᵒᵖ := { fix := λ x, by { op_induction x, simp } } /-- The conjugation quandle of a group. Each element of the group acts by the corresponding inner automorphism. -/ @[nolint has_inhabited_instance] def conj (G : Type*) := G instance conj.quandle (G : Type*) [group G] : quandle (conj G) := { act := (λ x, @mul_aut.conj G _ x), self_distrib := λ x y z, begin dsimp only [mul_equiv.to_equiv_apply, mul_aut.conj_apply, conj], group, end, inv_act := (λ x, (@mul_aut.conj G _ x).symm), left_inv := λ x y, by { dsimp [act, conj], group }, right_inv := λ x y, by { dsimp [act, conj], group }, fix := λ x, by simp } @[simp] lemma conj_act_eq_conj {G : Type*} [group G] (x y : conj G) : x ◃ y = ((x : G) * (y : G) * (x : G)⁻¹ : G) := rfl lemma conj_swap {G : Type*} [group G] (x y : conj G) : x ◃ y = y ↔ y ◃ x = x := begin dsimp, split, repeat { intro h, conv_rhs { rw eq_mul_inv_of_mul_eq (eq_mul_inv_of_mul_eq h) }, simp, }, end /-- `conj` is functorial -/ def conj.map {G : Type*} {H : Type*} [group G] [group H] (f : G →* H) : conj G →◃ conj H := { to_fun := f, map_act' := by simp } instance {G : Type*} {H : Type*} [group G] [group H] : has_lift (G →* H) (conj G →◃ conj H) := { lift := conj.map } /-- The dihedral quandle. This is the conjugation quandle of the dihedral group restrict to flips. Used for Fox n-colorings of knots. -/ @[nolint has_inhabited_instance] def dihedral (n : ℕ) := zmod n /-- The operation for the dihedral quandle. It does not need to be an equivalence because it is an involution (see `dihedral_act.inv`). -/ def dihedral_act (n : ℕ) (a : zmod n) : zmod n → zmod n := λ b, 2 * a - b lemma dihedral_act.inv (n : ℕ) (a : zmod n) : function.involutive (dihedral_act n a) := by { intro b, dsimp [dihedral_act], ring } instance (n : ℕ) : quandle (dihedral n) := { act := dihedral_act n, self_distrib := λ x y z, begin dsimp [function.involutive.to_equiv, dihedral_act], ring, end, inv_act := dihedral_act n, left_inv := λ x, (dihedral_act.inv n x).left_inverse, right_inv := λ x, (dihedral_act.inv n x).right_inverse, fix := λ x, begin dsimp [function.involutive.to_equiv, dihedral_act], ring, end } end quandle namespace rack /-- This is the natural rack homomorphism to the conjugation quandle of the group `R ≃ R` that acts on the rack. -/ def to_conj (R : Type*) [rack R] : R →◃ quandle.conj (R ≃ R) := { to_fun := act, map_act' := ad_conj } section envel_group /-! ### Universal enveloping group of a rack The universal enveloping group `envel_group R` of a rack `R` is the universal group such that every rack homomorphism `R →◃ conj G` is induced by a unique group homomorphism `envel_group R →* G`. For quandles, Joyce called this group `AdConj R`. The `envel_group` functor is left adjoint to the `conj` forgetful functor, and the way we construct the enveloping group is via a technique that should work for left adjoints of forgetful functors in general. It involves thinking a little about 2-categories, but the payoff is that the map `envel_group R →* G` has a nice description. Let's think of a group as being a one-object category. The first step is to define `pre_envel_group`, which gives formal expressions for all the 1-morphisms and includes the unit element, elements of `R`, multiplication, and inverses. To introduce relations, the second step is to define `pre_envel_group_rel'`, which gives formal expressions for all 2-morphisms between the 1-morphisms. The 2-morphisms include associativity, multiplication by the unit, multiplication by inverses, compatibility with multiplication and inverses (`congr_mul` and `congr_inv`), the axioms for an equivalence relation, and, importantly, the relationship between conjugation and the rack action (see `rack.ad_conj`). None of this forms a 2-category yet, for example due to lack of associativity of `trans`. The `pre_envel_group_rel` relation is a `Prop`-valued version of `pre_envel_group_rel'`, and making it `Prop`-valued essentially introduces enough 3-isomorphisms so that every pair of compatible 2-morphisms is isomorphic. Now, while composition in `pre_envel_group` does not strictly satisfy the category axioms, `pre_envel_group` and `pre_envel_group_rel'` do form a weak 2-category. Since we just want a 1-category, the last step is to quotient `pre_envel_group` by `pre_envel_group_rel'`, and the result is the group `envel_group`. For a homomorphism `f : R →◃ conj G`, how does `envel_group.map f : envel_group R →* G` work? Let's think of `G` as being a 2-category with one object, a 1-morphism per element of `G`, and a single 2-morphism called `eq.refl` for each 1-morphism. We define the map using a "higher `quotient.lift`" -- not only do we evaluate elements of `pre_envel_group` as expressions in `G` (this is `to_envel_group.map_aux`), but we evaluate elements of `pre_envel_group'` as expressions of 2-morphisms of `G` (this is `to_envel_group.map_aux.well_def`). That is to say, `to_envel_group.map_aux.well_def` recursively evaluates formal expressions of 2-morphisms as equality proofs in `G`. Now that all morphisms are accounted for, the map descends to a homomorphism `envel_group R →* G`. Note: `Type`-valued relations are not common. The fact it is `Type`-valued is what makes `to_envel_group.map_aux.well_def` have well-founded recursion. -/ /-- Free generators of the enveloping group. -/ inductive pre_envel_group (R : Type u) : Type u | unit : pre_envel_group | incl (x : R) : pre_envel_group | mul (a b : pre_envel_group) : pre_envel_group | inv (a : pre_envel_group) : pre_envel_group instance pre_envel_group.inhabited (R : Type u) : inhabited (pre_envel_group R) := ⟨pre_envel_group.unit⟩ open pre_envel_group /-- Relations for the enveloping group. This is a type-valued relation because `to_envel_group.map_aux.well_def` inducts on it to show `to_envel_group.map` is well-defined. The relation `pre_envel_group_rel` is the `Prop`-valued version, which is used to define `envel_group` itself. -/ inductive pre_envel_group_rel' (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Type u | refl {a : pre_envel_group R} : pre_envel_group_rel' a a | symm {a b : pre_envel_group R} (hab : pre_envel_group_rel' a b) : pre_envel_group_rel' b a | trans {a b c : pre_envel_group R} (hab : pre_envel_group_rel' a b) (hbc : pre_envel_group_rel' b c) : pre_envel_group_rel' a c | congr_mul {a b a' b' : pre_envel_group R} (ha : pre_envel_group_rel' a a') (hb : pre_envel_group_rel' b b') : pre_envel_group_rel' (mul a b) (mul a' b') | congr_inv {a a' : pre_envel_group R} (ha : pre_envel_group_rel' a a') : pre_envel_group_rel' (inv a) (inv a') | assoc (a b c : pre_envel_group R) : pre_envel_group_rel' (mul (mul a b) c) (mul a (mul b c)) | one_mul (a : pre_envel_group R) : pre_envel_group_rel' (mul unit a) a | mul_one (a : pre_envel_group R) : pre_envel_group_rel' (mul a unit) a | mul_left_inv (a : pre_envel_group R) : pre_envel_group_rel' (mul (inv a) a) unit | act_incl (x y : R) : pre_envel_group_rel' (mul (mul (incl x) (incl y)) (inv (incl x))) (incl (x ◃ y)) instance pre_envel_group_rel'.inhabited (R : Type u) [rack R] : inhabited (pre_envel_group_rel' R unit unit) := ⟨pre_envel_group_rel'.refl⟩ /-- The `pre_envel_group_rel` relation as a `Prop`. Used as the relation for `pre_envel_group.setoid`. -/ inductive pre_envel_group_rel (R : Type u) [rack R] : pre_envel_group R → pre_envel_group R → Prop | rel {a b : pre_envel_group R} (r : pre_envel_group_rel' R a b) : pre_envel_group_rel a b /-- A quick way to convert a `pre_envel_group_rel'` to a `pre_envel_group_rel`. -/ lemma pre_envel_group_rel'.rel {R : Type u} [rack R] {a b : pre_envel_group R} : pre_envel_group_rel' R a b → pre_envel_group_rel R a b := pre_envel_group_rel.rel @[refl] lemma pre_envel_group_rel.refl {R : Type u} [rack R] {a : pre_envel_group R} : pre_envel_group_rel R a a := pre_envel_group_rel.rel pre_envel_group_rel'.refl @[symm] lemma pre_envel_group_rel.symm {R : Type u} [rack R] {a b : pre_envel_group R} : pre_envel_group_rel R a b → pre_envel_group_rel R b a | ⟨r⟩ := r.symm.rel @[trans] lemma pre_envel_group_rel.trans {R : Type u} [rack R] {a b c : pre_envel_group R} : pre_envel_group_rel R a b → pre_envel_group_rel R b c → pre_envel_group_rel R a c | ⟨rab⟩ ⟨rbc⟩ := (rab.trans rbc).rel instance pre_envel_group.setoid (R : Type*) [rack R] : setoid (pre_envel_group R) := { r := pre_envel_group_rel R, iseqv := begin split, apply pre_envel_group_rel.refl, split, apply pre_envel_group_rel.symm, apply pre_envel_group_rel.trans end } /-- The universal enveloping group for the rack R. -/ def envel_group (R : Type*) [rack R] := quotient (pre_envel_group.setoid R) instance (R : Type*) [rack R] : group (envel_group R) := { mul := λ a b, quotient.lift_on₂ a b (λ a b, ⟦pre_envel_group.mul a b⟧) (λ a b a' b' ⟨ha⟩ ⟨hb⟩, quotient.sound (pre_envel_group_rel'.congr_mul ha hb).rel), one := ⟦unit⟧, inv := λ a, quotient.lift_on a (λ a, ⟦pre_envel_group.inv a⟧) (λ a a' ⟨ha⟩, quotient.sound (pre_envel_group_rel'.congr_inv ha).rel), mul_assoc := λ a b c, quotient.induction_on₃ a b c (λ a b c, quotient.sound (pre_envel_group_rel'.assoc a b c).rel), one_mul := λ a, quotient.induction_on a (λ a, quotient.sound (pre_envel_group_rel'.one_mul a).rel), mul_one := λ a, quotient.induction_on a (λ a, quotient.sound (pre_envel_group_rel'.mul_one a).rel), mul_left_inv := λ a, quotient.induction_on a (λ a, quotient.sound (pre_envel_group_rel'.mul_left_inv a).rel) } instance envel_group.inhabited (R : Type*) [rack R] : inhabited (envel_group R) := ⟨1⟩ /-- The canonical homomorphism from a rack to its enveloping group. Satisfies universal properties given by `to_envel_group.map` and `to_envel_group.univ`. -/ def to_envel_group (R : Type*) [rack R] : R →◃ quandle.conj (envel_group R) := { to_fun := λ x, ⟦incl x⟧, map_act' := λ x y, quotient.sound (pre_envel_group_rel'.act_incl x y).symm.rel } /-- The preliminary definition of the induced map from the enveloping group. See `to_envel_group.map`. -/ def to_envel_group.map_aux {R : Type*} [rack R] {G : Type*} [group G] (f : R →◃ quandle.conj G) : pre_envel_group R → G | unit := 1 | (incl x) := f x | (mul a b) := to_envel_group.map_aux a * to_envel_group.map_aux b | (inv a) := (to_envel_group.map_aux a)⁻¹ namespace to_envel_group.map_aux open pre_envel_group_rel' /-- Show that `to_envel_group.map_aux` sends equivalent expressions to equal terms. -/ lemma well_def {R : Type*} [rack R] {G : Type*} [group G] (f : R →◃ quandle.conj G) : Π {a b : pre_envel_group R}, pre_envel_group_rel' R a b → to_envel_group.map_aux f a = to_envel_group.map_aux f b | a b refl := rfl | a b (symm h) := (well_def h).symm | a b (trans hac hcb) := eq.trans (well_def hac) (well_def hcb) | _ _ (congr_mul ha hb) := by { simp [to_envel_group.map_aux, well_def ha, well_def hb] } | _ _ (congr_inv ha) := by { simp [to_envel_group.map_aux, well_def ha] } | _ _ (assoc a b c) := by { apply mul_assoc } | _ _ (one_mul a) := by { simp [to_envel_group.map_aux] } | _ _ (mul_one a) := by { simp [to_envel_group.map_aux] } | _ _ (mul_left_inv a) := by { simp [to_envel_group.map_aux] } | _ _ (act_incl x y) := by { simp [to_envel_group.map_aux] } end to_envel_group.map_aux /-- Given a map from a rack to a group, lift it to being a map from the enveloping group. -/ def to_envel_group.map {R : Type*} [rack R] {G : Type*} [group G] (f : R →◃ quandle.conj G) : envel_group R →* G := { to_fun := λ x, quotient.lift_on x (to_envel_group.map_aux f) (λ a b ⟨hab⟩, to_envel_group.map_aux.well_def f hab), map_one' := begin change quotient.lift_on ⟦unit⟧ (to_envel_group.map_aux f) _ = 1, simp [to_envel_group.map_aux], end, map_mul' := λ x y, quotient.induction_on₂ x y (λ x y, begin change quotient.lift_on ⟦mul x y⟧ (to_envel_group.map_aux f) _ = _, simp [to_envel_group.map_aux], end) } /-- Given a homomorphism from a rack to a group, it factors through the enveloping group. -/ lemma to_envel_group.univ (R : Type*) [rack R] (G : Type*) [group G] (f : R →◃ quandle.conj G) : (quandle.conj.map (to_envel_group.map f)).comp (to_envel_group R) = f := by { ext, refl } /-- The homomorphism `to_envel_group.map f` is the unique map that fits into the commutative triangle in `to_envel_group.univ`. -/ lemma to_envel_group.univ_uniq (R : Type*) [rack R] (G : Type*) [group G] (f : R →◃ quandle.conj G) (g : envel_group R →* G) (h : f = (quandle.conj.map g).comp (to_envel_group R)) : g = to_envel_group.map f := begin subst f, ext, refine quotient.ind (λ x, _) x, induction x, convert g.map_one, refl, dunfold to_envel_group.map, simp [to_envel_group.map_aux, to_envel_group], have hm : ⟦x_a.mul x_b⟧ = @has_mul.mul (envel_group R) _ ⟦x_a⟧ ⟦x_b⟧ := rfl, rw hm, simpa [x_ih_a, x_ih_b], have hm : ⟦x_a.inv⟧ = @has_inv.inv (envel_group R) _ ⟦x_a⟧ := rfl, rw hm, simp [x_ih], end /-- The induced group homomorphism from the enveloping group into bijections of the rack, using `rack.to_conj`. Satisfies the property `envel_action_prop`. This gives the rack `R` the structure of an augmented rack over `envel_group R`. -/ def envel_action {R : Type*} [rack R] : envel_group R →* (R ≃ R) := to_envel_group.map (to_conj R) @[simp] lemma envel_action_prop {R : Type*} [rack R] (x y : R) : envel_action (to_envel_group R x) y = x ◃ y := rfl end envel_group end rack
660b6918d65fe69c629e743bdf809bca84c572b7
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/tests/lean/487.hlean
10e89c4a96e7fa3abe63b139804d0198cc814ed7
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
450
hlean
open eq is_trunc structure is_retraction [class] {A B : Type} (f : A → B) := (sect : B → A) (right_inverse : Π(b : B), f (sect b) = b) definition foo {A : Type} {B : Type} (f : A → B) (g : B → A) (ε : Πb, f (g b) = b) (b b' : B) : is_retraction (λ (q : g b = g b'), (ε b) ⁻¹ ⬝ ap f q ⬝ ε b') := begin fapply is_retraction.mk, {exact (@ap B A g b b') }, {intro p, cases p, esimp {eq.ap, eq.rec_on, eq.idp} } end
fe1e132d85d61cb31f78a3cd0ed3f7141ee30151
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monoidal/category.lean
d475a9e130525f16aaed1f9963692985063ac24d
[ "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
20,844
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison, Bhavik Mehta, Jakob von Raumer -/ import category_theory.products.basic /-! # Monoidal categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A monoidal category is a category equipped with a tensor product, unitors, and an associator. In the definition, we provide the tensor product as a pair of functions * `tensor_obj : C → C → C` * `tensor_hom : (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂))` and allow use of the overloaded notation `⊗` for both. The unitors and associator are provided componentwise. The tensor product can be expressed as a functor via `tensor : C × C ⥤ C`. The unitors and associator are gathered together as natural isomorphisms in `left_unitor_nat_iso`, `right_unitor_nat_iso` and `associator_nat_iso`. Some consequences of the definition are proved in other files, e.g. `(λ_ (𝟙_ C)).hom = (ρ_ (𝟙_ C)).hom` in `category_theory.monoidal.unitors_equal`. ## Implementation Dealing with unitors and associators is painful, and at this stage we do not have a useful implementation of coherence for monoidal categories. In an effort to lessen the pain, we put some effort into choosing the right `simp` lemmas. Generally, the rule is that the component index of a natural transformation "weighs more" in considering the complexity of an expression than does a structural isomorphism (associator, etc). As an example when we prove Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf> we state it as a `@[simp]` lemma as ``` (λ_ (X ⊗ Y)).hom = (α_ (𝟙_ C) X Y).inv ≫ (λ_ X).hom ⊗ (𝟙 Y) ``` This is far from completely effective, but seems to prove a useful principle. ## References * Tensor categories, Etingof, Gelaki, Nikshych, Ostrik, http://www-math.mit.edu/~etingof/egnobookfinal.pdf * <https://stacks.math.columbia.edu/tag/0FFK>. -/ open category_theory universes v u open category_theory open category_theory.category open category_theory.iso namespace category_theory /-- In a monoidal category, we can take the tensor product of objects, `X ⊗ Y` and of morphisms `f ⊗ g`. Tensor product does not need to be strictly associative on objects, but there is a specified associator, `α_ X Y Z : (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)`. There is a tensor unit `𝟙_ C`, with specified left and right unitor isomorphisms `λ_ X : 𝟙_ C ⊗ X ≅ X` and `ρ_ X : X ⊗ 𝟙_ C ≅ X`. These associators and unitors satisfy the pentagon and triangle equations. See <https://stacks.math.columbia.edu/tag/0FFK>. -/ class monoidal_category (C : Type u) [𝒞 : category.{v} C] := -- curried tensor product of objects: (tensor_obj : C → C → C) (infixr (name := tensor_obj) ` ⊗ `:70 := tensor_obj) -- This notation is only temporary -- curried tensor product of morphisms: (tensor_hom : Π {X₁ Y₁ X₂ Y₂ : C}, (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂))) (infixr ` ⊗' `:69 := tensor_hom) -- This notation is only temporary -- tensor product laws: (tensor_id' : ∀ (X₁ X₂ : C), (𝟙 X₁) ⊗' (𝟙 X₂) = 𝟙 (X₁ ⊗ X₂) . obviously) (tensor_comp' : ∀ {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂), (f₁ ≫ g₁) ⊗' (f₂ ≫ g₂) = (f₁ ⊗' f₂) ≫ (g₁ ⊗' g₂) . obviously) -- tensor unit: (tensor_unit [] : C) (notation `𝟙_` := tensor_unit) -- associator: (associator : Π X Y Z : C, (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)) (notation `α_` := associator) (associator_naturality' : ∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃), ((f₁ ⊗' f₂) ⊗' f₃) ≫ (α_ Y₁ Y₂ Y₃).hom = (α_ X₁ X₂ X₃).hom ≫ (f₁ ⊗' (f₂ ⊗' f₃)) . obviously) -- left unitor: (left_unitor : Π X : C, 𝟙_ ⊗ X ≅ X) (notation `λ_` := left_unitor) (left_unitor_naturality' : ∀ {X Y : C} (f : X ⟶ Y), ((𝟙 𝟙_) ⊗' f) ≫ (λ_ Y).hom = (λ_ X).hom ≫ f . obviously) -- right unitor: (right_unitor : Π X : C, X ⊗ 𝟙_ ≅ X) (notation `ρ_` := right_unitor) (right_unitor_naturality' : ∀ {X Y : C} (f : X ⟶ Y), (f ⊗' (𝟙 𝟙_)) ≫ (ρ_ Y).hom = (ρ_ X).hom ≫ f . obviously) -- pentagon identity: (pentagon' : ∀ W X Y Z : C, ((α_ W X Y).hom ⊗' (𝟙 Z)) ≫ (α_ W (X ⊗ Y) Z).hom ≫ ((𝟙 W) ⊗' (α_ X Y Z).hom) = (α_ (W ⊗ X) Y Z).hom ≫ (α_ W X (Y ⊗ Z)).hom . obviously) -- triangle identity: (triangle' : ∀ X Y : C, (α_ X 𝟙_ Y).hom ≫ ((𝟙 X) ⊗' (λ_ Y).hom) = (ρ_ X).hom ⊗' (𝟙 Y) . obviously) restate_axiom monoidal_category.tensor_id' attribute [simp] monoidal_category.tensor_id restate_axiom monoidal_category.tensor_comp' attribute [reassoc] monoidal_category.tensor_comp -- This would be redundant in the simp set. attribute [simp] monoidal_category.tensor_comp restate_axiom monoidal_category.associator_naturality' attribute [reassoc] monoidal_category.associator_naturality restate_axiom monoidal_category.left_unitor_naturality' attribute [reassoc] monoidal_category.left_unitor_naturality restate_axiom monoidal_category.right_unitor_naturality' attribute [reassoc] monoidal_category.right_unitor_naturality restate_axiom monoidal_category.pentagon' restate_axiom monoidal_category.triangle' attribute [reassoc] monoidal_category.pentagon attribute [simp, reassoc] monoidal_category.triangle open monoidal_category infixr (name := tensor_obj) ` ⊗ `:70 := tensor_obj infixr (name := tensor_hom) ` ⊗ `:70 := tensor_hom notation `𝟙_` := tensor_unit notation `α_` := associator notation `λ_` := left_unitor notation `ρ_` := right_unitor /-- The tensor product of two isomorphisms is an isomorphism. -/ @[simps] def tensor_iso {C : Type u} {X Y X' Y' : C} [category.{v} C] [monoidal_category.{v} C] (f : X ≅ Y) (g : X' ≅ Y') : X ⊗ X' ≅ Y ⊗ Y' := { hom := f.hom ⊗ g.hom, inv := f.inv ⊗ g.inv, hom_inv_id' := by rw [←tensor_comp, iso.hom_inv_id, iso.hom_inv_id, ←tensor_id], inv_hom_id' := by rw [←tensor_comp, iso.inv_hom_id, iso.inv_hom_id, ←tensor_id] } infixr (name := tensor_iso) ` ⊗ `:70 := tensor_iso namespace monoidal_category section variables {C : Type u} [category.{v} C] [monoidal_category.{v} C] instance tensor_is_iso {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : is_iso (f ⊗ g) := is_iso.of_iso (as_iso f ⊗ as_iso g) @[simp] lemma inv_tensor {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : inv (f ⊗ g) = inv f ⊗ inv g := by { ext, simp [←tensor_comp], } variables {U V W X Y Z : C} lemma tensor_dite {P : Prop} [decidable P] {W X Y Z : C} (f : W ⟶ X) (g : P → (Y ⟶ Z)) (g' : ¬P → (Y ⟶ Z)) : f ⊗ (if h : P then g h else g' h) = if h : P then f ⊗ g h else f ⊗ g' h := by { split_ifs; refl } lemma dite_tensor {P : Prop} [decidable P] {W X Y Z : C} (f : W ⟶ X) (g : P → (Y ⟶ Z)) (g' : ¬P → (Y ⟶ Z)) : (if h : P then g h else g' h) ⊗ f = if h : P then g h ⊗ f else g' h ⊗ f := by { split_ifs; refl } @[reassoc, simp] lemma comp_tensor_id (f : W ⟶ X) (g : X ⟶ Y) : (f ≫ g) ⊗ (𝟙 Z) = (f ⊗ (𝟙 Z)) ≫ (g ⊗ (𝟙 Z)) := by { rw ←tensor_comp, simp } @[reassoc, simp] lemma id_tensor_comp (f : W ⟶ X) (g : X ⟶ Y) : (𝟙 Z) ⊗ (f ≫ g) = (𝟙 Z ⊗ f) ≫ (𝟙 Z ⊗ g) := by { rw ←tensor_comp, simp } @[simp, reassoc] lemma id_tensor_comp_tensor_id (f : W ⟶ X) (g : Y ⟶ Z) : ((𝟙 Y) ⊗ f) ≫ (g ⊗ (𝟙 X)) = g ⊗ f := by { rw [←tensor_comp], simp } @[simp, reassoc] lemma tensor_id_comp_id_tensor (f : W ⟶ X) (g : Y ⟶ Z) : (g ⊗ (𝟙 W)) ≫ ((𝟙 Z) ⊗ f) = g ⊗ f := by { rw [←tensor_comp], simp } @[simp] lemma right_unitor_conjugation {X Y : C} (f : X ⟶ Y) : (f ⊗ (𝟙 (𝟙_ C))) = (ρ_ X).hom ≫ f ≫ (ρ_ Y).inv := by rw [←right_unitor_naturality_assoc, iso.hom_inv_id, category.comp_id] @[simp] lemma left_unitor_conjugation {X Y : C} (f : X ⟶ Y) : ((𝟙 (𝟙_ C)) ⊗ f) = (λ_ X).hom ≫ f ≫ (λ_ Y).inv := by rw [←left_unitor_naturality_assoc, iso.hom_inv_id, category.comp_id] @[reassoc] lemma left_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : f ≫ (λ_ X').inv = (λ_ X).inv ≫ (𝟙 _ ⊗ f) := by simp @[reassoc] lemma right_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : f ≫ (ρ_ X').inv = (ρ_ X).inv ≫ (f ⊗ 𝟙 _) := by simp lemma tensor_left_iff {X Y : C} (f g : X ⟶ Y) : ((𝟙 (𝟙_ C)) ⊗ f = (𝟙 (𝟙_ C)) ⊗ g) ↔ (f = g) := by simp lemma tensor_right_iff {X Y : C} (f g : X ⟶ Y) : (f ⊗ (𝟙 (𝟙_ C)) = g ⊗ (𝟙 (𝟙_ C))) ↔ (f = g) := by simp /-! The lemmas in the next section are true by coherence, but we prove them directly as they are used in proving the coherence theorem. -/ section @[reassoc] lemma pentagon_inv (W X Y Z : C) : ((𝟙 W) ⊗ (α_ X Y Z).inv) ≫ (α_ W (X ⊗ Y) Z).inv ≫ ((α_ W X Y).inv ⊗ (𝟙 Z)) = (α_ W X (Y ⊗ Z)).inv ≫ (α_ (W ⊗ X) Y Z).inv := category_theory.eq_of_inv_eq_inv (by simp [pentagon]) @[reassoc, simp] lemma right_unitor_tensor (X Y : C) : (ρ_ (X ⊗ Y)).hom = (α_ X Y (𝟙_ C)).hom ≫ ((𝟙 X) ⊗ (ρ_ Y).hom) := by rw [←tensor_right_iff, comp_tensor_id, ←cancel_mono (α_ X Y (𝟙_ C)).hom, assoc, associator_naturality, ←triangle_assoc, ←triangle, id_tensor_comp, pentagon_assoc, ←associator_naturality, tensor_id] @[reassoc, simp] lemma right_unitor_tensor_inv (X Y : C) : ((ρ_ (X ⊗ Y)).inv) = ((𝟙 X) ⊗ (ρ_ Y).inv) ≫ (α_ X Y (𝟙_ C)).inv := eq_of_inv_eq_inv (by simp) @[simp, reassoc] lemma triangle_assoc_comp_right (X Y : C) : (α_ X (𝟙_ C) Y).inv ≫ ((ρ_ X).hom ⊗ 𝟙 Y) = ((𝟙 X) ⊗ (λ_ Y).hom) := by rw [←triangle, iso.inv_hom_id_assoc] @[simp, reassoc] lemma triangle_assoc_comp_left_inv (X Y : C) : ((𝟙 X) ⊗ (λ_ Y).inv) ≫ (α_ X (𝟙_ C) Y).inv = ((ρ_ X).inv ⊗ 𝟙 Y) := begin apply (cancel_mono ((ρ_ X).hom ⊗ 𝟙 Y)).1, simp only [triangle_assoc_comp_right, assoc], rw [←id_tensor_comp, iso.inv_hom_id, ←comp_tensor_id, iso.inv_hom_id] end end @[reassoc] lemma associator_inv_naturality {X Y Z X' Y' Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') : (f ⊗ (g ⊗ h)) ≫ (α_ X' Y' Z').inv = (α_ X Y Z).inv ≫ ((f ⊗ g) ⊗ h) := by { rw [comp_inv_eq, assoc, associator_naturality], simp } @[reassoc, simp] lemma associator_conjugation {X X' Y Y' Z Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') : (f ⊗ g) ⊗ h = (α_ X Y Z).hom ≫ (f ⊗ (g ⊗ h)) ≫ (α_ X' Y' Z').inv := by rw [associator_inv_naturality, hom_inv_id_assoc] @[reassoc] lemma associator_inv_conjugation {X X' Y Y' Z Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') : f ⊗ g ⊗ h = (α_ X Y Z).inv ≫ ((f ⊗ g) ⊗ h) ≫ (α_ X' Y' Z').hom := by rw [associator_naturality, inv_hom_id_assoc] -- TODO these next two lemmas aren't so fundamental, and perhaps could be removed -- (replacing their usages by their proofs). @[reassoc] lemma id_tensor_associator_naturality {X Y Z Z' : C} (h : Z ⟶ Z') : (𝟙 (X ⊗ Y) ⊗ h) ≫ (α_ X Y Z').hom = (α_ X Y Z).hom ≫ (𝟙 X ⊗ (𝟙 Y ⊗ h)) := by { rw [←tensor_id, associator_naturality], } @[reassoc] lemma id_tensor_associator_inv_naturality {X Y Z X' : C} (f : X ⟶ X') : (f ⊗ 𝟙 (Y ⊗ Z)) ≫ (α_ X' Y Z).inv = (α_ X Y Z).inv ≫ ((f ⊗ 𝟙 Y) ⊗ 𝟙 Z) := by { rw [←tensor_id, associator_inv_naturality] } @[simp, reassoc] lemma hom_inv_id_tensor {V W X Y Z : C} (f : V ≅ W) (g : X ⟶ Y) (h : Y ⟶ Z) : (f.hom ⊗ g) ≫ (f.inv ⊗ h) = (𝟙 V ⊗ g) ≫ (𝟙 V ⊗ h) := by rw [←tensor_comp, f.hom_inv_id, id_tensor_comp] @[simp, reassoc] lemma inv_hom_id_tensor {V W X Y Z : C} (f : V ≅ W) (g : X ⟶ Y) (h : Y ⟶ Z) : (f.inv ⊗ g) ≫ (f.hom ⊗ h) = (𝟙 W ⊗ g) ≫ (𝟙 W ⊗ h) := by rw [←tensor_comp, f.inv_hom_id, id_tensor_comp] @[simp, reassoc] lemma tensor_hom_inv_id {V W X Y Z : C} (f : V ≅ W) (g : X ⟶ Y) (h : Y ⟶ Z) : (g ⊗ f.hom) ≫ (h ⊗ f.inv) = (g ⊗ 𝟙 V) ≫ (h ⊗ 𝟙 V) := by rw [←tensor_comp, f.hom_inv_id, comp_tensor_id] @[simp, reassoc] lemma tensor_inv_hom_id {V W X Y Z : C} (f : V ≅ W) (g : X ⟶ Y) (h : Y ⟶ Z) : (g ⊗ f.inv) ≫ (h ⊗ f.hom) = (g ⊗ 𝟙 W) ≫ (h ⊗ 𝟙 W) := by rw [←tensor_comp, f.inv_hom_id, comp_tensor_id] @[simp, reassoc] lemma hom_inv_id_tensor' {V W X Y Z : C} (f : V ⟶ W) [is_iso f] (g : X ⟶ Y) (h : Y ⟶ Z) : (f ⊗ g) ≫ (inv f ⊗ h) = (𝟙 V ⊗ g) ≫ (𝟙 V ⊗ h) := by rw [←tensor_comp, is_iso.hom_inv_id, id_tensor_comp] @[simp, reassoc] lemma inv_hom_id_tensor' {V W X Y Z : C} (f : V ⟶ W) [is_iso f] (g : X ⟶ Y) (h : Y ⟶ Z) : (inv f ⊗ g) ≫ (f ⊗ h) = (𝟙 W ⊗ g) ≫ (𝟙 W ⊗ h) := by rw [←tensor_comp, is_iso.inv_hom_id, id_tensor_comp] @[simp, reassoc] lemma tensor_hom_inv_id' {V W X Y Z : C} (f : V ⟶ W) [is_iso f] (g : X ⟶ Y) (h : Y ⟶ Z) : (g ⊗ f) ≫ (h ⊗ inv f) = (g ⊗ 𝟙 V) ≫ (h ⊗ 𝟙 V) := by rw [←tensor_comp, is_iso.hom_inv_id, comp_tensor_id] @[simp, reassoc] lemma tensor_inv_hom_id' {V W X Y Z : C} (f : V ⟶ W) [is_iso f] (g : X ⟶ Y) (h : Y ⟶ Z) : (g ⊗ inv f) ≫ (h ⊗ f) = (g ⊗ 𝟙 W) ≫ (h ⊗ 𝟙 W) := by rw [←tensor_comp, is_iso.inv_hom_id, comp_tensor_id] end section variables (C : Type u) [category.{v} C] [monoidal_category.{v} C] /-- The tensor product expressed as a functor. -/ @[simps] def tensor : (C × C) ⥤ C := { obj := λ X, X.1 ⊗ X.2, map := λ {X Y : C × C} (f : X ⟶ Y), f.1 ⊗ f.2 } /-- The left-associated triple tensor product as a functor. -/ def left_assoc_tensor : (C × C × C) ⥤ C := { obj := λ X, (X.1 ⊗ X.2.1) ⊗ X.2.2, map := λ {X Y : C × C × C} (f : X ⟶ Y), (f.1 ⊗ f.2.1) ⊗ f.2.2 } @[simp] lemma left_assoc_tensor_obj (X) : (left_assoc_tensor C).obj X = (X.1 ⊗ X.2.1) ⊗ X.2.2 := rfl @[simp] lemma left_assoc_tensor_map {X Y} (f : X ⟶ Y) : (left_assoc_tensor C).map f = (f.1 ⊗ f.2.1) ⊗ f.2.2 := rfl /-- The right-associated triple tensor product as a functor. -/ def right_assoc_tensor : (C × C × C) ⥤ C := { obj := λ X, X.1 ⊗ (X.2.1 ⊗ X.2.2), map := λ {X Y : C × C × C} (f : X ⟶ Y), f.1 ⊗ (f.2.1 ⊗ f.2.2) } @[simp] lemma right_assoc_tensor_obj (X) : (right_assoc_tensor C).obj X = X.1 ⊗ (X.2.1 ⊗ X.2.2) := rfl @[simp] lemma right_assoc_tensor_map {X Y} (f : X ⟶ Y) : (right_assoc_tensor C).map f = f.1 ⊗ (f.2.1 ⊗ f.2.2) := rfl /-- The functor `λ X, 𝟙_ C ⊗ X`. -/ def tensor_unit_left : C ⥤ C := { obj := λ X, 𝟙_ C ⊗ X, map := λ {X Y : C} (f : X ⟶ Y), (𝟙 (𝟙_ C)) ⊗ f } /-- The functor `λ X, X ⊗ 𝟙_ C`. -/ def tensor_unit_right : C ⥤ C := { obj := λ X, X ⊗ 𝟙_ C, map := λ {X Y : C} (f : X ⟶ Y), f ⊗ (𝟙 (𝟙_ C)) } -- We can express the associator and the unitors, given componentwise above, -- as natural isomorphisms. /-- The associator as a natural isomorphism. -/ @[simps] def associator_nat_iso : left_assoc_tensor C ≅ right_assoc_tensor C := nat_iso.of_components (by { intros, apply monoidal_category.associator }) (by { intros, apply monoidal_category.associator_naturality }) /-- The left unitor as a natural isomorphism. -/ @[simps] def left_unitor_nat_iso : tensor_unit_left C ≅ 𝟭 C := nat_iso.of_components (by { intros, apply monoidal_category.left_unitor }) (by { intros, apply monoidal_category.left_unitor_naturality }) /-- The right unitor as a natural isomorphism. -/ @[simps] def right_unitor_nat_iso : tensor_unit_right C ≅ 𝟭 C := nat_iso.of_components (by { intros, apply monoidal_category.right_unitor }) (by { intros, apply monoidal_category.right_unitor_naturality }) section variables {C} /-- Tensoring on the left with a fixed object, as a functor. -/ @[simps] def tensor_left (X : C) : C ⥤ C := { obj := λ Y, X ⊗ Y, map := λ Y Y' f, (𝟙 X) ⊗ f, } /-- Tensoring on the left with `X ⊗ Y` is naturally isomorphic to tensoring on the left with `Y`, and then again with `X`. -/ def tensor_left_tensor (X Y : C) : tensor_left (X ⊗ Y) ≅ tensor_left Y ⋙ tensor_left X := nat_iso.of_components (associator _ _) (λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_naturality }) @[simp] lemma tensor_left_tensor_hom_app (X Y Z : C) : (tensor_left_tensor X Y).hom.app Z = (associator X Y Z).hom := rfl @[simp] lemma tensor_left_tensor_inv_app (X Y Z : C) : (tensor_left_tensor X Y).inv.app Z = (associator X Y Z).inv := by { simp [tensor_left_tensor], } /-- Tensoring on the right with a fixed object, as a functor. -/ @[simps] def tensor_right (X : C) : C ⥤ C := { obj := λ Y, Y ⊗ X, map := λ Y Y' f, f ⊗ (𝟙 X), } variables (C) /-- Tensoring on the left, as a functor from `C` into endofunctors of `C`. TODO: show this is a op-monoidal functor. -/ @[simps] def tensoring_left : C ⥤ C ⥤ C := { obj := tensor_left, map := λ X Y f, { app := λ Z, f ⊗ (𝟙 Z) } } instance : faithful (tensoring_left C) := { map_injective' := λ X Y f g h, begin injections with h, replace h := congr_fun h (𝟙_ C), simpa using h, end } /-- Tensoring on the right, as a functor from `C` into endofunctors of `C`. We later show this is a monoidal functor. -/ @[simps] def tensoring_right : C ⥤ C ⥤ C := { obj := tensor_right, map := λ X Y f, { app := λ Z, (𝟙 Z) ⊗ f } } instance : faithful (tensoring_right C) := { map_injective' := λ X Y f g h, begin injections with h, replace h := congr_fun h (𝟙_ C), simpa using h, end } variables {C} /-- Tensoring on the right with `X ⊗ Y` is naturally isomorphic to tensoring on the right with `X`, and then again with `Y`. -/ def tensor_right_tensor (X Y : C) : tensor_right (X ⊗ Y) ≅ tensor_right X ⋙ tensor_right Y := nat_iso.of_components (λ Z, (associator Z X Y).symm) (λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_inv_naturality }) @[simp] lemma tensor_right_tensor_hom_app (X Y Z : C) : (tensor_right_tensor X Y).hom.app Z = (associator Z X Y).inv := rfl @[simp] lemma tensor_right_tensor_inv_app (X Y Z : C) : (tensor_right_tensor X Y).inv.app Z = (associator Z X Y).hom := by simp [tensor_right_tensor] end end section universes v₁ v₂ u₁ u₂ variables (C₁ : Type u₁) [category.{v₁} C₁] [monoidal_category.{v₁} C₁] variables (C₂ : Type u₂) [category.{v₂} C₂] [monoidal_category.{v₂} C₂] local attribute [simp] associator_naturality left_unitor_naturality right_unitor_naturality pentagon @[simps tensor_obj tensor_hom tensor_unit associator] instance prod_monoidal : monoidal_category (C₁ × C₂) := { tensor_obj := λ X Y, (X.1 ⊗ Y.1, X.2 ⊗ Y.2), tensor_hom := λ _ _ _ _ f g, (f.1 ⊗ g.1, f.2 ⊗ g.2), tensor_unit := (𝟙_ C₁, 𝟙_ C₂), associator := λ X Y Z, (α_ X.1 Y.1 Z.1).prod (α_ X.2 Y.2 Z.2), left_unitor := λ ⟨X₁, X₂⟩, (λ_ X₁).prod (λ_ X₂), right_unitor := λ ⟨X₁, X₂⟩, (ρ_ X₁).prod (ρ_ X₂) } @[simp] lemma prod_monoidal_left_unitor_hom_fst (X : C₁ × C₂) : ((λ_ X).hom : (𝟙_ _) ⊗ X ⟶ X).1 = (λ_ X.1).hom := by { cases X, refl } @[simp] lemma prod_monoidal_left_unitor_hom_snd (X : C₁ × C₂) : ((λ_ X).hom : (𝟙_ _) ⊗ X ⟶ X).2 = (λ_ X.2).hom := by { cases X, refl } @[simp] lemma prod_monoidal_left_unitor_inv_fst (X : C₁ × C₂) : ((λ_ X).inv : X ⟶ (𝟙_ _) ⊗ X).1 = (λ_ X.1).inv := by { cases X, refl } @[simp] lemma prod_monoidal_left_unitor_inv_snd (X : C₁ × C₂) : ((λ_ X).inv : X ⟶ (𝟙_ _) ⊗ X).2 = (λ_ X.2).inv := by { cases X, refl } @[simp] lemma prod_monoidal_right_unitor_hom_fst (X : C₁ × C₂) : ((ρ_ X).hom : X ⊗ (𝟙_ _) ⟶ X).1 = (ρ_ X.1).hom := by { cases X, refl } @[simp] lemma prod_monoidal_right_unitor_hom_snd (X : C₁ × C₂) : ((ρ_ X).hom : X ⊗ (𝟙_ _) ⟶ X).2 = (ρ_ X.2).hom := by { cases X, refl } @[simp] lemma prod_monoidal_right_unitor_inv_fst (X : C₁ × C₂) : ((ρ_ X).inv : X ⟶ X ⊗ (𝟙_ _)).1 = (ρ_ X.1).inv := by { cases X, refl } @[simp] lemma prod_monoidal_right_unitor_inv_snd (X : C₁ × C₂) : ((ρ_ X).inv : X ⟶ X ⊗ (𝟙_ _)).2 = (ρ_ X.2).inv := by { cases X, refl } end end monoidal_category end category_theory
f63677b9d4a780e2b942c12068b4305a5d3f5619
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/f2.lean
effd3cb8e3f47b6a255e4894381af73d0bde31d9
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
7,297
lean
import tactic.ring data.int.modeq data.fintype group_theory.sylow universe u local attribute [instance, priority 0] classical.prop_decidable open fintype finset nat private def S (p : ℕ) : finset (ℕ × ℕ × ℕ) := ((range p).product ((range p).product (range p))).filter (λ v, v.1 ^ 2 + 4 * v.2.1 * v.2.2 = p) lemma mem_S (p : ℕ) (v : ℕ × ℕ × ℕ) : v.1 ^ 2 + 4 * v.2.1 * v.2.2 = p → v ∈ S p := begin rcases v with ⟨x, y, z⟩, suffices : x ^ 2 + 4 * y * z = p → (x < p ∧ y < p ∧ z < p), { simp [S], tauto }, assume h, refine ⟨_, _, _⟩, { calc x ≤ x ^ 2 : by rw pow_two; exact le_mul_self x ... ≤ x ^ 2 + 4 * y * z : _ ... < _ : sorry }, end lemma nat.not_prime_mul_self (n : ℕ) : ¬prime (n * n) := λ h, or.by_cases (h.2 _ $ dvd_mul_right n n) (λ h₁, (dec_trivial : ¬ 1 ≥ 2) (h₁ ▸ h : prime (1 * 1)).1) (λ h₁, have h₂ : n * 1 = n * n := by rwa mul_one, have h₃ : 1 = n := (@nat.mul_left_inj n 1 n (prime.pos (h₁.symm ▸ h))).1 h₂, (dec_trivial : ¬ 1 ≥ 2) (h₃.symm ▸ h : prime (1 * 1)).1) @[reducible] private def f₁ (v : ℕ × ℕ × ℕ) : ℕ × ℕ × ℕ := (v.1, v.2.2, v.2.1) @[reducible] private def f₂ (v : ℕ × ℕ × ℕ) : ℕ × ℕ × ℕ := if v.1 + v.2.2 < v.2.1 then (v.1 + 2 * v.2.2, v.2.2, v.2.1 - v.1 - v.2.2) else if 2 * v.2.1 < v.1 then (v.1 - 2 * v.2.1, v.1 - v.2.1 + v.2.2, v.2.1) else (2 * v.2.1 - v.1, v.2.1, v.1 - v.2.1 + v.2.2) variables {p : ℕ} (hp : prime p) (hp₁ : p % 4 = 1) include hp hp₁ private lemma f₁_mem_S : ∀ v : ℕ × ℕ × ℕ, v ∈ S p → f₁ v ∈ S p := λ ⟨x, y, z⟩, by simp [S, mul_comm, *, mul_assoc, mul_left_comm, *, f₁] {contextual := tt} private lemma f₁_involution : ∀ v : ℕ × ℕ × ℕ, f₁ (f₁ v) = v := λ ⟨x, y, z⟩, rfl private lemma f₂_mem_S₁ {x y z : ℕ} (hxp : x < p) (hyp : y < p) (hzp : z < p) (hxyz : x + z < y) : ∀ v : ℕ × ℕ × ℕ, v ∈ S p → f₂ v ∈ S p private lemma f₂_S : ∀ v : ℕ × ℕ × ℕ, v ∈ S p → f₂ v ∈ S p := λ ⟨x, y, z⟩, begin clear_aux_decl, simp [S, f₂] at *, split_ifs; simp *, end private lemma f₂_invo_on_S : ∀ v : ℤ × ℤ × ℤ, v ∈ S p → f₂ (f₂ v) = v := λ ⟨x, y, z⟩ hv, have xp : 0 < x := x_pos hp hp₁ (x, y, z) hv, have yzp : 0 < y ∧ 0 < z := yz_pos hp hp₁ (x, y, z) hv, or.by_cases (decidable.em (x + z < y)) (λ h, have h₁ : ¬ x + (y + (2 * z + (-x + -z))) < z := have h₁ : x + (y + (2 * z + (-x + -z))) = y + z := by ring, not_lt_of_ge (h₁.symm ▸ le_add_of_nonneg_left hv.2.2.1), by simp[f₂, h, h₁, xp]; ring) $ λ h, or.by_cases (decidable.em (2 * y < x)) (λ h₁, have h₂ : y + -(2 * y) < z + -y := have h₂ : y + -(2 * y) = -y := by ring, h₂.symm ▸ lt_add_of_pos_left _ yzp.2, by simp[f₂, h, h₁, h₂]; ring) $ λ h₁, have h₂ : ¬ x + (z + (2 * y + (-x + -y))) < y := have h₁ : x + (z + (2 * y + (-x + -y))) = z + y := by ring, not_lt_of_ge (h₁.symm ▸ le_add_of_nonneg_left hv.2.2.2), have h₃ : ¬ 0 < -x := not_lt_of_ge $ le_of_lt $ neg_neg_of_pos xp, by simp [f₂, h, h₁, h₂, h₃]; ring private lemma f₂_fixed_point : ∃! v : S p, f₂ v = v := have hp4 : (0 : ℤ) ≤ p / 4 := int.div_nonneg (int.coe_nat_nonneg _) dec_trivial, have h : ¬ (1 : ℤ) + p / 4 < 1 := not_lt_of_ge $ le_add_of_nonneg_right hp4, ⟨⟨(1, 1, (p / 4 : ℤ)), ⟨show (1 : ℤ) + 4 * (p / 4) = p, from have h : (p : ℤ) % 4 = 1 := (int.coe_nat_eq_coe_nat_iff _ _).2 hp₁, have h₁ : (p : ℤ) = p % 4 + 4 * (p / 4) := (int.mod_add_div _ _).symm, by rw [h₁] {occs := occurrences.pos [2]}; rw h, dec_trivial, dec_trivial, hp4 ⟩⟩, ⟨by simp [f₂, h, (dec_trivial : ¬ (2 : ℤ) < 1)]; refl, λ ⟨⟨x, y, z⟩, ⟨hv, hx, hy, hz⟩ ⟩ hf, have xp : 0 < x := x_pos hp hp₁ (x, y, z) ⟨hv, hx, hy, hz⟩, have yzp : 0 < y ∧ 0 < z := yz_pos hp hp₁ (x, y, z) ⟨hv, hx, hy, hz⟩, or.by_cases (decidable.em (x + z < y)) (λ h₁, have h₂ : x + 2 * z ≠ x := λ h₃, have h₄ : x + 2 * z = x + 0 := by rwa add_zero, not_or dec_trivial (ne_of_lt yzp.2).symm (mul_eq_zero.1 ((add_left_inj _).1 h₄)), by simpa [f₂, h₁, h₂] using hf) $ λ h₁, or.by_cases (decidable.em (2 * y < x)) (λ h₂, have h₃ : x + -(2 * y) ≠ x := λ h₄, have h₅ : x + -2 * y = x + 0 := by rwa [← neg_mul_eq_neg_mul, add_zero], not_or dec_trivial (ne_of_lt yzp.1).symm (mul_eq_zero.1 ((add_left_inj _).1 h₅)), by simp [f₂, h₁, h₂, h₃] at hf; trivial) $ λ h₂, have hf₁ : 2 * y - x = x ∧ x + (z + -y) = z := by simp [f₂, h₁, h₂] at hf; assumption, have hxy : y = x := by rw [sub_eq_iff_eq_add, ← two_mul] at hf₁; exact eq_of_mul_eq_mul_left dec_trivial hf₁.1, subtype.eq $ show (x, y, z) = (1, 1, p / 4), from begin rw [hxy, mul_comm (4 : ℤ), mul_assoc] at hv, have hxp : int.nat_abs x ∣ p := int.coe_nat_dvd.1 (int.nat_abs_dvd.2 (hv ▸ dvd_add (dvd_mul_right _ _) (dvd_mul_right _ _))), have h4 : ((4 : ℕ) : ℤ) = 4 := rfl, cases hp.2 _ (hxp) with h₃ h₃, { have h₄ : x = 1 := by rwa [← int.coe_nat_eq_coe_nat_iff, int.nat_abs_of_nonneg hx] at h₃, rw [← mod_add_div p 4, hp₁, h₄, int.coe_nat_add, int.coe_nat_one, mul_one, one_mul, add_left_cancel_iff, int.coe_nat_mul] at hv, have : z = p / 4 := eq_of_mul_eq_mul_left_of_ne_zero dec_trivial hv, rw [hxy, h₄, this] }, { have h4 : ((4 : ℕ) : ℤ) = 4 := rfl, rw [← int.nat_abs_of_nonneg hx, ← int.nat_abs_of_nonneg hz, h₃, ← mul_add] at hv, have := int.eq_one_of_mul_eq_self_right (int.coe_nat_ne_zero.2 (ne_of_lt (prime.pos hp)).symm) hv, rw [← h4, ← int.coe_nat_mul, ← int.coe_nat_add, ← int.coe_nat_one, int.coe_nat_eq_coe_nat_iff] at this, have : p ≤ 1 := this ▸ (le_add_right p (4 * int.nat_abs z)), exact absurd (prime.gt_one hp) (not_lt_of_ge this) } end ⟩ ⟩ theorem fermat_sum_two_squares : ∃ a b : ℕ, a^2 + b^2 = p := have fS : fintype (S p) := fintype_S hp hp₁, let f₁' : S p → S p := λ ⟨v, hv⟩, ⟨f₁ v, f₁_S hp hp₁ _ hv⟩ in let f₂' : S p → S p := λ ⟨v, hv⟩, ⟨f₂ v, f₂_S hp hp₁ _ hv⟩ in have hf₁ : ∀ v, f₁' (f₁' v) = v := λ ⟨v, hv⟩, subtype.eq $ f₁_invo_on_S hp hp₁ v, have hf₂ : ∀ v, f₂' (f₂' v) = v := λ ⟨v, hv⟩, subtype.eq $ f₂_invo_on_S hp hp₁ v hv, have hf₂u : ∃! v : S p, f₂' v = v := let ⟨⟨v, vS⟩, ⟨hv₁, hv₂⟩⟩ := f₂_fixed_point hp hp₁ in ⟨⟨v, vS⟩, ⟨subtype.eq hv₁, λ ⟨w, wS⟩ hw, hv₂ ⟨w, wS⟩ (subtype.mk.inj hw) ⟩ ⟩, let h := @odd_card_of_involution_of_unique_fixed_point _ _ fS hf₂ hf₂u in let ⟨⟨⟨x, y, z⟩, hvp, ⟨hx, hy, hz⟩⟩, h⟩ := @exists_fixed_point_of_involution_of_odd_card _ _ fS h hf₁ in have h : y = z := (prod.eq_iff_fst_eq_snd_eq.1 (prod.eq_iff_fst_eq_snd_eq.1 (subtype.mk.inj h)).2).2, ⟨int.nat_abs x, 2 * int.nat_abs y, begin simp only [nat.pow_succ, nat.pow_zero, one_mul], rw [mul_right_comm 2, mul_assoc, mul_assoc, ← int.coe_nat_eq_coe_nat_iff, int.coe_nat_add, int.nat_abs_mul_self, int.coe_nat_mul, int.coe_nat_mul, int.nat_abs_mul_self, ← hvp, h], simp, ring, end⟩ #print axioms fermat_sum_two_squares
5589cef245fcf8c6435391db7457749143bc932b
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/topology/opens.lean
cda033c26cc177e8819e736756a4a42ace571634
[ "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
8,136
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Floris van Doorn -/ import topology.bases import topology.homeomorph /-! # Open sets ## Summary We define the subtype of open sets in a topological space. ## Main Definitions - `opens α` is the type of open subsets of a topological space `α`. - `open_nhds_of x` is the type of open subsets of a topological space `α` containing `x : α`. - -/ open filter set variables {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] namespace topological_space variable (α) /-- The type of open subsets of a topological space. -/ def opens := {s : set α // is_open s} variable {α} namespace opens instance : has_coe (opens α) (set α) := { coe := subtype.val } lemma val_eq_coe (U : opens α) : U.1 = ↑U := rfl /-- the coercion `opens α → set α` applied to a pair is the same as taking the first component -/ lemma coe_mk {α : Type*} [topological_space α] {U : set α} {hU : is_open U} : ↑(⟨U, hU⟩ : opens α) = U := rfl instance : has_subset (opens α) := { subset := λ U V, (U : set α) ⊆ V } instance : has_mem α (opens α) := { mem := λ a U, a ∈ (U : set α) } @[simp] lemma subset_coe {U V : opens α} : ((U : set α) ⊆ (V : set α)) = (U ⊆ V) := rfl @[simp] lemma mem_coe {x : α} {U : opens α} : (x ∈ (U : set α)) = (x ∈ U) := rfl @[ext] lemma ext {U V : opens α} (h : (U : set α) = V) : U = V := subtype.ext_iff.mpr h @[ext] lemma ext_iff {U V : opens α} : (U : set α) = V ↔ U = V := ⟨opens.ext, congr_arg coe⟩ instance : partial_order (opens α) := subtype.partial_order _ /-- The interior of a set, as an element of `opens`. -/ def interior (s : set α) : opens α := ⟨interior s, is_open_interior⟩ lemma gc : galois_connection (coe : opens α → set α) interior := λ U s, ⟨λ h, interior_maximal h U.property, λ h, le_trans h interior_subset⟩ /-- The galois insertion between sets and opens, but ordered by reverse inclusion. -/ def gi : @galois_insertion (order_dual (set α)) (order_dual (opens α)) _ _ interior subtype.val := { choice := λ s hs, ⟨s, interior_eq_iff_open.mp $ le_antisymm interior_subset hs⟩, gc := gc.dual, le_l_u := λ _, interior_subset, choice_eq := λ s hs, le_antisymm interior_subset hs } @[simp] lemma gi_choice_val {s : order_dual (set α)} {hs} : (gi.choice s hs).val = s := rfl instance : complete_lattice (opens α) := complete_lattice.copy (@order_dual.complete_lattice _ (galois_insertion.lift_complete_lattice (@gi α _))) /- le -/ (λ U V, U ⊆ V) rfl /- top -/ ⟨set.univ, is_open_univ⟩ (subtype.ext_iff_val.mpr interior_univ.symm) /- bot -/ ⟨∅, is_open_empty⟩ rfl /- sup -/ (λ U V, ⟨↑U ∪ ↑V, is_open.union U.2 V.2⟩) rfl /- inf -/ (λ U V, ⟨↑U ∩ ↑V, is_open.inter U.2 V.2⟩) begin funext, apply subtype.ext_iff_val.mpr, exact (is_open.inter U.2 V.2).interior_eq.symm, end /- Sup -/ _ rfl /- Inf -/ _ rfl lemma le_def {U V : opens α} : U ≤ V ↔ (U : set α) ≤ (V : set α) := by refl @[simp] lemma mk_inf_mk {U V : set α} {hU : is_open U} {hV : is_open V} : (⟨U, hU⟩ ⊓ ⟨V, hV⟩ : opens α) = ⟨U ⊓ V, is_open.inter hU hV⟩ := rfl @[simp,norm_cast] lemma coe_inf {U V : opens α} : ((U ⊓ V : opens α) : set α) = (U : set α) ⊓ (V : set α) := rfl instance : has_inter (opens α) := ⟨λ U V, U ⊓ V⟩ instance : has_union (opens α) := ⟨λ U V, U ⊔ V⟩ instance : has_emptyc (opens α) := ⟨⊥⟩ instance : inhabited (opens α) := ⟨∅⟩ @[simp] lemma inter_eq (U V : opens α) : U ∩ V = U ⊓ V := rfl @[simp] lemma union_eq (U V : opens α) : U ∪ V = U ⊔ V := rfl @[simp] lemma empty_eq : (∅ : opens α) = ⊥ := rfl @[simp] lemma Sup_s {Us : set (opens α)} : ↑(Sup Us) = ⋃₀ ((coe : _ → set α) '' Us) := by { rw [(@gc α _).l_Sup, set.sUnion_image], refl } lemma supr_def {ι} (s : ι → opens α) : (⨆ i, s i) = ⟨⋃ i, s i, is_open_Union $ λ i, (s i).2⟩ := by { ext, simp only [supr, opens.Sup_s, sUnion_image, bUnion_range], refl } @[simp] lemma supr_mk {ι} (s : ι → set α) (h : Π i, is_open (s i)) : (⨆ i, ⟨s i, h i⟩ : opens α) = ⟨⋃ i, s i, is_open_Union h⟩ := by { rw supr_def, simp } @[simp] lemma supr_s {ι} (s : ι → opens α) : ((⨆ i, s i : opens α) : set α) = ⋃ i, s i := by simp [supr_def] @[simp] theorem mem_supr {ι} {x : α} {s : ι → opens α} : x ∈ supr s ↔ ∃ i, x ∈ s i := by { rw [←mem_coe], simp, } @[simp] lemma mem_Sup {Us : set (opens α)} {x : α} : x ∈ Sup Us ↔ ∃ u ∈ Us, x ∈ u := by simp_rw [Sup_eq_supr, mem_supr] lemma open_embedding_of_le {U V : opens α} (i : U ≤ V) : open_embedding (set.inclusion i) := { inj := set.inclusion_injective i, induced := (@induced_compose _ _ _ _ (set.inclusion i) coe).symm, open_range := begin rw set.range_inclusion i, exact U.property.preimage continuous_subtype_val end, } /-- A set of `opens α` is a basis if the set of corresponding sets is a topological basis. -/ def is_basis (B : set (opens α)) : Prop := is_topological_basis ((coe : _ → set α) '' B) lemma is_basis_iff_nbhd {B : set (opens α)} : is_basis B ↔ ∀ {U : opens α} {x}, x ∈ U → ∃ U' ∈ B, x ∈ U' ∧ U' ⊆ U := begin split; intro h, { rintros ⟨sU, hU⟩ x hx, rcases h.mem_nhds_iff.mp (is_open.mem_nhds hU hx) with ⟨sV, ⟨⟨V, H₁, H₂⟩, hsV⟩⟩, refine ⟨V, H₁, _⟩, cases V, dsimp at H₂, subst H₂, exact hsV }, { refine is_topological_basis_of_open_of_nhds _ _, { rintros sU ⟨U, ⟨H₁, H₂⟩⟩, subst H₂, exact U.property }, { intros x sU hx hsU, rcases @h (⟨sU, hsU⟩ : opens α) x hx with ⟨V, hV, H⟩, exact ⟨V, ⟨V, hV, rfl⟩, H⟩ } } end lemma is_basis_iff_cover {B : set (opens α)} : is_basis B ↔ ∀ U : opens α, ∃ Us ⊆ B, U = Sup Us := begin split, { intros hB U, refine ⟨{V : opens α | V ∈ B ∧ V ⊆ U}, λ U hU, hU.left, _⟩, apply ext, rw [Sup_s, hB.open_eq_sUnion' U.prop], simp_rw [sUnion_image, sUnion_eq_bUnion, Union, supr_and, supr_image], refl }, { intro h, rw is_basis_iff_nbhd, intros U x hx, rcases h U with ⟨Us, hUs, rfl⟩, rcases mem_Sup.1 hx with ⟨U, Us, xU⟩, exact ⟨U, hUs Us, xU, le_Sup Us⟩ } end /-- The preimage of an open set, as an open set. -/ def comap {f : α → β} (hf : continuous f) (V : opens β) : opens α := ⟨f ⁻¹' V.1, V.2.preimage hf⟩ @[simp] lemma comap_id (U : opens α) : U.comap continuous_id = U := by { ext, refl } lemma comap_mono {f : α → β} (hf : continuous f) {V W : opens β} (hVW : V ⊆ W) : V.comap hf ⊆ W.comap hf := λ _ h, hVW h @[simp] lemma coe_comap {f : α → β} (hf : continuous f) (U : opens β) : ↑(U.comap hf) = f ⁻¹' U := rfl @[simp] lemma comap_val {f : α → β} (hf : continuous f) (U : opens β) : (U.comap hf).1 = f ⁻¹' U := rfl protected lemma comap_comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) (U : opens γ) : U.comap (hg.comp hf) = (U.comap hg).comap hf := by { ext1, simp only [coe_comap, preimage_preimage] } /-- A homeomorphism induces an equivalence on open sets, by taking comaps. -/ @[simp] protected def equiv (f : α ≃ₜ β) : opens α ≃ opens β := { to_fun := opens.comap f.symm.continuous, inv_fun := opens.comap f.continuous, left_inv := by { intro U, ext1, simp only [coe_comap, ← preimage_comp, f.symm_comp_self, preimage_id] }, right_inv := by { intro U, ext1, simp only [coe_comap, ← preimage_comp, f.self_comp_symm, preimage_id] } } end opens /-- The open neighborhoods of a point. See also `opens` or `nhds`. -/ def open_nhds_of (x : α) : Type* := { s : set α // is_open s ∧ x ∈ s } instance open_nhds_of.inhabited {α : Type*} [topological_space α] (x : α) : inhabited (open_nhds_of x) := ⟨⟨set.univ, is_open_univ, set.mem_univ _⟩⟩ end topological_space
ecd85324f04a65b0078cfd1234d048de2dc7087c
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/algebra/category/constructions/comma.hlean
f6477420ad198d16686543d90f92b68c7e3df4b1
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
6,768
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Comma category -/ import ..functor.basic ..strict ..category open eq functor equiv sigma sigma.ops is_trunc iso is_equiv namespace category structure comma_object {A B C : Precategory} (S : A ⇒ C) (T : B ⇒ C) := (a : A) (b : B) (f : S a ⟶ T b) abbreviation ob1 [unfold 6] := @comma_object.a abbreviation ob2 [unfold 6] := @comma_object.b abbreviation mor [unfold 6] := @comma_object.f variables {A B C : Precategory} (S : A ⇒ C) (T : B ⇒ C) definition comma_object_sigma_char : (Σ(a : A) (b : B), S a ⟶ T b) ≃ comma_object S T := begin fapply equiv.MK, { intro u, exact comma_object.mk u.1 u.2.1 u.2.2}, { intro x, cases x with a b f, exact ⟨a, b, f⟩}, { intro x, cases x, reflexivity}, { intro u, cases u with u1 u2, cases u2, reflexivity}, end theorem is_trunc_comma_object (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B] [H : Π(s d : C), is_trunc n (hom s d)] : is_trunc n (comma_object S T) := by apply is_trunc_equiv_closed;apply comma_object_sigma_char variables {S T} definition comma_object_eq' {x y : comma_object S T} (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y) : x = y := begin cases x with a b f, cases y with a' b' f', cases p, cases q, esimp [ap011,congr,ap,subst] at r, eapply (idp_rec_on r), reflexivity end --TODO: remove. This is a different version where Hq is not in square brackets -- definition eq_comp_inverse_of_comp_eq' {ob : Type} {C : precategory ob} {d c b : ob} {r : hom c d} -- {q : hom b c} {x : hom b d} {Hq : is_iso q} (p : r ∘ q = x) : r = x ∘ q⁻¹ʰ := -- sorry -- := sorry --eq_inverse_comp_of_comp_eq p definition comma_object_eq {x y : comma_object S T} (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : T (hom_of_eq q) ∘ mor x ∘ S (inv_of_eq p) = mor y) : x = y := begin cases x with a b f, cases y with a' b' f', cases p, cases q, apply ap (comma_object.mk a' b'), rewrite [▸* at r, -r, +respect_id, id_leftright] end definition ap_ob1_comma_object_eq' (x y : comma_object S T) (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y) : ap ob1 (comma_object_eq' p q r) = p := begin cases x with a b f, cases y with a' b' f', cases p, cases q, eapply (idp_rec_on r), reflexivity end definition ap_ob2_comma_object_eq' (x y : comma_object S T) (p : ob1 x = ob1 y) (q : ob2 x = ob2 y) (r : mor x =[ap011 (@hom C C) (ap (to_fun_ob S) p) (ap (to_fun_ob T) q)] mor y) : ap ob2 (comma_object_eq' p q r) = q := begin cases x with a b f, cases y with a' b' f', cases p, cases q, eapply (idp_rec_on r), reflexivity end structure comma_morphism (x y : comma_object S T) := mk' :: (g : ob1 x ⟶ ob1 y) (h : ob2 x ⟶ ob2 y) (p : T h ∘ mor x = mor y ∘ S g) (p' : mor y ∘ S g = T h ∘ mor x) abbreviation mor1 := @comma_morphism.g abbreviation mor2 := @comma_morphism.h abbreviation coh := @comma_morphism.p abbreviation coh' := @comma_morphism.p' protected definition comma_morphism.mk [constructor] [reducible] {x y : comma_object S T} (g h p) : comma_morphism x y := comma_morphism.mk' g h p p⁻¹ variables (x y z w : comma_object S T) definition comma_morphism_sigma_char : (Σ(g : ob1 x ⟶ ob1 y) (h : ob2 x ⟶ ob2 y), T h ∘ mor x = mor y ∘ S g) ≃ comma_morphism x y := begin fapply equiv.MK, { intro u, exact (comma_morphism.mk u.1 u.2.1 u.2.2)}, { intro f, cases f with g h p p', exact ⟨g, h, p⟩}, { intro f, cases f with g h p p', esimp, apply ap (comma_morphism.mk' g h p), apply is_hprop.elim}, { intro u, cases u with u1 u2, cases u2 with u2 u3, reflexivity}, end theorem is_trunc_comma_morphism (n : trunc_index) [H1 : is_trunc n (ob1 x ⟶ ob1 y)] [H2 : is_trunc n (ob2 x ⟶ ob2 y)] [Hp : Πm1 m2, is_trunc n (T m2 ∘ mor x = mor y ∘ S m1)] : is_trunc n (comma_morphism x y) := by apply is_trunc_equiv_closed; apply comma_morphism_sigma_char variables {x y z w} definition comma_morphism_eq {f f' : comma_morphism x y} (p : mor1 f = mor1 f') (q : mor2 f = mor2 f') : f = f' := begin cases f with g h p₁ p₁', cases f' with g' h' p₂ p₂', cases p, cases q, apply ap011 (comma_morphism.mk' g' h'), apply is_hprop.elim, apply is_hprop.elim end definition comma_compose (g : comma_morphism y z) (f : comma_morphism x y) : comma_morphism x z := comma_morphism.mk (mor1 g ∘ mor1 f) (mor2 g ∘ mor2 f) (by rewrite [+respect_comp,-assoc,coh,assoc,coh,-assoc]) local infix `∘∘`:60 := comma_compose definition comma_id : comma_morphism x x := comma_morphism.mk id id (by rewrite [+respect_id,id_left,id_right]) theorem comma_assoc (h : comma_morphism z w) (g : comma_morphism y z) (f : comma_morphism x y) : h ∘∘ (g ∘∘ f) = (h ∘∘ g) ∘∘ f := comma_morphism_eq !assoc !assoc theorem comma_id_left (f : comma_morphism x y) : comma_id ∘∘ f = f := comma_morphism_eq !id_left !id_left theorem comma_id_right (f : comma_morphism x y) : f ∘∘ comma_id = f := comma_morphism_eq !id_right !id_right variables (S T) definition comma_category [constructor] : Precategory := precategory.MK (comma_object S T) comma_morphism (λa b, !is_trunc_comma_morphism) (@comma_compose _ _ _ _ _) (@comma_id _ _ _ _ _) (@comma_assoc _ _ _ _ _) (@comma_id_left _ _ _ _ _) (@comma_id_right _ _ _ _ _) --TODO: this definition doesn't use category structure of A and B definition strict_precategory_comma [HA : strict_precategory A] [HB : strict_precategory B] : strict_precategory (comma_object S T) := strict_precategory.mk (comma_category S T) !is_trunc_comma_object /- --set_option pp.notation false definition is_univalent_comma (HA : is_univalent A) (HB : is_univalent B) : is_univalent (comma_category S T) := begin intros c d, fapply adjointify, { intro i, cases i with f s, cases s with g l r, cases f with fA fB fp, cases g with gA gB gp, esimp at *, fapply comma_object_eq, {apply iso_of_eq⁻¹ᶠ, exact (iso.MK fA gA (ap mor1 l) (ap mor1 r))}, {apply iso_of_eq⁻¹ᶠ, exact (iso.MK fB gB (ap mor2 l) (ap mor2 r))}, { apply sorry /-rewrite hom_of_eq_eq_of_iso,-/ }}, { apply sorry}, { apply sorry}, end -/ end category
2c76b20bdb223c8267b38e9eb04dfee5217269c2
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/group4.lean
12cb774747fdb0b51f1e53c86e163e5aeca6f928
[ "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
4,049
lean
-- Copyright (c) 2014 Jeremy Avigad. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Jeremy Avigad, Leonardo de Moura -- algebra.group -- ============= -- Various structures with 1, *, inv, including groups. import logic.eq import data.unit data.sigma data.prod import algebra.binary open eq namespace algebra structure has_mul [class] (A : Type) := mk :: (mul : A → A → A) structure has_one [class] (A : Type) := mk :: (one : A) structure has_inv [class] (A : Type) := mk :: (inv : A → A) infixl `*` := has_mul.mul postfix `⁻¹` := has_inv.inv notation 1 := !has_one.one structure semigroup [class] (A : Type) extends has_mul A := mk :: (assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c)) set_option pp.notation false -- set_option pp.implicit true -- set_option pp.coercions true print instances has_mul section variables {A : Type} [s : semigroup A] include s variables a b : A example : a * b = semigroup.mul a b := rfl theorem mul_assoc (a b c : A) : a * b * c = a * (b * c) := semigroup.assoc a b c end structure comm_semigroup [class] (A : Type) extends semigroup A := mk :: (comm : ∀a b, mul a b = mul b a) namespace comm_semigroup variables {A : Type} [s : comm_semigroup A] include s variables a b c : A theorem mul_comm : a * b = b * a := !comm_semigroup.comm theorem mul_left_comm : a * (b * c) = b * (a * c) := binary.left_comm mul_comm mul_assoc a b c end comm_semigroup structure monoid [class] (A : Type) extends semigroup A, has_one A := mk :: (right_id : ∀a, mul a one = a) (left_id : ∀a, mul one a = a) section variables {A : Type} [s : monoid A] variable a : A include s theorem mul_right_id : a * 1 = a := !monoid.right_id theorem mul_left_id : 1 * a = a := !monoid.left_id end structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A print prefix algebra.comm_monoid structure Semigroup := mk :: (carrier : Type) (struct : semigroup carrier) attribute Semigroup.carrier [coercion] attribute Semigroup.struct [instance] structure CommSemigroup := mk :: (carrier : Type) (struct : comm_semigroup carrier) attribute CommSemigroup.carrier [coercion] attribute CommSemigroup.struct [instance] structure Monoid := mk :: (carrier : Type) (struct : monoid carrier) attribute Monoid.carrier [coercion] attribute Monoid.struct [instance] structure CommMonoid := mk :: (carrier : Type) (struct : comm_monoid carrier) attribute CommMonoid.carrier [coercion] attribute CommMonoid.struct [instance] end algebra open algebra section examples theorem test1 {S : Semigroup} (a b c d : S) : a * (b * c) * d = a * b * (c * d) := calc a * (b * c) * d = a * b * c * d : mul_assoc ... = a * b * (c * d) : mul_assoc theorem test2 {M : CommSemigroup} (a b : M) : a * b = a * b := rfl theorem test3 {M : Monoid} (a b c d : M) : a * (b * c) * d = a * b * (c * d) := calc a * (b * c) * d = a * b * c * d : mul_assoc ... = a * b * (c * d) : mul_assoc -- for test4b to work, we need instances at the level of the bundled structures as well definition Monoid_Semigroup [coercion] [reducible] (M : Monoid) : Semigroup := Semigroup.mk (Monoid.carrier M) _ theorem test4 {M : Monoid} (a b c d : M) : a * (b * c) * d = a * b * (c * d) := test1 a b c d theorem test5 {M : Monoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : {!mul_right_id} ... = a * (b * c) : mul_assoc theorem test5a {M : Monoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : {!mul_right_id} ... = a * (b * c) : mul_assoc theorem test5b {A : Type} {M : monoid A} (a b c : A) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : mul_right_id ... = a * (b * c) : mul_assoc theorem test6 {M : CommMonoid} (a b c : M) : a * 1 * b * c = a * (b * c) := calc a * 1 * b * c = a * b * c : mul_right_id ... = a * (b * c) : mul_assoc end examples
98a0ba6255a7c859f3e064b26881438a0f4dd13e
618003631150032a5676f229d13a079ac875ff77
/src/measure_theory/indicator_function.lean
2ac21470a2de7e2f4bcb29e0e0e7f4d8ab9f3352
[ "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
5,605
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import data.indicator_function import measure_theory.measure_space /-! # Indicator function Properties of indicator functions. ## Tags indicator, characteristic -/ noncomputable theory open_locale classical open set measure_theory filter universes u v variables {α : Type u} {β : Type v} section has_zero variables [has_zero β] {s t : set α} {f g : α → β} {a : α} lemma indicator_congr_ae [measure_space α] (h : ∀ₘ a, a ∈ s → f a = g a) : ∀ₘ a, indicator s f a = indicator s g a := begin filter_upwards [h], simp only [mem_set_of_eq, indicator], assume a ha, split_ifs with h₁, { exact ha h₁ }, refl end lemma indicator_congr_of_set [measure_space α] (h : ∀ₘ a, a ∈ s ↔ a ∈ t) : ∀ₘ a, indicator s f a = indicator t f a := begin filter_upwards [h], simp only [mem_set_of_eq, indicator], assume a ha, split_ifs with h₁ h₂ h₂, { refl }, { have := ha.1 h₁, contradiction }, { have := ha.2 h₂, contradiction }, refl end end has_zero section has_add variables [add_monoid β] {s t : set α} {f g : α → β} {a : α} lemma indicator_union_ae [measure_space α] {β : Type*} [add_monoid β] (h : ∀ₘ a, a ∉ s ∩ t) (f : α → β) : ∀ₘ a, indicator (s ∪ t) f a = indicator s f a + indicator t f a := begin filter_upwards [h], simp only [mem_set_of_eq], assume a ha, exact indicator_union_of_not_mem_inter ha _ end end has_add section norm variables [normed_group β] {s t : set α} {f g : α → β} {a : α} lemma norm_indicator_le_of_subset (h : s ⊆ t) (f : α → β) (a : α) : ∥indicator s f a∥ ≤ ∥indicator t f a∥ := begin simp only [indicator], split_ifs with h₁ h₂, { refl }, { exact absurd (h h₁) h₂ }, { simp only [norm_zero, norm_nonneg] }, refl end lemma norm_indicator_le_norm_self (f : α → β) (a : α) : ∥indicator s f a∥ ≤ ∥f a∥ := by { convert norm_indicator_le_of_subset (subset_univ s) f a, rw indicator_univ } lemma norm_indicator_eq_indicator_norm (f : α → β) (a : α) : ∥indicator s f a∥ = indicator s (λa, ∥f a∥) a := by { simp only [indicator], split_ifs, { refl }, rw norm_zero } lemma indicator_norm_le_norm_self (f : α → β) (a : α) : indicator s (λa, ∥f a∥) a ≤ ∥f a∥ := by { rw ← norm_indicator_eq_indicator_norm, exact norm_indicator_le_norm_self _ _ } end norm section order variables [has_zero β] [preorder β] {s t : set α} {f g : α → β} {a : α} lemma indicator_le_indicator_ae [measure_space α] (h : ∀ₘ a, a ∈ s → f a ≤ g a) : ∀ₘ a, indicator s f a ≤ indicator s g a := begin refine h.mono (λ a h, _), simp only [indicator], split_ifs with ha, { exact h ha }, refl end end order section tendsto variables {ι : Type*} [semilattice_sup ι] [has_zero β] lemma tendsto_indicator_of_monotone [nonempty ι] (s : ι → set α) (hs : monotone s) (f : α → β) (a : α) : tendsto (λi, indicator (s i) f a) at_top (pure $ indicator (Union s) f a) := begin by_cases h : ∃i, a ∈ s i, { simp only [tendsto_pure, mem_at_top_sets, mem_set_of_eq], rcases h with ⟨i, hi⟩, use i, assume n hn, rw [indicator_of_mem (hs hn hi) _, indicator_of_mem ((subset_Union _ _) hi) _] }, { rw [not_exists] at h, have : (λi, indicator (s i) f a) = λi, 0 := funext (λi, indicator_of_not_mem (h i) _), rw this, have : indicator (Union s) f a = 0, { apply indicator_of_not_mem, simpa only [not_exists, mem_Union] }, rw this, exact tendsto_const_pure } end lemma tendsto_indicator_of_antimono [nonempty ι] (s : ι → set α) (hs : ∀i j, i ≤ j → s j ⊆ s i) (f : α → β) (a : α) : tendsto (λi, indicator (s i) f a) at_top (pure $ indicator (Inter s) f a) := begin by_cases h : ∃i, a ∉ s i, { simp only [tendsto_pure, mem_at_top_sets, mem_set_of_eq], rcases h with ⟨i, hi⟩, use i, assume n hn, rw [indicator_of_not_mem _ _, indicator_of_not_mem _ _], { simp only [mem_Inter, not_forall], exact ⟨i, hi⟩ }, { assume h, have := hs i _ hn h, contradiction } }, { simp only [not_exists, not_not_mem] at h, have : (λi, indicator (s i) f a) = λi, f a := funext (λi, indicator_of_mem (h i) _), rw this, have : indicator (Inter s) f a = f a, { apply indicator_of_mem, simpa only [mem_Inter] }, rw this, exact tendsto_const_pure } end lemma tendsto_indicator_bUnion_finset (s : ι → set α) (f : α → β) (a : α) : tendsto (λ (n : finset ι), indicator (⋃i∈n, s i) f a) at_top (pure $ indicator (Union s) f a) := begin by_cases h : ∃i, a ∈ s i, { simp only [mem_at_top_sets, tendsto_pure, mem_set_of_eq, ge_iff_le, finset.le_iff_subset], rcases h with ⟨i, hi⟩, use {i}, assume n hn, replace hn : i ∈ n := hn (finset.mem_singleton_self _), rw [indicator_of_mem, indicator_of_mem], { rw [mem_Union], use i, assumption }, { rw [mem_Union], use i, rw [mem_Union], use hn, assumption } }, { rw [not_exists] at h, have : (λ (n : finset ι), indicator (⋃ (i : ι) (H : i ∈ n), s i) f a) = λi, 0, { funext, rw indicator_of_not_mem, simp only [not_exists, exists_prop, mem_Union, not_and], intros, apply h }, rw this, have : indicator (Union s) f a = 0, { apply indicator_of_not_mem, simpa only [not_exists, mem_Union] }, rw this, exact tendsto_const_pure } end end tendsto
0c6c9dc8aa95cfa784496c6d5012500754f3f238
56e5b79a7ab4f2c52e6eb94f76d8100a25273cf3
/src/tools/proof_replay.lean
e383f1513e92c6a83e93cd56fafe93d4658c212f
[ "Apache-2.0" ]
permissive
DyeKuu/lean-tpe-public
3a9968f286ca182723ef7e7d97e155d8cb6b1e70
750ade767ab28037e80b7a80360d213a875038f8
refs/heads/master
1,682,842,633,115
1,621,330,793,000
1,621,330,793,000
368,475,816
0
0
Apache-2.0
1,621,330,745,000
1,621,330,744,000
null
UTF-8
Lean
false
false
5,850
lean
import utils import evaluation import all import basic.table import system.io section parse_nm meta def parse_nm : string → tactic name := λ nm_str, do { flip lean.parser.run_with_input nm_str $ iterate_until lean.parser.ident (λ nm, pure ∘ bnot $ nm = name.anonymous) 100 } end parse_nm meta def unpack_tactic_strings : json → tactic (list string) := λ msg, match msg with | (json.array $ msgs) := do { msgs.mmap $ λ msg, match msg with | (json.of_string x) := pure x | exc := tactic.fail format! "UNEXPECTED {exc}" end } | exc := tactic.fail format! "UNEXPECTED {exc}" end meta def get_decl_name_and_tactics (msg : json) : tactic $ name × list string := do { decl_name_msg ← msg.lookup "task_id", decl_name_str ← match decl_name_msg with | (json.of_string x) := pure x | exc := tactic.fail format! "UNEXPECTED {exc}" end, decl_name ← parse_nm decl_name_str, tacs_msg ← msg.lookup "tactics", tac_strings ← unpack_tactic_strings tacs_msg, pure ⟨decl_name, tac_strings⟩ } -- #eval do { -- msg ← option.to_monad $ json.parse " { \"task_id\":\"and.comm\", \"tactics\":[\"intros\", \"refine ⟨_,_⟩; intro h; cases h; exact and.intro ‹_› ‹_›\"]}", -- x@⟨nm, tacs⟩ ← io.run_tactic' (get_decl_name_and_tactics msg), -- io.put_str_ln' format! "{x}" -- } example : ∀ {a b : Prop}, a ∧ b ↔ b ∧ a := begin intros, refine ⟨_,_⟩; intro h; cases h; exact and.intro ‹_› ‹_› end meta def example_msg : tactic json := json.parse " { \"task_id\":\"finset.filter_not\", \"tactics\":[ \"intros a\", \"intros\", \"ext b\", \"by_cases p b; simp *\" ] }" meta def buggy_example_msg : tactic json := json.parse $ " { \"task_id\":\"mvqpf.cofix.bisim\", \"tactics\":[ \"intros x y h\", \"rintros x₀ y₀ q₀ hr\", \"intros x y h\", \"induction x using fin2.elim0\" ] }" meta def replay_proof (namespaces : list name := []) : (name × list string) → tactic expr := λ ⟨decl_name, tacs⟩, do { env₀ ← tactic.get_env, tsd ← get_tsd_at_decl decl_name, env ← get_env_at_decl decl_name, tactic.set_env_core env, rebuild_tactic_state tsd, [g] ← tactic.get_goals, goal ← tactic.infer_type g, tactic.trace format! "[replay_proof] TACTICS: {tacs}", for_ tacs $ λ tac_str, do { tac ← parse_itactic tac_str, tac }, pf ← tactic.get_assignment g >>= tactic.instantiate_mvars, tactic.set_env_core env₀, tactic.done <|> tactic.fail format! "[replay_proof] ERROR: NOT DONE WITH {decl_name}", validate_proof pf, pure pf } -- this should pass all checks -- run_cmd do { -- msg ← example_msg, -- get_decl_name_and_tactics msg >>= replay_proof -- } -- this should pass `done` check but fail validation -- run_cmd do { -- msg ← buggy_example_msg, -- get_decl_name_and_tactics msg >>= replay_proof -- } meta def pf_term_size (pf : expr) : tactic ℕ := do { str ← (format.to_string ∘ format.flatten) <$> tactic.pp pf, pure str.length } meta def build_namespace_index (decls_file : string) : io $ dict name (list name) := do { nm_strs ← (io.mk_file_handle decls_file io.mode.read >>= λ f, (string.split (λ c, c = '\n') <$> buffer.to_string <$> io.fs.read_to_end f)), -- io.put_str_ln' format!"NM STRS: {nm_strs}", (nms : list (name × list name)) ← (nm_strs.filter $ λ nm_str, string.length nm_str > 0).mmap $ λ nm_str, do { ((io.run_tactic' ∘ parse_decl_nm_and_open_ns) $ nm_str) }, io.put_str_ln' format!"[evaluation_harness_from_decls_file] GOT {nms.length} NAMES", -- io.put_str_ln' format!"NMS: {nms}", -- additionally filter out non-theorems -- TODO(): do this offline in a separate Lean script let nms_unfiltered_len := nms.length, nms ← io.run_tactic' $ do { env ← tactic.get_env, nms.mfilter $ λ ⟨nm, _⟩, (do { decl ← env.get nm, pure decl.is_theorem } <|> pure ff) }, pure $ dict.of_list nms } meta def mk_shorter_proof_jsonline (old_size : ℕ) (new_size : ℕ) (decl_nm : name) (tacs : list string) : json := do { json.array $ [old_size, new_size, decl_nm.to_string, json.array $ json.of_string <$> tacs] } meta def main : io unit := do { args ← io.cmdline_args, jsons_file ← args.nth_except 0 "jsons_file", dest ← args.nth_except 1 "dest", ns_index_path ← args.nth_except 2 "ns_index", msg_strs ← io.mk_file_handle jsons_file io.mode.read >>= λ f, (string.split (λ c, c = '\n') <$> buffer.to_string <$> io.fs.read_to_end f), let msg_strs := msg_strs.filter (λ x, x.length > 0), msgs ← msg_strs.mmap (λ msg_str, lift_option $ json.parse msg_str), dest_handle ← io.mk_file_handle dest io.mode.write, ns_index ← build_namespace_index ns_index_path, for_ msgs $ λ msg, io.run_tactic' $ do { x@⟨decl_nm, tacs⟩ ← get_decl_name_and_tactics msg, if tacs.length = 0 then tactic.trace format! "SKIPPING {decl_nm}" else do tactic.trace format! "REPLAYING {decl_nm}", old_pf_term ← tactic.get_proof_from_env decl_nm, tactic.trace format! "PROCESSING DECL_NM {decl_nm}", env₀ ← tactic.get_env, tactic.try $ do { open_ns ← ns_index.get decl_nm, new_pf_term ← replay_proof open_ns x, tactic.set_env_core env₀, old_size ← pf_term_size old_pf_term, tactic.trace format! "OLD SIZE: {old_size}", new_size ← pf_term_size new_pf_term, tactic.trace format! "NEW SIZE: {new_size}", when (new_size < old_size) $ tactic.unsafe_run_io $ do { io.put_str_ln "FOUND SMALLER PROOF", io.fs.put_str_ln_flush dest_handle $ json.unparse $ mk_shorter_proof_jsonline old_size new_size decl_nm tacs }}, tactic.set_env_core env₀ } }
8fe8ccc271297f33036b359915b10959fab6f973
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/multiset/powerset.lean
8ba3dc84c3a5ff63608b738fb27172d4354fa760
[ "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
9,218
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 data.multiset.basic /-! # The powerset of a multiset -/ namespace multiset open list variables {α : Type*} /-! ### powerset -/ /-- A helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists_aux`), as multisets. -/ 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 @[simp] theorem mem_powerset_aux {l : list α} {s} : s ∈ powerset_aux l ↔ s ≤ ↑l := quotient.induction_on s $ by simp [powerset_aux_eq_map_coe, subperm, and.comm] /-- Helper function for the powerset of a multiset. Given a list `l`, returns a list of sublists of `l` (using `sublists'`), as multisets. -/ 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 (sublists_perm_sublists' _).map _ @[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 IH.append (IH.map _) }, { simp, apply perm.append_left, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { 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 /-- The power set of a multiset. -/ 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 powerset_zero : @powerset α 0 = 0::0 := rfl @[simp] theorem powerset_cons (a : α) (s) : powerset (a::s) = powerset s + map (cons a) (powerset s) := quotient.induction_on s $ λ l, by simp; refl @[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 ((map_ret_sublist_sublists _).map _).subperm end @[simp] theorem card_powerset (s : multiset α) : card (powerset s) = 2 ^ card s := quotient.induction_on s $ by simp theorem revzip_powerset_aux {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists _ _ _ h) end theorem revzip_powerset_aux' {l : list α} ⦃x⦄ (h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l := begin rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h, simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩, exact quot.sound (revzip_sublists' _ _ _ h) end theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α) {l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) : revzip l' = l'.map (λ x, (x, ↑l - x)) := begin have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s)) (revzip l') ((revzip l').map prod.fst), { rw forall₂_map_right_iff, apply forall₂_same, rintro ⟨s, t⟩ h, dsimp, rw [← H h, add_sub_cancel_left] }, rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa end theorem revzip_powerset_aux_perm_aux' {l : list α} : revzip (powerset_aux l) ~ revzip (powerset_aux' l) := begin haveI := classical.dec_eq α, rw [revzip_powerset_aux_lemma l revzip_powerset_aux, revzip_powerset_aux_lemma l revzip_powerset_aux'], exact powerset_aux_perm_powerset_aux'.map _ end theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) := begin haveI := classical.dec_eq α, simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p], exact (powerset_aux_perm p).map _ end /-! ### powerset_len -/ /-- Helper function for `powerset_len`. Given a list `l`, `powerset_len_aux n l` is the list of sublists of length `n`, as multisets. -/ def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) := sublists_len_aux n l coe [] theorem powerset_len_aux_eq_map_coe {n} {l : list α} : powerset_len_aux n l = (sublists_len n l).map coe := by rw [powerset_len_aux, sublists_len_aux_eq, append_nil] @[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} : s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n := quotient.induction_on s $ by simp [powerset_len_aux_eq_map_coe, subperm]; exact λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, p.symm.length_eq.trans e⟩, λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, p.length_eq.trans e⟩, p⟩⟩ @[simp] theorem powerset_len_aux_zero (l : list α) : powerset_len_aux 0 l = [0] := by simp [powerset_len_aux_eq_map_coe] @[simp] theorem powerset_len_aux_nil (n : ℕ) : powerset_len_aux (n+1) (@nil α) = [] := rfl @[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) : powerset_len_aux (n+1) (a::l) = powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) := by simp [powerset_len_aux_eq_map_coe]; refl theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) : powerset_len_aux n l₁ ~ powerset_len_aux n l₂ := begin induction n with n IHn generalizing l₁ l₂, {simp}, induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl}, { simp, exact IH.append ((IHn p).map _) }, { simp, apply perm.append_left, cases n, {simp, apply perm.swap}, simp, rw [← append_assoc, ← append_assoc, (by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)], exact perm_append_comm.append_right _ }, { exact IH₁.trans IH₂ } end /-- `powerset_len n s` is the multiset of all submultisets of `s` of length `n`. -/ def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) := quot.lift_on s (λ l, (powerset_len_aux n l : multiset (multiset α))) (λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h)) theorem powerset_len_coe' (n) (l : list α) : @powerset_len α n l = powerset_len_aux n l := rfl theorem powerset_len_coe (n) (l : list α) : @powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) := congr_arg coe powerset_len_aux_eq_map_coe @[simp] theorem powerset_len_zero_left (s : multiset α) : powerset_len 0 s = 0::0 := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem powerset_len_zero_right (n : ℕ) : @powerset_len α (n + 1) 0 = 0 := rfl @[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) : powerset_len (n + 1) (a::s) = powerset_len (n + 1) s + map (cons a) (powerset_len n s) := quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl @[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} : s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n := quotient.induction_on t $ λ l, by simp [powerset_len_coe'] @[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) : card (powerset_len n s) = nat.choose (card s) n := quotient.induction_on s $ by simp [powerset_len_coe] theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) : powerset_len n s ≤ powerset s := quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact ((sublists_len_sublist_sublists' _ _).map _).subperm theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) : powerset_len n s ≤ powerset_len n t := le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact ((sublists_len_sublist_of_sublist _ h).map _).subperm end multiset
510077bfd37a8604013b1b374ceaf9bcd6aa40ee
82e44445c70db0f03e30d7be725775f122d72f3e
/src/topology/subset_properties.lean
ef82990574710b194bb2c777c7dd189893987b11
[ "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
66,639
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, Yury Kudryashov -/ import topology.bases import data.finset.order import data.set.accumulate /-! # Properties of subsets of topological spaces In this file we define various properties of subsets of a topological space, and some classes on topological spaces. ## Main definitions We define the following properties for sets in a topological space: * `is_compact`: each open cover has a finite subcover. This is defined in mathlib using filters. The main property of a compact set is `is_compact.elim_finite_subcover`. * `is_clopen`: a set that is both open and closed. * `is_irreducible`: a nonempty set that has contains no non-trivial pair of disjoint opens. See also the section below in the module doc. For each of these definitions (except for `is_clopen`), we also have a class stating that the whole space satisfies that property: `compact_space`, `irreducible_space` Furthermore, we have two more classes: * `locally_compact_space`: for every point `x`, every open neighborhood of `x` contains a compact neighborhood of `x`. The definition is formulated in terms of the neighborhood filter. * `sigma_compact_space`: a space that is the union of a countably many compact subspaces. ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preirreducible`. In other words, the only difference is whether the empty space counts as irreducible. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set filter classical topological_space open_locale classical topological_space filter universes u v variables {α : Type u} {β : Type v} [topological_space α] {s t : set α} /- compact sets -/ section compact /-- A set `s` is compact if for every nontrivial filter `f` that contains `s`, there exists `a ∈ s` such that every set of `f` meets every neighborhood of `a`. -/ def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃a∈s, cluster_pt a f /-- The complement to a compact set belongs to a filter `f` if it belongs to each filter `𝓝 a ⊓ f`, `a ∈ s`. -/ lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) : sᶜ ∈ f := begin contrapose! hf, simp only [not_mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢, exact @hs _ hf inf_le_right end /-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t` within `s` such that `tᶜ` belongs to `f`. -/ lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) : sᶜ ∈ f := begin refine hs.compl_mem_sets (λ a ha, _), rcases hf a ha with ⟨t, ht, hst⟩, replace ht := mem_inf_principal.1 ht, refine mem_inf_sets.2 ⟨_, ht, _, hst, _⟩, rintros x ⟨h₁, h₂⟩ hs, exact h₂ (h₁ hs) end /-- If `p : set α → Prop` is stable under restriction and union, and each point `x` of a compact set `s` has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/ @[elab_as_eliminator] lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅) (hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t)) (hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) : p s := let f : filter α := { sets := {t | p tᶜ}, univ_sets := by simpa, sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁, inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds), by simpa /-- The intersection of a compact set and a closed set is a compact set. -/ lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) : is_compact (s ∩ t) := begin introsI f hnf hstf, obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f := hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))), have : a ∈ t := (ht.mem_of_nhds_within_ne_bot $ ha.mono $ le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))), exact ⟨a, ⟨hsa, this⟩, ha⟩ end /-- The intersection of a closed set and a compact set is a compact set. -/ lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) := inter_comm t s ▸ ht.inter_right hs /-- The set difference of a compact set and an open set is a compact set. -/ lemma is_compact.diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) := hs.inter_right (is_closed_compl_iff.mpr ht) /-- A closed subset of a compact set is a compact set. -/ lemma compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) : is_compact t := inter_eq_self_of_subset_right h ▸ hs.inter_right ht lemma is_compact.adherence_nhdset {f : filter α} (hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀a∈s, cluster_pt a f → a ∈ t) : t ∈ f := classical.by_cases mem_sets_of_eq_bot $ assume : f ⊓ 𝓟 tᶜ ≠ ⊥, let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs ⟨this⟩ $ inf_le_of_left_le hf₂ in have a ∈ t, from ht₂ a ha (hfa.of_inf_left), have tᶜ ∩ t ∈ 𝓝[tᶜ] a, from inter_mem_nhds_within _ (is_open.mem_nhds ht₁ this), have A : 𝓝[tᶜ] a = ⊥, from empty_in_sets_eq_bot.1 $ compl_inter_self t ▸ this, have 𝓝[tᶜ] a ≠ ⊥, from hfa.of_inf_right.ne, absurd A this lemma is_compact_iff_ultrafilter_le_nhds : is_compact s ↔ (∀f : ultrafilter α, ↑f ≤ 𝓟 s → ∃a∈s, ↑f ≤ 𝓝 a) := begin refine (forall_ne_bot_le_iff _).trans _, { rintro f g hle ⟨a, has, haf⟩, exact ⟨a, has, haf.mono hle⟩ }, { simp only [ultrafilter.cluster_pt_iff] } end alias is_compact_iff_ultrafilter_le_nhds ↔ is_compact.ultrafilter_le_nhds _ /-- For every open directed cover of a compact set, there exists a single element of the cover which itself includes the set. -/ lemma is_compact.elim_directed_cover {ι : Type v} [hι : nonempty ι] (hs : is_compact s) (U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) (hdU : directed (⊆) U) : ∃ i, s ⊆ U i := hι.elim $ λ i₀, is_compact.induction_on hs ⟨i₀, empty_subset _⟩ (λ s₁ s₂ hs ⟨i, hi⟩, ⟨i, subset.trans hs hi⟩) (λ s₁ s₂ ⟨i, hi⟩ ⟨j, hj⟩, let ⟨k, hki, hkj⟩ := hdU i j in ⟨k, union_subset (subset.trans hi hki) (subset.trans hj hkj)⟩) (λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in ⟨U i, mem_nhds_within_of_mem_nhds (is_open.mem_nhds (hUo i) hi), i, subset.refl _⟩) /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s) (U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) : ∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i := hs.elim_directed_cover _ (λ t, is_open_bUnion $ λ i _, hUo i) (Union_eq_Union_finset U ▸ hsU) (directed_of_sup $ λ t₁ t₂ h, bUnion_subset_bUnion_left h) lemma is_compact.elim_nhds_subcover' (hs : is_compact s) (U : Π x ∈ s, set α) (hU : ∀ x ∈ s, U x ‹x ∈ s› ∈ 𝓝 x) : ∃ t : finset s, s ⊆ ⋃ x ∈ t, U (x : s) x.2 := (hs.elim_finite_subcover (λ x : s, interior (U x x.2)) (λ x, is_open_interior) (λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 $ hU _ _⟩)).imp $ λ t ht, subset.trans ht $ bUnion_subset_bUnion_right $ λ _ _, interior_subset lemma is_compact.elim_nhds_subcover (hs : is_compact s) (U : α → set α) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) : ∃ t : finset α, (∀ x ∈ t, x ∈ s) ∧ s ⊆ ⋃ x ∈ t, U x := let ⟨t, ht⟩ := hs.elim_nhds_subcover' (λ x _, U x) hU in ⟨t.image coe, λ x hx, let ⟨y, hyt, hyx⟩ := finset.mem_image.1 hx in hyx ▸ y.2, by rwa finset.set_bUnion_finset_image⟩ /-- For every family of closed sets whose intersection avoids a compact set, there exists a finite subfamily whose intersection avoids this compact set. -/ lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) : ∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ := let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) (λ i, (hZc i).is_open_compl) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩ /-- If `s` is a compact set in a topological space `α` and `f : ι → set α` is a locally finite family of sets, then `f i ∩ s` is nonempty only for a finitely many `i`. -/ lemma locally_finite.finite_nonempty_inter_compact {ι : Type*} {f : ι → set α} (hf : locally_finite f) {s : set α} (hs : is_compact s) : finite {i | (f i ∩ s).nonempty} := begin choose U hxU hUf using hf, rcases hs.elim_nhds_subcover U (λ x _, hxU x) with ⟨t, -, hsU⟩, refine (t.finite_to_set.bUnion (λ x _, hUf x)).subset _, rintro i ⟨x, hx⟩, rcases mem_bUnion_iff.1 (hsU hx.2) with ⟨c, hct, hcx⟩, exact mem_bUnion hct ⟨x, hx.1, hcx⟩ end /-- To show that a compact set intersects the intersection of a family of closed sets, it is sufficient to show that it intersects every finite subfamily. -/ lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) : (s ∩ ⋂ i, Z i).nonempty := begin simp only [← ne_empty_iff_nonempty] at hsZ ⊢, apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ end /-- Cantor's intersection theorem: the intersection of a directed family of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed {ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z) (hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := begin apply hι.elim, intro i₀, let Z' := λ i, Z i ∩ Z i₀, suffices : (⋂ i, Z' i).nonempty, { exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this }, rw ← ne_empty_iff_nonempty, intro H, obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅, from (hZc i₀).elim_finite_subfamily_closed Z' (assume i, is_closed.inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]), obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i, { rcases directed.finset_le hZd t with ⟨i, hi⟩, rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩, use [i₁, hi₁₀], intros j hj, exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ }, suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty, { rw ← ne_empty_iff_nonempty at this, contradiction }, refine nonempty.mono _ (hZn i₁), exact subset_inter hi₁.left (subset_bInter hi₁.right) end /-- Cantor's intersection theorem for sequences indexed by `ℕ`: the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed (Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i) (hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := have Zmono : _, from @monotone_of_monotone_nat (order_dual _) _ Z hZd, have hZd : directed (⊇) Z, from directed_of_sup Zmono, have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i, have hZc : ∀ i, is_compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i), is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover_image {b : set β} {c : β → set α} (hs : is_compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) : ∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i := begin rcases hs.elim_finite_subcover (λ i, c i : b → set α) _ _ with ⟨d, hd⟩; [skip, simpa using hc₁, simpa using hc₂], refine ⟨↑(d.image coe), _, finset.finite_to_set _, _⟩, { simp }, { rwa [finset.coe_image, bUnion_image] } end /-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem is_compact_of_finite_subfamily_closed (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) : is_compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, cluster_pt x f), have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥, by simpa only [cluster_pt, not_exists, not_not, ne_bot_iff], have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in have ∅ ∈ 𝓝[t₂] x, from (𝓝[t₂] x).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht, have 𝓝[t₂] x = ⊥, by rwa [empty_in_sets_eq_bot] at this, by simp only [closure_eq_cluster_pts] at hx; exact (hx t₂ ht₂).ne this, let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure) (by simpa [eq_empty_iff_forall_not_mem, not_exists]) in have (⋂i∈t, subtype.val i) ∈ f, from t.Inter_mem_sets.2 $ assume i hi, i.2, have s ∩ (⋂i∈t, subtype.val i) ∈ f, from inter_mem_sets (le_principal_iff.1 hfs) this, have ∅ ∈ f, from mem_sets_of_superset this $ assume x ⟨hxs, hx⟩, let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i), by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit), show false, from hxi this, hfn.ne $ by rwa [empty_in_sets_eq_bot] at this /-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/ lemma is_compact_of_finite_subcover (h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) : is_compact s := is_compact_of_finite_subfamily_closed $ assume ι Z hZc hsZ, let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union, exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩ /-- A set `s` is compact if and only if for every open cover of `s`, there exists a finite subcover. -/ lemma is_compact_iff_finite_subcover : is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) := ⟨assume hs ι, hs.elim_finite_subcover, is_compact_of_finite_subcover⟩ /-- A set `s` is compact if and only if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem is_compact_iff_finite_subfamily_closed : is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) := ⟨assume hs ι, hs.elim_finite_subfamily_closed, is_compact_of_finite_subfamily_closed⟩ @[simp] lemma is_compact_empty : is_compact (∅ : set α) := assume f hnf hsf, not.elim hnf.ne $ empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf @[simp] lemma is_compact_singleton {a : α} : is_compact ({a} : set α) := λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds' (hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩ lemma set.subsingleton.is_compact {s : set α} (hs : s.subsingleton) : is_compact s := subsingleton.induction_on hs is_compact_empty $ λ x, is_compact_singleton lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s) (hf : ∀i ∈ s, is_compact (f i)) : is_compact (⋃i ∈ s, f i) := is_compact_of_finite_subcover $ assume ι U hUo hsU, have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo (calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃j, U j : hsU), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in by haveI : fintype (subtype s) := hs.fintype; exact let t := finset.bUnion finset.univ finite_subcovers in have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $ assume i hi, calc f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩) ... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $ assume j hj, finset.mem_bUnion.mpr ⟨_, finset.mem_univ _, hj⟩, ⟨t, this⟩ lemma finset.compact_bUnion (s : finset β) {f : β → set α} (hf : ∀i ∈ s, is_compact (f i)) : is_compact (⋃i ∈ s, f i) := s.finite_to_set.compact_bUnion hf lemma compact_accumulate {K : ℕ → set α} (hK : ∀ n, is_compact (K n)) (n : ℕ) : is_compact (accumulate K n) := (finite_le_nat n).compact_bUnion $ λ k _, hK k lemma compact_Union {f : β → set α} [fintype β] (h : ∀i, is_compact (f i)) : is_compact (⋃i, f i) := by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i) lemma set.finite.is_compact (hs : finite s) : is_compact s := bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, is_compact_singleton) lemma finite_of_is_compact_of_discrete [discrete_topology α] (s : set α) (hs : is_compact s) : s.finite := begin have := hs.elim_finite_subcover (λ x : α, ({x} : set α)) (λ x, is_open_discrete _), simp only [set.subset_univ, forall_prop_of_true, set.Union_of_singleton] at this, rcases this with ⟨t, ht⟩, suffices : (⋃ (i : α) (H : i ∈ t), {i} : set α) = (t : set α), { rw this at ht, exact t.finite_to_set.subset ht }, ext x, simp only [exists_prop, set.mem_Union, set.mem_singleton_iff, exists_eq_right', finset.mem_coe] end lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) := by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption) lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) := is_compact_singleton.union hs /-- If `V : ι → set α` is a decreasing family of closed compact sets then any neighborhood of `⋂ i, V i` contains some `V i`. We assume each `V i` is compact *and* closed because `α` is not assumed to be Hausdorff. See `exists_subset_nhd_of_compact` for version assuming this. -/ lemma exists_subset_nhd_of_compact' {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_cpct : ∀ i, is_compact (V i)) (hV_closed : ∀ i, is_closed (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := begin set Y := ⋂ i, V i, obtain ⟨W, hsubW, W_op, hWU⟩ : ∃ W, Y ⊆ W ∧ is_open W ∧ W ⊆ U, from exists_open_set_nhds hU, suffices : ∃ i, V i ⊆ W, { rcases this with ⟨i, hi⟩, refine ⟨i, set.subset.trans hi hWU⟩ }, by_contradiction H, push_neg at H, replace H : ∀ i, (V i ∩ Wᶜ).nonempty := λ i, set.inter_compl_nonempty_iff.mpr (H i), have : (⋂ i, V i ∩ Wᶜ).nonempty, { apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _ _ H, { intro i, exact (hV_cpct i).inter_right W_op.is_closed_compl }, { intro i, apply (hV_closed i).inter W_op.is_closed_compl }, { intros i j, rcases hV i j with ⟨k, hki, hkj⟩, use k, split ; intro x ; simp only [and_imp, mem_inter_eq, mem_compl_eq] ; tauto } }, have : ¬ (⋂ (i : ι), V i) ⊆ W, by simpa [← Inter_inter, inter_compl_nonempty_iff], contradiction end /-- `filter.cocompact` is the filter generated by complements to compact sets. -/ def filter.cocompact (α : Type*) [topological_space α] : filter α := ⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ) lemma filter.has_basis_cocompact : (filter.cocompact α).has_basis is_compact compl := has_basis_binfi_principal' (λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t), compl_subset_compl.2 (subset_union_right s t)⟩) ⟨∅, is_compact_empty⟩ lemma filter.mem_cocompact : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s := filter.has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop lemma filter.mem_cocompact' : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t := filter.mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm lemma is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α := filter.has_basis_cocompact.mem_of_mem hs section tube_lemma variables [topological_space β] /-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes a product of an open neighborhood of `s` by an open neighborhood of `t`. -/ def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (hn.preimage continuous_swap) (by rwa [←image_subset_iff, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀x : subtype s, ∃uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n, from assume ⟨x, hx⟩, have set.prod {x} t ⊆ n, from subset.trans (prod_mono (by simpa) (subset.refl _)) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃i, (uvs i).1, from assume x hx, subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, s0_cover⟩ := hs.elim_finite_subcover _ (λi, (h i).1) us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1), have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1), have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩ /-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/ lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type*) [topological_space α] : Prop := (compact_univ : is_compact (univ : set α)) @[priority 10] -- see Note [lower instance priority] instance subsingleton.compact_space [subsingleton α] : compact_space α := ⟨subsingleton_univ.is_compact⟩ lemma compact_univ [h : compact_space α] : is_compact (univ : set α) := h.compact_univ lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] : ∃ x, cluster_pt x f := by simpa using compact_univ (show f ≤ 𝓟 univ, by simp) lemma compact_space.elim_nhds_subcover {α : Type*} [topological_space α] [compact_space α] (U : α → set α) (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, U x) = ⊤ := begin obtain ⟨t, -, s⟩ := is_compact.elim_nhds_subcover compact_univ U (λ x m, hU x), exact ⟨t, by { rw eq_top_iff, exact s }⟩, end theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α] (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → (⋂ i, Z i) = ∅ → ∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅) : compact_space α := { compact_univ := begin apply is_compact_of_finite_subfamily_closed, intros ι Z, specialize h Z, simpa using h end } lemma is_closed.is_compact [compact_space α] {s : set α} (h : is_closed s) : is_compact s := compact_of_is_closed_subset compact_univ h (subset_univ _) /-- A compact discrete space is finite. -/ noncomputable def fintype_of_compact_of_discrete [compact_space α] [discrete_topology α] : fintype α := fintype_of_univ_finite $ finite_of_is_compact_of_discrete _ compact_univ lemma finite_cover_nhds_interior [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, interior (U x)) = univ := let ⟨t, ht⟩ := compact_univ.elim_finite_subcover (λ x, interior (U x)) (λ x, is_open_interior) (λ x _, mem_Union.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩) in ⟨t, univ_subset_iff.1 ht⟩ lemma finite_cover_nhds [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) : ∃ t : finset α, (⋃ x ∈ t, U x) = univ := let ⟨t, ht⟩ := finite_cover_nhds_interior hU in ⟨t, univ_subset_iff.1 $ ht ▸ bUnion_subset_bUnion_right (λ x hx, interior_subset)⟩ /-- If `α` is a compact space, then a locally finite family of sets of `α` can have only finitely many nonempty elements. -/ lemma locally_finite.finite_nonempty_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) : finite {i | (f i).nonempty} := by simpa only [inter_univ] using hf.finite_nonempty_inter_compact compact_univ /-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only finitely many elements, `set.finite` version. -/ lemma locally_finite.finite_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : finite (univ : set ι) := by simpa only [hne] using hf.finite_nonempty_of_compact /-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only finitely many elements, `fintype` version. -/ noncomputable def locally_finite.fintype_of_compact {ι : Type*} [compact_space α] {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : fintype ι := fintype_of_univ_finite (hf.finite_of_compact hne) variables [topological_space β] lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : is_compact (f '' s) := begin intros l lne ls, have : ne_bot (l.comap f ⊓ 𝓟 s) := comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls), obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right, use [f a, mem_image_of_mem f has], have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l), { convert (hf a has).inf (@tendsto_comap _ _ f l) using 1, rw nhds_within, ac_refl }, exact @@tendsto.ne_bot _ this ha, end lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) : is_compact (f '' s) := hs.image_of_continuous_on hf.continuous_on lemma is_compact_range [compact_space α] {f : α → β} (hf : continuous f) : is_compact (range f) := by rw ← image_univ; exact compact_univ.image hf /-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/ theorem is_closed_proj_of_is_compact {X : Type*} [topological_space X] [compact_space X] {Y : Type*} [topological_space Y] : is_closed_map (prod.snd : X × Y → Y) := begin set πX := (prod.fst : X × Y → X), set πY := (prod.snd : X × Y → Y), assume C (hC : is_closed C), rw is_closed_iff_cluster_pt at hC ⊢, assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)), have : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), { suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)), by simpa only [map_ne_bot_iff], convert y_closure, calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) = 𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _ ... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal }, resetI, obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), from cluster_point_of_compact _, refine ⟨⟨x, y⟩, _, by simp [πY]⟩, apply hC, rw [cluster_pt, ← filter.map_ne_bot_iff πX], convert hx, calc map πX (𝓝 (x, y) ⊓ 𝓟 C) = map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod] ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull ... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm end lemma exists_subset_nhd_of_compact_space [compact_space α] {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V) (hV_closed : ∀ i, is_closed (V i)) {U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U := exists_subset_nhd_of_compact' hV (λ i, (hV_closed i).is_compact) hV_closed hU lemma embedding.is_compact_iff_is_compact_image {f : α → β} (hf : embedding f) : is_compact s ↔ is_compact (f '' s) := iff.intro (assume h, h.image hf.continuous) $ assume h, begin rw is_compact_iff_ultrafilter_le_nhds at ⊢ h, intros u us', have : ↑(u.map f) ≤ 𝓟 (f '' s), begin rw [ultrafilter.coe_map, map_le_iff_le_comap, comap_principal], convert us', exact preimage_image_eq _ hf.inj end, rcases h (u.map f) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩, refine ⟨a, ha, _⟩, rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap] end /-- A closed embedding is proper, ie, inverse images of compact sets are contained in compacts. -/ lemma closed_embedding.tendsto_cocompact {f : α → β} (hf : closed_embedding f) : tendsto f (filter.cocompact α) (filter.cocompact β) := begin rw filter.has_basis_cocompact.tendsto_iff filter.has_basis_cocompact, intros K hK, refine ⟨f ⁻¹' (K ∩ (set.range f)), _, λ x hx, by simpa using hx⟩, apply hf.to_embedding.is_compact_iff_is_compact_image.mpr, rw set.image_preimage_eq_of_subset (set.inter_subset_right _ _), exact hK.inter_right hf.closed_range, end lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} : is_compact s ↔ is_compact ((coe : _ → α) '' s) := embedding_subtype_coe.is_compact_iff_is_compact_image lemma is_compact_iff_is_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.range_coe]; refl lemma is_compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s := is_compact_iff_is_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) : is_compact (set.prod s t) := begin rw is_compact_iff_ultrafilter_le_nhds at hs ht ⊢, intros f hfs, rw le_principal_iff at hfs, obtain ⟨a : α, sa : a ∈ s, ha : map prod.fst ↑f ≤ 𝓝 a⟩ := hs (f.map prod.fst) (le_principal_iff.2 $ mem_map.2 $ mem_sets_of_superset hfs (λ x, and.left)), obtain ⟨b : β, tb : b ∈ t, hb : map prod.snd ↑f ≤ 𝓝 b⟩ := ht (f.map prod.snd) (le_principal_iff.2 $ mem_map.2 $ mem_sets_of_superset hfs (λ x, and.right)), rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end lemma inducing.is_compact_iff {f : α → β} (hf : inducing f) {s : set α} : is_compact (f '' s) ↔ is_compact s := begin split, { introsI hs F F_ne_bot F_le, obtain ⟨_, ⟨x, x_in : x ∈ s, rfl⟩, hx : cluster_pt (f x) (map f F)⟩ := hs (calc map f F ≤ map f (𝓟 s) : map_mono F_le ... = 𝓟 (f '' s) : map_principal), use [x, x_in], suffices : (map f (𝓝 x ⊓ F)).ne_bot, by simpa [filter.map_ne_bot_iff], rwa calc map f (𝓝 x ⊓ F) = map f ((comap f $ 𝓝 $ f x) ⊓ F) : by rw hf.nhds_eq_comap ... = 𝓝 (f x) ⊓ map f F : filter.push_pull' _ _ _ }, { intro hs, exact hs.image hf.continuous } end /-- Finite topological spaces are compact. -/ @[priority 100] instance fintype.compact_space [fintype α] : compact_space α := { compact_univ := finite_univ.is_compact } /-- The product of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩ /-- The disjoint union of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin rw ← range_inl_union_range_inr, exact (is_compact_range continuous_inl).union (is_compact_range continuous_inr) end⟩ /-- The coproduct of the cocompact filters on two topological spaces is the cocompact filter on their product. -/ lemma filter.coprod_cocompact {β : Type*} [topological_space β]: (filter.cocompact α).coprod (filter.cocompact β) = filter.cocompact (α × β) := begin ext S, simp only [mem_coprod_iff, exists_prop, mem_comap_sets, filter.mem_cocompact], split, { rintro ⟨⟨A, ⟨t, ht, hAt⟩, hAS⟩, B, ⟨t', ht', hBt'⟩, hBS⟩, refine ⟨t.prod t', ht.prod ht', _⟩, refine subset.trans _ (union_subset hAS hBS), rw compl_subset_comm at ⊢ hAt hBt', refine subset.trans _ (set.prod_mono hAt hBt'), intros x, simp only [compl_union, mem_inter_eq, mem_prod, mem_preimage, mem_compl_eq], tauto }, { rintros ⟨t, ht, htS⟩, refine ⟨⟨(prod.fst '' t)ᶜ, _, _⟩, ⟨(prod.snd '' t)ᶜ, _, _⟩⟩, { exact ⟨prod.fst '' t, ht.image continuous_fst, subset.rfl⟩ }, { rw preimage_compl, rw compl_subset_comm at ⊢ htS, exact subset.trans htS (subset_preimage_image prod.fst _) }, { exact ⟨prod.snd '' t, ht.image continuous_snd, subset.rfl⟩ }, { rw preimage_compl, rw compl_subset_comm at ⊢ htS, exact subset.trans htS (subset_preimage_image prod.snd _) } } end section tychonoff variables {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)] /-- **Tychonoff's theorem** -/ lemma is_compact_pi_infinite {s : Π i, set (π i)} : (∀ i, is_compact (s i)) → is_compact {x : Π i, π i | ∀ i, x i ∈ s i} := begin simp only [is_compact_iff_ultrafilter_le_nhds, nhds_pi, exists_prop, mem_set_of_eq, le_infi_iff, le_principal_iff], intros h f hfs, have : ∀i:ι, ∃a, a∈s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a), { refine λ i, h i (f.map _) (mem_map.2 _), exact mem_sets_of_superset hfs (λ x hx, hx i) }, choose a ha, exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩ end /-- A version of Tychonoff's theorem that uses `set.pi`. -/ lemma is_compact_univ_pi {s : Π i, set (π i)} (h : ∀ i, is_compact (s i)) : is_compact (pi univ s) := by { convert is_compact_pi_infinite h, simp only [pi, forall_prop_of_true, mem_univ] } instance pi.compact_space [∀ i, compact_space (π i)] : compact_space (Πi, π i) := ⟨by { rw [← pi_univ univ], exact is_compact_univ_pi (λ i, compact_univ) }⟩ /-- Product of compact sets is compact -/ lemma filter.Coprod_cocompact {δ : Type*} {κ : δ → Type*} [Π d, topological_space (κ d)] : filter.Coprod (λ d, filter.cocompact (κ d)) = filter.cocompact (Π d, κ d) := begin ext S, simp only [mem_coprod_iff, exists_prop, mem_comap_sets, filter.mem_cocompact], split, { intros h, rw filter.mem_Coprod_iff at h, choose t ht1 ht2 using h, choose t1 ht11 ht12 using λ d, filter.mem_cocompact.mp (ht1 d), refine ⟨set.pi set.univ t1, _, _⟩, { convert is_compact_pi_infinite ht11, ext, simp }, { refine subset.trans _ (set.Union_subset ht2), intros x, simp only [mem_Union, mem_univ_pi, exists_imp_distrib, mem_compl_eq, not_forall], intros d h, exact ⟨d, ht12 d h⟩ } }, { rintros ⟨t, h1, h2⟩, rw filter.mem_Coprod_iff, intros d, refine ⟨((λ (k : Π (d : δ), κ d), k d) '' t)ᶜ, _, _⟩, { rw filter.mem_cocompact, refine ⟨(λ (k : Π (d : δ), κ d), k d) '' t, _, set.subset.refl _⟩, exact is_compact.image h1 (continuous_pi_iff.mp (continuous_id) d) }, refine subset.trans _ h2, intros x hx, simp only [not_exists, mem_image, mem_preimage, mem_compl_eq] at hx, simpa using mt (hx x) }, end end tychonoff instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨by { rw ← range_quot_mk, exact is_compact_range continuous_quot_mk }⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] : Prop := (local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s) lemma compact_basis_nhds [locally_compact_space α] (x : α) : (𝓝 x).has_basis (λ s, s ∈ 𝓝 x ∧ is_compact s) (λ s, s) := has_basis_self.2 $ by simpa only [and_comm] using locally_compact_space.local_compact_nhds x lemma locally_compact_space_of_has_basis {ι : α → Type*} {p : Π x, ι x → Prop} {s : Π x, ι x → set α} (h : ∀ x, (𝓝 x).has_basis (p x) (s x)) (hc : ∀ x i, p x i → is_compact (s x i)) : locally_compact_space α := ⟨λ x t ht, let ⟨i, hp, ht⟩ := (h x).mem_iff.1 ht in ⟨s x i, (h x).mem_of_mem hp, ht, hc x i hp⟩⟩ instance locally_compact_space.prod (α : Type*) (β : Type*) [topological_space α] [topological_space β] [locally_compact_space α] [locally_compact_space β] : locally_compact_space (α × β) := have _ := λ x : α × β, (compact_basis_nhds x.1).prod_nhds' (compact_basis_nhds x.2), locally_compact_space_of_has_basis this $ λ x s ⟨⟨_, h₁⟩, _, h₂⟩, h₁.prod h₂ /-- A reformulation of the definition of locally compact space: In a locally compact space, every open set containing `x` has a compact subset containing `x` in its interior. -/ lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α} (hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U := begin rcases locally_compact_space.local_compact_nhds x U (hU.mem_nhds hx) with ⟨K, h1K, h2K, h3K⟩, exact ⟨K, h3K, mem_interior_iff_mem_nhds.2 h1K, h2K⟩, end /-- In a locally compact space every point has a compact neighborhood. -/ lemma exists_compact_mem_nhds [locally_compact_space α] (x : α) : ∃ K, is_compact K ∧ K ∈ 𝓝 x := let ⟨K, hKc, hx, H⟩ := exists_compact_subset is_open_univ (mem_univ x) in ⟨K, hKc, mem_interior_iff_mem_nhds.1 hx⟩ /-- In a locally compact space, every compact set is contained in the interior of a compact set. -/ lemma exists_compact_superset [locally_compact_space α] {K : set α} (hK : is_compact K) : ∃ K', is_compact K' ∧ K ⊆ interior K' := begin choose U hUc hxU using λ x : K, exists_compact_mem_nhds (x : α), have : K ⊆ ⋃ x, interior (U x), from λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 (hxU _)⟩, rcases hK.elim_finite_subcover _ _ this with ⟨t, ht⟩, { refine ⟨_, t.compact_bUnion (λ x _, hUc x), λ x hx, _⟩, rcases mem_bUnion_iff.1 (ht hx) with ⟨y, hyt, hy⟩, exact interior_mono (subset_bUnion_of_mem hyt) hy }, { exact λ _, is_open_interior } end lemma ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) : ↑F ≤ 𝓝 (@Lim _ _ (F : filter α).nonempty_of_ne_bot F) := begin rcases compact_univ.ultrafilter_le_nhds F (by simp) with ⟨x, -, h⟩, exact le_nhds_Lim ⟨x,h⟩, end theorem is_closed.exists_minimal_nonempty_closed_subset [compact_space α] {S : set α} (hS : is_closed S) (hne : S.nonempty) : ∃ (V : set α), V ⊆ S ∧ V.nonempty ∧ is_closed V ∧ (∀ (V' : set α), V' ⊆ V → V'.nonempty → is_closed V' → V' = V) := begin let opens := {U : set α | Sᶜ ⊆ U ∧ is_open U ∧ Uᶜ.nonempty}, obtain ⟨U, ⟨Uc, Uo, Ucne⟩, h⟩ := zorn.zorn_subset opens (λ c hc hz, begin by_cases hcne : c.nonempty, { obtain ⟨U₀, hU₀⟩ := hcne, haveI : nonempty {U // U ∈ c} := ⟨⟨U₀, hU₀⟩⟩, obtain ⟨U₀compl, U₀opn, U₀ne⟩ := hc hU₀, use ⋃₀ c, refine ⟨⟨_, _, _⟩, λ U hU a ha, ⟨U, hU, ha⟩⟩, { exact λ a ha, ⟨U₀, hU₀, U₀compl ha⟩ }, { exact is_open_sUnion (λ _ h, (hc h).2.1) }, { convert_to (⋂(U : {U // U ∈ c}), U.1ᶜ).nonempty, { ext, simp only [not_exists, exists_prop, not_and, set.mem_Inter, subtype.forall, set.mem_set_of_eq, set.mem_compl_eq, subtype.val_eq_coe], refl, }, apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed, { rintros ⟨U, hU⟩ ⟨U', hU'⟩, obtain ⟨V, hVc, hVU, hVU'⟩ := zorn.chain.directed_on hz U hU U' hU', exact ⟨⟨V, hVc⟩, set.compl_subset_compl.mpr hVU, set.compl_subset_compl.mpr hVU'⟩, }, { exact λ U, (hc U.2).2.2, }, { exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1).is_compact, }, { exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1), } } }, { use Sᶜ, refine ⟨⟨set.subset.refl _, is_open_compl_iff.mpr hS, _⟩, λ U Uc, (hcne ⟨U, Uc⟩).elim⟩, rw compl_compl, exact hne, } end), refine ⟨Uᶜ, set.compl_subset_comm.mp Uc, Ucne, is_closed_compl_iff.mpr Uo, _⟩, intros V' V'sub V'ne V'cls, have : V'ᶜ = U, { refine h V'ᶜ ⟨_, is_open_compl_iff.mpr V'cls, _⟩ (set.subset_compl_comm.mp V'sub), exact set.subset.trans Uc (set.subset_compl_comm.mp V'sub), simp only [compl_compl, V'ne], }, rw [←this, compl_compl], end /-- A σ-compact space is a space that is the union of a countable collection of compact subspaces. Note that a locally compact separable T₂ space need not be σ-compact. The sequence can be extracted using `topological_space.compact_covering`. -/ class sigma_compact_space (α : Type*) [topological_space α] : Prop := (exists_compact_covering : ∃ K : ℕ → set α, (∀ n, is_compact (K n)) ∧ (⋃ n, K n) = univ) @[priority 200] -- see Note [lower instance priority] instance compact_space.sigma_compact [compact_space α] : sigma_compact_space α := ⟨⟨λ _, univ, λ _, compact_univ, Union_const _⟩⟩ lemma sigma_compact_space.of_countable (S : set (set α)) (Hc : countable S) (Hcomp : ∀ s ∈ S, is_compact s) (HU : ⋃₀ S = univ) : sigma_compact_space α := ⟨(exists_seq_cover_iff_countable ⟨_, is_compact_empty⟩).2 ⟨S, Hc, Hcomp, HU⟩⟩ @[priority 100] -- see Note [lower instance priority] instance sigma_compact_space_of_locally_compact_second_countable [locally_compact_space α] [second_countable_topology α] : sigma_compact_space α := begin choose K hKc hxK using λ x : α, exists_compact_mem_nhds x, rcases countable_cover_nhds hxK with ⟨s, hsc, hsU⟩, refine sigma_compact_space.of_countable _ (hsc.image K) (ball_image_iff.2 $ λ x _, hKc x) _, rwa sUnion_image end variables (α) [sigma_compact_space α] open sigma_compact_space /-- A choice of compact covering for a `σ`-compact space, chosen to be monotone. -/ def compact_covering : ℕ → set α := accumulate exists_compact_covering.some lemma is_compact_compact_covering (n : ℕ) : is_compact (compact_covering α n) := compact_accumulate (classical.some_spec sigma_compact_space.exists_compact_covering).1 n lemma Union_compact_covering : (⋃ n, compact_covering α n) = univ := begin rw [compact_covering, Union_accumulate], exact (classical.some_spec sigma_compact_space.exists_compact_covering).2 end @[mono] lemma compact_covering_subset ⦃m n : ℕ⦄ (h : m ≤ n) : compact_covering α m ⊆ compact_covering α n := monotone_accumulate h variable {α} lemma exists_mem_compact_covering (x : α) : ∃ n, x ∈ compact_covering α n := Union_eq_univ_iff.mp (Union_compact_covering α) x /-- If `α` is a `σ`-compact space, then a locally finite family of nonempty sets of `α` can have only countably many elements, `set.countable` version. -/ lemma locally_finite.countable_of_sigma_compact {ι : Type*} {f : ι → set α} (hf : locally_finite f) (hne : ∀ i, (f i).nonempty) : countable (univ : set ι) := begin have := λ n, hf.finite_nonempty_inter_compact (is_compact_compact_covering α n), refine (countable_Union (λ n, (this n).countable)).mono (λ i hi, _), rcases hne i with ⟨x, hx⟩, rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩, exact mem_Union.2 ⟨n, x, hx, hn⟩ end /-- In a topological space with sigma compact topology, if `f` is a function that sends each point `x` of a closed set `s` to a neighborhood of `x` within `s`, then for some countable set `t ⊆ s`, the neighborhoods `f x`, `x ∈ t`, cover the whole set `s`. -/ lemma countable_cover_nhds_within_of_sigma_compact {f : α → set α} {s : set α} (hs : is_closed s) (hf : ∀ x ∈ s, f x ∈ 𝓝[s] x) : ∃ t ⊆ s, countable t ∧ s ⊆ ⋃ x ∈ t, f x := begin simp only [nhds_within, mem_inf_principal] at hf, choose t ht hsub using λ n, ((is_compact_compact_covering α n).inter_right hs).elim_nhds_subcover _ (λ x hx, hf x hx.right), refine ⟨⋃ n, (t n : set α), Union_subset $ λ n x hx, (ht n x hx).2, countable_Union $ λ n, (t n).countable_to_set, λ x hx, mem_bUnion_iff.2 _⟩, rcases exists_mem_compact_covering x with ⟨n, hn⟩, rcases mem_bUnion_iff.1 (hsub n ⟨hn, hx⟩) with ⟨y, hyt : y ∈ t n, hyf : x ∈ s → x ∈ f y⟩, exact ⟨y, mem_Union.2 ⟨n, hyt⟩, hyf hx⟩ end /-- In a topological space with sigma compact topology, if `f` is a function that sends each point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`, `x ∈ s`, cover the whole space. -/ lemma countable_cover_nhds_of_sigma_compact {f : α → set α} (hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, countable s ∧ (⋃ x ∈ s, f x) = univ := begin simp only [← nhds_within_univ] at hf, rcases countable_cover_nhds_within_of_sigma_compact is_closed_univ (λ x _, hf x) with ⟨s, -, hsc, hsU⟩, exact ⟨s, hsc, univ_subset_iff.1 hsU⟩ end end compact /-- An [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a topological space is a sequence of compact sets `K n` such that `K n ⊆ interior (K (n + 1))` and `(⋃ n, K n) = univ`. If `X` is a locally compact sigma compact space, then `compact_exhaustion.choice X` provides a choice of an exhaustion by compact sets. This choice is also available as `(default : compact_exhaustion X)`. -/ structure compact_exhaustion (X : Type*) [topological_space X] := (to_fun : ℕ → set X) (is_compact' : ∀ n, is_compact (to_fun n)) (subset_interior_succ' : ∀ n, to_fun n ⊆ interior (to_fun (n + 1))) (Union_eq' : (⋃ n, to_fun n) = univ) namespace compact_exhaustion instance : has_coe_to_fun (compact_exhaustion α) := ⟨_, to_fun⟩ variables {α} (K : compact_exhaustion α) protected lemma is_compact (n : ℕ) : is_compact (K n) := K.is_compact' n lemma subset_interior_succ (n : ℕ) : K n ⊆ interior (K (n + 1)) := K.subset_interior_succ' n lemma subset_succ (n : ℕ) : K n ⊆ K (n + 1) := subset.trans (K.subset_interior_succ n) interior_subset @[mono] protected lemma subset ⦃m n : ℕ⦄ (h : m ≤ n) : K m ⊆ K n := show K m ≤ K n, from monotone_of_monotone_nat K.subset_succ h lemma subset_interior ⦃m n : ℕ⦄ (h : m < n) : K m ⊆ interior (K n) := subset.trans (K.subset_interior_succ m) $ interior_mono $ K.subset h lemma Union_eq : (⋃ n, K n) = univ := K.Union_eq' lemma exists_mem (x : α) : ∃ n, x ∈ K n := Union_eq_univ_iff.1 K.Union_eq x /-- The minimal `n` such that `x ∈ K n`. -/ protected noncomputable def find (x : α) : ℕ := nat.find (K.exists_mem x) lemma mem_find (x : α) : x ∈ K (K.find x) := nat.find_spec (K.exists_mem x) lemma mem_iff_find_le {x : α} {n : ℕ} : x ∈ K n ↔ K.find x ≤ n := ⟨λ h, nat.find_min' (K.exists_mem x) h, λ h, K.subset h $ K.mem_find x⟩ /-- Prepend the empty set to a compact exhaustion `K n`. -/ def shiftr : compact_exhaustion α := { to_fun := λ n, nat.cases_on n ∅ K, is_compact' := λ n, nat.cases_on n is_compact_empty K.is_compact, subset_interior_succ' := λ n, nat.cases_on n (empty_subset _) K.subset_interior_succ, Union_eq' := Union_eq_univ_iff.2 $ λ x, ⟨K.find x + 1, K.mem_find x⟩ } @[simp] lemma find_shiftr (x : α) : K.shiftr.find x = K.find x + 1 := nat.find_comp_succ _ _ (not_mem_empty _) lemma mem_diff_shiftr_find (x : α) : x ∈ K.shiftr (K.find x + 1) \ K.shiftr (K.find x) := ⟨K.mem_find _, mt K.shiftr.mem_iff_find_le.1 $ by simp only [find_shiftr, not_le, nat.lt_succ_self]⟩ /-- A choice of an [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a locally compact sigma compact space. -/ noncomputable def choice (X : Type*) [topological_space X] [locally_compact_space X] [sigma_compact_space X] : compact_exhaustion X := begin apply classical.choice, let K : ℕ → {s : set X // is_compact s} := λ n, nat.rec_on n ⟨∅, is_compact_empty⟩ (λ n s, ⟨(exists_compact_superset s.2).some ∪ compact_covering X n, (exists_compact_superset s.2).some_spec.1.union (is_compact_compact_covering _ _)⟩), refine ⟨⟨λ n, K n, λ n, (K n).2, λ n, _, _⟩⟩, { exact subset.trans (exists_compact_superset (K n).2).some_spec.2 (interior_mono $ subset_union_left _ _) }, { refine univ_subset_iff.1 (Union_compact_covering X ▸ _), exact Union_subset_Union2 (λ n, ⟨n + 1, subset_union_right _ _⟩) } end noncomputable instance [locally_compact_space α] [sigma_compact_space α] : inhabited (compact_exhaustion α) := ⟨compact_exhaustion.choice α⟩ end compact_exhaustion section clopen /-- A set is clopen if it is both open and closed. -/ def is_clopen (s : set α) : Prop := is_open s ∧ is_closed s theorem is_clopen.union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := ⟨is_open.union hs.1 ht.1, is_closed.union hs.2 ht.2⟩ theorem is_clopen.inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := ⟨is_open.inter hs.1 ht.1, is_closed.inter hs.2 ht.2⟩ @[simp] theorem is_clopen_empty : is_clopen (∅ : set α) := ⟨is_open_empty, is_closed_empty⟩ @[simp] theorem is_clopen_univ : is_clopen (univ : set α) := ⟨is_open_univ, is_closed_univ⟩ theorem is_clopen.compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ := ⟨hs.2.is_open_compl, is_closed_compl_iff.2 hs.1⟩ @[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s := ⟨λ h, compl_compl s ▸ is_clopen.compl h, is_clopen.compl⟩ theorem is_clopen.diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) := hs.inter ht.compl lemma is_clopen_Union {β : Type*} [fintype β] {s : β → set α} (h : ∀ i, is_clopen (s i)) : is_clopen (⋃ i, s i) := ⟨is_open_Union (forall_and_distrib.1 h).1, is_closed_Union (forall_and_distrib.1 h).2⟩ lemma is_clopen_bUnion {β : Type*} {s : finset β} {f : β → set α} (h : ∀i ∈ s, is_clopen $ f i) : is_clopen (⋃ i ∈ s, f i) := begin refine ⟨is_open_bUnion (λ i hi, (h i hi).1), _⟩, show is_closed (⋃ (i : β) (H : i ∈ (s : set β)), f i), rw bUnion_eq_Union, exact is_closed_Union (λ ⟨i, hi⟩,(h i hi).2) end lemma is_clopen_Inter {β : Type*} [fintype β] {s : β → set α} (h : ∀ i, is_clopen (s i)) : is_clopen (⋂ i, s i) := ⟨(is_open_Inter (forall_and_distrib.1 h).1), (is_closed_Inter (forall_and_distrib.1 h).2)⟩ lemma is_clopen_bInter {β : Type*} {s : finset β} {f : β → set α} (h : ∀i∈s, is_clopen (f i)) : is_clopen (⋂i∈s, f i) := ⟨ is_open_bInter ⟨finset_coe.fintype s⟩ (λ i hi, (h i hi).1), by {show is_closed (⋂ (i : β) (H : i ∈ (↑s : set β)), f i), rw bInter_eq_Inter, apply is_closed_Inter, rintro ⟨i, hi⟩, exact (h i hi).2}⟩ lemma continuous_on.preimage_clopen_of_clopen {β: Type*} [topological_space β] {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ f⁻¹' t) := ⟨continuous_on.preimage_open_of_open hf hs.1 ht.1, continuous_on.preimage_closed_of_closed hf hs.2 ht.2⟩ /-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/ theorem is_clopen_inter_of_disjoint_cover_clopen {Z a b : set α} (h : is_clopen Z) (cover : Z ⊆ a ∪ b) (ha : is_open a) (hb : is_open b) (hab : a ∩ b = ∅) : is_clopen (Z ∩ a) := begin refine ⟨is_open.inter h.1 ha, _⟩, have : is_closed (Z ∩ bᶜ) := is_closed.inter h.2 (is_closed_compl_iff.2 hb), convert this using 1, apply subset.antisymm, { exact inter_subset_inter_right Z (subset_compl_iff_disjoint.2 hab) }, { rintros x ⟨hx₁, hx₂⟩, exact ⟨hx₁, by simpa [not_mem_of_mem_compl hx₂] using cover hx₁⟩ } end end clopen section preirreducible /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def is_preirreducible (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def is_irreducible (s : set α) : Prop := s.nonempty ∧ is_preirreducible s lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) : s.nonempty := h.1 lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) : is_preirreducible s := h.2 theorem is_preirreducible_empty : is_preirreducible (∅ : set α) := λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) := ⟨singleton_nonempty x, λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3; substs y z; exact ⟨x, rfl, h2, h4⟩⟩ theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) : is_preirreducible (closure s) := λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ lemma is_irreducible.closure {s : set α} (h : is_irreducible s) : is_irreducible (closure s) := ⟨h.nonempty.closure, h.is_preirreducible.closure⟩ theorem exists_preirreducible (s : set α) (H : is_preirreducible s) : ∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset_nonempty {t : set α | is_preirreducible t} (λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in ⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩, let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy, ⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in or.cases_on (zorn.chain.total hcc hpc hqc) (assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) (assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩), λ x hxc, subset_sUnion_of_mem hxc⟩) s H in ⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩ /-- A maximal irreducible set that contains a given point. -/ def irreducible_component (x : α) : set α := classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) lemma irreducible_component_property (x : α) : is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧ ∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) := classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x := singleton_subset_iff.1 (irreducible_component_property x).2.1 theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) := ⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩ theorem eq_irreducible_component {x : α} : ∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x := (irreducible_component_property x).2.2 theorem is_closed_irreducible_component {x : α} : is_closed (irreducible_component x) := closure_eq_iff_is_closed.1 $ eq_irreducible_component is_irreducible_irreducible_component.is_preirreducible.closure subset_closure /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class preirreducible_space (α : Type u) [topological_space α] : Prop := (is_preirreducible_univ [] : is_preirreducible (univ : set α)) /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop := (to_nonempty [] : nonempty α) -- see Note [lower instance priority] attribute [instance, priority 50] irreducible_space.to_nonempty theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} : is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preirreducible_space.is_preirreducible_univ α _ _ s t theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s) (f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) := begin rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩, rw ← mem_preimage at hxu hyv, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, have := H u' v' hu' hv', rw [inter_comm s u', ← u'_eq] at this, rw [inter_comm s v', ← v'_eq] at this, rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩, refine ⟨f z, mem_image_of_mem f hzs, _, _⟩, all_goals { rw ← mem_preimage, apply mem_of_mem_inter_left, show z ∈ _ ∩ s, simp [*] } end theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s) (f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩ lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) : preirreducible_space s := { is_preirreducible_univ := begin intros u v hu hv hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩ end } lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) : irreducible_space s := { is_preirreducible_univ := (subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ lemma is_irreducible_iff_sInter {s : set α} : is_irreducible s ↔ ∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty), (s ∩ ⋂₀ ↑U).nonempty := begin split; intro h, { intro U, apply finset.induction_on U, { intros, simpa using h.nonempty }, { intros u U hu IH hU H, rw [finset.coe_insert, sInter_insert], apply h.2, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sInter (finset.finite_to_set U), intros, solve_by_elim [finset.mem_insert_of_mem] }, { solve_by_elim [finset.mem_insert_self] }, { apply IH, all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } }, { split, { simpa using h ∅ _ _; intro u; simp }, intros u v hu hv hu' hv', simpa using h {u,v} _ _, all_goals { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption } } end /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ lemma is_preirreducible_iff_closed_union_closed {s : set α} : is_preirreducible s ↔ ∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := begin split, all_goals { intros h t₁ t₂ ht₁ ht₂, specialize h t₁ᶜ t₂ᶜ, simp only [is_open_compl_iff, is_closed_compl_iff] at h, specialize h ht₁ ht₂ }, { contrapose!, simp only [not_subset], rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩, rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩, rw ← compl_union at hz', exact ⟨z, hz, hz'⟩ }, { rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, rw ← compl_inter at h, delta set.nonempty, rw imp_iff_not_or at h, contrapose! h, split, { intros z hz hz', exact h z ⟨hz, hz'⟩ }, { split; intro H; refine H _ ‹_›; assumption } } end /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ lemma is_irreducible_iff_sUnion_closed {s : set α} : is_irreducible s ↔ ∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z), ∃ z ∈ Z, s ⊆ z := begin rw [is_irreducible, is_preirreducible_iff_closed_union_closed], split; intro h, { intro Z, apply finset.induction_on Z, { intros, rw [finset.coe_empty, sUnion_empty] at H, rcases h.1 with ⟨x, hx⟩, exfalso, tauto }, { intros z Z hz IH hZ H, cases h.2 z (⋃₀ ↑Z) _ _ _ with h' h', { exact ⟨z, finset.mem_insert_self _ _, h'⟩ }, { rcases IH _ h' with ⟨z', hz', hsz'⟩, { exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { rw sUnion_eq_bUnion, apply is_closed_bUnion (finset.finite_to_set Z), { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { simpa using H } } }, { split, { by_contradiction hs, simpa using h ∅ _ _, { intro z, simp }, { simpa [set.nonempty] using hs } }, intros z₁ z₂ hz₁ hz₂ H, have := h {z₁, z₂} _ _, simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this, { rcases this with ⟨z, rfl|rfl, hz⟩; tauto }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using H } } end end preirreducible
6ce4d3a56d48e04a4436365f490e50d19b950790
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/data/list/defs.lean
258d2e139aa76f2273ec0755fcbadfb7f7cc4fea
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,562
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro Extra definitions on lists. -/ import data.option.defs import logic.basic import tactic.cache namespace list open function nat universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} /-- Returns whether a list is []. Returns a boolean even if `l = []` is not decidable. -/ def is_nil {α} : list α → bool | [] := tt | _ := ff instance [decidable_eq α] : has_sdiff (list α) := ⟨ list.diff ⟩ /-- Split a list at an index. split_at 2 [a, b, c] = ([a, b], [c]) -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] : list α → (list α → list α) → list (list α) | [] f := [f []] | (h :: t) f := if P h then f [] :: split_on_p_aux t id else split_on_p_aux t (λ l, f (h :: l)) /-- Split a list at every element satisfying a predicate. -/ def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) := split_on_p_aux P l id /-- Split a list at every occurrence of an element. [1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/ def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) := as.split_on_p (=a) /-- Concatenate an element at the end of a list. concat [a, b] c = [a, b, c] -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a /-- `head' xs` returns the first element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def head' : list α → option α | [] := none | (a :: l) := some a /-- Convert a list into an array (whose length is the length of `l`). -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /-- Apply a function to the nth tail of `l`. Returns the input without using `f` if the index is larger than the length of the list. modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n section take' variable [inhabited α] def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail end take' /-- Get the longest initial segment of the list whose members all satisfy `p`. take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /-- Fold a function `f` over the list from the left, returning the list of partial results. scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' /-- Product of a list. prod [a, b, c] = ((1 * a) * b) * c -/ def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 /-- Sum of a list. sum [a, b, c] = ((0 + a) + b) + c -/ -- Later this will be tagged with `to_additive`, but this can't be done yet because of import -- dependencies. def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0 def partition_map (f : α → β ⊕ γ) : list α → list β × list γ | [] := ([],[]) | (x::xs) := match f x with | (sum.inr r) := prod.map id (cons r) $ partition_map xs | (sum.inl l) := prod.map (cons l) id $ partition_map xs end /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat | [] n := [] | (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := find_indexes_aux p l 0 /-- `lookmap` is a combination of `lookup` and `filter_map`. `lookmap f l` will apply `f : α → option α` to each element of the list, replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/ def lookmap (f : α → option α) : list α → list α | [] := [] | (a::l) := match f a with | some b := b :: l | none := a :: lookmap l end def map_with_index_core (f : ℕ → α → β) : ℕ → list α → list β | k [] := [] | k (a::as) := f k a::(map_with_index_core (k+1) as) def map_with_index (f : ℕ → α → β) (as : list α) : list β := map_with_index_core f 0 as /-- `indexes_of a l` is the list of all indexes of `a` in `l`. indexes_of a [a, b, a, a] = [0, 2, 3] -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) /-- Auxilliary definition for `indexes_values`. -/ def indexes_values_aux {α} (f : α → bool) : list α → ℕ → list (ℕ × α) | [] n := [] | (x::xs) n := let ns := indexes_values_aux xs (n+1) in if f x then (n, x)::ns else ns /-- Returns `(l.find_indexes f).zip l`, i.e. pairs of `(n, x)` such that `f x = tt` and `l.nth = some x`, in increasing order of first arguments. -/ def indexes_values {α} (l : list α) (f : α → bool) : list (ℕ × α) := indexes_values_aux f l 0 /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count [decidable_eq α] (a : α) : list α → nat := countp (eq a) /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix /-- `inits l` is the list of initial segments of `l`. inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) /-- `tails l` is the list of terminal segments of `l`. tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'` for a different ordering. sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) attribute [simp] forall₂.nil end forall₂ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l section permutations def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ (lt_add_of_pos_left _ (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] end permutations def erasep (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then l else a :: erasep l def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α | [] := (none, []) | (a::l) := if p a then (some a, l) else let (a', l') := extractp l in (a', a :: l') def revzip (l : list α) : list (α × α) := zip l l.reverse /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : _ then some (f ⟨i, h⟩) else none /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false section pairwise variables (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) variables {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) := by induction l with hd tl ih; [exact is_true pairwise.nil, exactI decidable_of_iff' _ pairwise_cons] end pairwise /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function (cf. `erase_dup`), and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ inductive chain : α → list α → Prop | nil {a : α} : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) /-- `chain' R l` means that `R` holds between adjacent elements of `l`. chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ def chain' : list α → Prop | [] := true | (a :: l) := chain R a l variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] chain.nil instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) := by cases l; dunfold chain'; apply_instance end chain /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). Defined as `pw_filter (≠)`. erase_dup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def erase_dup [decidable_eq α] : list α → list α := pw_filter (≠) /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n def reduce_option {α} : list (option α) → list α := list.filter_map id def map_head {α} (f : α → α) : list α → list α | [] := [] | (x :: xs) := f x :: xs def map_last {α} (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: map_last xs /-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty; it returns `x` otherwise -/ @[simp] def ilast' {α} : α → list α → α | a [] := a | a (b::l) := ilast' b l /-- `last' xs` returns the last element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def last' {α} : list α → option α | [] := none | [a] := some a | (b::l) := last' l /-- `rotate l n` rotates the elements of `l` to the left by `n` rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/ def rotate (l : list α) (n : ℕ) : list α := let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁ /-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/ def rotate' : list α → ℕ → list α | [] n := [] | l 0 := l | (a::l) (n+1) := rotate' (l ++ [a]) n section choose variables (p : α → Prop) [decidable_pred p] (l : list α) def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } | [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left)) | (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp (λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in ⟨a, ⟨or.inr a_mem_ls, pa⟩⟩ def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp end choose /-- Filters and maps elements of a list -/ def mmap_filter {m : Type → Type v} [monad m] {α β} (f : α → m (option β)) : list α → m (list β) | [] := return [] | (h :: t) := do b ← f h, t' ← t.mmap_filter, return $ match b with none := t' | (some x) := x::t' end protected def traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) : list α → F (list β) | [] := pure [] | (x :: xs) := list.cons <$> f x <*> traverse xs /-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`. If `l₁` is not a prefix of `l`, returns `none` -/ def get_rest [decidable_eq α] : list α → list α → option (list α) | l [] := some l | [] _ := none | (x::l) (y::l₁) := if x = y then get_rest l l₁ else none end list
4bf264ae2559a6b6ed5089c34c21038c0bfbbde3
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/app/MCStdLib.lean
179f6f6e2b4c6bd8a8ba946d8f9df926d4389e10
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
7,915
lean
-- This file contains all the SMT symbols that the VCG expects to use, -- incl. memory operations and stack bounds. import SMTLIB.Syntax import ReoptVCG.VCGBackend import ReoptVCG.WordSize namespace x86 namespace vcg open SMT (sort term smtM command) abbrev memory_t := SMT.sort.array (SMT.sort.bitvec 64) (SMT.sort.bitvec 8) def memory := term memory_t ------------------------------------------------------- -- MC memory operations ------------------------------------------------------- namespace memory protected def read_byte (mem : memory) (addr : memaddr) : byte := SMT.select _ _ mem addr protected def store_byte (mem : memory) (addr : memaddr) (b : byte) : memory := SMT.store _ _ mem addr b protected def store_bytes (m : memory) (addr : memaddr) (bs : List byte) : memory := let f (a : memory × memaddr) b : memory × memaddr := match a with | (m', addr') => (m'.store_byte addr' b, SMT.bvadd addr' (SMT.bvimm 64 1)); (List.foldl f (m, addr) bs).fst protected def read_bytes (m : memory) (addr : memaddr) (n : Nat) : List byte := let f i := m.read_byte (SMT.bvadd addr (SMT.bvimm 64 i)); List.map f (Nat.upto0_lt n).reverse def store_word {n : Nat} (m : memory) (addr : memaddr) (b : bitvec (8 * n)) : memory := m.store_bytes addr (b.split_list 8).reverse def read_word (n : Nat) (m : memory) (addr : memaddr) : bitvec (8 * n) := let bs := m.read_bytes addr n; let w : bitvec (8 * bs.length) := bitvec.concat_list bs; let pf : 8 * bs.length = 8 * n := sorryAx _; bitvec.cong pf w end memory structure SupportedMemType (s : SMT.sort) := (readMem : memory -> memaddr -> SMT.term s) (writeMem : memory -> memaddr -> SMT.term s -> memory) namespace SupportedMemType def make (nBytes : Nat) : smtM (SupportedMemType (SMT.sort.bitvec (8 * nBytes))) := do let n := 8 * nBytes; rm <- SMT.define_fun ("mem_readbv" ++ repr n) [memory_t, SMT.sort.bitvec 64] (SMT.sort.bitvec n) (memory.read_word nBytes); wm <- SMT.define_fun ("mem_writebv" ++ repr n) [memory_t, SMT.sort.bitvec 64, SMT.sort.bitvec n] memory_t memory.store_word; pure { readMem := rm, writeMem := wm } end SupportedMemType -- FIXME: the name is wrong, maybe something like MCSMTContext or something? -- cf. `mcMemDecls` structure MCStdLib := (memOps : forall (w : WordSize), SupportedMemType w.sort) (funStartRegs : RegState) (blockStartMem : memory) (onStack : memaddr -> bitvec 64 -> s_bool) namespace MCStdLib def memOpsBySort (m : MCStdLib) (s : SMT.sort) : Option (SupportedMemType s) := let mops := m.memOps; match s with | SMT.sort.bitvec 8 => some $ mops WordSize.word8 | SMT.sort.bitvec 16 => some $ mops WordSize.word16 | SMT.sort.bitvec 32 => some $ mops WordSize.word32 | SMT.sort.bitvec 64 => some $ mops WordSize.word64 | _ => none end MCStdLib -------------------------------------------------------------------------------- -- Memory operations def mkMemOps : smtM (forall (w : WordSize), SupportedMemType w.sort) := do sm8 <- SupportedMemType.make 1; sm16 <- SupportedMemType.make 2; sm32 <- SupportedMemType.make 4; sm64 <- SupportedMemType.make 8; pure $ fun w => match w with | WordSize.word8 => sm8 | WordSize.word16 => sm16 | WordSize.word32 => sm32 | WordSize.word64 => sm64 -------------------------------------------------------------------------------- -- Stack properties -- | @defineRangeCheck nm low high@ introduces the definition for a -- function named @nm@ that takes an address @a@ and size @sz@, and -- checks that @[a..a+sz)@ is in @[low..high)@ and that @a+sz@ does not overflow. def defineRangeCheck (name : String) (low : memaddr) (high : memaddr) : smtM (memaddr -> bitvec 64 -> s_bool) := do eName <- SMT.freshSymbol "e"; SMT.define_fun name [SMT.sort.bitvec 64, SMT.sort.bitvec 64] SMT.sort.smt_bool $ fun addr sz => SMT.smt_let eName (SMT.bvadd addr sz) $ fun e => SMT.and (SMT.bvule low addr) (SMT.and (SMT.bvule addr e) (SMT.bvule e high)) -- | Defines a predicate @(not_in_stack_range a sz)@ that holds if @a + sz@ -- does not overflow and @[a..a+sz)@ does not overlap with the -- range @[stack_alloc_min..stack_max)@. -- -- See `mcMemDecls` for details about `stack_alloc_max` and `stack_max`. def defineNotInStackRange (stack_alloc_min : memaddr) (stack_max : memaddr) : smtM (memaddr -> bitvec 64 -> s_bool) := do eName <- SMT.freshSymbol "e"; SMT.define_fun "not_in_stack_range" [SMT.sort.bitvec 64, SMT.sort.bitvec 64] SMT.sort.smt_bool $ fun addr sz => SMT.smt_let eName (SMT.bvadd addr sz) $ fun e => SMT.and (SMT.bvule addr e) (SMT.or (SMT.bvule e stack_alloc_min) (SMT.bvule stack_max addr)) -- FIXME: define -- def defineMCOnlyStackRange (on_stack : memaddr -> bitvec 64 -> s_bool) (allocas : ... ) -- : smtM (memaddr -> bitvec 64 -> s_bool) := do -- eName <- SMT.freshSymbol "e"; -- SMT.define_fun "mc_only_stack_range" [SMT.sort.bitvec 64, SMT.sort.bitvec 64] SMT.sort.smt_bool $ -- fun addr sz => -- SMT.smt_let eName (SMT.bvadd addr sz) $ fun e => -- SMT.and (on_stack addr sz) -- -- ++ [ isDisjoint ("a", "e") (allocaMCBaseVar nm, allocaMCEndVar nm) -- -- | a <- allocas -- -- , let nm = Ann.allocaIdent a -- -- ] -- nbits should be > 0, nbits should be a power of 2 def isAligned {n : Nat} (v : bitvec n) (nbits : Nat) : s_bool := SMT.eq (SMT.bvand v (SMT.bvimm _ (nbits - 1))) (SMT.bvimm _ 0) namespace MCStdLib -- FIXME def rsp_idx : Fin 16 := 4 -- FIXME: some of this is not used in the absence of allocas def make (ip : Nat) (pageSize : Nat) (guardPageCount : Nat) : smtM MCStdLib := do -- FIXME: add checks memOps <- mkMemOps; funStartRegs <- RegState.declare_const "fnstart_" ip; let stackHighTerm := funStartRegs.get_gpreg rsp_idx; blockStartMem <- SMT.declare_fun "init_mem" [] memory_t; let guardSize := pageSize * guardPageCount; stack_alloc_min <- SMT.declare_fun "stack_alloc_min" [] (SMT.sort.bitvec 64); SMT.assert $ isAligned stack_alloc_min pageSize; SMT.assert $ SMT.bvult (SMT.bvimm _ guardSize) stack_alloc_min; stack_guard_min <- SMT.define_fun "stack_guard_min" [] (SMT.sort.bitvec 64) $ SMT.bvsub stack_alloc_min (SMT.bvimm _ guardSize); SMT.assert $ SMT.bvult stack_guard_min stack_alloc_min; -- Declare the upper bound on stack address. stack_max <- SMT.declare_fun "stack_max" [] (SMT.sort.bitvec 64); SMT.assert $ isAligned stack_max pageSize; -- Assert stack_alloc_min < stack_max SMT.assert $ SMT.bvult stack_alloc_min stack_max; -- Assert RSP is between stack_alloc_min and stack_max - return address size SMT.assert $ SMT.bvule stack_alloc_min stackHighTerm; SMT.assert $ SMT.bvule stackHighTerm (SMT.bvsub stack_max (SMT.bvimm _ 8)); -- Define check to assert stack is in given range onStack <- defineRangeCheck "on_stack" stack_guard_min stack_max; -- Declare not in stack that asserts a range is not on the stack. notInStack <- defineNotInStackRange stack_alloc_min stack_max; -- Assert that stack pointer is at least 8 below stack high SMT.assert $ SMT.bvult stackHighTerm (SMT.bvsub stack_max (SMT.bvimm _ 8)); -- High water stack pointer includes 8 bytes for return address. -- The return address top must be aligned to a 16-byte boundary. SMT.assert $ isAligned (SMT.bvadd stackHighTerm (SMT.bvimm _ 8)) 16; -- ++ concatMap allocaMCBaseEndDecls allocas -- FIXME -- Declare mcOnlyStackRange -- defineMCOnlyStackRange onStack pure { memOps := memOps , funStartRegs := funStartRegs , blockStartMem := blockStartMem , onStack := onStack } end MCStdLib end vcg end x86
b27212fa4eccbd6b1f0c4f263f4a74f6253f5e3b
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/interactive.lean
ec7e04bd573d4c6baa4579c61e0a48c0a05de88d
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
41,769
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison -/ import tactic.lint open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr /-- Similar to `constructor`, but does not reorder goals. -/ meta def fconstructor : tactic unit := concat_tags tactic.fconstructor add_tactic_doc { name := "fconstructor", category := doc_category.tactic, decl_names := [`tactic.interactive.fconstructor], tags := ["logic", "goal management"] } /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, λ s, match _root_.try_for max (tac s) with | some r := r | none := (tactic.trace "try_for timeout, using sorry" >> admit) s end /-- Multiple `subst`. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible) add_tactic_doc { name := "substs", category := doc_category.tactic, decl_names := [`tactic.interactive.substs], tags := ["rewrite"] } /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [ ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe, ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc add_tactic_doc { name := "unfold_coes", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold_coes], tags := ["simplification"] } /-- Unfold auxiliary definitions associated with the current declaration. -/ meta def unfold_aux : tactic unit := do tgt ← target, name ← decl_name, let to_unfold := (tgt.list_names_with_prefix name), guard (¬ to_unfold.empty), -- should we be using simp_lemmas.mk_default? simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := metavariables >>= tactic.set_goals /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := λ s, result.cases_on (tac s) (λ a, result.success ()) (λ e ref, result.success ()) /-- `swap n` will move the `n`th goal to the front. `swap` defaults to `swap 2`, and so interchanges the first and second goals. -/ meta def swap (n := 2) : tactic unit := do gs ← get_goals, match gs.nth (n-1) with | (some g) := set_goals (g :: gs.remove_nth (n-1)) | _ := skip end add_tactic_doc { name := "swap", category := doc_category.tactic, decl_names := [`tactic.interactive.swap], tags := ["goal management"] } /-- `rotate` moves the first goal to the back. `rotate n` will do this `n` times. -/ meta def rotate (n := 1) : tactic unit := tactic.rotate n add_tactic_doc { name := "rotate", category := doc_category.tactic, decl_names := [`tactic.interactive.rotate], tags := ["goal management"] } /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ λ h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (¬ cl), tactic.clear h add_tactic_doc { name := "clear_", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_], tags := ["context management"] } meta def apply_iff_congr_core : tactic unit := applyc ``iff_of_eq meta def congr_core' : tactic unit := do tgt ← target, apply_eq_congr_core tgt <|> apply_heq_congr_core <|> apply_iff_congr_core <|> fail "congr tactic failed" /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. If, at any point, a subgoal matches a hypothesis then the subgoal will be closed. -/ meta def congr' : parse (with_desc "n" small_nat)? → tactic unit | (some 0) := failed | o := focus1 (assumption <|> (congr_core' >> all_goals (reflexivity <|> `[apply proof_irrel_heq] <|> `[apply proof_irrel] <|> try (congr' (nat.pred <$> o))))) add_tactic_doc { name := "congr'", category := doc_category.tactic, decl_names := [`tactic.interactive.congr', `tactic.interactive.congr], tags := ["congruence"], inherit_description_from := `tactic.interactive.congr' } /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), «have» h q₁ q₂, match old, q₂ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end add_tactic_doc { name := "replace", category := doc_category.tactic, decl_names := [`tactic.interactive.replace], tags := ["context management"] } /-- Make every proposition in the context decidable. -/ meta def classical := tactic.classical add_tactic_doc { name := "classical", category := doc_category.tactic, decl_names := [`tactic.interactive.classical], tags := ["classical logic", "type class"] } private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux @[nolint def_lemma] lemma {u} generalize_a_aux {α : Sort u} (h : ∀ x : Sort u, (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if ¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end add_tactic_doc { name := "generalize_hyp", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize_hyp], tags := ["context management"] } /-- The `exact e` and `refine e` tactics require a term `e` whose type is definitionally equal to the goal. `convert e` is similar to `refine e`, but the type of `e` is not required to exactly match the goal. Instead, new goals are created for differences between the type of `e` and the goal. For example, in the proof state ```lean n : ℕ, e : prime (2 * n + 1) ⊢ prime (n + n + 1) ``` the tactic `convert e` will change the goal to ```lean ⊢ n + n = 2 * n ``` In this example, the new goal can be solved using `ring`. The syntax `convert ← e` will reverse the direction of the new goals (producing `⊢ 2 * n = n + n` in this example). Internally, `convert e` works by creating a new goal asserting that the goal equals the type of `e`, then simplifying it using `congr'`. The syntax `convert e using n` can be used to control the depth of matching (like `congr' n`). In the example, `convert e using 1` would produce a new goal `⊢ n + n + 1 = 2 * n + 1`. -/ meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := do v ← mk_mvar, if sym.is_some then refine ``(eq.mp %%v %%r) else refine ``(eq.mpr %%v %%r), gs ← get_goals, set_goals [v], try (congr' n), gs' ← get_goals, set_goals $ gs' ++ gs add_tactic_doc { name := "convert", category := doc_category.tactic, decl_names := [`tactic.interactive.convert], tags := ["congruence"] } meta def compact_decl_aux : list name → binder_info → expr → list expr → tactic (list (list name × binder_info × expr)) | ns bi t [] := pure [(ns.reverse, bi, t)] | ns bi t (v'@(local_const n pp bi' t') :: xs) := do t' ← get_local pp >>= infer_type, if bi = bi' ∧ t = t' then compact_decl_aux (pp :: ns) bi t xs else do vs ← compact_decl_aux [pp] bi' t' xs, pure $ (ns.reverse, bi, t) :: vs | ns bi t (_ :: xs) := compact_decl_aux ns bi t xs /-- go from (x₀ : t₀) (x₁ : t₀) (x₂ : t₀) to (x₀ x₁ x₂ : t₀) -/ meta def compact_decl : list expr → tactic (list (list name × binder_info × expr)) | [] := pure [] | (v@(local_const n pp bi t) :: xs) := do t ← infer_type v, compact_decl_aux [pp] bi t xs | (_ :: xs) := compact_decl xs meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, fields ← expanded_field_list struct_n, let exp_fields := fields.filter (λ x, x.2 ∈ missing), exp_fields.mmap $ λ ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (expr×structure_instance_info) := do tgt ← target, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd), let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mzip_with (λ (n : name × name) v, do set_goals [v], try (dsimp_target simp_lemmas.mk), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ```lean refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- α : Type u, -- ⊢ α → α → α -- case semigroup, mul_assoc -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` `have_field`, used after `refine_struct _`, poses `field` as a local constant with the type of the field of the current goal: ```lean refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ```lean refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def refine_struct : parse texpr → tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p /-- `guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast to `guard_expr`, this tests strict (syntactic) equality. We use this tactic for writing tests. -/ meta def guard_expr_strict (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (t = e) /-- `guard_target_strict t` fails if the target of the main goal is not syntactically `t`. We use this tactic for writing tests. -/ meta def guard_target_strict (p : parse texpr) : tactic unit := do t ← target, guard_expr_strict t p /-- `guard_hyp_strict h := t` fails if the hypothesis `h` does not have type syntactically equal to `t`. We use this tactic for writing tests. -/ meta def guard_hyp_strict (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p meta def guard_hyp_nums (n : ℕ) : tactic unit := do k ← local_context, guard (n = k.length) <|> fail format!"{k.length} hypotheses found" meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) /-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with error message `msg` (for test writing purposes). -/ meta def success_if_fail_with_msg (tac : tactic.interactive.itactic) := tactic.success_if_fail_with_msg tac meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) meta def field (n : parse ident) (tac : itactic) : tactic unit := do gs ← get_goals, ts ← gs.mmap get_tag, ([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n), set_goals [g.1], tac, done, set_goals $ gs'.map prod.fst /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ```lean refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ```lean refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc add_tactic_doc { name := "refine_struct", category := doc_category.tactic, decl_names := [`tactic.interactive.refine_struct, `tactic.interactive.apply_field, `tactic.interactive.have_field], tags := ["structures"], inherit_description_from := `tactic.interactive.refine_struct } /-- `apply_rules hs n` applies the list of lemmas `hs` and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. `n` is optional, equal to 50 by default. `hs` can contain user attributes: in this case all theorems with this attribute are added to the list of rules. For instance: ```lean @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := -- any of the following lines solve the goal: add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] by apply_rules [mono_rules] by apply_rules mono_rules ``` -/ meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit := tactic.apply_rules hs n add_tactic_doc { name := "apply_rules", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_rules], tags := ["lemma application"] } meta def return_cast (f : option expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) (e x x' eq_h : expr) : tactic (option (expr × expr) × list (expr × expr × expr)) := (do guard (¬ e.has_var), unify x x', u ← mk_meta_univ, f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)], t' ← infer_type e, some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es), infer_type e >>= is_def_eq t, unify f f', return (some (f,t), (e,x',eq_h) :: es)) <|> return (t, es) meta def list_cast_of_aux (x : expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) : expr → tactic (option (expr × expr) × list (expr × expr × expr)) | e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x' | e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h | e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x' | e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h | e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h | e := return (t,es) meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) := (list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e) private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def h_generalize_arg_p : parser (pexpr × name) := with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. - `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`; - `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `α = β`; - `h_generalize! Hx : e == x` reverts `Hx`; - when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ meta def h_generalize (rev : parse (tk "!")?) (h : parse ident_?) (_ : parse (tk ":")) (arg : parse h_generalize_arg_p) (eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) : tactic unit := do let (e,n) := arg, let h' := if h = `_ then none else h, h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string), e ← to_expr e, tgt ← target, ((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found", interactive.generalize h' () (to_pexpr e, n), asm ← get_local h', v ← get_local n, hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]), (eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do h ← if h ≠ `_ then pure h else get_unused_name `h, () <$ note h none eq_h ), hs.mmap' (λ h, do h' ← assert `h h, tactic.exact asm, try (rewrite_target h'), tactic.clear h' ), when h.is_some (do (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm) <|> to_expr ``(heq_of_eq_mp %%eq_h %%asm)) >>= note h' none >> pure ()), tactic.clear asm, when rev.is_some (interactive.revert [n]) add_tactic_doc { name := "h_generalize", category := doc_category.tactic, decl_names := [`tactic.interactive.h_generalize], tags := ["context management"] } /-- `choose a b h using hyp` takes an hypothesis `hyp` of the form `∀ (x : X) (y : Y), ∃ (a : A) (b : B), P x y a b` for some `P : X → Y → A → B → Prop` and outputs into context a function `a : X → Y → A`, `b : X → Y → B` and a proposition `h` stating `∀ (x : X) (y : Y), P x y (a x y) (b x y)`. It presumably also works with dependent versions. Example: ```lean example (h : ∀n m : ℕ, ∃i j, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := ℕ → ℕ → ℕ, guard_hyp j := ℕ → ℕ → ℕ, guard_hyp h := ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n, trivial end ``` -/ meta def choose (first : parse ident) (names : parse ident*) (tgt : parse (tk "using" *> texpr)?) : tactic unit := do tgt ← match tgt with | none := get_local `this | some e := tactic.i_to_expr_strict e end, tactic.choose tgt (first :: names), try (interactive.simp none tt [simp_arg_type.expr ``(exists_prop)] [] (loc.ns $ some <$> names)), try (tactic.clear tgt) add_tactic_doc { name := "choose", category := doc_category.tactic, decl_names := [`tactic.interactive.choose], tags := ["classical logic"] } /-- The goal of `field_simp` is to reduce an expression in a field to an expression of the form `n / d` where neither `n` nor `d` contains any division symbol, just using the simplifier (with a carefully crafted simpset named `field_simps`) to reduce the number of division symbols whenever possible by iterating the following steps: - write an inverse as a division - in any product, move the division to the right - if there are several divisions in a product, group them together at the end and write them as a single division - reduce a sum to a common denominator If the goal is an equality, this simpset will also clear the denominators, so that the proof can normally be concluded by an application of `ring` or `ring_exp`. `field_simp [hx, hy]` is a short form for `simp [-one_div_eq_inv, hx, hy] with field_simps` Note that this naive algorithm will not try to detect common factors in denominators to reduce the complexity of the resulting expression. Instead, it relies on the ability of `ring` to handle complicated expressions in the next step. As always with the simplifier, reduction steps will only be applied if the preconditions of the lemmas can be checked. This means that proofs that denominators are nonzero should be included. The fact that a product is nonzero when all factors are, and that a power of a nonzero number is nonzero, are included in the simpset, but more complicated assertions (especially dealing with sums) should be given explicitly. If your expression is not completely reduced by the simplifier invocation, check the denominators of the resulting expression and provide proofs that they are nonzero to enable further progress. The invocation of `field_simp` removes the lemma `one_div_eq_inv` (which is marked as a simp lemma in core) from the simpset, as this lemma works against the algorithm explained above. For example, ```lean example (a b c d x y : ℂ) (hx : x ≠ 0) (hy : y ≠ 0) : a + b / x + c / x^2 + d / x^3 = a + x⁻¹ * (y * b / y + (d / x + c) / x) := begin field_simp [hx, hy], ring end ``` -/ meta def field_simp (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 := let attr_names := `field_simps :: attr_names, hs := simp_arg_type.except `one_div_eq_inv :: hs in propagate_tags (simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat) add_tactic_doc { name := "field_simp", category := doc_category.tactic, decl_names := [`tactic.interactive.field_simp], tags := ["simplification", "arithmetic"] } meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, is_def_eq t e /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target' (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq' t p add_tactic_doc { name := "guard_target'", category := doc_category.tactic, decl_names := [`tactic.interactive.guard_target'], tags := ["testing"] } /-- a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true, unfolding only `reducible` constants. -/ meta def triv : tactic unit := tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed" add_tactic_doc { name := "triv", category := doc_category.tactic, decl_names := [`tactic.interactive.triv], tags := ["finishing"] } /-- Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`. It will then try to close the new goal using `triv`, or try to simplify it by applying `exists_prop`. Unlike `existsi`, `x` is elaborated with respect to the expected type. `use` will alternatively take a list of terms `[x0, ..., xn]`. `use` will work with constructors of arbitrary inductive types. Examples: ```lean example (α : Type) : ∃ S : set α, S = S := by use ∅ example : ∃ x : ℤ, x = x := by use 42 example : ∃ n > 0, n = n := begin use 1, -- goal is now 1 > 0 ∧ 1 = 1, whereas it would be ∃ (H : 1 > 0), 1 = 1 after existsi 1. exact ⟨zero_lt_one, rfl⟩, end example : ∃ a b c : ℤ, a + b + c = 6 := by use [1, 2, 3] example : ∃ p : ℤ × ℤ, p.1 = 1 := by use ⟨1, 42⟩ example : Σ x y : ℤ, (ℤ × ℤ) × ℤ := by use [1, 2, 3, 4, 5] inductive foo | mk : ℕ → bool × ℕ → ℕ → foo example : foo := by use [100, tt, 4, 3] ``` -/ meta def use (l : parse pexpr_list_or_texpr) : tactic unit := focus1 $ tactic.use l; try (triv <|> (do `(Exists %%p) ← target, to_expr ``(exists_prop.mpr) >>= tactic.apply >> skip)) add_tactic_doc { name := "use", category := doc_category.tactic, decl_names := [`tactic.interactive.use, `tactic.interactive.existsi], tags := ["logic"], inherit_description_from := `tactic.interactive.use } /-- `clear_aux_decl` clears every `aux_decl` in the local context for the current goal. This includes the induction hypothesis when using the equation compiler and `_let_match` and `_fun_match`. It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these auxiliary declarations, and produce an error saying the recursion is not well founded. ```lean example (n m : ℕ) (h₁ : n = m) (h₂ : ∃ a : ℕ, a = n ∧ a = m) : 2 * m = 2 * n := let ⟨a, ha⟩ := h₂ in begin clear_aux_decl, -- subst will fail without this line subst h₁ end example (x y : ℕ) (h₁ : ∃ n : ℕ, n * 1 = 2) (h₂ : 1 + 1 = 2 → x * 1 = y) : x = y := let ⟨n, hn⟩ := h₁ in begin clear_aux_decl, -- finish produces an error without this line finish end ``` -/ meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl add_tactic_doc { name := "clear_aux_decl", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_aux_decl, `tactic.clear_aux_decl], tags := ["context management"], inherit_description_from := `tactic.interactive.clear_aux_decl } meta def loc.get_local_pp_names : loc → tactic (list name) | loc.wildcard := list.map expr.local_pp_name <$> local_context | (loc.ns l) := return l.reduce_option meta def loc.get_local_uniq_names (l : loc) : tactic (list name) := list.map expr.local_uniq_name <$> l.get_locals /-- The logic of `change x with y at l` fails when there are dependencies. `change'` mimics the behavior of `change`, except in the case of `change x with y at l`. In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses in `l`. As long as `x` and `y` are defeq, it should never fail. -/ meta def change' (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do l' ← loc.get_local_pp_names l, l'.mmap' (λ e, try (change_with_at q w e)), when l.include_goal $ change q w (loc.ns [none]) add_tactic_doc { name := "change'", category := doc_category.tactic, decl_names := [`tactic.interactive.change', `tactic.interactive.change], tags := ["renaming"], inherit_description_from := `tactic.interactive.change' } meta def convert_to_core (r : pexpr) : tactic unit := do tgt ← target, h ← to_expr ``(_ : %%tgt = %%r), rewrite_target h, swap /-- `convert_to g using n` attempts to change the current goal to `g`, but unlike `change`, it will generate equality proof obligations using `congr' n` to resolve discrepancies. `convert_to g` defaults to using `congr' 1`. `ac_change` is `convert_to` followed by `ac_refl`. It is useful for rearranging/reassociating e.g. sums: ```lean example (a b c d e f g N : ℕ) : (a + b) + (c + d) + (e + f) + g ≤ N := begin ac_change a + d + e + f + c + g + b ≤ _, -- ⊢ a + d + e + f + c + g + b ≤ N end ``` -/ meta def convert_to (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := match n with | none := convert_to_core r >> `[congr' 1] | (some 0) := convert_to_core r | (some o) := convert_to_core r >> congr' o end /-- `ac_change g using n` is `convert_to g using n; try {ac_refl}`. -/ meta def ac_change (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := convert_to r n; try ac_refl add_tactic_doc { name := "convert_to", category := doc_category.tactic, decl_names := [`tactic.interactive.convert_to, `tactic.interactive.ac_change], tags := ["congruence"], inherit_description_from := `tactic.interactive.convert_to } private meta def opt_dir_with : parser (option (bool × name)) := (do tk "with", arrow ← (tk "<-")?, h ← ident, return (arrow.is_some, h)) <|> return none /-- `set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. `set a := t with ←h` will add `h : t = a` instead. `set! a := t with h` does not do any replacing. ```lean example (x : ℕ) (h : x = 3) : x + x + x = 9 := begin set y := x with ←h_xy, /- x : ℕ, y : ℕ := x, h_xy : x = y, h : y = 3 ⊢ y + y + y = 9 -/ end ``` -/ meta def set (h_simp : parse (tk "!")?) (a : parse ident) (tp : parse ((tk ":") >> texpr)?) (_ : parse (tk ":=")) (pv : parse texpr) (rev_name : parse opt_dir_with) := do let vt := match tp with | some t := t | none := pexpr.mk_placeholder end, let pv := ``(%%pv : %%vt), v ← to_expr pv, tp ← infer_type v, definev a tp v, when h_simp.is_none $ change' pv (some (expr.const a [])) loc.wildcard, match rev_name with | some (flip, id) := do nv ← get_local a, pf ← to_expr (cond flip ``(%%pv = %%nv) ``(%%nv = %%pv)) >>= assert id, reflexivity | none := skip end add_tactic_doc { name := "set", category := doc_category.tactic, decl_names := [`tactic.interactive.set], tags := ["context management"] } /-- `clear_except h₀ h₁` deletes all the assumptions it can except for `h₀` and `h₁`. -/ meta def clear_except (xs : parse ident *) : tactic unit := do n ← xs.mmap (try_core ∘ get_local) >>= revert_lst ∘ list.filter_map id, ls ← local_context, ls.reverse.mmap' $ try ∘ tactic.clear, intron n add_tactic_doc { name := "clear_except", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_except], tags := ["context management"] } meta def format_names (ns : list name) : format := format.join $ list.intersperse " " (ns.map to_fmt) private meta def indent_bindents (l r : string) : option (list name) → expr → tactic format | none e := do e ← pp e, pformat!"{l}{format.nest l.length e}{r}" | (some ns) e := do e ← pp e, let ns := format_names ns, let margin := l.length + ns.to_string.length + " : ".length, pformat!"{l}{ns} : {format.nest margin e}{r}" private meta def format_binders : list name × binder_info × expr → tactic format | (ns, binder_info.default, t) := indent_bindents "(" ")" ns t | (ns, binder_info.implicit, t) := indent_bindents "{" "}" ns t | (ns, binder_info.strict_implicit, t) := indent_bindents "⦃" "⦄" ns t | ([n], binder_info.inst_implicit, t) := if "_".is_prefix_of n.to_string then indent_bindents "[" "]" none t else indent_bindents "[" "]" [n] t | (ns, binder_info.inst_implicit, t) := indent_bindents "[" "]" ns t | (ns, binder_info.aux_decl, t) := indent_bindents "(" ")" ns t private meta def partition_vars' (s : name_set) : list expr → list expr → list expr → tactic (list expr × list expr) | [] as bs := pure (as.reverse, bs.reverse) | (x :: xs) as bs := do t ← infer_type x, if t.has_local_in s then partition_vars' xs as (x :: bs) else partition_vars' xs (x :: as) bs private meta def partition_vars : tactic (list expr × list expr) := do ls ← local_context, partition_vars' (name_set.of_list $ ls.map expr.local_uniq_name) ls [] [] /-- Format the current goal as a stand-alone example. Useful for testing tactic. * `extract_goal`: formats the statement as an `example` declaration * `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration called `my_decl` * `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration Examples: ```lean example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := begin extract_goal, -- prints: -- example {i j k : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- end extract_goal my_lemma -- lemma my_lemma {i j k : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- end end example {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k := begin extract_goal my_lemma, -- prints: -- lemma my_lemma {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) -- (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k := -- begin -- end extract_goal my_lemma with i j k -- prints: -- lemma my_lemma {i j k : ℕ} : i ≤ k := -- begin -- end end ``` -/ meta def extract_goal (print_use : parse $ tt <$ tk "!" <|> pure ff) (n : parse ident?) (vs : parse with_ident_list) : tactic unit := do tgt ← target, ((cxt₀,cxt₁),_) ← solve_aux tgt $ when (¬ vs.empty) (clear_except vs) >> partition_vars, tgt ← target, is_prop ← is_prop tgt, let title := match n, is_prop with | none, _ := to_fmt "example" | (some n), tt := format!"lemma {n}" | (some n), ff := format!"def {n}" end, cxt₀ ← compact_decl cxt₀ >>= list.mmap format_binders, cxt₁ ← compact_decl cxt₁ >>= list.mmap format_binders, stmt ← pformat!"{tgt} :=", let fmt := format.group $ format.nest 2 $ title ++ cxt₀.foldl (λ acc x, acc ++ format.group (format.line ++ x)) "" ++ format.line ++ format.intercalate format.line cxt₁ ++ " :" ++ format.line ++ stmt, trace $ fmt.to_string $ options.mk.set_nat `pp.width 80, trace!"begin\n admit\nend\n" add_tactic_doc { name := "extract_goal", category := doc_category.tactic, decl_names := [`tactic.interactive.extract_goal], tags := ["goal management", "proof extraction"] } /-- `inhabit α` tries to derive a `nonempty α` instance and then upgrades this to an `inhabited α` instance. If the target is a `Prop`, this is done constructively; otherwise, it uses `classical.choice`. ```lean example (α) [nonempty α] : ∃ a : α, true := begin inhabit α, existsi default α, trivial end ``` -/ meta def inhabit (t : parse parser.pexpr) (inst_name : parse ident?) : tactic unit := do ty ← i_to_expr t, nm ← get_unused_name `inst, mcond (target >>= is_prop) (do mk_mapp `nonempty.elim_to_inhabited [ty, none] >>= tactic.apply <|> fail "could not infer nonempty instance", introI $ inst_name.get_or_else nm) (do mk_mapp `classical.inhabited_of_nonempty' [ty, none] >>= note nm none <|> fail "could not infer nonempty instance", resetI) add_tactic_doc { name := "inhabit", category := doc_category.tactic, decl_names := [`tactic.interactive.inhabit], tags := ["context management", "type class"] } /-- `revert_deps n₁ n₂ ...` reverts all the hypotheses that depend on one of `n₁, n₂, ...` It does not revert `n₁, n₂, ...` themselves (unless they depend on another `nᵢ`). -/ meta def revert_deps (ns : parse ident*) : tactic unit := propagate_tags $ ns.reverse.mmap' $ λ n, get_local n >>= tactic.revert_deps add_tactic_doc { name := "revert_deps", category := doc_category.tactic, decl_names := [`tactic.interactive.revert_deps], tags := ["context management", "goal management"] } /-- `revert_after n` reverts all the hypotheses after `n`. -/ meta def revert_after (n : parse ident) : tactic unit := propagate_tags $ get_local n >>= tactic.revert_after >> skip add_tactic_doc { name := "revert_after", category := doc_category.tactic, decl_names := [`tactic.interactive.revert_after], tags := ["context management", "goal management"] } /-- `clear_value n₁ n₂ ...` clears the bodies of the local definitions `n₁, n₂ ...`, changing them into regular hypotheses. A hypothesis `n : α := t` is changed to `n : α`. -/ meta def clear_value (ns : parse ident*) : tactic unit := propagate_tags $ ns.reverse.mmap' $ λ n, get_local n >>= tactic.clear_value add_tactic_doc { name := "clear_value", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_value], tags := ["context management"] } /-- `generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize' h : e = x` in addition registers the hypothesis `h : e = x`. `generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also succeeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis `x` is not a local definition. -/ meta def generalize' (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit := propagate_tags $ do let (p, x) := p, e ← i_to_expr p, some h ← pure h | tactic.generalize' e x >> skip, tgt ← target, -- if generalizing fails, fall back to not replacing anything tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize' e x >> target), to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Π x, %%e = x → %%tgt), t ← assert h tgt', swap, exact ``(%%t %%e rfl), intro x, intro h add_tactic_doc { name := "generalize'", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize'], tags := ["context management"] } end interactive end tactic
1b5872d538d531b13709ad8908b51ebefed9b378
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/data/buffer.lean
50726917fad6a2167e0a7209280145de2abb1d5c
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
4,118
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 char) : string := b.to_array.to_list.as_string 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.to_list 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
63474fade54206148d3b8a2f853c14a5516f27a1
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/backtrackable_estate.lean
16c1365e37c789376c4ff28988c8538962682bdf
[ "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
700
lean
import Init.System.IO new_frontend structure MyState := (bs : Nat := 0) -- backtrackable state (ps : Nat := 0) -- non backtrackable state instance : HasRepr MyState := ⟨fun s => repr (s.bs, s.ps)⟩ instance : EStateM.Backtrackable Nat MyState := { save := fun s => s.bs, restore := fun s d => { s with bs := d } } abbrev M := EStateM String MyState def bInc : M Unit := -- increment backtrackble counter modify $ fun s => { s with bs := s.bs + 1 } def pInc : M Unit := -- increment nonbacktrackable counter modify $ fun s => { s with ps := s.ps + 1 } def tst : M MyState := do bInc; pInc; ((bInc *> throw "failed") <|> pInc); pInc; get #eval tst.run' {} -- (some (1, 3))
914182dba5ab54164ec4b75dc502951cd4d776d9
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
/Exercises 8/31_exercise_sheet.lean
28563d22f44f7ffad094468fce0de5a6455b185b
[]
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
11,413
lean
/- Exercise 3.1: Program Semantics — Operational Semantics -/ /- We start by repeating some material from the lecture. We use the same `program` syntax and the big-step semantics as presented in the lecture. -/ attribute [pattern] or.intro_left or.intro_right inductive program (σ : Type) : Type | skip {} : program | assign : (σ → σ) → program | seq : program → program → program | ite : (σ → Prop) → program → program → program | while : (σ → Prop) → program → program namespace program variables {σ : Type} {c : σ → Prop} {f : σ → σ} {p p₀ p₁ p₂ : program σ} {s s₀ s₁ s₂ t u : σ} inductive big_step : (program σ × σ) → σ → Prop | skip {s} : big_step (skip, s) s | assign {f s} : big_step (assign f, s) (f s) | seq {p₁ p₂ s u} (t) (h₁ : big_step (p₁, s) t) (h₂ : big_step (p₂, t) u) : big_step (seq p₁ p₂, s) u | ite_true {c : σ → Prop} {p₁ p₀ s t} (hs : c s) (h : big_step (p₁, s) t) : big_step (ite c p₁ p₀, s) t | ite_false {c : σ → Prop} {p₁ p₀ s t} (hs : ¬ c s) (h : big_step (p₀, s) t) : big_step (ite c p₁ p₀, s) t | while_true {c : σ → Prop} {p s u} (t) (hs : c s) (hp : big_step (p, s) t) (hw : big_step (while c p, t) u) : big_step (while c p, s) u | while_false {c : σ → Prop} {p s} (hs : ¬ c s) : big_step (while c p, s) s infix ` ⟹ `:110 := big_step /- We copy also the inversion rules from the lecture. Do not prove these. -/ @[simp] lemma big_step_skip_iff : (skip, s) ⟹ t ↔ t = s := sorry @[simp] lemma big_step_assign_iff : (assign f, s) ⟹ t ↔ t = f s := sorry @[simp] lemma big_step_seq_iff : (seq p₁ p₂, s) ⟹ t ↔ (∃u, (p₁, s) ⟹ u ∧ (p₂, u) ⟹ t) := sorry @[simp] lemma big_step_ite_iff : (ite c p₁ p₀, s) ⟹ t ↔ ((c s ∧ (p₁, s) ⟹ t) ∨ (¬ c s ∧ (p₀, s) ⟹ t)) := sorry lemma big_step_while_iff : (while c p, s) ⟹ t ↔ (∃u, c s ∧ (p, s) ⟹ u ∧ (while c p, u) ⟹ t) ∨ (¬ c s ∧ t = s) := sorry @[simp] lemma big_step_while_true_iff (hs : c s) : (while c p, s) ⟹ t ↔ (∃u, (p, s) ⟹ u ∧ (while c p, u) ⟹ t) := sorry @[simp] lemma big_step_while_false_iff (hs : ¬ c s) : (while c p, s) ⟹ t ↔ t = s := sorry /- Question 1: Program equivalence -/ /- For this question, we introduce the notation of program equivalence `p₁ ≈ p₂`. `≈` is entered as `\approx`. -/ def program_equiv (p₁ p₂ : program σ) : Prop := ∀s t, (p₁, s) ⟹ t ↔ (p₂, s) ⟹ t local infix ` ≈ ` := program_equiv /- Program equivalence is a equivalence relation, i.e. it is reflexive, symmetric, and transitive. -/ @[refl] lemma program_equiv.refl : p ≈ p := assume s t, by refl @[symm] lemma program_equiv.symm : p₁ ≈ p₂ → p₂ ≈ p₁ := assume h s t, (h s t).symm @[trans] lemma program_equiv.trans {p₃} (h₁₂ : p₁ ≈ p₂) (h₂₃ : p₂ ≈ p₃) : p₁ ≈ p₃ := assume s t, iff.trans (h₁₂ s t) (h₂₃ s t) /- 1.1. Prove the following program equivalences. -/ lemma program_equiv_seq_skip1 {p : program σ} : seq skip p ≈ p := begin intros s t, apply iff.intro, intro h, cases h, cases h_h₁, assumption, intro h, apply big_step.seq s, end lemma program_equiv_seq_skip2 {p : program σ} : seq p skip ≈ p := begin intros s t, apply iff.intro, intro h, cases h, cases h_h₂, assumption, intro h, apply big_step.seq t, assumption, apply big_step.skip end lemma program_equiv_seq_congr {p₁ p₂ p₃ p₄ : program σ} (h₁₂ : p₁ ≈ p₂) (h₃₄ : p₃ ≈ p₄) : seq p₁ p₃ ≈ seq p₂ p₄ := begin intros s t, apply iff.intro, intro h, apply big_step.seq t, cases h, apply big_step.seq h_t h₁₂ h_h₁, end lemma program_equiv.ite_seq_while : ite c (seq p (while c p)) skip ≈ while c p := begin intros s t, apply iff.intro, intro h, cases h, cases h_h, apply big_step.while_true h_h_t h_hs h_h_h₁ h_h_h₂, cases h_h, apply big_step.while_false h_hs, intro h, cases h, apply big_step.ite_true h_hs, apply big_step.seq h_t h_hp h_hw, apply big_step.ite_false h_hs, apply big_step.skip end lemma program_equiv.ite_seq_while' : ite c (seq p (while c p)) skip ≈ while c p := begin intros s t, apply iff.intro, intro h, cases h, cases h_h, apply big_step.while_true h_h_t h_hs h_h_h₁ h_h_h₂, cases h_h, apply big_step.while_false, assumption, intro h, cases h, apply big_step.ite_true h_hs, apply big_step.seq h_t h_hp h_hw, apply big_step.ite_false, assumption, apply big_step.skip end /- 1.2. Prove one more equivalence. `@id σ` is the identity function on states. -/ lemma program_equiv.skip_assign_id : assign (@id σ) ≈ skip := sorry /- 1.3. Why do you think `@id σ` is necessary, as opposed to `id`? -/ /- Answer: enter your answer here. -/ example {p p' : program σ} : seq (while (λ_, true) p) p' ≈ while (λ_, true) p := begin intros l t, apply iff.intro, intro s, cases s, apply big_step.while_true s_t s_h₁ s_h₂, end end program /- Question 2: The guarded command language (GCL) -/ /- In 1976, E. W. Dijkstra introduced the guarded command language, as a language with built-in nondeterminism. Its grammar is as follows: p ::= x := e -- assignment | assert b -- assertion | p ; p -- sequential composition | p | ... | p -- nondeterministic choice | loop p -- nondeterministic iteration Assignment and sequential composition are as in the WHILE language. The other statements have the following semantics: * `assert b` aborts if `b` evaluates to false; otherwise, the command is a no-op. * `p | ... | p` chooses **any** of the branches and executes it, ignoring the other branches. * `loop p` executes `p` **any** number of times. In Lean, GCL is captured by the following inductive type: -/ inductive gcl (σ : Type) : Type | assign : (σ → σ) → gcl | assert : (σ → Prop) → gcl | seq : gcl → gcl → gcl | choice : list gcl → gcl | loop : gcl → gcl namespace gcl variable {σ : Type} variables {c : σ → Prop} {f : σ → σ} {p p₀ p₁ p₂ : gcl σ} {ps : list (gcl σ)} {s s₀ s₁ s₂ t u : σ} /- The big-step semantics is defined as follows: -/ inductive big_step : (gcl σ × σ) → σ → Prop | assign {f s} : big_step (assign f, s) (f s) | assert {c : σ → Prop} {s} (hs : c s) : big_step (assert c, s) s | seq {p₁ p₂ s u} (t) (h₁ : big_step (p₁, s) t) (h₂ : big_step (p₂, t) u) : big_step (seq p₁ p₂, s) u | choice {ps : list (gcl σ)} {s t} (i : ℕ) (hi : i < list.length ps) (h : big_step (list.nth_le ps i hi, s) t) : big_step (choice ps, s) t | loop_base {p s} : big_step (loop p, s) s | loop_step {p s t} (u) (h₁ : big_step (p, s) u) (h₂ : big_step (loop p, u) t) : big_step (loop p, s) t /- Some convenience syntax: -/ infix ` ~> `:110 := big_step /- 2.1. Prove the following inversion rules, as we did in the lecture for the WHILE language. -/ @[simp] lemma big_step_assign : (assign f, s) ~> t ↔ t = f s := begin apply iff.intro, intro h, cases h, trivial, intro h, cases h, apply big_step.assign end @[simp] lemma big_step_assert : (assert c, s) ~> t ↔ (t = s ∧ c s) := begin apply iff.intro, intro h, cases h, apply and.intro, trivial, assumption, intro h, cases h, cases h_left, apply big_step.assert h_right end @[simp] lemma big_step_seq : (seq p₁ p₂, s) ~> t ↔ (∃u, (p₁, s) ~> u ∧ (p₂, u) ~> t) := begin apply iff.intro, intro h, cases h, apply exists.intro h_t, apply and.intro, assumption, assumption, intro h, cases h, cases h_h, apply big_step.seq h_w h_h_left h_h_right end lemma big_step_loop : (loop p, s) ~> t ↔ (s = t ∨ (∃u, (p, s) ~> u ∧ (loop p, u) ~> t)) := begin apply iff.intro, intro h, cases h, apply or.intro_left, trivial, apply or.intro_right, apply exists.intro h_u, apply and.intro, repeat{assumption}, intro h, cases h, cases h, exact big_step.loop_base, cases h, cases h_h, exact big_step.loop_step h_w h_h_left h_h_right end @[simp] lemma big_step_choice : (choice ps, s) ~> t ↔ (∃(i : ℕ) (hi : i < list.length ps), (list.nth_le ps i hi, s) ~> t) := begin apply iff.intro, intro h, apply exists.intro, apply exists.intro, cases h, end /- 2.2. Fill in the translation below of a deterministic program to a GCL program, by filling in the `sorry` placeholders below. -/ -- def of_program : program σ → gcl σ -- | program.skip := assign id -- | (program.assign f) := assign f -- | (program.seq p₁ p₂) := -- seq (of_program p₁) (of_program p₂) -- | (program.ite c p₁ p₂) := -- choice [ -- seq (assert c) (of_program p₁), -- seq (assert (λs, ¬ c s)) (of_program p₂) -- ] -- | (program.while c p) := seq (loop (seq (assert c) (of_program p))) (assert (λs, ¬ c s)) -- inductive program (σ : Type) : Type -- | skip {} : program -- | assign : (σ → σ) → program -- | seq : program → program → program -- | ite : (σ → Prop) → program → program → program -- | while : (σ → Prop) → program → program -- inductive gcl (σ : Type) : Type -- | assign : (σ → σ) → gcl -- | assert : (σ → Prop) → gcl -- | seq : gcl → gcl → gcl -- | choice : list gcl → gcl -- | loop : gcl → gcl def of_program : program σ → gcl σ | program.skip := assign id | (program.assign f) := assign f | (program.seq f s) := seq (of_program f) (of_program s) | (program.ite c p1 p2) := choice [seq (assert c) (of_program p1), seq(assert (λs,¬c s)) (of_program p2)] | (program.while c p) := seq(loop(seq(assert c) (of_program p))) (assert(λs, ¬ c s)) /- 2.3. Prove that `of_program` is correct, in the sense that whenever the deterministic program `p` can make a big step, the corresponding GCL program makes a big step. This is a difficult exercise. Try to get as far as possible. **Hints:** * In the each induction subgoal, use `cases h` on an equality `h : (p, s) = (q, t)`. When one side is a variable, it will be replaced by the other side. In our case, one side is always a variable. * Use `specialize h rfl` to instantiate a hypothesis, i.e. to replace a hypothesis of the form `h : ∀{x y}, (x, y) = (p, s) → q x y` with `h : q p s`. * At some point you need to prove statements such as `0 < 1 + 1`. Here, you can use use the `dec_trival` proof term (e.g. in tactic mode, you must write `exact dec_trivial`) * You need to use `cases` in the `while_true` case, to cope with a hypothesis of the form `h : of_program (while c p, s) ~> t`. This breaks the hypothesis down and will allow you to retrieve the intermediate states and steps. * You may want to use lemmas from the `program` namespace, e.g. the inversion rules (`program.big_step_while_iff`, etc.). -/ lemma big_step_of_program {p : program σ} {s t} : (p, s) ⟹ t → (of_program p, s) ~> t := begin /- The term `(p, s)` needs to be replaced by a variable. We use the same tools as in the lecture: * `generalize` replaces a term in our goal by a new variable and an equality assumption. * `generalizing p s` tells the `induction` tactic that `p` and `s` should be quantified. -/ generalize eq : (p, s) = ps, intro h, induction h generalizing p s; cases eq; clear eq, { simp [of_program] }, { sorry }, { sorry }, { sorry }, { sorry }, { sorry }, { sorry } end end gcl
873b40428d95df86c64bba11d6c88f7e99c58ccf
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/algebra/category/yoneda.hlean
00152c60ec9390db5a518d8e15eff1c27274ded3
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,266
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ --note: modify definition in category.set import .constructions.functor .constructions.hset .constructions.product .constructions.opposite .adjoint open category eq category.ops functor prod.ops is_trunc iso namespace yoneda -- set_option class.conservative false definition representable_functor_assoc [C : Precategory] {a1 a2 a3 a4 a5 a6 : C} (f1 : hom a5 a6) (f2 : hom a4 a5) (f3 : hom a3 a4) (f4 : hom a2 a3) (f5 : hom a1 a2) : (f1 ∘ f2) ∘ f3 ∘ (f4 ∘ f5) = f1 ∘ (f2 ∘ f3 ∘ f4) ∘ f5 := calc _ = f1 ∘ f2 ∘ f3 ∘ f4 ∘ f5 : by rewrite -assoc ... = f1 ∘ (f2 ∘ f3) ∘ f4 ∘ f5 : by rewrite -assoc ... = f1 ∘ ((f2 ∘ f3) ∘ f4) ∘ f5 : by rewrite -(assoc (f2 ∘ f3) _ _) ... = _ : by rewrite (assoc f2 f3 f4) definition hom_functor.{u v} [constructor] (C : Precategory.{u v}) : Cᵒᵖ ×c C ⇒ set.{v} := functor.mk (λ (x : Cᵒᵖ ×c C), @homset (Cᵒᵖ) C x.1 x.2) (λ (x y : Cᵒᵖ ×c C) (f : @category.precategory.hom (Cᵒᵖ ×c C) (Cᵒᵖ ×c C) x y) (h : @homset (Cᵒᵖ) C x.1 x.2), f.2 ∘[C] (h ∘[C] f.1)) (λ x, @eq_of_homotopy _ _ _ (ID (@homset Cᵒᵖ C x.1 x.2)) (λ h, concat (by apply @id_left) (by apply @id_right))) (λ x y z g f, eq_of_homotopy (by intros; apply @representable_functor_assoc)) end yoneda open is_equiv equiv namespace functor open prod nat_trans variables {C D E : Precategory} (F : C ×c D ⇒ E) (G : C ⇒ E ^c D) definition functor_curry_ob [reducible] [constructor] (c : C) : E ^c D := functor.mk (λd, F (c,d)) (λd d' g, F (id, g)) (λd, !respect_id) (λd₁ d₂ d₃ g' g, calc F (id, g' ∘ g) = F (id ∘ id, g' ∘ g) : by rewrite id_id ... = F ((id,g') ∘ (id, g)) : by esimp ... = F (id,g') ∘ F (id, g) : by rewrite respect_comp) local abbreviation Fob := @functor_curry_ob definition functor_curry_hom [constructor] ⦃c c' : C⦄ (f : c ⟶ c') : Fob F c ⟹ Fob F c' := begin fapply @nat_trans.mk, {intro d, exact F (f, id)}, {intro d d' g, calc F (id, g) ∘ F (f, id) = F (id ∘ f, g ∘ id) : respect_comp F ... = F (f, g ∘ id) : by rewrite id_left ... = F (f, g) : by rewrite id_right ... = F (f ∘ id, g) : by rewrite id_right ... = F (f ∘ id, id ∘ g) : by rewrite id_left ... = F (f, id) ∘ F (id, g) : (respect_comp F (f, id) (id, g))⁻¹ᵖ } end local abbreviation Fhom := @functor_curry_hom theorem functor_curry_hom_def ⦃c c' : C⦄ (f : c ⟶ c') (d : D) : (Fhom F f) d = to_fun_hom F (f, id) := idp theorem functor_curry_id (c : C) : Fhom F (ID c) = nat_trans.id := nat_trans_eq (λd, respect_id F _) theorem functor_curry_comp ⦃c c' c'' : C⦄ (f' : c' ⟶ c'') (f : c ⟶ c') : Fhom F (f' ∘ f) = Fhom F f' ∘n Fhom F f := begin apply @nat_trans_eq, intro d, calc natural_map (Fhom F (f' ∘ f)) d = F (f' ∘ f, id) : by rewrite functor_curry_hom_def ... = F (f' ∘ f, id ∘ id) : by rewrite id_id ... = F ((f',id) ∘ (f, id)) : by esimp ... = F (f',id) ∘ F (f, id) : by rewrite [respect_comp F] ... = natural_map ((Fhom F f') ∘ (Fhom F f)) d : by esimp end definition functor_curry [reducible] [constructor] : C ⇒ E ^c D := functor.mk (functor_curry_ob F) (functor_curry_hom F) (functor_curry_id F) (functor_curry_comp F) definition functor_uncurry_ob [reducible] (p : C ×c D) : E := to_fun_ob (G p.1) p.2 local abbreviation Gob := @functor_uncurry_ob definition functor_uncurry_hom ⦃p p' : C ×c D⦄ (f : hom p p') : Gob G p ⟶ Gob G p' := to_fun_hom (to_fun_ob G p'.1) f.2 ∘ natural_map (to_fun_hom G f.1) p.2 local abbreviation Ghom := @functor_uncurry_hom theorem functor_uncurry_id (p : C ×c D) : Ghom G (ID p) = id := calc Ghom G (ID p) = to_fun_hom (to_fun_ob G p.1) id ∘ natural_map (to_fun_hom G id) p.2 : by esimp ... = id ∘ natural_map (to_fun_hom G id) p.2 : by rewrite respect_id ... = id ∘ natural_map nat_trans.id p.2 : by rewrite respect_id ... = id : id_id theorem functor_uncurry_comp ⦃p p' p'' : C ×c D⦄ (f' : p' ⟶ p'') (f : p ⟶ p') : Ghom G (f' ∘ f) = Ghom G f' ∘ Ghom G f := calc Ghom G (f' ∘ f) = to_fun_hom (to_fun_ob G p''.1) (f'.2 ∘ f.2) ∘ natural_map (to_fun_hom G (f'.1 ∘ f.1)) p.2 : by esimp ... = (to_fun_hom (to_fun_ob G p''.1) f'.2 ∘ to_fun_hom (to_fun_ob G p''.1) f.2) ∘ natural_map (to_fun_hom G (f'.1 ∘ f.1)) p.2 : by rewrite respect_comp ... = (to_fun_hom (to_fun_ob G p''.1) f'.2 ∘ to_fun_hom (to_fun_ob G p''.1) f.2) ∘ natural_map (to_fun_hom G f'.1 ∘ to_fun_hom G f.1) p.2 : by rewrite respect_comp ... = (to_fun_hom (to_fun_ob G p''.1) f'.2 ∘ to_fun_hom (to_fun_ob G p''.1) f.2) ∘ (natural_map (to_fun_hom G f'.1) p.2 ∘ natural_map (to_fun_hom G f.1) p.2) : by esimp ... = (to_fun_hom (to_fun_ob G p''.1) f'.2 ∘ natural_map (to_fun_hom G f'.1) p'.2) ∘ (to_fun_hom (to_fun_ob G p'.1) f.2 ∘ natural_map (to_fun_hom G f.1) p.2) : by rewrite [square_prepostcompose (!naturality⁻¹ᵖ) _ _] ... = Ghom G f' ∘ Ghom G f : by esimp definition functor_uncurry [reducible] [constructor] : C ×c D ⇒ E := functor.mk (functor_uncurry_ob G) (functor_uncurry_hom G) (functor_uncurry_id G) (functor_uncurry_comp G) theorem functor_uncurry_functor_curry : functor_uncurry (functor_curry F) = F := functor_eq (λp, ap (to_fun_ob F) !prod.eta) begin intro cd cd' fg, cases cd with c d, cases cd' with c' d', cases fg with f g, transitivity to_fun_hom (functor_uncurry (functor_curry F)) (f, g), apply id_leftright, show (functor_uncurry (functor_curry F)) (f, g) = F (f,g), from calc (functor_uncurry (functor_curry F)) (f, g) = to_fun_hom F (id, g) ∘ to_fun_hom F (f, id) : by esimp ... = F (id ∘ f, g ∘ id) : by krewrite [-respect_comp F (id,g) (f,id)] ... = F (f, g ∘ id) : by rewrite id_left ... = F (f,g) : by rewrite id_right, end definition functor_curry_functor_uncurry_ob (c : C) : functor_curry (functor_uncurry G) c = G c := begin fapply functor_eq, {intro d, reflexivity}, {intro d d' g, apply concat, apply id_leftright, show to_fun_hom (functor_curry (functor_uncurry G) c) g = to_fun_hom (G c) g, from calc to_fun_hom (functor_curry (functor_uncurry G) c) g = to_fun_hom (G c) g ∘ natural_map (to_fun_hom G (ID c)) d : by esimp ... = to_fun_hom (G c) g ∘ natural_map (ID (G c)) d : by rewrite respect_id ... = to_fun_hom (G c) g ∘ id : by reflexivity ... = to_fun_hom (G c) g : by rewrite id_right} end theorem functor_curry_functor_uncurry : functor_curry (functor_uncurry G) = G := begin fapply functor_eq, exact (functor_curry_functor_uncurry_ob G), intro c c' f, fapply nat_trans_eq, intro d, apply concat, {apply (ap (λx, x ∘ _)), apply concat, apply natural_map_hom_of_eq, apply (ap hom_of_eq), apply ap010_functor_eq}, apply concat, {apply (ap (λx, _ ∘ x)), apply (ap (λx, _ ∘ x)), apply concat, apply natural_map_inv_of_eq, apply (ap (λx, hom_of_eq x⁻¹)), apply ap010_functor_eq}, apply concat, apply id_leftright, apply concat, apply (ap (λx, x ∘ _)), apply respect_id, apply id_left end definition prod_functor_equiv_functor_functor [constructor] (C D E : Precategory) : (C ×c D ⇒ E) ≃ (C ⇒ E ^c D) := equiv.MK functor_curry functor_uncurry functor_curry_functor_uncurry functor_uncurry_functor_curry definition functor_prod_flip [constructor] (C D : Precategory) : C ×c D ⇒ D ×c C := functor.mk (λp, (p.2, p.1)) (λp p' h, (h.2, h.1)) (λp, idp) (λp p' p'' h' h, idp) definition functor_prod_flip_functor_prod_flip (C D : Precategory) : functor_prod_flip D C ∘f (functor_prod_flip C D) = functor.id := begin fapply functor_eq, {intro p, apply prod.eta}, intro p p' h, cases p with c d, cases p' with c' d', apply id_leftright, end end functor open functor namespace yoneda open category.set nat_trans lift /- These attributes make sure that the fields of the category "set" reduce to the right things However, we don't want to have them globally, because that will unfold the composition g ∘ f in a Category to category.category.comp g f -/ local attribute Category.to.precategory category.to_precategory [constructor] -- should this be defined as "yoneda_embedding Cᵒᵖ"? definition contravariant_yoneda_embedding [reducible] (C : Precategory) : Cᵒᵖ ⇒ set ^c C := functor_curry !hom_functor definition yoneda_embedding (C : Precategory) : C ⇒ set ^c Cᵒᵖ := functor_curry (!hom_functor ∘f !functor_prod_flip) notation `ɏ` := yoneda_embedding _ definition yoneda_lemma_hom [constructor] {C : Precategory} (c : C) (F : Cᵒᵖ ⇒ set) (x : trunctype.carrier (F c)) : ɏ c ⟹ F := begin fapply nat_trans.mk, { intro c', esimp [yoneda_embedding], intro f, exact F f x}, { intro c' c'' f, esimp [yoneda_embedding], apply eq_of_homotopy, intro f', refine _ ⬝ ap (λy, to_fun_hom F y x) !(@id_left _ C)⁻¹, exact ap10 !(@respect_comp Cᵒᵖ set)⁻¹ x} end definition yoneda_lemma_equiv [constructor] {C : Precategory} (c : C) (F : Cᵒᵖ ⇒ set) : hom (ɏ c) F ≃ lift (F c) := begin fapply equiv.MK, { intro η, exact up (η c id)}, { intro x, induction x with x, exact yoneda_lemma_hom c F x}, { exact abstract begin intro x, induction x with x, esimp, apply ap up, exact ap10 !respect_id x end end}, { exact abstract begin intro η, esimp, apply nat_trans_eq, intro c', esimp, apply eq_of_homotopy, intro f, esimp [yoneda_embedding] at f, transitivity (F f ∘ η c) id, reflexivity, rewrite naturality, esimp [yoneda_embedding], rewrite [id_left], apply ap _ !id_left end end}, end definition yoneda_lemma {C : Precategory} (c : C) (F : Cᵒᵖ ⇒ set) : homset (ɏ c) F ≅ lift_functor (F c) := begin apply iso_of_equiv, esimp, apply yoneda_lemma_equiv, end theorem yoneda_lemma_natural_ob {C : Precategory} (F : Cᵒᵖ ⇒ set) {c c' : C} (f : c' ⟶ c) (η : ɏ c ⟹ F) : to_fun_hom (lift_functor ∘f F) f (to_hom (yoneda_lemma c F) η) = to_hom (yoneda_lemma c' F) (η ∘n to_fun_hom ɏ f) := begin esimp [yoneda_lemma,yoneda_embedding], apply ap up, transitivity (F f ∘ η c) id, reflexivity, rewrite naturality, esimp [yoneda_embedding], apply ap (η c'), esimp [yoneda_embedding, Opposite], rewrite [+id_left,+id_right], end -- TODO: Investigate what is the bottleneck to type check the next theorem -- attribute yoneda_lemma lift_functor Precategory_hset precategory_hset homset -- yoneda_embedding nat_trans.compose functor_nat_trans_compose [reducible] -- attribute tlift functor.compose [reducible] theorem yoneda_lemma_natural_functor.{u v} {C : Precategory.{u v}} (c : C) (F F' : Cᵒᵖ ⇒ set) (θ : F ⟹ F') (η : to_fun_ob ɏ c ⟹ F) : (lift_functor.{v u} ∘fn θ) c (to_hom (yoneda_lemma c F) η) = proof to_hom (yoneda_lemma c F') (θ ∘n η) qed := by reflexivity -- theorem xx.{u v} {C : Precategory.{u v}} (c : C) (F F' : Cᵒᵖ ⇒ set) -- (θ : F ⟹ F') (η : to_fun_ob ɏ c ⟹ F) : -- proof _ qed = -- to_hom (yoneda_lemma c F') (θ ∘n η) := -- by reflexivity -- theorem yy.{u v} {C : Precategory.{u v}} (c : C) (F F' : Cᵒᵖ ⇒ set) -- (θ : F ⟹ F') (η : to_fun_ob ɏ c ⟹ F) : -- (lift_functor.{v u} ∘fn θ) c (to_hom (yoneda_lemma c F) η) = -- proof _ qed := -- by reflexivity definition fully_faithful_yoneda_embedding [instance] (C : Precategory) : fully_faithful (ɏ : C ⇒ set ^c Cᵒᵖ) := begin intro c c', fapply is_equiv_of_equiv_of_homotopy, { symmetry, transitivity _, apply @equiv_of_iso (homset _ _), rexact yoneda_lemma c (ɏ c'), esimp [yoneda_embedding], exact !equiv_lift⁻¹ᵉ}, { intro f, apply nat_trans_eq, intro c, apply eq_of_homotopy, intro f', esimp [equiv.symm,equiv.trans], esimp [yoneda_lemma,yoneda_embedding,Opposite], rewrite [id_left,id_right]} end definition is_embedding_yoneda_embedding (C : Category) : is_embedding (ɏ : C → Cᵒᵖ ⇒ set) := begin intro c c', fapply is_equiv_of_equiv_of_homotopy, { exact !eq_equiv_iso ⬝e !iso_equiv_F_iso_F ⬝e !eq_equiv_iso⁻¹ᵉ}, { intro p, induction p, esimp [equiv.trans, equiv.symm], esimp [to_fun_iso], rewrite -eq_of_iso_refl, apply ap eq_of_iso, apply iso_eq, esimp, apply nat_trans_eq, intro c', apply eq_of_homotopy, esimp [yoneda_embedding], intro f, rewrite [category.category.id_left], apply id_right} end definition is_representable {C : Precategory} (F : Cᵒᵖ ⇒ set) := Σ(c : C), ɏ c ≅ F definition is_hprop_representable {C : Category} (F : Cᵒᵖ ⇒ set) : is_hprop (is_representable F) := begin fapply is_trunc_equiv_closed, { transitivity _, rotate 1, { apply sigma.sigma_equiv_sigma_id, intro c, exact !eq_equiv_iso}, { apply fiber.sigma_char}}, { apply function.is_hprop_fiber_of_is_embedding, apply is_embedding_yoneda_embedding} end end yoneda
f25e2f7de63c3cc6bff80d954d94a054563ff1e8
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/logic/nontrivial.lean
c8ad9369628b3cc0ba6f5efad3983ff8c299edd5
[ "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
7,272
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.prod.basic import data.subtype import logic.function.basic import logic.unique /-! # Nontrivial types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/547 > Any changes to this file require a corresponding PR to mathlib4. A type is *nontrivial* if it contains at least two elements. This is useful in particular for rings (where it is equivalent to the fact that zero is different from one) and for vector spaces (where it is equivalent to the fact that the dimension is positive). We introduce a typeclass `nontrivial` formalizing this property. -/ variables {α : Type*} {β : Type*} open_locale classical /-- Predicate typeclass for expressing that a type is not reduced to a single element. In rings, this is equivalent to `0 ≠ 1`. In vector spaces, this is equivalent to positive dimension. -/ class nontrivial (α : Type*) : Prop := (exists_pair_ne : ∃ (x y : α), x ≠ y) lemma nontrivial_iff : nontrivial α ↔ ∃ (x y : α), x ≠ y := ⟨λ h, h.exists_pair_ne, λ h, ⟨h⟩⟩ lemma exists_pair_ne (α : Type*) [nontrivial α] : ∃ (x y : α), x ≠ y := nontrivial.exists_pair_ne -- See Note [decidable namespace] protected lemma decidable.exists_ne [nontrivial α] [decidable_eq α] (x : α) : ∃ y, y ≠ x := begin rcases exists_pair_ne α with ⟨y, y', h⟩, by_cases hx : x = y, { rw ← hx at h, exact ⟨y', h.symm⟩ }, { exact ⟨y, ne.symm hx⟩ } end lemma exists_ne [nontrivial α] (x : α) : ∃ y, y ≠ x := by classical; exact decidable.exists_ne x -- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`. lemma nontrivial_of_ne (x y : α) (h : x ≠ y) : nontrivial α := ⟨⟨x, y, h⟩⟩ -- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`. lemma nontrivial_of_lt [preorder α] (x y : α) (h : x < y) : nontrivial α := ⟨⟨x, y, ne_of_lt h⟩⟩ lemma exists_pair_lt (α : Type*) [nontrivial α] [linear_order α] : ∃ (x y : α), x < y := begin rcases exists_pair_ne α with ⟨x, y, hxy⟩, cases lt_or_gt_of_ne hxy; exact ⟨_, _, h⟩ end lemma nontrivial_iff_lt [linear_order α] : nontrivial α ↔ ∃ (x y : α), x < y := ⟨λ h, @exists_pair_lt α h _, λ ⟨x, y, h⟩, nontrivial_of_lt x y h⟩ lemma nontrivial_iff_exists_ne (x : α) : nontrivial α ↔ ∃ y, y ≠ x := ⟨λ h, @exists_ne α h x, λ ⟨y, hy⟩, nontrivial_of_ne _ _ hy⟩ lemma subtype.nontrivial_iff_exists_ne (p : α → Prop) (x : subtype p) : nontrivial (subtype p) ↔ ∃ (y : α) (hy : p y), y ≠ x := by simp only [nontrivial_iff_exists_ne x, subtype.exists, ne.def, subtype.ext_iff, subtype.coe_mk] instance : nontrivial Prop := ⟨⟨true, false, true_ne_false⟩⟩ /-- See Note [lower instance priority] Note that since this and `nonempty_of_inhabited` are the most "obvious" way to find a nonempty instance if no direct instance can be found, we give this a higher priority than the usual `100`. -/ @[priority 500] instance nontrivial.to_nonempty [nontrivial α] : nonempty α := let ⟨x, _⟩ := exists_pair_ne α in ⟨x⟩ attribute [instance, priority 500] nonempty_of_inhabited /-- An inhabited type is either nontrivial, or has a unique element. -/ noncomputable def nontrivial_psum_unique (α : Type*) [inhabited α] : psum (nontrivial α) (unique α) := if h : nontrivial α then psum.inl h else psum.inr { default := default, uniq := λ (x : α), begin change x = default, contrapose! h, use [x, default] end } lemma subsingleton_iff : subsingleton α ↔ ∀ (x y : α), x = y := ⟨by { introsI h, exact subsingleton.elim }, λ h, ⟨h⟩⟩ lemma not_nontrivial_iff_subsingleton : ¬(nontrivial α) ↔ subsingleton α := by { rw [nontrivial_iff, subsingleton_iff], push_neg, refl } lemma not_nontrivial (α) [subsingleton α] : ¬nontrivial α := λ ⟨⟨x, y, h⟩⟩, h $ subsingleton.elim x y lemma not_subsingleton (α) [h : nontrivial α] : ¬subsingleton α := let ⟨⟨x, y, hxy⟩⟩ := h in λ ⟨h'⟩, hxy $ h' x y /-- A type is either a subsingleton or nontrivial. -/ lemma subsingleton_or_nontrivial (α : Type*) : subsingleton α ∨ nontrivial α := by { rw [← not_nontrivial_iff_subsingleton, or_comm], exact classical.em _ } lemma false_of_nontrivial_of_subsingleton (α : Type*) [nontrivial α] [subsingleton α] : false := let ⟨x, y, h⟩ := exists_pair_ne α in h $ subsingleton.elim x y instance option.nontrivial [nonempty α] : nontrivial (option α) := by { inhabit α, use [none, some default] } /-- Pushforward a `nontrivial` instance along an injective function. -/ protected lemma function.injective.nontrivial [nontrivial α] {f : α → β} (hf : function.injective f) : nontrivial β := let ⟨x, y, h⟩ := exists_pair_ne α in ⟨⟨f x, f y, hf.ne h⟩⟩ /-- Pullback a `nontrivial` instance along a surjective function. -/ protected lemma function.surjective.nontrivial [nontrivial β] {f : α → β} (hf : function.surjective f) : nontrivial α := begin rcases exists_pair_ne β with ⟨x, y, h⟩, rcases hf x with ⟨x', hx'⟩, rcases hf y with ⟨y', hy'⟩, have : x' ≠ y', by { contrapose! h, rw [← hx', ← hy', h] }, exact ⟨⟨x', y', this⟩⟩ end /-- An injective function from a nontrivial type has an argument at which it does not take a given value. -/ protected lemma function.injective.exists_ne [nontrivial α] {f : α → β} (hf : function.injective f) (y : β) : ∃ x, f x ≠ y := begin rcases exists_pair_ne α with ⟨x₁, x₂, hx⟩, by_cases h : f x₂ = y, { exact ⟨x₁, (hf.ne_iff' h).2 hx⟩ }, { exact ⟨x₂, h⟩ } end instance nontrivial_prod_right [nonempty α] [nontrivial β] : nontrivial (α × β) := prod.snd_surjective.nontrivial instance nontrivial_prod_left [nontrivial α] [nonempty β] : nontrivial (α × β) := prod.fst_surjective.nontrivial namespace pi variables {I : Type*} {f : I → Type*} /-- A pi type is nontrivial if it's nonempty everywhere and nontrivial somewhere. -/ lemma nontrivial_at (i' : I) [inst : Π i, nonempty (f i)] [nontrivial (f i')] : nontrivial (Π i : I, f i) := by classical; exact (function.update_injective (λ i, classical.choice (inst i)) i').nontrivial /-- As a convenience, provide an instance automatically if `(f default)` is nontrivial. If a different index has the non-trivial type, then use `haveI := nontrivial_at that_index`. -/ instance nontrivial [inhabited I] [inst : Π i, nonempty (f i)] [nontrivial (f default)] : nontrivial (Π i : I, f i) := nontrivial_at default end pi instance function.nontrivial [h : nonempty α] [nontrivial β] : nontrivial (α → β) := h.elim $ λ a, pi.nontrivial_at a mk_simp_attribute nontriviality "Simp lemmas for `nontriviality` tactic" protected lemma subsingleton.le [preorder α] [subsingleton α] (x y : α) : x ≤ y := le_of_eq (subsingleton.elim x y) attribute [nontriviality] eq_iff_true_of_subsingleton subsingleton.le namespace bool instance : nontrivial bool := ⟨⟨tt,ff, tt_eq_ff_eq_false⟩⟩ end bool
627589bb6c432e3b30689e8eedc0b8da6a6efc15
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/src/Lean/Meta/WHNF.lean
da3dc0176dff17eb2f89eb9a07b19363ceb4faef
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,906
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ToExpr import Lean.AuxRecursor import Lean.Meta.Basic import Lean.Meta.LevelDefEq import Lean.Meta.GetConst import Lean.Meta.Match.MatcherInfo namespace Lean.Meta /- =========================== Smart unfolding support =========================== -/ def smartUnfoldingSuffix := "_sunfold" @[inline] def mkSmartUnfoldingNameFor (n : Name) : Name := Name.mkStr n smartUnfoldingSuffix def smartUnfoldingDefault := true builtin_initialize registerOption `smartUnfolding { defValue := smartUnfoldingDefault, group := "", descr := "when computing weak head normal form, use auxiliary definition created for functions defined by structural recursion" } private def useSmartUnfolding (opts : Options) : Bool := opts.getBool `smartUnfolding smartUnfoldingDefault /- =========================== Helper methods =========================== -/ def isAuxDef (constName : Name) : MetaM Bool := do let env ← getEnv pure (isAuxRecursor env constName || isNoConfusion env constName) @[inline] private def matchConstAux {α} (e : Expr) (failK : Unit → MetaM α) (k : ConstantInfo → List Level → MetaM α) : MetaM α := match e with | Expr.const name lvls _ => do let (some cinfo) ← getConst? name | failK () k cinfo lvls | _ => failK () /- =========================== Helper functions for reducing recursors =========================== -/ private def getFirstCtor (d : Name) : MetaM (Option Name) := do let some (ConstantInfo.inductInfo { ctors := ctor::_, ..}) ← getConstNoEx? d | pure none pure (some ctor) private def mkNullaryCtor (type : Expr) (nparams : Nat) : MetaM (Option Expr) := match type.getAppFn with | Expr.const d lvls _ => do let (some ctor) ← getFirstCtor d | pure none pure $ mkAppN (mkConst ctor lvls) (type.getAppArgs.shrink nparams) | _ => pure none def toCtorIfLit : Expr → Expr | Expr.lit (Literal.natVal v) _ => if v == 0 then mkConst `Nat.zero else mkApp (mkConst `Nat.succ) (mkNatLit (v-1)) | Expr.lit (Literal.strVal v) _ => mkApp (mkConst `String.mk) (toExpr v.toList) | e => e private def getRecRuleFor (recVal : RecursorVal) (major : Expr) : Option RecursorRule := match major.getAppFn with | Expr.const fn _ _ => recVal.rules.find? $ fun r => r.ctor == fn | _ => none private def toCtorWhenK (recVal : RecursorVal) (major : Expr) : MetaM (Option Expr) := do let majorType ← inferType major let majorType ← whnf majorType let majorTypeI := majorType.getAppFn if !majorTypeI.isConstOf recVal.getInduct then pure none else if majorType.hasExprMVar && majorType.getAppArgs[recVal.nparams:].any Expr.hasExprMVar then pure none else do let (some newCtorApp) ← mkNullaryCtor majorType recVal.nparams | pure none let newType ← inferType newCtorApp if (← isDefEq majorType newType) then pure newCtorApp else pure none /-- Auxiliary function for reducing recursor applications. -/ private def reduceRec {α} (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let mut major ← whnf major if recVal.k then let newMajor ← toCtorWhenK recVal major major := newMajor.getD major let major := toCtorIfLit major match getRecRuleFor recVal major with | some rule => let majorArgs := major.getAppArgs if recLvls.length != recVal.lparams.length then failK () else let rhs := rule.rhs.instantiateLevelParams recVal.lparams recLvls -- Apply parameters, motives and minor premises from recursor application. let rhs := mkAppRange rhs 0 (recVal.nparams+recVal.nmotives+recVal.nminors) recArgs /- The number of parameters in the constructor is not necessarily equal to the number of parameters in the recursor when we have nested inductive types. -/ let nparams := majorArgs.size - rule.nfields let rhs := mkAppRange rhs nparams majorArgs.size majorArgs let rhs := mkAppRange rhs (majorIdx + 1) recArgs.size recArgs successK rhs | none => failK () else failK () /- =========================== Helper functions for reducing Quot.lift and Quot.ind =========================== -/ /-- Auxiliary function for reducing `Quot.lift` and `Quot.ind` applications. -/ private def reduceQuotRec {α} (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) (failK : Unit → MetaM α) (successK : Expr → MetaM α) : MetaM α := let process (majorPos argPos : Nat) : MetaM α := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major match major with | Expr.app (Expr.app (Expr.app (Expr.const majorFn _ _) _ _) _ _) majorArg _ => do let some (ConstantInfo.quotInfo { kind := QuotKind.ctor, .. }) ← getConstNoEx? majorFn | failK () let f := recArgs[argPos] let r := mkApp f majorArg let recArity := majorPos + 1 successK $ mkAppRange r recArity recArgs.size recArgs | _ => failK () else failK () match recVal.kind with | QuotKind.lift => process 5 3 | QuotKind.ind => process 4 3 | _ => failK () /- =========================== Helper function for extracting "stuck term" =========================== -/ mutual private partial def isRecStuck? (recVal : RecursorVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) := if recVal.k then -- TODO: improve this case pure none else do let majorIdx := recVal.getMajorIdx if h : majorIdx < recArgs.size then do let major := recArgs.get ⟨majorIdx, h⟩ let major ← whnf major getStuckMVar? major else pure none private partial def isQuotRecStuck? (recVal : QuotVal) (recLvls : List Level) (recArgs : Array Expr) : MetaM (Option MVarId) := let process? (majorPos : Nat) : MetaM (Option MVarId) := if h : majorPos < recArgs.size then do let major := recArgs.get ⟨majorPos, h⟩ let major ← whnf major getStuckMVar? major else pure none match recVal.kind with | QuotKind.lift => process? 5 | QuotKind.ind => process? 4 | _ => pure none /-- Return `some (Expr.mvar mvarId)` if metavariable `mvarId` is blocking reduction. -/ partial def getStuckMVar? : Expr → MetaM (Option MVarId) | Expr.mdata _ e _ => getStuckMVar? e | Expr.proj _ _ e _ => do getStuckMVar? (← whnf e) | e@(Expr.mvar mvarId _) => pure (some mvarId) | e@(Expr.app f _ _) => let f := f.getAppFn match f with | Expr.mvar mvarId _ => pure (some mvarId) | Expr.const fName fLvls _ => do let cinfo? ← getConstNoEx? fName match cinfo? with | some $ ConstantInfo.recInfo recVal => isRecStuck? recVal fLvls e.getAppArgs | some $ ConstantInfo.quotInfo recVal => isQuotRecStuck? recVal fLvls e.getAppArgs | _ => pure none | _ => pure none | _ => pure none end /- =========================== Weak Head Normal Form auxiliary combinators =========================== -/ /-- Auxiliary combinator for handling easy WHNF cases. It takes a function for handling the "hard" cases as an argument -/ @[specialize] private partial def whnfEasyCases : Expr → (Expr → MetaM Expr) → MetaM Expr | e@(Expr.forallE _ _ _ _), _ => pure e | e@(Expr.lam _ _ _ _), _ => pure e | e@(Expr.sort _ _), _ => pure e | e@(Expr.lit _ _), _ => pure e | e@(Expr.bvar _ _), _ => unreachable! | Expr.mdata _ e _, k => whnfEasyCases e k | e@(Expr.letE _ _ _ _ _), k => k e | e@(Expr.fvar fvarId _), k => do let decl ← getLocalDecl fvarId match decl with | LocalDecl.cdecl _ _ _ _ _ => pure e | LocalDecl.ldecl _ _ _ _ v nonDep => let cfg ← getConfig if nonDep && !cfg.zetaNonDep then pure e else when cfg.trackZeta do modify fun s => { s with zetaFVarIds := s.zetaFVarIds.insert fvarId } whnfEasyCases v k | e@(Expr.mvar mvarId _), k => do match (← getExprMVarAssignment? mvarId) with | some v => whnfEasyCases v k | none => pure e | e@(Expr.const _ _ _), k => k e | e@(Expr.app _ _ _), k => k e | e@(Expr.proj _ _ _ _), k => k e /-- Return true iff term is of the form `idRhs ...` -/ private def isIdRhsApp (e : Expr) : Bool := e.isAppOf `idRhs /-- (@idRhs T f a_1 ... a_n) ==> (f a_1 ... a_n) -/ private def extractIdRhs (e : Expr) : Expr := if !isIdRhsApp e then e else let args := e.getAppArgs if args.size < 2 then e else mkAppRange args[1] 2 args.size args @[specialize] private def deltaDefinition {α} (c : ConstantInfo) (lvls : List Level) (failK : Unit → α) (successK : Expr → α) : α := if c.lparams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls successK (extractIdRhs val) @[specialize] private def deltaBetaDefinition {α} (c : ConstantInfo) (lvls : List Level) (revArgs : Array Expr) (failK : Unit → α) (successK : Expr → α) : α := if c.lparams.length != lvls.length then failK () else let val := c.instantiateValueLevelParams lvls let val := val.betaRev revArgs successK (extractIdRhs val) inductive ReduceMatcherResult where | reduced (val : Expr) | stuck (val : Expr) | notMatcher | partialApp def reduceMatcher? (e : Expr) : MetaM ReduceMatcherResult := do match e.getAppFn with | Expr.const declName declLevels _ => do let some info ← getMatcherInfo? declName | pure ReduceMatcherResult.notMatcher let args := e.getAppArgs let prefixSz := info.numParams + 1 + info.numDiscrs if args.size < prefixSz + info.numAlts then pure ReduceMatcherResult.partialApp else let constInfo ← getConstInfo declName let f := constInfo.instantiateValueLevelParams declLevels let auxApp := mkAppN f args[0:prefixSz] let auxAppType ← inferType auxApp forallBoundedTelescope auxAppType info.numAlts fun hs _ => do let auxApp := mkAppN auxApp hs let auxApp ← whnf auxApp let auxAppFn := auxApp.getAppFn let mut i := prefixSz for h in hs do if auxAppFn == h then let result := mkAppN args[i] auxApp.getAppArgs let result := mkAppN result args[prefixSz + info.numAlts:args.size] return ReduceMatcherResult.reduced result.headBeta i := i + 1 return ReduceMatcherResult.stuck auxApp | _ => pure ReduceMatcherResult.notMatcher /- Given an expression `e`, compute its WHNF and if the result is a constructor, return field #i. -/ def project? (e : Expr) (i : Nat) : MetaM (Option Expr) := do let e ← whnf e matchConstCtor e.getAppFn (fun _ => pure none) fun ctorVal _ => let numArgs := e.getAppNumArgs let idx := ctorVal.nparams + i if idx < numArgs then pure (some (e.getArg! idx)) else pure none def reduceProj? (e : Expr) : MetaM (Option Expr) := do match e with | Expr.proj _ i c _ => project? c i | _ => return none /-- Apply beta-reduction, zeta-reduction (i.e., unfold let local-decls), iota-reduction, expand let-expressions, expand assigned meta-variables. -/ partial def whnfCore (e : Expr) : MetaM Expr := whnfEasyCases e fun e => do trace[Meta.whnf]! e match e with | Expr.const .. => pure e | Expr.letE _ _ v b _ => whnfCore $ b.instantiate1 v | Expr.app f .. => let f := f.getAppFn let f' ← whnfCore f if f'.isLambda then let revArgs := e.getAppRevArgs whnfCore <| f'.betaRev revArgs else match (← reduceMatcher? e) with | ReduceMatcherResult.reduced eNew => whnfCore eNew | ReduceMatcherResult.partialApp => pure e | ReduceMatcherResult.stuck _ => pure e | ReduceMatcherResult.notMatcher => let done : Unit → MetaM Expr := fun _ => if f == f' then pure e else pure $ e.updateFn f' matchConstAux f' done fun cinfo lvls => match cinfo with | ConstantInfo.recInfo rec => reduceRec rec lvls e.getAppArgs done whnfCore | ConstantInfo.quotInfo rec => reduceQuotRec rec lvls e.getAppArgs done whnfCore | c@(ConstantInfo.defnInfo _) => do if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs done whnfCore else done () | _ => done () | Expr.proj .. => match (← reduceProj? e) with | some e => whnfCore e | none => return e | _ => unreachable! mutual /-- Reduce `e` until `idRhs` application is exposed or it gets stuck. This is a helper method for implementing smart unfolding. -/ private partial def whnfUntilIdRhs (e : Expr) : MetaM Expr := do let e ← whnfCore e match (← getStuckMVar? e) with | some mvarId => /- Try to "unstuck" by resolving pending TC problems -/ if (← Meta.synthPending mvarId) then whnfUntilIdRhs e else pure e -- failed because metavariable is blocking reduction | _ => if isIdRhsApp e then pure e -- done else match (← unfoldDefinition? e) with | some e => whnfUntilIdRhs e | none => pure e -- failed because of symbolic argument /-- Unfold definition using "smart unfolding" if possible. -/ partial def unfoldDefinition? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app f _ _ => matchConstAux f.getAppFn (fun _ => pure none) fun fInfo fLvls => do if fInfo.lparams.length != fLvls.length then pure none else let unfoldDefault (_ : Unit) : MetaM (Option Expr) := if fInfo.hasValue then deltaBetaDefinition fInfo fLvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else pure none if useSmartUnfolding (← getOptions) then let fAuxInfo? ← getConstNoEx? (mkSmartUnfoldingNameFor fInfo.name) match fAuxInfo? with | some $ fAuxInfo@(ConstantInfo.defnInfo _) => deltaBetaDefinition fAuxInfo fLvls e.getAppRevArgs (fun _ => pure none) $ fun e₁ => do let e₂ ← whnfUntilIdRhs e₁ if isIdRhsApp e₂ then pure (some (extractIdRhs e₂)) else pure none | _ => unfoldDefault () else unfoldDefault () | Expr.const name lvls _ => do let (some (cinfo@(ConstantInfo.defnInfo _))) ← getConstNoEx? name | pure none deltaDefinition cinfo lvls (fun _ => pure none) (fun e => pure (some e)) | _ => pure none end @[specialize] partial def whnfHeadPred (e : Expr) (pred : Expr → MetaM Bool) : MetaM Expr := whnfEasyCases e fun e => do let e ← whnfCore e if (← pred e) then match (← unfoldDefinition? e) with | some e => whnfHeadPred e pred | none => pure e else pure e def whnfUntil (e : Expr) (declName : Name) : MetaM (Option Expr) := do let e ← whnfHeadPred e (fun e => pure $ !e.isAppOf declName) if e.isAppOf declName then pure e else pure none /-- Try to reduce matcher/recursor/quot applications. We say they are all "morally" recursor applications. -/ def reduceRecMatcher? (e : Expr) : MetaM (Option Expr) := do if !e.isApp then return none else match (← reduceMatcher? e) with | ReduceMatcherResult.reduced e => return e | _ => matchConstAux e.getAppFn (fun _ => pure none) fun cinfo lvls => match cinfo with | ConstantInfo.recInfo «rec» => reduceRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | ConstantInfo.quotInfo «rec» => reduceQuotRec «rec» lvls e.getAppArgs (fun _ => pure none) (fun e => pure (some e)) | c@(ConstantInfo.defnInfo _) => do if (← isAuxDef c.name) then deltaBetaDefinition c lvls e.getAppRevArgs (fun _ => pure none) (fun e => pure (some e)) else pure none | _ => pure none unsafe def reduceBoolNativeUnsafe (constName : Name) : MetaM Bool := evalConstCheck Bool `Bool constName unsafe def reduceNatNativeUnsafe (constName : Name) : MetaM Nat := evalConstCheck Nat `Nat constName @[implementedBy reduceBoolNativeUnsafe] constant reduceBoolNative (constName : Name) : MetaM Bool @[implementedBy reduceNatNativeUnsafe] constant reduceNatNative (constName : Name) : MetaM Nat def reduceNative? (e : Expr) : MetaM (Option Expr) := match e with | Expr.app (Expr.const fName _ _) (Expr.const argName _ _) _ => if fName == `Lean.reduceBool then do let b ← reduceBoolNative argName pure $ toExpr b else if fName == `Lean.reduceNat then do let n ← reduceNatNative argName pure $ toExpr n else pure none | _ => pure none @[inline] def withNatValue {α} (a : Expr) (k : Nat → MetaM (Option α)) : MetaM (Option α) := do let a ← whnf a match a with | Expr.const `Nat.zero _ _ => k 0 | Expr.lit (Literal.natVal v) _ => k v | _ => pure none def reduceUnaryNatOp (f : Nat → Nat) (a : Expr) : MetaM (Option Expr) := withNatValue a fun a => pure $ mkNatLit $ f a def reduceBinNatOp (f : Nat → Nat → Nat) (a b : Expr) : MetaM (Option Expr) := withNatValue a fun a => withNatValue b fun b => do trace[Meta.isDefEq.whnf.reduceBinOp]! "{a} op {b}" pure $ mkNatLit $ f a b def reduceBinNatPred (f : Nat → Nat → Bool) (a b : Expr) : MetaM (Option Expr) := do withNatValue a fun a => withNatValue b fun b => pure $ toExpr $ f a b def reduceNat? (e : Expr) : MetaM (Option Expr) := if e.hasFVar || e.hasMVar then pure none else match e with | Expr.app (Expr.const fn _ _) a _ => if fn == `Nat.succ then reduceUnaryNatOp Nat.succ a else pure none | Expr.app (Expr.app (Expr.const fn _ _) a1 _) a2 _ => if fn == `Nat.add then reduceBinNatOp Nat.add a1 a2 else if fn == `Nat.sub then reduceBinNatOp Nat.sub a1 a2 else if fn == `Nat.mul then reduceBinNatOp Nat.mul a1 a2 else if fn == `Nat.div then reduceBinNatOp Nat.div a1 a2 else if fn == `Nat.mod then reduceBinNatOp Nat.mod a1 a2 else if fn == `Nat.beq then reduceBinNatPred Nat.beq a1 a2 else if fn == `Nat.ble then reduceBinNatPred Nat.ble a1 a2 else pure none | _ => pure none @[inline] private def useWHNFCache (e : Expr) : MetaM Bool := do -- We cache only closed terms without expr metavars. -- Potential refinement: cache if `e` is not stuck at a metavariable if e.hasFVar || e.hasExprMVar then pure false else let ctx ← read pure $ ctx.config.transparency != TransparencyMode.reducible @[inline] private def cached? (useCache : Bool) (e : Expr) : MetaM (Option Expr) := do if useCache then let ctx ← read let s ← get match ctx.config.transparency with | TransparencyMode.default => pure $ s.cache.whnfDefault.find? e | TransparencyMode.all => pure $ s.cache.whnfAll.find? e | _ => unreachable! else pure none private def cache (useCache : Bool) (e r : Expr) : MetaM Expr := do let ctx ← read if useCache then match ctx.config.transparency with | TransparencyMode.default => modify fun s => { s with cache := { s.cache with whnfDefault := s.cache.whnfDefault.insert e r } } | TransparencyMode.all => modify fun s => { s with cache := { s.cache with whnfAll := s.cache.whnfAll.insert e r } } | _ => unreachable! pure r partial def whnfImp (e : Expr) : MetaM Expr := whnfEasyCases e fun e => do let useCache ← useWHNFCache e match (← cached? useCache e) with | some e' => pure e' | none => let e' ← whnfCore e match (← reduceNat? e') with | some v => cache useCache e v | none => match (← reduceNative? e') with | some v => cache useCache e v | none => match (← unfoldDefinition? e') with | some e => whnfImp e | none => cache useCache e e' @[builtinInit] def setWHNFRef : IO Unit := whnfRef.set whnfImp builtin_initialize registerTraceClass `Meta.whnf end Lean.Meta
2b2ad8947b21e9b81ac1b95f404a150f37db6639
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/specific_limits/normed.lean
6ae1ad1fc27b0718522551b78380aae043ef6083
[ "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
30,266
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker, Sébastien Gouëzel, Yury G. Kudryashov, Dylan MacKenzie, Patrick Massot -/ import algebra.order.field import analysis.asymptotics.asymptotics import analysis.specific_limits.basic /-! # A collection of specific limit computations This file contains important specific limit computations in (semi-)normed groups/rings/spaces, as as well as such computations in `ℝ` when the natural proof passes through a fact about normed spaces. -/ noncomputable theory open classical set function filter finset metric asymptotics open_locale classical topological_space nat big_operators uniformity nnreal ennreal variables {α : Type*} {β : Type*} {ι : Type*} lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top := tendsto_abs_at_top_at_top lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} : (∃r, tendsto (λn, (∑ i in range n, |f i|)) at_top (𝓝 r)) → summable f | ⟨r, hr⟩ := begin refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩, exact assume i, norm_nonneg _, simpa only using hr end /-! ### Powers -/ lemma tendsto_norm_zero' {𝕜 : Type*} [normed_add_comm_group 𝕜] : tendsto (norm : 𝕜 → ℝ) (𝓝[≠] 0) (𝓝[>] 0) := tendsto_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx namespace normed_field lemma tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] : tendsto (λ x:𝕜, ∥x⁻¹∥) (𝓝[≠] 0) at_top := (tendsto_inv_zero_at_top.comp tendsto_norm_zero').congr $ λ x, (norm_inv x).symm lemma tendsto_norm_zpow_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] {m : ℤ} (hm : m < 0) : tendsto (λ x : 𝕜, ∥x ^ m∥) (𝓝[≠] 0) at_top := begin rcases neg_surjective m with ⟨m, rfl⟩, rw neg_lt_zero at hm, lift m to ℕ using hm.le, rw int.coe_nat_pos at hm, simp only [norm_pow, zpow_neg, zpow_coe_nat, ← inv_pow], exact (tendsto_pow_at_top hm.ne').comp normed_field.tendsto_norm_inverse_nhds_within_0_at_top end /-- The (scalar) product of a sequence that tends to zero with a bounded one also tends to zero. -/ lemma tendsto_zero_smul_of_tendsto_zero_of_bounded {ι 𝕜 𝔸 : Type*} [normed_field 𝕜] [normed_add_comm_group 𝔸] [normed_space 𝕜 𝔸] {l : filter ι} {ε : ι → 𝕜} {f : ι → 𝔸} (hε : tendsto ε l (𝓝 0)) (hf : filter.is_bounded_under (≤) l (norm ∘ f)) : tendsto (ε • f) l (𝓝 0) := begin rw ← is_o_one_iff 𝕜 at hε ⊢, simpa using is_o.smul_is_O hε (hf.is_O_const (one_ne_zero : (1 : 𝕜) ≠ 0)) end @[simp] lemma continuous_at_zpow {𝕜 : Type*} [nontrivially_normed_field 𝕜] {m : ℤ} {x : 𝕜} : continuous_at (λ x, x ^ m) x ↔ x ≠ 0 ∨ 0 ≤ m := begin refine ⟨_, continuous_at_zpow₀ _ _⟩, contrapose!, rintro ⟨rfl, hm⟩ hc, exact not_tendsto_at_top_of_tendsto_nhds (hc.tendsto.mono_left nhds_within_le_nhds).norm (tendsto_norm_zpow_nhds_within_0_at_top hm) end @[simp] lemma continuous_at_inv {𝕜 : Type*} [nontrivially_normed_field 𝕜] {x : 𝕜} : continuous_at has_inv.inv x ↔ x ≠ 0 := by simpa [(@zero_lt_one ℤ _ _).not_le] using @continuous_at_zpow _ _ (-1) x end normed_field lemma is_o_pow_pow_of_lt_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ < r₂) : (λ n : ℕ, r₁ ^ n) =o[at_top] (λ n, r₂ ^ n) := have H : 0 < r₂ := h₁.trans_lt h₂, is_o_of_tendsto (λ n hn, false.elim $ H.ne' $ pow_eq_zero hn) $ (tendsto_pow_at_top_nhds_0_of_lt_1 (div_nonneg h₁ (h₁.trans h₂.le)) ((div_lt_one H).2 h₂)).congr (λ n, div_pow _ _ _) lemma is_O_pow_pow_of_le_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ ≤ r₂) : (λ n : ℕ, r₁ ^ n) =O[at_top] (λ n, r₂ ^ n) := h₂.eq_or_lt.elim (λ h, h ▸ is_O_refl _ _) (λ h, (is_o_pow_pow_of_lt_left h₁ h).is_O) lemma is_o_pow_pow_of_abs_lt_left {r₁ r₂ : ℝ} (h : |r₁| < |r₂|) : (λ n : ℕ, r₁ ^ n) =o[at_top] (λ n, r₂ ^ n) := begin refine (is_o.of_norm_left _).of_norm_right, exact (is_o_pow_pow_of_lt_left (abs_nonneg r₁) h).congr (pow_abs r₁) (pow_abs r₂) end /-- Various statements equivalent to the fact that `f n` grows exponentially slower than `R ^ n`. * 0: $f n = o(a ^ n)$ for some $-R < a < R$; * 1: $f n = o(a ^ n)$ for some $0 < a < R$; * 2: $f n = O(a ^ n)$ for some $-R < a < R$; * 3: $f n = O(a ^ n)$ for some $0 < a < R$; * 4: there exist `a < R` and `C` such that one of `C` and `R` is positive and $|f n| ≤ Ca^n$ for all `n`; * 5: there exists `0 < a < R` and a positive `C` such that $|f n| ≤ Ca^n$ for all `n`; * 6: there exists `a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`; * 7: there exists `0 < a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`. NB: For backwards compatibility, if you add more items to the list, please append them at the end of the list. -/ lemma tfae_exists_lt_is_o_pow (f : ℕ → ℝ) (R : ℝ) : tfae [∃ a ∈ Ioo (-R) R, f =o[at_top] pow a, ∃ a ∈ Ioo 0 R, f =o[at_top] (pow a), ∃ a ∈ Ioo (-R) R, f =O[at_top] pow a, ∃ a ∈ Ioo 0 R, f =O[at_top] pow a, ∃ (a < R) C (h₀ : 0 < C ∨ 0 < R), ∀ n, |f n| ≤ C * a ^ n, ∃ (a ∈ Ioo 0 R) (C > 0), ∀ n, |f n| ≤ C * a ^ n, ∃ a < R, ∀ᶠ n in at_top, |f n| ≤ a ^ n, ∃ a ∈ Ioo 0 R, ∀ᶠ n in at_top, |f n| ≤ a ^ n] := begin have A : Ico 0 R ⊆ Ioo (-R) R, from λ x hx, ⟨(neg_lt_zero.2 (hx.1.trans_lt hx.2)).trans_le hx.1, hx.2⟩, have B : Ioo 0 R ⊆ Ioo (-R) R := subset.trans Ioo_subset_Ico_self A, -- First we prove that 1-4 are equivalent using 2 → 3 → 4, 1 → 3, and 2 → 1 tfae_have : 1 → 3, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩, tfae_have : 2 → 1, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩, tfae_have : 3 → 2, { rintro ⟨a, ha, H⟩, rcases exists_between (abs_lt.2 ha) with ⟨b, hab, hbR⟩, exact ⟨b, ⟨(abs_nonneg a).trans_lt hab, hbR⟩, H.trans_is_o (is_o_pow_pow_of_abs_lt_left (hab.trans_le (le_abs_self b)))⟩ }, tfae_have : 2 → 4, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩, tfae_have : 4 → 3, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩, -- Add 5 and 6 using 4 → 6 → 5 → 3 tfae_have : 4 → 6, { rintro ⟨a, ha, H⟩, rcases bound_of_is_O_nat_at_top H with ⟨C, hC₀, hC⟩, refine ⟨a, ha, C, hC₀, λ n, _⟩, simpa only [real.norm_eq_abs, abs_pow, abs_of_nonneg ha.1.le] using hC (pow_ne_zero n ha.1.ne') }, tfae_have : 6 → 5, from λ ⟨a, ha, C, H₀, H⟩, ⟨a, ha.2, C, or.inl H₀, H⟩, tfae_have : 5 → 3, { rintro ⟨a, ha, C, h₀, H⟩, rcases sign_cases_of_C_mul_pow_nonneg (λ n, (abs_nonneg _).trans (H n)) with rfl | ⟨hC₀, ha₀⟩, { obtain rfl : f = 0, by { ext n, simpa using H n }, simp only [lt_irrefl, false_or] at h₀, exact ⟨0, ⟨neg_lt_zero.2 h₀, h₀⟩, is_O_zero _ _⟩ }, exact ⟨a, A ⟨ha₀, ha⟩, is_O_of_le' _ (λ n, (H n).trans $ mul_le_mul_of_nonneg_left (le_abs_self _) hC₀.le)⟩ }, -- Add 7 and 8 using 2 → 8 → 7 → 3 tfae_have : 2 → 8, { rintro ⟨a, ha, H⟩, refine ⟨a, ha, (H.def zero_lt_one).mono (λ n hn, _)⟩, rwa [real.norm_eq_abs, real.norm_eq_abs, one_mul, abs_pow, abs_of_pos ha.1] at hn }, tfae_have : 8 → 7, from λ ⟨a, ha, H⟩, ⟨a, ha.2, H⟩, tfae_have : 7 → 3, { rintro ⟨a, ha, H⟩, have : 0 ≤ a, from nonneg_of_eventually_pow_nonneg (H.mono $ λ n, (abs_nonneg _).trans), refine ⟨a, A ⟨this, ha⟩, is_O.of_bound 1 _⟩, simpa only [real.norm_eq_abs, one_mul, abs_pow, abs_of_nonneg this] }, tfae_finish end /-- For any natural `k` and a real `r > 1` we have `n ^ k = o(r ^ n)` as `n → ∞`. -/ lemma is_o_pow_const_const_pow_of_one_lt {R : Type*} [normed_ring R] (k : ℕ) {r : ℝ} (hr : 1 < r) : (λ n, n ^ k : ℕ → R) =o[at_top] (λ n, r ^ n) := begin have : tendsto (λ x : ℝ, x ^ k) (𝓝[>] 1) (𝓝 1), from ((continuous_id.pow k).tendsto' (1 : ℝ) 1 (one_pow _)).mono_left inf_le_left, obtain ⟨r' : ℝ, hr' : r' ^ k < r, h1 : 1 < r'⟩ := ((this.eventually (gt_mem_nhds hr)).and self_mem_nhds_within).exists, have h0 : 0 ≤ r' := zero_le_one.trans h1.le, suffices : (λ n, n ^ k : ℕ → R) =O[at_top] (λ n : ℕ, (r' ^ k) ^ n), from this.trans_is_o (is_o_pow_pow_of_lt_left (pow_nonneg h0 _) hr'), conv in ((r' ^ _) ^ _) { rw [← pow_mul, mul_comm, pow_mul] }, suffices : ∀ n : ℕ, ∥(n : R)∥ ≤ (r' - 1)⁻¹ * ∥(1 : R)∥ * ∥r' ^ n∥, from (is_O_of_le' _ this).pow _, intro n, rw mul_right_comm, refine n.norm_cast_le.trans (mul_le_mul_of_nonneg_right _ (norm_nonneg _)), simpa [div_eq_inv_mul, real.norm_eq_abs, abs_of_nonneg h0] using n.cast_le_pow_div_sub h1 end /-- For a real `r > 1` we have `n = o(r ^ n)` as `n → ∞`. -/ lemma is_o_coe_const_pow_of_one_lt {R : Type*} [normed_ring R] {r : ℝ} (hr : 1 < r) : (coe : ℕ → R) =o[at_top] (λ n, r ^ n) := by simpa only [pow_one] using @is_o_pow_const_const_pow_of_one_lt R _ 1 _ hr /-- If `∥r₁∥ < r₂`, then for any naturak `k` we have `n ^ k r₁ ^ n = o (r₂ ^ n)` as `n → ∞`. -/ lemma is_o_pow_const_mul_const_pow_const_pow_of_norm_lt {R : Type*} [normed_ring R] (k : ℕ) {r₁ : R} {r₂ : ℝ} (h : ∥r₁∥ < r₂) : (λ n, n ^ k * r₁ ^ n : ℕ → R) =o[at_top] (λ n, r₂ ^ n) := begin by_cases h0 : r₁ = 0, { refine (is_o_zero _ _).congr' (mem_at_top_sets.2 $ ⟨1, λ n hn, _⟩) eventually_eq.rfl, simp [zero_pow (zero_lt_one.trans_le hn), h0] }, rw [← ne.def, ← norm_pos_iff] at h0, have A : (λ n, n ^ k : ℕ → R) =o[at_top] (λ n, (r₂ / ∥r₁∥) ^ n), from is_o_pow_const_const_pow_of_one_lt k ((one_lt_div h0).2 h), suffices : (λ n, r₁ ^ n) =O[at_top] (λ n, ∥r₁∥ ^ n), by simpa [div_mul_cancel _ (pow_pos h0 _).ne'] using A.mul_is_O this, exact is_O.of_bound 1 (by simpa using eventually_norm_pow_le r₁) end lemma tendsto_pow_const_div_const_pow_of_one_lt (k : ℕ) {r : ℝ} (hr : 1 < r) : tendsto (λ n, n ^ k / r ^ n : ℕ → ℝ) at_top (𝓝 0) := (is_o_pow_const_const_pow_of_one_lt k hr).tendsto_div_nhds_zero /-- If `|r| < 1`, then `n ^ k r ^ n` tends to zero for any natural `k`. -/ lemma tendsto_pow_const_mul_const_pow_of_abs_lt_one (k : ℕ) {r : ℝ} (hr : |r| < 1) : tendsto (λ n, n ^ k * r ^ n : ℕ → ℝ) at_top (𝓝 0) := begin by_cases h0 : r = 0, { exact tendsto_const_nhds.congr' (mem_at_top_sets.2 ⟨1, λ n hn, by simp [zero_lt_one.trans_le hn, h0]⟩) }, have hr' : 1 < (|r|)⁻¹, from one_lt_inv (abs_pos.2 h0) hr, rw tendsto_zero_iff_norm_tendsto_zero, simpa [div_eq_mul_inv] using tendsto_pow_const_div_const_pow_of_one_lt k hr' end /-- If `0 ≤ r < 1`, then `n ^ k r ^ n` tends to zero for any natural `k`. This is a specialized version of `tendsto_pow_const_mul_const_pow_of_abs_lt_one`, singled out for ease of application. -/ lemma tendsto_pow_const_mul_const_pow_of_lt_one (k : ℕ) {r : ℝ} (hr : 0 ≤ r) (h'r : r < 1) : tendsto (λ n, n ^ k * r ^ n : ℕ → ℝ) at_top (𝓝 0) := tendsto_pow_const_mul_const_pow_of_abs_lt_one k (abs_lt.2 ⟨neg_one_lt_zero.trans_le hr, h'r⟩) /-- If `|r| < 1`, then `n * r ^ n` tends to zero. -/ lemma tendsto_self_mul_const_pow_of_abs_lt_one {r : ℝ} (hr : |r| < 1) : tendsto (λ n, n * r ^ n : ℕ → ℝ) at_top (𝓝 0) := by simpa only [pow_one] using tendsto_pow_const_mul_const_pow_of_abs_lt_one 1 hr /-- If `0 ≤ r < 1`, then `n * r ^ n` tends to zero. This is a specialized version of `tendsto_self_mul_const_pow_of_abs_lt_one`, singled out for ease of application. -/ lemma tendsto_self_mul_const_pow_of_lt_one {r : ℝ} (hr : 0 ≤ r) (h'r : r < 1) : tendsto (λ n, n * r ^ n : ℕ → ℝ) at_top (𝓝 0) := by simpa only [pow_one] using tendsto_pow_const_mul_const_pow_of_lt_one 1 hr h'r /-- In a normed ring, the powers of an element x with `∥x∥ < 1` tend to zero. -/ lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {R : Type*} [normed_ring R] {x : R} (h : ∥x∥ < 1) : tendsto (λ (n : ℕ), x ^ n) at_top (𝓝 0) := begin apply squeeze_zero_norm' (eventually_norm_pow_le x), exact tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) h, end lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : |r| < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := tendsto_pow_at_top_nhds_0_of_norm_lt_1 h /-! ### Geometric series-/ section geometric variables {K : Type*} [normed_field K] {ξ : K} lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ := begin have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] }, have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds, rw [has_sum_iff_tendsto_nat_of_summable_norm], { simpa [geom_sum_eq, xi_ne_one, neg_inv, div_eq_mul_inv] using A }, { simp [norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] } end lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) := ⟨_, has_sum_geometric_of_norm_lt_1 h⟩ lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : ∑'n:ℕ, ξ ^ n = (1 - ξ)⁻¹ := (has_sum_geometric_of_norm_lt_1 h).tsum_eq lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : |r| < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := has_sum_geometric_of_norm_lt_1 h lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : |r| < 1) : summable (λn:ℕ, r ^ n) := summable_geometric_of_norm_lt_1 h lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : |r| < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := tsum_geometric_of_norm_lt_1 h /-- A geometric series in a normed field is summable iff the norm of the common ratio is less than one. -/ @[simp] lemma summable_geometric_iff_norm_lt_1 : summable (λ n : ℕ, ξ ^ n) ↔ ∥ξ∥ < 1 := begin refine ⟨λ h, _, summable_geometric_of_norm_lt_1⟩, obtain ⟨k : ℕ, hk : dist (ξ ^ k) 0 < 1⟩ := (h.tendsto_cofinite_zero.eventually (ball_mem_nhds _ zero_lt_one)).exists, simp only [norm_pow, dist_zero_right] at hk, rw [← one_pow k] at hk, exact lt_of_pow_lt_pow _ zero_le_one hk end end geometric section mul_geometric lemma summable_norm_pow_mul_geometric_of_norm_lt_1 {R : Type*} [normed_ring R] (k : ℕ) {r : R} (hr : ∥r∥ < 1) : summable (λ n : ℕ, ∥(n ^ k * r ^ n : R)∥) := begin rcases exists_between hr with ⟨r', hrr', h⟩, exact summable_of_is_O_nat (summable_geometric_of_lt_1 ((norm_nonneg _).trans hrr'.le) h) (is_o_pow_const_mul_const_pow_const_pow_of_norm_lt _ hrr').is_O.norm_left end lemma summable_pow_mul_geometric_of_norm_lt_1 {R : Type*} [normed_ring R] [complete_space R] (k : ℕ) {r : R} (hr : ∥r∥ < 1) : summable (λ n, n ^ k * r ^ n : ℕ → R) := summable_of_summable_norm $ summable_norm_pow_mul_geometric_of_norm_lt_1 _ hr /-- If `∥r∥ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`, `has_sum` version. -/ lemma has_sum_coe_mul_geometric_of_norm_lt_1 {𝕜 : Type*} [normed_field 𝕜] [complete_space 𝕜] {r : 𝕜} (hr : ∥r∥ < 1) : has_sum (λ n, n * r ^ n : ℕ → 𝕜) (r / (1 - r) ^ 2) := begin have A : summable (λ n, n * r ^ n : ℕ → 𝕜), by simpa using summable_pow_mul_geometric_of_norm_lt_1 1 hr, have B : has_sum (pow r : ℕ → 𝕜) (1 - r)⁻¹, from has_sum_geometric_of_norm_lt_1 hr, refine A.has_sum_iff.2 _, have hr' : r ≠ 1, by { rintro rfl, simpa [lt_irrefl] using hr }, set s : 𝕜 := ∑' n : ℕ, n * r ^ n, calc s = (1 - r) * s / (1 - r) : (mul_div_cancel_left _ (sub_ne_zero.2 hr'.symm)).symm ... = (s - r * s) / (1 - r) : by rw [sub_mul, one_mul] ... = ((0 : ℕ) * r ^ 0 + (∑' n : ℕ, (n + 1 : ℕ) * r ^ (n + 1)) - r * s) / (1 - r) : by rw ← tsum_eq_zero_add A ... = (r * (∑' n : ℕ, (n + 1) * r ^ n) - r * s) / (1 - r) : by simp [pow_succ, mul_left_comm _ r, tsum_mul_left] ... = r / (1 - r) ^ 2 : by simp [add_mul, tsum_add A B.summable, mul_add, B.tsum_eq, ← div_eq_mul_inv, sq, div_div] end /-- If `∥r∥ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`. -/ lemma tsum_coe_mul_geometric_of_norm_lt_1 {𝕜 : Type*} [normed_field 𝕜] [complete_space 𝕜] {r : 𝕜} (hr : ∥r∥ < 1) : (∑' n : ℕ, n * r ^ n : 𝕜) = (r / (1 - r) ^ 2) := (has_sum_coe_mul_geometric_of_norm_lt_1 hr).tsum_eq end mul_geometric section summable_le_geometric variables [seminormed_add_comm_group α] {r C : ℝ} {f : ℕ → α} lemma seminormed_add_comm_group.cauchy_seq_of_le_geometric {C : ℝ} {r : ℝ} (hr : r < 1) {u : ℕ → α} (h : ∀ n, ∥u n - u (n + 1)∥ ≤ C*r^n) : cauchy_seq u := cauchy_seq_of_le_geometric r C hr (by simpa [dist_eq_norm] using h) lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) : dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n := begin rw [sum_range_succ, dist_eq_norm, ← norm_neg, neg_sub, add_sub_cancel'], exact hf n, end /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) : cauchy_seq (λ s : finset (ℕ), ∑ x in s, f x) := cauchy_seq_finset_of_norm_bounded _ (aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) {a : α} (ha : has_sum f a) (n : ℕ) : ∥(∑ x in finset.range n, f x) - a∥ ≤ (C * r ^ n) / (1 - r) := begin rw ← dist_eq_norm, apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf), exact ha.tendsto_sum_nat end @[simp] lemma dist_partial_sum (u : ℕ → α) (n : ℕ) : dist (∑ k in range (n + 1), u k) (∑ k in range n, u k) = ∥u n∥ := by simp [dist_eq_norm, sum_range_succ] @[simp] lemma dist_partial_sum' (u : ℕ → α) (n : ℕ) : dist (∑ k in range n, u k) (∑ k in range (n+1), u k) = ∥u n∥ := by simp [dist_eq_norm', sum_range_succ] lemma cauchy_series_of_le_geometric {C : ℝ} {u : ℕ → α} {r : ℝ} (hr : r < 1) (h : ∀ n, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range n, u k) := cauchy_seq_of_le_geometric r C hr (by simp [h]) lemma normed_add_comm_group.cauchy_series_of_le_geometric' {C : ℝ} {u : ℕ → α} {r : ℝ} (hr : r < 1) (h : ∀ n, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := (cauchy_series_of_le_geometric hr h).comp_tendsto $ tendsto_add_at_top_nat 1 lemma normed_add_comm_group.cauchy_series_of_le_geometric'' {C : ℝ} {u : ℕ → α} {N : ℕ} {r : ℝ} (hr₀ : 0 < r) (hr₁ : r < 1) (h : ∀ n ≥ N, ∥u n∥ ≤ C*r^n) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := begin set v : ℕ → α := λ n, if n < N then 0 else u n, have hC : 0 ≤ C, from (zero_le_mul_right $ pow_pos hr₀ N).mp ((norm_nonneg _).trans $ h N $ le_refl N), have : ∀ n ≥ N, u n = v n, { intros n hn, simp [v, hn, if_neg (not_lt.mpr hn)] }, refine cauchy_seq_sum_of_eventually_eq this (normed_add_comm_group.cauchy_series_of_le_geometric' hr₁ _), { exact C }, intro n, dsimp [v], split_ifs with H H, { rw norm_zero, exact mul_nonneg hC (pow_nonneg hr₀.le _) }, { push_neg at H, exact h _ H } end end summable_le_geometric section normed_ring_geometric variables {R : Type*} [normed_ring R] [complete_space R] open normed_space /-- A geometric series in a complete normed ring is summable. Proved above (same name, different namespace) for not-necessarily-complete normed fields. -/ lemma normed_ring.summable_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : summable (λ (n:ℕ), x ^ n) := begin have h1 : summable (λ (n:ℕ), ∥x∥ ^ n) := summable_geometric_of_lt_1 (norm_nonneg _) h, refine summable_of_norm_bounded_eventually _ h1 _, rw nat.cofinite_eq_at_top, exact eventually_norm_pow_le x, end /-- Bound for the sum of a geometric series in a normed ring. This formula does not assume that the normed ring satisfies the axiom `∥1∥ = 1`. -/ lemma normed_ring.tsum_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : ∥∑' n:ℕ, x ^ n∥ ≤ ∥(1:R)∥ - 1 + (1 - ∥x∥)⁻¹ := begin rw tsum_eq_zero_add (normed_ring.summable_geometric_of_norm_lt_1 x h), simp only [pow_zero], refine le_trans (norm_add_le _ _) _, have : ∥∑' b : ℕ, (λ n, x ^ (n + 1)) b∥ ≤ (1 - ∥x∥)⁻¹ - 1, { refine tsum_of_norm_bounded _ (λ b, norm_pow_le' _ (nat.succ_pos b)), convert (has_sum_nat_add_iff' 1).mpr (has_sum_geometric_of_lt_1 (norm_nonneg x) h), simp }, linarith end lemma geom_series_mul_neg (x : R) (h : ∥x∥ < 1) : (∑' i:ℕ, x ^ i) * (1 - x) = 1 := begin have := ((normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_right (1 - x)), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (𝓝 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←geom_sum_mul_neg, finset.sum_mul], end lemma mul_neg_geom_series (x : R) (h : ∥x∥ < 1) : (1 - x) * ∑' i:ℕ, x ^ i = 1 := begin have := (normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_left (1 - x), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←mul_neg_geom_sum, finset.mul_sum] end end normed_ring_geometric /-! ### Summability tests based on comparison with geometric series -/ lemma summable_of_ratio_norm_eventually_le {α : Type*} [seminormed_add_comm_group α] [complete_space α] {f : ℕ → α} {r : ℝ} (hr₁ : r < 1) (h : ∀ᶠ n in at_top, ∥f (n+1)∥ ≤ r * ∥f n∥) : summable f := begin by_cases hr₀ : 0 ≤ r, { rw eventually_at_top at h, rcases h with ⟨N, hN⟩, rw ← @summable_nat_add_iff α _ _ _ _ N, refine summable_of_norm_bounded (λ n, ∥f N∥ * r^n) (summable.mul_left _ $ summable_geometric_of_lt_1 hr₀ hr₁) (λ n, _), conv_rhs {rw [mul_comm, ← zero_add N]}, refine le_geom hr₀ n (λ i _, _), convert hN (i + N) (N.le_add_left i) using 3, ac_refl }, { push_neg at hr₀, refine summable_of_norm_bounded_eventually 0 summable_zero _, rw nat.cofinite_eq_at_top, filter_upwards [h] with _ hn, by_contra' h, exact not_lt.mpr (norm_nonneg _) (lt_of_le_of_lt hn $ mul_neg_of_neg_of_pos hr₀ h), }, end lemma summable_of_ratio_test_tendsto_lt_one {α : Type*} [normed_add_comm_group α] [complete_space α] {f : ℕ → α} {l : ℝ} (hl₁ : l < 1) (hf : ∀ᶠ n in at_top, f n ≠ 0) (h : tendsto (λ n, ∥f (n+1)∥/∥f n∥) at_top (𝓝 l)) : summable f := begin rcases exists_between hl₁ with ⟨r, hr₀, hr₁⟩, refine summable_of_ratio_norm_eventually_le hr₁ _, filter_upwards [eventually_le_of_tendsto_lt hr₀ h, hf] with _ _ h₁, rwa ← div_le_iff (norm_pos_iff.mpr h₁), end lemma not_summable_of_ratio_norm_eventually_ge {α : Type*} [seminormed_add_comm_group α] {f : ℕ → α} {r : ℝ} (hr : 1 < r) (hf : ∃ᶠ n in at_top, ∥f n∥ ≠ 0) (h : ∀ᶠ n in at_top, r * ∥f n∥ ≤ ∥f (n+1)∥) : ¬ summable f := begin rw eventually_at_top at h, rcases h with ⟨N₀, hN₀⟩, rw frequently_at_top at hf, rcases hf N₀ with ⟨N, hNN₀ : N₀ ≤ N, hN⟩, rw ← @summable_nat_add_iff α _ _ _ _ N, refine mt summable.tendsto_at_top_zero (λ h', not_tendsto_at_top_of_tendsto_nhds (tendsto_norm_zero.comp h') _), convert tendsto_at_top_of_geom_le _ hr _, { refine lt_of_le_of_ne (norm_nonneg _) _, intro h'', specialize hN₀ N hNN₀, simp only [comp_app, zero_add] at h'', exact hN h''.symm }, { intro i, dsimp only [comp_app], convert (hN₀ (i + N) (hNN₀.trans (N.le_add_left i))) using 3, ac_refl } end lemma not_summable_of_ratio_test_tendsto_gt_one {α : Type*} [seminormed_add_comm_group α] {f : ℕ → α} {l : ℝ} (hl : 1 < l) (h : tendsto (λ n, ∥f (n+1)∥/∥f n∥) at_top (𝓝 l)) : ¬ summable f := begin have key : ∀ᶠ n in at_top, ∥f n∥ ≠ 0, { filter_upwards [eventually_ge_of_tendsto_gt hl h] with _ hn hc, rw [hc, div_zero] at hn, linarith }, rcases exists_between hl with ⟨r, hr₀, hr₁⟩, refine not_summable_of_ratio_norm_eventually_ge hr₀ key.frequently _, filter_upwards [eventually_ge_of_tendsto_gt hr₁ h, key] with _ _ h₁, rwa ← le_div_iff (lt_of_le_of_ne (norm_nonneg _) h₁.symm) end section /-! ### Dirichlet and alternating series tests -/ variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] variables {b : ℝ} {f : ℕ → ℝ} {z : ℕ → E} /-- **Dirichlet's Test** for monotone sequences. -/ theorem monotone.cauchy_seq_series_mul_of_tendsto_zero_of_bounded (hfa : monotone f) (hf0 : tendsto f at_top (𝓝 0)) (hgb : ∀ n, ∥∑ i in range n, z i∥ ≤ b) : cauchy_seq (λ n, ∑ i in range (n + 1), (f i) • z i) := begin simp_rw [finset.sum_range_by_parts _ _ (nat.succ _), sub_eq_add_neg, nat.succ_sub_succ_eq_sub, tsub_zero], apply (normed_field.tendsto_zero_smul_of_tendsto_zero_of_bounded hf0 ⟨b, eventually_map.mpr $ eventually_of_forall $ λ n, hgb $ n+1⟩).cauchy_seq.add, apply (cauchy_seq_range_of_norm_bounded _ _ (_ : ∀ n, _ ≤ b * |f(n+1) - f(n)|)).neg, { exact normed_uniform_group }, { simp_rw [abs_of_nonneg (sub_nonneg_of_le (hfa (nat.le_succ _))), ← mul_sum], apply real.uniform_continuous_const_mul.comp_cauchy_seq, simp_rw [sum_range_sub, sub_eq_add_neg], exact (tendsto.cauchy_seq hf0).add_const }, { intro n, rw [norm_smul, mul_comm], exact mul_le_mul_of_nonneg_right (hgb _) (abs_nonneg _) }, end /-- **Dirichlet's test** for antitone sequences. -/ theorem antitone.cauchy_seq_series_mul_of_tendsto_zero_of_bounded (hfa : antitone f) (hf0 : tendsto f at_top (𝓝 0)) (hzb : ∀ n, ∥∑ i in range n, z i∥ ≤ b) : cauchy_seq (λ n, ∑ i in range (n+1), (f i) • z i) := begin have hfa': monotone (λ n, -f n) := λ _ _ hab, neg_le_neg $ hfa hab, have hf0': tendsto (λ n, -f n) at_top (𝓝 0) := by { convert hf0.neg, norm_num }, convert (hfa'.cauchy_seq_series_mul_of_tendsto_zero_of_bounded hf0' hzb).neg, funext, simp end lemma norm_sum_neg_one_pow_le (n : ℕ) : ∥∑ i in range n, (-1 : ℝ) ^ i∥ ≤ 1 := by { rw [neg_one_geom_sum], split_ifs; norm_num } /-- The **alternating series test** for monotone sequences. See also `tendsto_alternating_series_of_monotone_tendsto_zero`. -/ theorem monotone.cauchy_seq_alternating_series_of_tendsto_zero (hfa : monotone f) (hf0 : tendsto f at_top (𝓝 0)) : cauchy_seq (λ n, ∑ i in range (n+1), (-1) ^ i * f i) := begin simp_rw [mul_comm], exact hfa.cauchy_seq_series_mul_of_tendsto_zero_of_bounded hf0 norm_sum_neg_one_pow_le end /-- The **alternating series test** for monotone sequences. -/ theorem monotone.tendsto_alternating_series_of_tendsto_zero (hfa : monotone f) (hf0 : tendsto f at_top (𝓝 0)) : ∃ l, tendsto (λ n, ∑ i in range (n+1), (-1) ^ i * f i) at_top (𝓝 l) := cauchy_seq_tendsto_of_complete $ hfa.cauchy_seq_alternating_series_of_tendsto_zero hf0 /-- The **alternating series test** for antitone sequences. See also `tendsto_alternating_series_of_antitone_tendsto_zero`. -/ theorem antitone.cauchy_seq_alternating_series_of_tendsto_zero (hfa : antitone f) (hf0 : tendsto f at_top (𝓝 0)) : cauchy_seq (λ n, ∑ i in range (n+1), (-1) ^ i * f i) := begin simp_rw [mul_comm], exact hfa.cauchy_seq_series_mul_of_tendsto_zero_of_bounded hf0 norm_sum_neg_one_pow_le end /-- The **alternating series test** for antitone sequences. -/ theorem antitone.tendsto_alternating_series_of_tendsto_zero (hfa : antitone f) (hf0 : tendsto f at_top (𝓝 0)) : ∃ l, tendsto (λ n, ∑ i in range (n+1), (-1) ^ i * f i) at_top (𝓝 l) := cauchy_seq_tendsto_of_complete $ hfa.cauchy_seq_alternating_series_of_tendsto_zero hf0 end /-! ### Factorial -/ /-- The series `∑' n, x ^ n / n!` is summable of any `x : ℝ`. See also `exp_series_div_summable` for a version that also works in `ℂ`, and `exp_series_summable'` for a version that works in any normed algebra over `ℝ` or `ℂ`. -/ lemma real.summable_pow_div_factorial (x : ℝ) : summable (λ n, x ^ n / n! : ℕ → ℝ) := begin -- We start with trivial extimates have A : (0 : ℝ) < ⌊∥x∥⌋₊ + 1, from zero_lt_one.trans_le (by simp), have B : ∥x∥ / (⌊∥x∥⌋₊ + 1) < 1, from (div_lt_one A).2 (nat.lt_floor_add_one _), -- Then we apply the ratio test. The estimate works for `n ≥ ⌊∥x∥⌋₊`. suffices : ∀ n ≥ ⌊∥x∥⌋₊, ∥x ^ (n + 1) / (n + 1)!∥ ≤ ∥x∥ / (⌊∥x∥⌋₊ + 1) * ∥x ^ n / ↑n!∥, from summable_of_ratio_norm_eventually_le B (eventually_at_top.2 ⟨⌊∥x∥⌋₊, this⟩), -- Finally, we prove the upper estimate intros n hn, calc ∥x ^ (n + 1) / (n + 1)!∥ = (∥x∥ / (n + 1)) * ∥x ^ n / n!∥ : by rw [pow_succ, nat.factorial_succ, nat.cast_mul, ← div_mul_div_comm, norm_mul, norm_div, real.norm_coe_nat, nat.cast_succ] ... ≤ (∥x∥ / (⌊∥x∥⌋₊ + 1)) * ∥x ^ n / n!∥ : by mono* with [0 ≤ ∥x ^ n / n!∥, 0 ≤ ∥x∥]; apply norm_nonneg end lemma real.tendsto_pow_div_factorial_at_top (x : ℝ) : tendsto (λ n, x ^ n / n! : ℕ → ℝ) at_top (𝓝 0) := (real.summable_pow_div_factorial x).tendsto_at_top_zero
a72d7f879cf89c31cf2c325e8463a8c4db33f0dc
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/Meta/ExprDefEq.lean
cc4a80fcf418f3d09f650fc16d2f8977f82fe278
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
53,952
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ProjFns import Lean.Meta.WHNF import Lean.Meta.InferType import Lean.Meta.FunInfo import Lean.Meta.LevelDefEq import Lean.Meta.Check import Lean.Meta.Offset import Lean.Meta.ForEachExpr import Lean.Meta.UnificationHint namespace Lean.Meta /-- Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`. Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean. Example: ``` (fun x : A => f ?m) =?= f ``` The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/ private def isDefEqEta (a b : Expr) : MetaM Bool := do if a.isLambda && !b.isLambda then let bType ← inferType b let bType ← whnfD bType match bType with | Expr.forallE n d _ c => let b' := mkLambda n c.binderInfo d (mkApp b (mkBVar 0)) commitWhen $ Meta.isExprDefEqAux a b' | _ => pure false else pure false /-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/ def isDefEqNative (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM $ Meta.isExprDefEqAux s t let s? ← reduceNative? s let t? ← reduceNative? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for reducing Nat basic operations. -/ def isDefEqNat (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM $ Meta.isExprDefEqAux s t if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then pure LBool.undef else let s? ← reduceNat? s let t? ← reduceNat? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for constraints of the form `("..." =?= String.mk cs)` -/ def isDefEqStringLit (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM $ Meta.isExprDefEqAux s t if s.isStringLit && t.isAppOf `String.mk then isDefEq (toCtorIfLit s) t else if s.isAppOf `String.mk && t.isStringLit then isDefEq s (toCtorIfLit t) else pure LBool.undef /-- Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned. Remark: `n` may be 0. -/ def isEtaUnassignedMVar (e : Expr) : MetaM Bool := do match e.etaExpanded? with | some (Expr.mvar mvarId _) => if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then pure false else if (← isExprMVarAssigned mvarId) then pure false else pure true | _ => pure false /- First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases Here, we say a case is easy if it is of the form ?m =?= t or t =?= ?m where `?m` is unassigned. These easy cases are not just an optimization. When `?m` is a function, by assigning it to t, we make sure a unification constraint (in the explicit part) ``` ?m t =?= f s ``` is not higher-order. We also handle the eta-expanded cases: ``` fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ This is important because type inference often produces eta-expanded terms, and without this extra case, we could introduce counter intuitive behavior. Pre: `paramInfo.size <= args₁.size = args₂.size` -/ private partial def isDefEqArgsFirstPass (paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : MetaM (Option (Array Nat)) := do let rec loop (i : Nat) (postponed : Array Nat) := do if h : i < paramInfo.size then let info := paramInfo.get ⟨i, h⟩ let a₁ := args₁[i] let a₂ := args₂[i] if info.implicit || info.instImplicit then if (← isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) then if (← Meta.isExprDefEqAux a₁ a₂) then loop (i+1) postponed else pure none else loop (i+1) (postponed.push i) else if (← Meta.isExprDefEqAux a₁ a₂) then loop (i+1) postponed else pure none else pure (some postponed) loop 0 #[] @[specialize] private def trySynthPending (e : Expr) : MetaM Bool := do let mvarId? ← getStuckMVar? e match mvarId? with | some mvarId => Meta.synthPending mvarId | none => pure false private partial def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := if h : args₁.size = args₂.size then do let finfo ← getFunInfoNArgs f args₁.size let (some postponed) ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ | pure false let rec processOtherArgs (i : Nat) : MetaM Bool := do if h₁ : i < args₁.size then let a₁ := args₁.get ⟨i, h₁⟩ let a₂ := args₂.get ⟨i, Eq.subst h h₁⟩ if (← Meta.isExprDefEqAux a₁ a₂) then processOtherArgs (i+1) else pure false else pure true if (← processOtherArgs finfo.paramInfo.size) then postponed.allM fun i => do /- Second pass: unify implicit arguments. In the second pass, we make sure we are unfolding at least non reducible definitions (default setting). -/ let a₁ := args₁[i] let a₂ := args₂[i] let info := finfo.paramInfo[i] if info.instImplicit then discard <| trySynthPending a₁ discard <| trySynthPending a₂ withAtLeastTransparency TransparencyMode.default $ Meta.isExprDefEqAux a₁ a₂ else pure false else pure false /-- Check whether the types of the free variables at `fvars` are definitionally equal to the types at `ds₂`. Pre: `fvars.size == ds₂.size` This method also updates the set of local instances, and invokes the continuation `k` with the updated set. We can't use `withNewLocalInstances` because the `isDeq fvarType d₂` may use local instances. -/ @[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) (k : MetaM Bool) : MetaM Bool := let rec loop (i : Nat) := do if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩ let fvarDecl ← getFVarLocalDecl fvar let fvarType := fvarDecl.type let d₂ := ds₂[i] if (← Meta.isExprDefEqAux fvarType d₂) then match (← isClass? fvarType) with | some className => withNewLocalInstance className fvar $ loop (i+1) | none => loop (i+1) else pure false else k loop 0 /- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`. It accumulates the new free variables in `fvars`, and declare them at `lctx`. We use the domain types of `e₁` to create the new free variables. We store the domain types of `e₂` at `ds₂`. -/ private partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e₁ e₂ : Expr) (ds₂ : Array Expr) : MetaM Bool := let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do let d₁ := d₁.instantiateRev fvars let d₂ := d₂.instantiateRev fvars let fvarId ← mkFreshId let lctx := lctx.mkLocalDecl fvarId n d₁ let fvars := fvars.push (mkFVar fvarId) isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂) match e₁, e₂ with | Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | _, _ => withReader (fun ctx => { ctx with lctx := lctx }) do isDefEqBindingDomain fvars ds₂ $ Meta.isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars) @[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do let lctx ← getLCtx isDefEqBindingAux lctx #[] a b #[] private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign.checkTypes do if !mvar.isMVar then trace[Meta.isDefEq.assign.final]! "metavariable expected at {mvar} := {v}" return false else -- must check whether types are definitionally equal or not, before assigning and returning true let mvarType ← inferType mvar let vType ← inferType v if (← withTransparency TransparencyMode.default $ Meta.isExprDefEqAux mvarType vType) then trace[Meta.isDefEq.assign.final]! "{mvar} := {v}" assignExprMVar mvar.mvarId! v pure true else trace[Meta.isDefEq.assign.typeMismatch]! "{mvar} : {mvarType} := {v} : {vType}" pure false /-- Auxiliary method for solving constraints of the form `?m xs := v`. It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`. `ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`. For example, suppose we have `xs` of the form `#[a, c]` where ``` a : Nat b : Nat := f a c : b = a ``` In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`, and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`. Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type `(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`, and may not even be type correct. The issue here is that we are not capturing the `let`-declarations. This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t. some `x` in `xs` depends on `y`. `ys` is the `xs` with these extra let-declarations included. In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces `fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`. Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations. This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`. where the index is the position in the local context. -/ private partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do if not (← hasLetDeclsInBetween) then mkLambdaFVars xs v else let ys ← addLetDeps trace[Meta.debug]! "ys: {ys}, v: {v}" mkLambdaFVars ys v where /- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`. We use it a quick-check to avoid the more expensive collection procedure. -/ hasLetDeclsInBetween : MetaM Bool := do let check (lctx : LocalContext) : Bool := do let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index for i in [start+1:stop] do match lctx.getAt! i with | some localDecl => if localDecl.isLet then return true | _ => pure () return false if xs.size <= 1 then pure false else check (← getLCtx) /- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(← read)`. The context `Nat` is the position of `xs[0]` in the local context. -/ collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT NameHashSet MetaM) Unit := do let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT NameHashSet MetaM)) Unit := checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | Expr.proj _ _ b _ => visit b | Expr.fvar fvarId _ => let localDecl ← getLocalDecl fvarId if localDecl.isLet && localDecl.index > (← read) then modify fun s => s.insert localDecl.fvarId | _ => pure () visit (← instantiateMVars e) |>.run /- Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards. The `Nat` argument is the current position in the local context being visited, and it is less than or equal to the position of `xs.back` in the local context. The `Nat` context `(← read)` is the position of `xs[0]` in the local context. -/ collectLetDepsAux : Nat → ReaderT Nat (StateRefT NameHashSet MetaM) Unit | 0 => return () | i+1 => do if i+1 == (← read) then return () else match (← getLCtx).getAt! (i+1) with | none => collectLetDepsAux i | some localDecl => if (← get).contains localDecl.fvarId then collectLetDeclsFrom localDecl.type match localDecl.value? with | some val => collectLetDeclsFrom val | _ => pure () collectLetDepsAux i /- Computes the set `ys`. It is a set of `FVarId`s, -/ collectLetDeps : MetaM NameHashSet := do let lctx ← getLCtx let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId! let (_, s) ← collectLetDepsAux stop |>.run start |>.run s return s /- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that some `x` in `xs` depends on. -/ addLetDeps : MetaM (Array Expr) := do let lctx ← getLCtx let s ← collectLetDeps /- Convert `s` into the the array `ys` -/ let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index let mut ys := #[] for i in [start:stop+1] do match lctx.getAt! i with | none => pure () | some localDecl => if s.contains localDecl.fvarId then ys := ys.push localDecl.toExpr return ys /- Each metavariable is declared in a particular local context. We use the notation `C |- ?m : t` to denote a metavariable `?m` that was declared at the local context `C` with type `t` (see `MetavarDecl`). We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. The following method process the unification constraint ?m@C a₁ ... aₙ =?= t We say the unification constraint is a pattern IFF 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` Claim: we don't have to check free variable declarations. That is, if `t` contains a reference to `x : A := v`, we don't need to check `v`. Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3). If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`. So, condition 4 and 5 are satisfied. If the conditions above have been satisfied, then the solution for the unification constrain is ?m := fun a₁ ... aₙ => t Now, we consider some workarounds/approximations. A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3) (precise) solution: unfold `x` in `t`. A2) Suppose some `aᵢ` is in `C` (failed condition 2) (approximated) solution (when `config.ctxApprox` is set to true) : ignore condition and also use ?m := fun a₁ ... aₙ => t Here is an example where this approximation fails: Given `C` containing `a : nat`, consider the following two constraints ?m@C a =?= a ?m@C b =?= a If we use the approximation in the first constraint, we get ?m := fun x => x when we apply this solution to the second one we get a failure. IMPORTANT: When applying this approximation we need to make sure the abstracted term `fun a₁ ... aₙ => t` is type correct. The check can only be skipped in the pattern case described above. Consider the following example. Given the local context (α : Type) (a : α) we try to solve ?m α =?= @id α a If we use the approximation above we obtain: ?m := (fun α' => @id α' a) which is a type incorrect term. `a` has type `α` but it is expected to have type `α'`. The problem occurs because the right hand side contains a free variable `a` that depends on the free variable `α` being abstracted. Note that this dependency cannot occur in patterns. We can address this by type checking the term after abstraction. This is not a significant performance bottleneck because this case doesn't happen very often in practice (262 times when compiling stdlib on Jan 2018). The second example is trickier, but it also occurs less frequently (8 times when compiling stdlib on Jan 2018, and all occurrences were at Init/Control when we define monads and auxiliary combinators for them). We considered three options for the addressing the issue on the second example: A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1). In Lean3, we would try to approximate this case using an approach similar to A2. However, this approximation complicates the code, and is never used in the Lean3 stdlib and mathlib. A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`. If `?m'` is assigned, we substitute. If not, we create an auxiliary metavariable with a smaller scope. Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step. A5) If some `aᵢ` is not a free variable, then we use first-order unification (if `config.foApprox` is set to true) ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k reduces to ?M a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k A6) If (m =?= v) is of the form ?m a_1 ... a_n =?= ?m b_1 ... b_k then we use first-order unification (if `config.foApprox` is set to true) A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form ``` ?m s₁ ... sₙ =?= t ``` where `s₁ ... sₙ` are arbitrary terms. We solve them by assigning the constant function to `?m`. ``` ?m := fun _ ... _ => t ``` In general, this approximation may produce bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure "hello"; f () ``` with expected type `IO String`. In this example, the following unification contraint is generated. ``` ?m () String =?= IO String ``` It is not a higher-order pattern, first-order approximation reduces it to ``` ?m () =?= IO ``` which fails to be solved. However, constant approximation solves it by assigning ``` ?m := fun _ => IO ``` Note that `f`s type is `(x : ?α) -> ?m x String`. The metavariable `?m` may depend on `x`. If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide whether we should apply it or not. The heuristic is based on observing where the constraints above come from. In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f` does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected by any functional programmer used to non-dependently type languages (e.g., Haskell). We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks how many metavariable arguments are representing dependencies. -/ def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs namespace CheckAssignment builtin_initialize checkAssignmentExceptionId : InternalExceptionId ← registerInternalExceptionId `checkAssignment builtin_initialize outOfScopeExceptionId : InternalExceptionId ← registerInternalExceptionId `outOfScope structure State where cache : ExprStructMap Expr := {} structure Context where mvarId : MVarId mvarDecl : MetavarDecl fvars : Array Expr hasCtxLocals : Bool rhs : Expr abbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM def throwCheckAssignmentFailure {α} : CheckAssignmentM α := throw $ Exception.internal checkAssignmentExceptionId def throwOutOfScopeFVar {α} : CheckAssignmentM α := throw $ Exception.internal outOfScopeExceptionId private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do return (← get).cache.find? e private def cache (e r : Expr) : CheckAssignmentM Unit := do modify fun s => { s with cache := s.cache.insert e r } instance : MonadCache Expr Expr CheckAssignmentM := { findCached? := findCached?, cache := cache } @[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr := if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e (fun _ => f e) private def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do let ctx ← read return m!" @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}" @[specialize] def checkFVar (check : Expr → CheckAssignmentM Expr) (fvar : Expr) : CheckAssignmentM Expr := do let ctxMeta ← readThe Meta.Context let ctx ← read if ctx.mvarDecl.lctx.containsFVar fvar then pure fvar else let lctx := ctxMeta.lctx match lctx.findFVar? fvar with | some (LocalDecl.ldecl _ _ _ _ v _) => visit check v | _ => if ctx.fvars.contains fvar then pure fvar else traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar throwOutOfScopeFVar @[specialize] def checkMVar (check : Expr → CheckAssignmentM Expr) (mvar : Expr) : CheckAssignmentM Expr := do let mvarId := mvar.mvarId! let ctx ← read let mctx ← getMCtx if mvarId == ctx.mvarId then traceM `Meta.isDefEq.assign.occursCheck $ addAssignmentInfo "occurs check failed" throwCheckAssignmentFailure else match mctx.getExprAssignment? mvarId with | some v => check v | none => match mctx.findDecl? mvarId with | none => throwUnknownMVar mvarId | some mvarDecl => if ctx.hasCtxLocals then throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned. We "substract" variables being abstracted because we use `elimMVarDeps` -/ pure mvar else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx $ addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure else let ctxMeta ← readThe Meta.Context if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then /- Create an auxiliary metavariable with a smaller context and "checked" type. Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains a metavariable that we also need to reduce the context. We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx` or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because `elimMVarDeps` will take care of them. First, we collect `toErase` the variables that need to be erased. Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`, we must also erase it. -/ let toErase := mvarDecl.lctx.foldl (init := #[]) fun toErase localDecl => if ctx.mvarDecl.lctx.contains localDecl.fvarId then toErase else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then if mctx.findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId then -- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too toErase.push localDecl.fvarId else toErase else toErase.push localDecl.fvarId let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar => lctx.erase toEraseFVar /- Compute new set of local instances. -/ let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId! let mvarType ← check mvarDecl.type let newMVar ← mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs modifyThe Meta.State fun s => { s with mctx := s.mctx.assignExpr mvarId newMVar } pure newMVar else pure mvar /- Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables, and one of them is out-of-scope. See `Expr.app` case at `check`. If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope, an assigning `?m := fun _ ... _ => ?n` -/ def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do let mvarType ← inferType mvar forallBoundedTelescope mvarType numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs newMVar | return false checkTypesAndAssign mvar v partial def check (e : Expr) : CheckAssignmentM Expr := do match e with | Expr.mdata _ b _ => return e.updateMData! (← visit check b) | Expr.proj _ _ s _ => return e.updateProj! (← visit check s) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit check d) (← visit check b) | Expr.forallE _ d b _ => return e.updateForallE! (← visit check d) (← visit check b) | Expr.letE _ t v b _ => return e.updateLet! (← visit check t) (← visit check v) (← visit check b) | Expr.bvar .. => return e | Expr.sort .. => return e | Expr.const .. => return e | Expr.lit .. => return e | Expr.fvar .. => visit (checkFVar check) e | Expr.mvar .. => visit (checkMVar check) e | Expr.app .. => e.withApp fun f args => do let ctxMeta ← readThe Meta.Context if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then let f ← visit (checkMVar check) f catchInternalId outOfScopeExceptionId (do let args ← args.mapM (visit check) pure $ mkAppN f args) (fun ex => do if (← f.isMVar <&&> isDelayedAssigned f.mvarId!) then throw ex else let eType ← inferType e let mvarType ← check eType /- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar` Note that `mvarType` may be different from `eType`. -/ let ctx ← read let newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType if (← assignToConstFun f args.size newMVar) then pure newMVar else throw ex) else let f ← visit check f let args ← args.mapM (visit check) pure $ mkAppN f args @[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do let mvarDecl ← getMVarDecl mvarId let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context } let x : CheckAssignmentM (Option Expr) := catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId] (do let e ← x; pure $ some e) (fun _ => pure none) x.run ctx |>.run' {} end CheckAssignment namespace CheckAssignmentQuick partial def check (hasCtxLocals ctxApprox : Bool) (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool := let rec visit (e : Expr) : Bool := if !e.hasExprMVar && !e.hasFVar then true else match e with | Expr.mdata _ b _ => visit b | Expr.proj _ _ s _ => visit s | Expr.app f a _ => visit f && visit a | Expr.lam _ d b _ => visit d && visit b | Expr.forallE _ d b _ => visit d && visit b | Expr.letE _ t v b _ => visit t && visit v && visit b | Expr.bvar .. => true | Expr.sort .. => true | Expr.const .. => true | Expr.lit .. => true | Expr.fvar fvarId .. => if mvarDecl.lctx.contains fvarId then true else match lctx.find? fvarId with | some (LocalDecl.ldecl _ _ _ _ v _) => false -- need expensive CheckAssignment.check | _ => if fvars.any $ fun x => x.fvarId! == fvarId then true else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it | Expr.mvar mvarId' _ => match mctx.getExprAssignment? mvarId' with | some _ => false -- use CheckAssignment.check to instantiate | none => if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception else match mctx.findDecl? mvarId' with | none => false | some mvarDecl' => if hasCtxLocals then false -- use CheckAssignment.check else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true else if mvarDecl'.depth != mctx.depth || mvarDecl'.kind.isSyntheticOpaque then false -- use CheckAssignment.check else if ctxApprox && mvarDecl.lctx.isSubPrefixOf mvarDecl'.lctx then false -- use CheckAssignment.check else true visit e end CheckAssignmentQuick -- See checkAssignment def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do CheckAssignment.run (CheckAssignment.check v) mvarId fvars hasCtxLocals v /-- Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`. It will check whether we can perform the assignment ``` ?m := fun fvars => t ``` The result is `none` if the assignment can't be performed. The result is `some newV` where `newV` is a possibly updated `v`. This method may need to unfold let-declarations. -/ def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do if !v.hasExprMVar && !v.hasFVar then pure (some v) else let mvarDecl ← getMVarDecl mvarId let hasCtxLocals := fvars.any $ fun fvar => mvarDecl.lctx.containsFVar fvar let ctx ← read let mctx ← getMCtx if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then pure (some v) else let v ← instantiateMVars v checkAssignmentAux mvarId fvars hasCtxLocals v private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := match v with | Expr.app f a _ => if args.isEmpty then pure false else Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f | _ => pure false /- Auxiliary method for applying first-order unification. It is an approximation. Remark: this method is trying to solve the unification constraint: ?m a₁ ... aₙ =?= v It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`. We have added support for unfolding here because we want to be able to solve unification problems such as ?m Unit =?= ITactic where `ITactic` is defined as def ITactic := Tactic Unit -/ private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := let rec loop (v : Expr) := do let cfg ← getConfig if !cfg.foApprox then pure false else trace[Meta.isDefEq.foApprox]! "{mvar} {args} := {v}" let v := v.headBeta if (← commitWhen $ processAssignmentFOApproxAux mvar args v) then pure true else match (← unfoldDefinition? v) with | none => pure false | some v => loop v loop v private partial def simpAssignmentArgAux : Expr → MetaM Expr | Expr.mdata _ e _ => simpAssignmentArgAux e | e@(Expr.fvar fvarId _) => do let decl ← getLocalDecl fvarId match decl.value? with | some value => simpAssignmentArgAux value | _ => pure e | e => pure e /- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`. We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`, and then removes metadata, and zeta-expand let-decls. -/ private def simpAssignmentArg (arg : Expr) : MetaM Expr := do let arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg simpAssignmentArgAux arg /- Assign `mvar := fun a_1 ... a_{numArgs} => v`. We use it at `processConstApprox` and `isDefEqMVarSelf` -/ private def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let mvarDecl ← getMVarDecl mvar.mvarId! forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs v | pure false trace[Meta.isDefEq.constApprox]! "{mvar} := {v}" checkTypesAndAssign mvar v private def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← getMVarDecl mvarId if mvarDecl.numScopeArgs == numArgs || cfg.constApprox then match (← checkAssignment mvarId #[] v) with | none => pure false | some v => assignConst mvar numArgs v else pure false /-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`. It assumes `?m` is unassigned. -/ private partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign do trace[Meta.isDefEq.assign]! "{mvarApp} := {v}" let mvar := mvarApp.getAppFn let mvarDecl ← getMVarDecl mvar.mvarId! let rec process (i : Nat) (args : Array Expr) (v : Expr) := do let cfg ← getConfig let useFOApprox (args : Array Expr) : MetaM Bool := processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v if h : i < args.size then let arg := args.get ⟨i, h⟩ let arg ← simpAssignmentArg arg let args := args.set ⟨i, h⟩ arg match arg with | Expr.fvar fvarId _ => if args[0:i].any fun prevArg => prevArg == arg then useFOApprox args else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then useFOApprox args else process (i+1) args v | _ => useFOApprox args else let v ← instantiateMVars v -- enforce A4 if v.getAppFn == mvar then -- using A6 useFOApprox args else let mvarId := mvar.mvarId! match (← checkAssignment mvarId args v) with | none => useFOApprox args | some v => do trace[Meta.isDefEq.assign.beforeMkLambda]! "{mvar} {args} := {v}" let some v ← mkLambdaFVarsWithLetDeps args v | return false if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ if (← isTypeCorrect v) then checkTypesAndAssign mvar v else trace[Meta.isDefEq.assign.typeError]! "{mvar} := {v}" useFOApprox args else checkTypesAndAssign mvar v process 0 mvarApp.getAppArgs v private def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) := match t.getAppFn with | Expr.const c _ _ => getConst? c | _ => pure none /-- Auxiliary method for isDefEqDelta -/ private def isListLevelDefEq (us vs : List Level) : MetaM LBool := toLBoolM $ isListLevelDefEqAux us vs /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeft]! fn toLBoolM $ Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldRight]! fn toLBoolM $ Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeftRight]! fn toLBoolM $ Meta.isExprDefEqAux t s /-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`. Auxiliary method for isDefEqDelta -/ private def tryHeuristic (t s : Expr) : MetaM Bool := let tFn := t.getAppFn let sFn := s.getAppFn traceCtx `Meta.isDefEq.delta do commitWhen do let b ← isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels! unless b do trace[Meta.isDefEq.delta]! "heuristic failed {t} =?= {s}" pure b /-- Auxiliary method for isDefEqDelta -/ private abbrev unfold {α} (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do match (← unfoldDefinition? e) with | some e => successK e | none => failK /-- Auxiliary method for isDefEqDelta -/ private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do match t, s with | Expr.const _ ls₁ _, Expr.const _ ls₂ _ => isListLevelDefEq ls₁ ls₂ | Expr.app _ _ _, Expr.app _ _ _ => if (← tryHeuristic t s) then pure LBool.true else unfold t (unfold s (pure LBool.false) (fun s => isDefEqRight fn t s)) (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s)) | _, _ => pure LBool.false private def sameHeadSymbol (t s : Expr) : Bool := match t.getAppFn, s.getAppFn with | Expr.const c₁ _ _, Expr.const c₂ _ _ => true | _, _ => false /-- - If headSymbol (unfold t) == headSymbol s, then unfold t - If headSymbol (unfold s) == headSymbol t, then unfold s - Otherwise unfold t and s if possible. Auxiliary method for isDefEqDelta -/ private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := unfold t (unfold s (pure LBool.undef) -- `t` and `s` failed to be unfolded (fun s => isDefEqRight sInfo.name t s)) (fun tNew => if sameHeadSymbol tNew s then isDefEqLeft tInfo.name tNew s else unfold s (isDefEqLeft tInfo.name tNew s) (fun sNew => if sameHeadSymbol t sNew then isDefEqRight sInfo.name t sNew else isDefEqLeftRight tInfo.name tNew sNew)) /-- If `t` and `s` do not contain metavariables, then use kernel definitional equality heuristics. Otherwise, use `unfoldComparingHeadsDefEq`. Auxiliary method for isDefEqDelta -/ private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := if !t.hasExprMVar && !s.hasExprMVar then /- If `t` and `s` do not contain metavariables, we simulate strategy used in the kernel. -/ if tInfo.hints.lt sInfo.hints then unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else if sInfo.hints.lt tInfo.hints then unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else unfoldComparingHeadsDefEq tInfo sInfo t s else unfoldComparingHeadsDefEq tInfo sInfo t s /-- When `TransparencyMode` is set to `default` or `all`. If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s` If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)` Otherwise, use `unfoldDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do if (← shouldReduceReducibleOnly) then unfoldDefEq tInfo sInfo t s else let tReducible ← isReducible tInfo.name let sReducible ← isReducible sInfo.name if tReducible && !sReducible then unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if !tReducible && sReducible then unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldDefEq tInfo sInfo t s /-- If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)` If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s` Otherwise, use `unfoldReducibeDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do let tProj? ← isProjectionFn tInfo.name let sProj? ← isProjectionFn sInfo.name if tProj? && !sProj? then unfold s (unfoldDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else if !tProj? && sProj? then unfold t (unfoldDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else unfoldReducibeDefEq tInfo sInfo t s /-- isDefEq by lazy delta reduction. This method implements many different heuristics: 1- If only `t` can be unfolded => then unfold `t` and continue 2- If only `s` can be unfolded => then unfold `s` and continue 3- If `t` and `s` can be unfolded and they have the same head symbol, then a) First try to solve unification by unifying arguments. b) If it fails, unfold both and continue. Implemented by `unfoldBothDefEq` 4- If `t` is a projection function application and `s` is not => then unfold `s` and continue. 5- If `s` is a projection function application and `t` is not => then unfold `t` and continue. Remark: 4&5 are implemented by `unfoldNonProjFnDefEq` 6- If `t` is reducible and `s` is not => then unfold `t` and continue. 7- If `s` is reducible and `t` is not => then unfold `s` and continue Remark: 6&7 are implemented by `unfoldReducibeDefEq` 8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel. Implemented by `unfoldDefEq` 9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue. 10- If `headSymbol (unfold s) == headSymbol t`, then unfold s 11- Otherwise, unfold `t` and `s` and continue. Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/ private def isDefEqDelta (t s : Expr) : MetaM LBool := do let tInfo? ← isDeltaCandidate? t.getAppFn let sInfo? ← isDeltaCandidate? s.getAppFn match tInfo?, sInfo? with | none, none => pure LBool.undef | some tInfo, none => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s | none, some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s | some tInfo, some sInfo => if tInfo.name == sInfo.name then unfoldBothDefEq tInfo.name t s else unfoldNonProjFnDefEq tInfo sInfo t s private def isAssigned : Expr → MetaM Bool | Expr.mvar mvarId _ => isExprMVarAssigned mvarId | _ => pure false private def isDelayedAssignedHead (tFn : Expr) (t : Expr) : MetaM Bool := do match tFn with | Expr.mvar mvarId _ => if (← isDelayedAssigned mvarId) then let tNew ← instantiateMVars t pure $ tNew != t else pure false | _ => pure false private def isSynthetic : Expr → MetaM Bool | Expr.mvar mvarId _ => do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.synthetic => pure true | MetavarKind.syntheticOpaque => pure true | MetavarKind.natural => pure false | _ => pure false private def isAssignable : Expr → MetaM Bool | Expr.mvar mvarId _ => do let b ← isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b) | _ => pure false private def etaEq (t s : Expr) : Bool := match t.etaExpanded? with | some t => t == s | none => false private def isLetFVar (fvarId : FVarId) : MetaM Bool := do let decl ← getLocalDecl fvarId pure decl.isLet private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do let status ← isProofQuick t match status with | LBool.false => pure LBool.undef | LBool.true => let tType ← inferType t let sType ← inferType s toLBoolM $ Meta.isExprDefEqAux tType sType | LBool.undef => let tType ← inferType t if (← isProp tType) then let sType ← inferType s toLBoolM $ Meta.isExprDefEqAux tType sType else pure LBool.undef /- Try to solve constraint of the form `?m args₁ =?= ?m args₂`. - First try to unify `args₁` and `args₂`, and return true if successful - Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n` where `?n` is a fresh metavariable. See `processConstApprox`. -/ private def isDefEqMVarSelf (mvar : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do if args₁.size != args₂.size then pure false else if (← isDefEqArgs mvar args₁ args₂) then pure true else if !(← isAssignable mvar) then pure false else let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← getMVarDecl mvarId if mvarDecl.numScopeArgs == args₁.size || cfg.constApprox then let type ← inferType (mkAppN mvar args₁) let auxMVar ← mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type assignConst mvar args₁.size auxMVar else pure false /- Remove unnecessary let-decls -/ private def consumeLet : Expr → Expr | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b | e => e mutual private partial def isDefEqQuick (t s : Expr) : MetaM LBool := let t := consumeLet t let s := consumeLet s match t, s with | Expr.lit l₁ _, Expr.lit l₂ _ => pure (l₁ == l₂).toLBool | Expr.sort u _, Expr.sort v _ => toLBoolM $ isLevelDefEqAux u v | t@(Expr.lam _ _ _ _), s@(Expr.lam _ _ _ _) => if t == s then pure LBool.true else toLBoolM $ isDefEqBinding t s | t@(Expr.forallE _ _ _ _), s@(Expr.forallE _ _ _ _) => if t == s then pure LBool.true else toLBoolM $ isDefEqBinding t s | Expr.mdata _ t _, s => isDefEqQuick t s | t, Expr.mdata _ s _ => isDefEqQuick t s | t@(Expr.fvar fvarId₁ _), s@(Expr.fvar fvarId₂ _) => do if (← isLetFVar fvarId₁ <||> isLetFVar fvarId₂) then pure LBool.undef else if fvarId₁ == fvarId₂ then pure LBool.true else isDefEqProofIrrel t s | t, s => isDefEqQuickOther t s private partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do if t == s then pure LBool.true else if etaEq t s || etaEq s t then pure LBool.true -- t =?= (fun xs => t xs) else let tFn := t.getAppFn let sFn := s.getAppFn if !tFn.isMVar && !sFn.isMVar then pure LBool.undef else if (← isAssigned tFn) then let t ← instantiateMVars t isDefEqQuick t s else if (← isAssigned sFn) then let s ← instantiateMVars s isDefEqQuick t s else if (← isDelayedAssignedHead tFn t) then let t ← instantiateMVars t isDefEqQuick t s else if (← isDelayedAssignedHead sFn s) then let s ← instantiateMVars s isDefEqQuick t s else if (← isSynthetic tFn <&&> trySynthPending tFn) then let t ← instantiateMVars t isDefEqQuick t s else if (← isSynthetic sFn <&&> trySynthPending sFn) then let s ← instantiateMVars s isDefEqQuick t s else if tFn.isMVar && sFn.isMVar && tFn == sFn then Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs else let tAssign? ← isAssignable tFn let sAssign? ← isAssignable sFn let assignableMsg (b : Bool) := if b then "[assignable]" else "[nonassignable]" trace[Meta.isDefEq]! "{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}" let assign (t s : Expr) : MetaM LBool := toLBoolM $ processAssignment t s if tAssign? && !sAssign? then toLBoolM $ processAssignment t s else if !tAssign? && sAssign? then toLBoolM $ processAssignment s t else if !tAssign? && !sAssign? then if tFn.isMVar || sFn.isMVar then let ctx ← read if ctx.config.isDefEqStuckEx then do trace[Meta.isDefEq.stuck]! "{t} =?= {s}" Meta.throwIsDefEqStuck else pure LBool.false else pure LBool.undef else isDefEqQuickMVarMVar t s -- Both `t` and `s` are terms of the form `?m ...` private partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do let tFn := t.getAppFn let sFn := s.getAppFn let tMVarDecl ← getMVarDecl tFn.mvarId! let sMVarDecl ← getMVarDecl sFn.mvarId! if s.isMVar && !t.isMVar then /- Solve `?m t =?= ?n` by trying first `?n := ?m t`. Reason: this assignment is precise. -/ if (← commitWhen (processAssignment s t)) then pure LBool.true else toLBoolM $ processAssignment t s else if (← commitWhen (processAssignment t s)) then pure LBool.true else toLBoolM $ processAssignment s t end @[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do let status ← x match status with | LBool.true => pure true | LBool.false => pure false | LBool.undef => k @[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do match (← getStuckMVar? e) with | some mvarId => trace[Meta.isDefEq.stuckMVar]! "found stuck MVar {mkMVar mvarId}" if (← Meta.synthPending mvarId) then let e ← instantiateMVars e successK e else failK | none => failK private def isDefEqOnFailure (t s : Expr) : MetaM Bool := unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <| unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <| tryUnificationHints t s <||> tryUnificationHints s t private def isDefEqProj : Expr → Expr → MetaM Bool | Expr.proj _ i t _, Expr.proj _ j s _ => pure (i == j) <&&> Meta.isExprDefEqAux t s | _, _ => pure false partial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := do trace[Meta.isDefEq.step]! "{t} =?= {s}" withNestedTraces do whenUndefDo (isDefEqQuick t s) $ whenUndefDo (isDefEqProofIrrel t s) do let t' ← whnfCore t let s' ← whnfCore s if t != t' || s != s' then isExprDefEqAuxImpl t' s' else do if (← (isDefEqEta t s <||> isDefEqEta s t)) then pure true else if (← isDefEqProj t s) then pure true else whenUndefDo (isDefEqNative t s) do whenUndefDo (isDefEqNat t s) do whenUndefDo (isDefEqOffset t s) do whenUndefDo (isDefEqDelta t s) do match t, s with | Expr.const c us _, Expr.const d vs _ => if c == d then isListLevelDefEqAux us vs else pure false | Expr.app _ _ _, Expr.app _ _ _ => let tFn := t.getAppFn if (← commitWhen (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then pure true else isDefEqOnFailure t s | _, _ => whenUndefDo (isDefEqStringLit t s) $ isDefEqOnFailure t s builtin_initialize isExprDefEqAuxRef.set isExprDefEqAuxImpl builtin_initialize registerTraceClass `Meta.isDefEq registerTraceClass `Meta.isDefEq.foApprox registerTraceClass `Meta.isDefEq.constApprox registerTraceClass `Meta.isDefEq.delta registerTraceClass `Meta.isDefEq.step registerTraceClass `Meta.isDefEq.assign end Lean.Meta
987e99fb81059913249ac6e4b4e3e90fda3581c1
9338c56dfd6ceacc3e5e63e32a7918cfec5d5c69
/src/Kenny/projective_line.lean
929684d2822e8f54069cb3265e2a81bcce77181f
[]
no_license
Project-Reykjavik/lean-scheme
7322eefce504898ba33737970be89dc751108e2b
6d3ec18fecfd174b79d0ce5c85a783f326dd50f6
refs/heads/master
1,669,426,172,632
1,578,284,588,000
1,578,284,588,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
97,709
lean
import Kenny.sheaf_of_rings_on_opens instances.affine_scheme data.polynomial universes u v w open topological_space theorem ring_equiv.bijective {α : Type u} {β : Type v} [ring α] [ring β] (e : α ≃+* β) : function.bijective e := e.to_equiv.bijective namespace localization variables {R : Type u} [comm_ring R] theorem away.inv_self_mul_of (x : R) : away.inv_self x * of x = 1 := show mk (1 * x) (⟨x, _⟩ * 1) = 1, by rw [one_mul, mul_one, mk_self] theorem away.of_mul_inv_self (x : R) : of x * away.inv_self x = 1 := show mk (x * 1) (1 * ⟨x, _⟩) = 1, by rw [one_mul, mul_one, mk_self] theorem away.lift'_inv_self (x : R) {A : Type v} [comm_ring A] (f : R → A) [is_ring_hom f] (g hg) : lift' f g hg (away.inv_self x) = ((g ⟨x, 1, pow_one x⟩)⁻¹ : units A) := by rw [away.inv_self, lift'_mk, is_ring_hom.map_one f, one_mul] theorem inj_Zariski_induced_localization_of (S : set R) [is_submonoid S] : function.injective (Zariski.induced (of : R → localization R S)) := λ p q h, subtype.eq $ calc p.1 = ideal.map of (ideal.comap of p.1) : (map_comap _ _).symm ... = ideal.map of ((Zariski.induced of p).1) : rfl ... = ideal.map of ((Zariski.induced of q).1) : by rw h ... = ideal.map of (ideal.comap of q.1) : rfl ... = q.1 : map_comap _ _ -- theorem Zariski_induced_localization_of_D (S : set R) [is_submonoid S] (r : R) (s : S) : -- Zariski.induced of '' (Spec.DO (localization R S) (mk r s)).1 = -- Spec.DO R r := -- set.ext $ λ p, ⟨λ ⟨q, hq, hqp⟩, by change mk r s ∉ q.1.1 at hq, _⟩ -- #exit theorem map_eq (S : set R) [is_submonoid S] (I : ideal R) : (I.map (of : R → localization R S)).1 = { m | ∃ r ∈ I, ∃ s ∈ S, mk r ⟨s, H⟩ = m } := set.ext $ λ x, ⟨λ hx, submodule.span_induction hx (λ x ⟨r, hrI, hrx⟩, ⟨r, hrI, 1, is_submonoid.one_mem S, hrx⟩) ⟨0, I.zero_mem, 1, is_submonoid.one_mem S, rfl⟩ (λ x y ⟨r1, hrI1, s1, hs1, ihx⟩ ⟨r2, hrI2, s2, hs2, ihy⟩, ⟨s1 * r2 + s2 * r1, I.add_mem (I.mul_mem_left hrI2) (I.mul_mem_left hrI1), s1 * s2, is_submonoid.mul_mem hs1 hs2, by rw [← ihx, ← ihy]; refl⟩) (λ c x ⟨r, hrI, s, hs, hx⟩, localization.induction_on c $ λ r2 s2, ⟨r2 * r, I.mul_mem_left hrI, s2.1 * s, is_submonoid.mul_mem s2.2 hs, hx ▸ rfl⟩), λ ⟨r, hrI, s, hs, hx⟩, by rw [← hx, mk_eq]; exact (I.map (of : R → localization R S)).mul_mem_right (ideal.mem_map_of_mem hrI)⟩ theorem mem_map (S : set R) [is_submonoid S] (I : ideal R) (x : localization R S) : x ∈ I.map (of : R → localization R S) ↔ ∃ r ∈ I, ∃ s ∈ S, mk r ⟨s, H⟩ = x := show x ∈ (I.map of).1 ↔ _, by rw map_eq; refl theorem comap_map (S : set R) [is_submonoid S] (I : ideal R) : ((I.map (of : R → localization R S)).comap of).1 = { r | ∃ s ∈ S, r * s ∈ I } := begin change of ⁻¹' (I.map of).1 = _, rw map_eq, ext x, split, { rintros ⟨r, hrI, s, hs, hx⟩, rcases quotient.exact hx with ⟨t, htS, ht⟩, change (s * x - 1 * r) * t = 0 at ht, rw [sub_mul, one_mul, sub_eq_zero] at ht, refine ⟨s * t, is_submonoid.mul_mem hs htS, _⟩, rw [mul_left_comm, ← mul_assoc, ht], exact I.mul_mem_right hrI }, { rintros ⟨s, hs, hxsI⟩, refine ⟨x * s, hxsI, s, hs, mk_mul_cancel_right x ⟨s, hs⟩⟩ } end theorem mem_comap_map (S : set R) [is_submonoid S] (I : ideal R) (x : R) : x ∈ (I.map (of : R → localization R S)).comap of ↔ ∃ s ∈ S, x * s ∈ I := show x ∈ ((I.map of).comap of).1 ↔ _, by rw comap_map; refl theorem prime_map (S : set R) [is_submonoid S] (p : ideal R) (hp1 : p.is_prime) (hp2 : S ∩ p.1 = ∅) : (p.map (of : R → localization R S)).is_prime := begin rw set.eq_empty_iff_forall_not_mem at hp2, split, { intros h1, have h2 : ((p.map (of : R → localization R S)).comap of).1 = set.univ, { rw h1, refl }, rw [comap_map, set.eq_univ_iff_forall] at h2, rcases h2 1 with ⟨s, hs, hsp⟩, rw one_mul at hsp, exact hp2 s ⟨hs, hsp⟩ }, intros x y, refine localization.induction_on x (λ r1 s1, localization.induction_on y (λ r2 s2, _)), cases s1 with s1 hs1, cases s2 with s2 hs2, rw [mem_map, mem_map, mem_map], rintros ⟨r, hrp, s, hs, h1⟩, rcases quotient.exact h1 with ⟨t, hts, ht⟩, change (s * (r1 * r2) - s1 * s2 * r) * t = 0 at ht, rw [sub_mul, sub_eq_zero] at ht, have h2 : s1 * s2 * r * t ∈ p := p.mul_mem_right (p.mul_mem_left hrp), rw ← ht at h2, have hsp : s ∉ p := mt (and.intro hs) (hp2 s), have htp : t ∉ p := mt (and.intro hts) (hp2 t), replace h2 := (hp1.2 h2).resolve_right htp, replace h2 := (hp1.2 h2).resolve_left hsp, cases hp1.2 h2 with hrp1 hrp2, { exact or.inl ⟨r1, hrp1, s1, hs1, rfl⟩ }, { exact or.inr ⟨r2, hrp2, s2, hs2, rfl⟩ } end theorem prime_map_away (x : R) (p : ideal R) (hp1 : p.is_prime) (hp2 : x ∉ p) : (p.map (of : R → localization.away x)).is_prime := prime_map _ _ hp1 $ set.eq_empty_iff_forall_not_mem.2 $ λ r ⟨⟨n, hn⟩, hr⟩, hp2 $ hp1.mem_of_pow_mem n (hn.symm ▸ hr) theorem comap_map_away (x : R) (p : ideal R) (hp1 : p.is_prime) (hp2 : x ∉ p) : (p.map (localization.of : R → localization.away x)).comap localization.of = p := ideal.ext $ λ y, by rw localization.mem_comap_map; exact ⟨λ ⟨_, ⟨n, rfl⟩, h⟩, (hp1.2 h).resolve_right (mt (hp1.mem_of_pow_mem n) hp2), λ hy, ⟨_, ⟨0, pow_zero x⟩, by rwa mul_one⟩⟩ end localization variables {R : Type u} [comm_ring R] theorem range_Zariski_induced_localization_of (S : set R) [is_submonoid S] : set.range (Zariski.induced (localization.of : R → localization R S)) = ⋂ s ∈ S, (Spec.DO R s).1 := set.ext $ λ p, ⟨λ ⟨q, hqp⟩, hqp ▸ set.mem_bInter (λ s hs hsq, p.2.1 $ p.1.eq_top_iff_one.2 $ have localization.mk s ⟨s, hs⟩ = 1, from localization.mk_self, by rw ← hqp; change localization.of (1:R) ∈ q.1; rw [localization.of_one, ← this, localization.mk_eq]; exact q.1.mul_mem_right hsq), λ hp, ⟨⟨ideal.map localization.of p.1, localization.prime_map _ _ p.2 (set.eq_empty_iff_forall_not_mem.2 $ λ r hr, set.mem_bInter_iff.1 hp r hr.1 hr.2)⟩, subtype.eq $ ideal.ext $ λ x, ⟨λ hx, let ⟨s, hs, hxsp⟩ := (localization.mem_comap_map _ _ _).1 hx in (p.2.2 hxsp).resolve_right $ set.mem_bInter_iff.1 hp s hs, λ hx, (localization.mem_comap_map _ _ _).2 ⟨1, is_submonoid.one_mem S, by rwa mul_one⟩⟩⟩⟩ @[simp] theorem Spec.D'_one : Spec.D' (1:R) = set.univ := set.eq_univ_of_forall $ λ p hp, p.2.1 $ p.1.eq_top_iff_one.2 hp @[simp] theorem Spec.DO_one : Spec.DO R 1 = ⊤ := opens.ext Spec.D'_one @[simp] theorem Spec.D'_pow_succ (x : R) (n : ℕ) : Spec.D' (x^(n+1)) = Spec.D' x := set.ext $ λ p, not_congr ⟨p.2.mem_of_pow_mem (n+1), p.1.mul_mem_right⟩ @[simp] theorem Spec.DO_pow_succ (x : R) {n : ℕ} : Spec.DO R (x^(n+1)) = Spec.DO R x := opens.ext $ Spec.D'_pow_succ x n theorem range_Zariski_induced_localization_away_of (x : R) : set.range (Zariski.induced (localization.of : R → localization.away x)) = (Spec.DO R x).1 := (range_Zariski_induced_localization_of _).trans $ set.subset.antisymm (set.bInter_subset_of_mem ⟨1, pow_one x⟩) (set.subset_bInter $ λ r ⟨n, hxnr⟩, hxnr ▸ nat.cases_on n (by rw [pow_zero, Spec.DO_one]; exact set.subset_univ _) (λ n, by rw Spec.DO_pow_succ; exact set.subset.refl _)) theorem exists_Zariski_induced_of_not_mem (x : R) (p : Spec R) (hp : x ∉ p.1) : ∃ q : Spec (localization.away x), Zariski.induced localization.of q = p := ((set.ext_iff _ _).1 (range_Zariski_induced_localization_away_of x) _).2 hp theorem localization.mk_mem_iff (S : set R) [is_submonoid S] (I : ideal (localization R S)) (r : R) (s : S) : localization.mk r s ∈ I ↔ localization.of r ∈ I := ⟨λ hx, have localization.mk r s * localization.mk s 1 ∈ I := I.mul_mem_right hx, by rwa [localization.mk_mul_mk, mul_one, localization.mk_mul_cancel_right] at this, λ hx, by rw localization.mk_eq_mul_mk_one; exact I.mul_mem_right hx⟩ theorem Zariski_induced_localization_of_V (S : set R) [is_submonoid S] (E : set (localization R S)) : Zariski.induced localization.of '' Spec.V E = Spec.V { r | ∃ s : S, localization.mk r s ∈ E } ∩ set.range (Zariski.induced (localization.of : R → localization R S)) := set.ext $ λ p, ⟨λ ⟨q, hq, hqp⟩, ⟨λ r ⟨s, hrs⟩, hqp ▸ (localization.mk_mem_iff _ _ _ _).1 (hq hrs), q, hqp⟩, λ ⟨hp, q, hqp⟩, ⟨q, λ x, localization.induction_on x $ λ r s hrs, (localization.mk_mem_iff _ _ _ _).2 (show r ∈ (Zariski.induced localization.of q).1, from hqp.symm ▸ hp ⟨s, hrs⟩), hqp⟩⟩ theorem set.image_compl_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : function.injective f) (s : set α) : f '' -s = set.range f \ f '' s := set.ext $ λ b, ⟨λ ⟨a, hnas, hab⟩, ⟨⟨a, hab⟩, λ ⟨x, hxs, hxb⟩, hnas (hf (hxb.trans hab.symm) ▸ hxs)⟩, λ ⟨⟨a, hab⟩, hnbs⟩, ⟨a, λ has, hnbs (hab ▸ ⟨a, has, rfl⟩), hab⟩⟩ theorem set.diff_inter {α : Type u} (s t u : set α) : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := set.ext $ λ x, by simp only [set.mem_diff, set.mem_inter_iff, set.mem_union, not_and, auto.classical.implies_iff_not_or, and_or_distrib_left] theorem Zariski_induced_localization_of_D (S : set R) [is_submonoid S] (E : set (localization R S)) : Zariski.induced localization.of '' Spec.D E = Spec.D { r | ∃ s : S, localization.mk r s ∈ E } ∩ set.range (Zariski.induced (localization.of : R → localization R S)) := by rw [Spec.D, set.image_compl_of_injective (localization.inj_Zariski_induced_localization_of S), Zariski_induced_localization_of_V, set.diff_inter, set.diff_self, set.union_empty, set.inter_comm]; refl theorem Zariski.is_open_iff (U : set (Spec R)) : is_open U ↔ ∃ E : set R, Spec.D E = U := ⟨λ ⟨E, HE⟩, ⟨E, set.compl_compl U ▸ HE ▸ rfl⟩, λ ⟨E, HE⟩, ⟨E, HE ▸ (set.compl_compl $ Spec.V E).symm⟩⟩ theorem open_Zariski_induced_localization_of (x : R) (U : set (Spec (localization.away x))) (hu : is_open U) : is_open (Zariski.induced localization.of '' U) := let ⟨E, HEU⟩ := (Zariski.is_open_iff U).1 hu in by rw [← HEU, Zariski_induced_localization_of_D, range_Zariski_induced_localization_away_of]; exact is_open_inter ((Zariski.is_open_iff _).2 ⟨_, rfl⟩) (Spec.DO R x).2 @[simp] lemma congr_arg_Zariski {A : Type v} [comm_ring A] {f g : R → A} [is_ring_hom f] [is_ring_hom g] (h : f = g) (p) : Zariski.induced f p = Zariski.induced g p := subtype.eq $ ideal.ext $ λ x, show f x ∈ p.1 ↔ g x ∈ p.1, by rw h @[simp] lemma Zariski_induced_id (p) : Zariski.induced (id : R → R) p = p := subtype.eq $ ideal.ext $ λ x, iff.rfl @[simp] lemma Zariski_induced_comp {A : Type v} [comm_ring A] {B : Type w} [comm_ring B] (f : R → A) [is_ring_hom f] (g : A → B) [is_ring_hom g] (p) : Zariski.induced (g ∘ f) p = Zariski.induced f (Zariski.induced g p) := rfl def ideal.principal (x : R) : ideal R := { carrier := { r | ∃ y, x * y = r }, zero := ⟨0, mul_zero x⟩, add := λ r s ⟨y, hy⟩ ⟨z, hz⟩, ⟨y + z, by rw [mul_add, hy, hz]⟩, smul := λ c r ⟨y, hy⟩, ⟨c * y, by rw [mul_left_comm, hy]; refl⟩ } theorem ideal.mem_principal {x : R} : x ∈ ideal.principal x := ⟨1, mul_one x⟩ theorem ideal.principal_le_iff {x : R} {I : ideal R} : ideal.principal x ≤ I ↔ x ∈ I := ⟨λ hx, hx ideal.mem_principal, λ hx r ⟨y, hy⟩, hy ▸ I.mul_mem_right hx⟩ theorem exists_maximal_of_mem_nonunits {x : R} (hx : x ∈ nonunits R) : ∃ M : ideal R, M.is_maximal ∧ x ∈ M := by simpa only [ideal.principal_le_iff] using ideal.exists_le_maximal (ideal.principal x) ((ideal.ne_top_iff_one _).2 $ λ ⟨y, hy⟩, hx $ is_unit_of_mul_one _ _ hy) noncomputable def of_Spec_top (R : Type u) [comm_ring R] : (Spec.locally_ringed_space R).O ⊤ → R := localization.lift id (λ r (hr : r ∈ S (⊤ : opens (Spec R))), classical.by_contradiction $ λ hrnu, let ⟨M, hm, hxm⟩ := exists_maximal_of_mem_nonunits hrnu in @hr ⟨M, hm.is_prime⟩ trivial hxm) ∘ of_presheaf_of_rings_extension _ (D_fs_standard_basis R) _ structure_presheaf_on_basis_is_sheaf_on_basis (D_fs_standard_basis R).1 instance of_Spec_top.is_ring_hom : is_ring_hom (of_Spec_top R) := by haveI := of_presheaf_of_rings_extension.is_ring_hom (D_fs_basis R) (D_fs_standard_basis R) (structure_presheaf_on_basis R) structure_presheaf_on_basis_is_sheaf_on_basis (D_fs_standard_basis R).1; exact @@is_ring_hom.comp _ _ _ _inst _ _ _ section variables {A : Type u} [comm_ring A] {B : Type v} [comm_ring B] (f : A → B) [is_ring_hom f] theorem comap_Zariski_mem_Dfs {U : opens (Spec A)} (HU : U ∈ D_fs A) : opens.comap (Zariski.induced.continuous f) U ∈ D_fs B := let ⟨g, hg⟩ := HU in ⟨f g, by rw hg; exact opens.ext (Zariski.induced.preimage_D f g)⟩ theorem of_mem_S {U : opens (Spec A)} {r : A} (hr : r ∈ S U) : f r ∈ S (opens.comap (Zariski.induced.continuous f) U) := λ q hqu hrq, hr hqu hrq def Zariski.induced.presheaf_on_basis (U : opens (Spec A)) (HUB : U ∈ D_fs A) (s : (structure_presheaf_on_basis A).to_presheaf_on_basis HUB) : (structure_presheaf_on_basis B).to_presheaf_on_basis (comap_Zariski_mem_Dfs f HUB) := localization.lift' (localization.of ∘ f) (λ z, localization.to_units ⟨f z.1, of_mem_S f z.2⟩) (λ z, rfl) s instance Zariski.induced.presheaf_on_basis.is_ring_hom (U : opens (Spec A)) (HUB : U ∈ D_fs A) : is_ring_hom (Zariski.induced.presheaf_on_basis f U HUB) := @@localization.lift'.is_ring_hom _ _ _ _ (@@is_ring_hom.comp _ _ _ _inst_4 _ _ localization.of.is_ring_hom) _ _ def Zariski.induced.stalk_on_basis_elem (p : Spec B) (g : stalk_on_basis.elem (structure_presheaf_on_basis A).to_presheaf_on_basis (Zariski.induced f p)) : stalk_on_basis.elem (structure_presheaf_on_basis B).to_presheaf_on_basis p := ⟨opens.comap (Zariski.induced.continuous f) g.1, comap_Zariski_mem_Dfs f g.2, g.3, Zariski.induced.presheaf_on_basis f g.1 g.2 g.4⟩ def Zariski.induced.stalk_on_basis (p : Spec B) (s : stalk_of_rings_on_standard_basis.stalk_of_rings_on_standard_basis (D_fs_standard_basis A) (structure_presheaf_on_basis A) (Zariski.induced f p)) : stalk_of_rings_on_standard_basis.stalk_of_rings_on_standard_basis (D_fs_standard_basis B) (structure_presheaf_on_basis B) p := quotient.lift_on s (λ g, ⟦Zariski.induced.stalk_on_basis_elem f p g⟧) $ λ g1 g2 ⟨U, HUB, HFPU, HU1, HU2, hg⟩, begin clear_, cases g1 with U1 HUB1 HFPU1 s1, cases g2 with U2 HUB2 HFPU2 s2, dsimp only at HU1 HU2 hg ⊢, revert hg, refine localization.induction_on s1 (λ r1 t1, _), refine localization.induction_on s2 (λ r2 t2, _), intros hg, rcases quotient.exact hg with ⟨t, hts, ht⟩, change (t1.1 * r2 - t2.1 * r1) * t = 0 at ht, refine quotient.sound ⟨opens.comap (Zariski.induced.continuous f) U, comap_Zariski_mem_Dfs f HUB, HFPU, opens.comap_mono _ _ _ HU1, opens.comap_mono _ _ _ HU2, quotient.sound ⟨f t, of_mem_S f hts, _⟩⟩, change ((1 * f t1.1) * (f r2 * 1) - (1 * f t2.1) * (f r1 * 1)) * f t = 0, rw [one_mul, mul_one, one_mul, mul_one, ← is_ring_hom.map_mul f, ← is_ring_hom.map_mul f, ← is_ring_hom.map_sub f, ← is_ring_hom.map_mul f, ht, is_ring_hom.map_zero f] end theorem Zariski.induced.stalk_on_basis.map_one (p : Spec B) : Zariski.induced.stalk_on_basis f p 1 = 1 := quotient.sound ⟨⊤, (D_fs_standard_basis B).1, trivial, show ⊤ ≤ opens.comap (Zariski.induced.continuous f) ⊤, by rw opens.comap_top; exact le_refl ⊤, show (⊤ : opens (Spec B)) ≤ ⊤, from le_refl ⊤, show localization.mk (f 1 * 1) ⟨1 * f 1, _⟩ = 1, by simp only [mul_one, one_mul, localization.mk_self]⟩ theorem Zariski.induced.stalk_on_basis.map_add (p : Spec B) (x y) : Zariski.induced.stalk_on_basis f p (x + y) = Zariski.induced.stalk_on_basis f p x + Zariski.induced.stalk_on_basis f p y := quotient.induction_on₂ x y $ λ p q, begin cases p with U HUB hfpU s, cases q with V HVB hfpV t, refine localization.induction_on s (λ r1 s1, _), refine localization.induction_on t (λ r2 s2, _), refine quotient.sound ⟨opens.comap (Zariski.induced.continuous f) (U ∩ V), comap_Zariski_mem_Dfs f ((D_fs_standard_basis A).2 HUB HVB), ⟨hfpU, hfpV⟩, set.subset.refl _, set.subset.refl _, _⟩, show localization.mk (f (s1.1 * r2 + s2.1 * r1) * 1) ⟨1 * f (s1.1 * s2.1), _⟩ = localization.mk ((1 * f s1.1) * (f r2 * 1) + (1 * f s2.1) * (f r1 * 1)) ⟨(1 * f s1.1) * (1 * f s2.1), _⟩, simp only [mul_one, one_mul, is_ring_hom.map_add f, is_ring_hom.map_mul f] end theorem Zariski.induced.stalk_on_basis.map_mul (p : Spec B) (x y) : Zariski.induced.stalk_on_basis f p (x * y) = Zariski.induced.stalk_on_basis f p x * Zariski.induced.stalk_on_basis f p y := quotient.induction_on₂ x y $ λ p q, begin cases p with U HUB hfpU s, cases q with V HVB hfpV t, refine localization.induction_on s (λ r1 s1, _), refine localization.induction_on t (λ r2 s2, _), refine quotient.sound ⟨opens.comap (Zariski.induced.continuous f) (U ∩ V), comap_Zariski_mem_Dfs f ((D_fs_standard_basis A).2 HUB HVB), ⟨hfpU, hfpV⟩, set.subset.refl _, set.subset.refl _, _⟩, show localization.mk (f (r1 * r2) * 1) ⟨1 * f (s1.1 * s2.1), _⟩ = localization.mk ((f r1 * 1) * (f r2 * 1)) ⟨(1 * f s1.1) * (1 * f s2.1), _⟩, simp only [mul_one, one_mul, is_ring_hom.map_mul f] end instance Spec.is_prime (p : Spec R) : ideal.is_prime p.1 := p.2 def to_stalk_on_basis {X : Type u} [topological_space X] {B : set (opens X)} {HB : opens.is_basis B} {Bstd : ⊤ ∈ B ∧ ∀ {U V}, U ∈ B → V ∈ B → U ∩ V ∈ B} {p : X} (F : presheaf_of_rings_on_basis X HB) (U : opens X) (HUB : U ∈ B) (hpU : p ∈ U) (s : F.1 HUB) : stalk_of_rings_on_standard_basis.stalk_of_rings_on_standard_basis Bstd F p := ⟦⟨U, HUB, hpU, s⟩⟧ instance to_stalk_on_basis.is_ring_hom {X : Type u} [topological_space X] {B : set (opens X)} {HB : opens.is_basis B} {Bstd : ⊤ ∈ B ∧ ∀ {U V}, U ∈ B → V ∈ B → U ∩ V ∈ B} {p : X} (F : presheaf_of_rings_on_basis.{u v} X HB) (U : opens X) (HUB : U ∈ B) (hpU : p ∈ U) : is_ring_hom (@to_stalk_on_basis _ _ _ _ Bstd _ F U HUB hpU) := { map_one := quotient.sound ⟨U, HUB, hpU, set.subset.refl U.1, set.subset_univ U.1, (is_ring_hom.map_one (F.to_presheaf_on_basis.res _ HUB _)).trans (is_ring_hom.map_one (F.to_presheaf_on_basis.res _ HUB _)).symm⟩, map_mul := λ x y, quotient.sound ⟨U, HUB, hpU, set.subset.refl U.1, set.subset_inter (set.subset.refl U.1) (set.subset.refl U.1), by dsimp only; rw [is_ring_hom.map_mul (F.1.res _ _ _), is_ring_hom.map_mul (F.1.res _ _ _), ← presheaf_on_basis.Hcomp', ← presheaf_on_basis.Hcomp']; apply_instance⟩, map_add := λ x y, quotient.sound ⟨U, HUB, hpU, set.subset.refl U.1, set.subset_inter (set.subset.refl U.1) (set.subset.refl U.1), by dsimp only; rw [is_ring_hom.map_add (F.1.res _ _ _), is_ring_hom.map_add (F.1.res _ _ _), ← presheaf_on_basis.Hcomp', ← presheaf_on_basis.Hcomp']; apply_instance⟩ } def stalk_on_basis_of (p : Spec R) (r : R) : stalk_of_rings_on_standard_basis.stalk_of_rings_on_standard_basis (D_fs_standard_basis R) (structure_presheaf_on_basis R) p := to_stalk_on_basis _ ⊤ (D_fs_standard_basis R).1 trivial (localization.of r) instance stalk_on_basis_of.is_ring_hom (p : Spec R) : is_ring_hom (stalk_on_basis_of p) := is_ring_hom.comp _ _ def stalk_on_basis_of_localization (p : Spec R) (x : localization.at_prime p.1) : stalk_of_rings_on_standard_basis.stalk_of_rings_on_standard_basis (D_fs_standard_basis R) (structure_presheaf_on_basis R) p := localization.lift' (stalk_on_basis_of p) (λ r : -(p.1 : set R), (units.map' (to_stalk_on_basis (structure_presheaf_on_basis R) (Spec.DO R r.1) ⟨r.1, rfl⟩ r.2): units (((structure_presheaf_on_basis R).to_presheaf_on_basis) ⟨r.1, rfl⟩) →* units (stalk_of_rings_on_standard_basis.stalk_of_rings_on_standard_basis (D_fs_standard_basis R) (structure_presheaf_on_basis R) p)) $ localization.to_units ⟨r.1, set.subset.refl _⟩) (λ r, quotient.sound ⟨Spec.DO R r.1, ⟨r.1, rfl⟩, r.2, set.subset.refl _, set.subset_univ _, rfl⟩) x instance stalk_on_basis_of_localization.is_ring_hom (p : Spec R) : is_ring_hom (stalk_on_basis_of_localization p) := localization.lift'.is_ring_hom _ _ _ theorem stalk_on_basis_of_localization.bijective (p : Spec R) : function.bijective (stalk_on_basis_of_localization p) := begin split, { intros x y, refine localization.induction_on x (λ r1 s1, _), refine localization.induction_on y (λ r2 s2, _), rintros h, replace h := quotient.exact h, rcases h with ⟨U, HUB, hpU, HU1, HU2, h⟩, dsimp only [opens.inter_eq] at HU1 HU2, replace h := quotient.exact h, rcases h with ⟨t, hts, ht⟩, change ((1 * s1.1) * (r2 * 1) - (1 * s2.1) * (r1 * 1)) * t = 0 at ht, rw lattice.top_inf_eq at HU1 HU2, simp only [mul_one, one_mul] at ht, refine quotient.sound ⟨t, hts hpU, ht⟩ }, { intros s, refine quotient.induction_on s (λ g, _), rcases g with ⟨U, HUB, hpU, g⟩, refine localization.induction_on g (λ r s, _), refine ⟨localization.mk r ⟨s, s.2 hpU⟩, quotient.sound ⟨U, HUB, hpU, set.subset_inter (set.subset_univ _) s.2, set.subset.refl _, _⟩⟩, change localization.mk (r * 1) ⟨1 * s.1, _⟩ = localization.mk r ⟨s.1, _⟩, simp only [mul_one, one_mul], } end theorem stalk_on_basis_of_localization.unit (p : Spec R) (x) : is_unit (stalk_on_basis_of_localization p x) ↔ is_unit x := begin split, { rw [is_unit_iff_exists_inv, is_unit_iff_exists_inv], rintros ⟨y, hxy⟩, rcases (stalk_on_basis_of_localization.bijective p).2 y with ⟨y, rfl⟩, rw [← is_ring_hom.map_mul (stalk_on_basis_of_localization p), ← is_ring_hom.map_one (stalk_on_basis_of_localization p)] at hxy, exact ⟨y, (stalk_on_basis_of_localization.bijective p).1 hxy⟩ }, { exact λ hx, is_unit.map' _ hx } end def Zariski.induced.stalk_on_basis.algebraic (p : Spec B) (s : localization.at_prime (Zariski.induced f p).1) : localization.at_prime p.1 := localization.lift' (localization.of ∘ f) (λ r : -((Zariski.induced f p).1 : set A), localization.to_units ⟨f r.1, r.2⟩) (λ s, rfl) s theorem Zariski.induced.stalk_on_basis.algebraic.coe (p : Spec B) (r : A) : Zariski.induced.stalk_on_basis.algebraic f p r = f r := localization.lift'_coe _ _ _ _ theorem Zariski.induced.stalk_on_basis.algebraic.of (p : Spec B) (r : A) : Zariski.induced.stalk_on_basis.algebraic f p (localization.of r) = localization.of (f r) := localization.lift'_of _ _ _ _ instance Zariski.induced.stalk_on_basis.algebraic.hom (p : Spec B) : is_ring_hom (Zariski.induced.stalk_on_basis.algebraic f p) := localization.lift'.is_ring_hom _ _ _ theorem Zariski.induced.stalk_on_basis.stalk_on_basis_of_localization (p : Spec B) (s) : Zariski.induced.stalk_on_basis f p (stalk_on_basis_of_localization (Zariski.induced f p) s) = stalk_on_basis_of_localization p (Zariski.induced.stalk_on_basis.algebraic f p s) := localization.induction_on s $ λ r s, quotient.sound ⟨opens.comap (Zariski.induced.continuous f) (Spec.DO A s.1), comap_Zariski_mem_Dfs f ⟨s.1, rfl⟩, s.2, set.subset_inter (set.subset_univ _) (set.subset.refl _), show opens.comap (Zariski.induced.continuous f) (Spec.DO A s.1) ≤ ⊤ ⊓ Spec.DO B (1 * f s.1), by rw [one_mul, lattice.top_inf_eq]; exact le_refl _, show localization.mk (f (r * 1) * 1) ⟨1 * f (1 * s.1), _⟩ = localization.mk (f r * 1 * 1) ⟨1 * (1 * f s.1), _⟩, by simp only [one_mul, mul_one]⟩ theorem Zariski.induced.stalk_on_basis.algebraic.hlocal (p : Spec B) (s) (H : is_unit (Zariski.induced.stalk_on_basis.algebraic f p s)) : is_unit s := begin refine localization.induction_on s (λ r s, _) H, change is_unit (localization.mk (f r * 1) ⟨1 * f s.1, _⟩) → is_unit (localization.mk r s), rw [is_unit_localization_mk, is_unit_localization_mk], rintros ⟨t, hr⟩, refine ⟨1, λ h, hr _⟩, rw mul_one at h ⊢, exact p.1.mul_mem_right h end theorem Zariski.induced.stalk_on_basis.hlocal (p : Spec B) (x) (H : is_unit (Zariski.induced.stalk_on_basis f p x)) : is_unit x := begin rcases (stalk_on_basis_of_localization.bijective $ Zariski.induced f p).2 x with ⟨s, rfl⟩, rw Zariski.induced.stalk_on_basis.stalk_on_basis_of_localization at H, rw stalk_on_basis_of_localization.unit at H ⊢, exact Zariski.induced.stalk_on_basis.algebraic.hlocal f p s H end set_option class.instance_max_depth 10 def Zariski.induced.locally_ringed_space {A : Type u} [comm_ring A] {B : Type v} [comm_ring B] (f : A → B) [is_ring_hom f] : locally_ringed_space.morphism (Spec.locally_ringed_space B) (Spec.locally_ringed_space A) := { f := Zariski.induced f, Hf := Zariski.induced.continuous f, fO := { map := λ U s, ⟨λ p hp, Zariski.induced.stalk_on_basis f p $ s.1 (Zariski.induced f p) hp, λ p hp, let ⟨V, HVB, hfpV, σ, hσ⟩ := s.2 (Zariski.induced f p) hp in ⟨opens.comap (Zariski.induced.continuous f) V, comap_Zariski_mem_Dfs f HVB, hfpV, Zariski.induced.presheaf_on_basis f V HVB σ, λ q hqUV, funext $ λ hq, by rw [hσ (Zariski.induced f q) hqUV]; refl⟩⟩, commutes := λ U V HVU, rfl }, hom := λ U, { map_one := subtype.eq $ by funext p hp; apply Zariski.induced.stalk_on_basis.map_one, map_mul := λ x y, subtype.eq $ by funext p hp; simp only [Fext_mul.eq]; apply Zariski.induced.stalk_on_basis.map_mul, map_add := λ x y, subtype.eq $ by funext p hp; simp only [Fext_add.eq]; apply Zariski.induced.stalk_on_basis.map_add }, Hstalks := begin rintros p s, refine quotient.induction_on s (λ g hg, _), cases g with U hfpU σ, change is_unit (to_stalk (Spec.locally_ringed_space B).O.F p (opens.comap (Zariski.induced.continuous f) U) hfpU _) at hg, change is_unit (to_stalk (Spec.locally_ringed_space A).O.F (Zariski.induced f p) U hfpU σ), erw is_unit_to_stalk_on_basis at hg ⊢, exact Zariski.induced.stalk_on_basis.hlocal f p _ hg, end } end section res_open variables {X : Type u} [topological_space X] def topological_space.opens.map_subtype_val {U : opens X} (V : opens U) : opens X := ⟨subtype.val '' V.1, let ⟨W, HW, HWV⟩ := V.2 in by rw [← HWV, subtype.image_preimage_val]; exact is_open_inter HW U.2⟩ theorem map_subtype_val_inf {U : opens X} (V W : opens U) : (V ⊓ W).map_subtype_val = V.map_subtype_val ⊓ W.map_subtype_val := opens.ext $ eq.symm $ set.image_inter subtype.val_injective def presheaf.res_open (F : presheaf X) (U : opens X) : presheaf U := { F := λ V, F V.map_subtype_val, res := λ V W HWV, F.res _ _ (set.image_subset _ HWV), Hid := λ V, F.Hid _, Hcomp := λ V W S HSW HWV, F.Hcomp _ _ _ _ _ } def covering.map_subtype_val {U : opens X} {V : opens U} (OC : covering V) : covering V.map_subtype_val := { γ := OC.γ, Uis := λ i, (OC.Uis i).map_subtype_val, Hcov := opens.ext $ set.subset.antisymm (set.sUnion_subset $ λ t ⟨u, ⟨i, hiu⟩, hut⟩, hut ▸ hiu ▸ set.image_subset _ (subset_covering i)) (λ v ⟨x, hxV, hxv⟩, let ⟨t, ⟨_, ⟨i, rfl⟩, rfl⟩, hxi⟩ := set.mem_sUnion.1 (((set.ext_iff _ _).1 (congr_arg subtype.val OC.Hcov) x).2 hxV) in hxv ▸ set.mem_sUnion.2 ⟨_, ⟨_, ⟨i, rfl⟩, rfl⟩, x, hxi, rfl⟩) } def presheaf_of_rings.res_open (F : presheaf_of_rings X) (U : opens X) : presheaf_of_rings U := { Fring := λ V, F.Fring _, res_is_ring_hom := λ V W HWV, F.res_is_ring_hom _ _ _, .. F.1.res_open U } theorem locality.res_open {F : presheaf X} (HF : locality F) (U : opens X) : locality (F.res_open U) := λ V OC s t H, HF OC.map_subtype_val s t H theorem gluing.res_open {F : presheaf X} (HF : gluing F) (U : opens X) : gluing (F.res_open U) := λ V OC s H, HF OC.map_subtype_val s $ λ j k, calc F.res (OC.Uis j).map_subtype_val ((OC.Uis j).map_subtype_val ⊓ (OC.Uis k).map_subtype_val) _ (s j) = F.res (OC.Uis j ⊓ OC.Uis k).map_subtype_val ((OC.Uis j).map_subtype_val ⊓ (OC.Uis k).map_subtype_val) (by rw [map_subtype_val_inf]; refl) (F.res (OC.Uis j).map_subtype_val (OC.Uis j ⊓ OC.Uis k).map_subtype_val (set.image_subset _ $ set.inter_subset_left _ _) (s j)) : by rw ← presheaf.Hcomp'; refl ... = F.res (OC.Uis j ⊓ OC.Uis k).map_subtype_val ((OC.Uis j).map_subtype_val ⊓ (OC.Uis k).map_subtype_val) (by rw [map_subtype_val_inf]; refl) (F.res (OC.Uis k).map_subtype_val (OC.Uis j ⊓ OC.Uis k).map_subtype_val (set.image_subset _ $ set.inter_subset_right _ _) (s k)) : congr_arg _ (H j k) ... = F.res (OC.Uis k).map_subtype_val ((OC.Uis j).map_subtype_val ⊓ (OC.Uis k).map_subtype_val) _ (s k) : by rw ← presheaf.Hcomp'; refl def sheaf.res_open (O : sheaf X) (U : opens X) : sheaf U := { locality := λ V, O.locality.res_open U, gluing := λ V, O.gluing.res_open U, .. O.to_presheaf.res_open U } def sheaf_of_rings.to_sheaf (O : sheaf_of_rings X) : sheaf X := { .. O, .. O.F } def sheaf_of_rings.res_open (O : sheaf_of_rings X) (U : opens X) : sheaf_of_rings U := { F := O.F.res_open U, .. O.to_sheaf.res_open U } def of_stalk_of_rings_res_open (F : presheaf_of_rings X) (U : opens X) (x : U) (s : stalk_of_rings (F.res_open U) x) : stalk_of_rings F x.1 := quotient.lift_on s (λ g, to_stalk F x.1 g.1.map_subtype_val (set.mem_image_of_mem _ g.2) g.3) $ λ g1 g2 ⟨V, hxV, HV1, HV2, hx⟩, quotient.sound ⟨V.map_subtype_val, set.mem_image_of_mem _ hxV, set.image_subset _ HV1, set.image_subset _ HV2, hx⟩ theorem of_stalk_of_rings_res_open_to_stalk (F : presheaf_of_rings X) (U : opens X) (x : U) (V : opens U) (HV : x ∈ V) (s) : of_stalk_of_rings_res_open F U x (to_stalk (F.res_open U) x V HV s) = to_stalk F x.1 V.map_subtype_val (set.mem_image_of_mem _ HV) s := rfl @[elab_as_eliminator] theorem stalk_of_rings.induction_on₂ {F : presheaf_of_rings.{u v} X} {p : X} {C : stalk_of_rings F p → stalk_of_rings F p → Prop} (s t : stalk_of_rings F p) (H : ∀ U HU x y, C (to_stalk F p U HU x) (to_stalk F p U HU y)) : C s t := quotient.induction_on₂ s t $ λ ⟨U, HU, x⟩ ⟨V, HV, y⟩, show C (to_stalk F p U HU x) (to_stalk F p V HV y), from to_stalk_res F p U (U ⊓ V) HU ⟨HU, HV⟩ (set.inter_subset_left _ _) x ▸ to_stalk_res F p V (U ⊓ V) HV ⟨HU, HV⟩ (set.inter_subset_right _ _) y ▸ H (U ⊓ V) ⟨HU, HV⟩ _ _ @[elab_as_eliminator] theorem stalk_of_rings.induction_on {F : presheaf_of_rings.{u v} X} {p : X} {C : stalk_of_rings F p → Prop} (s : stalk_of_rings F p) (H : ∀ U HU x, C (to_stalk F p U HU x)) : C s := quotient.induction_on s $ λ ⟨U, HU, x⟩, H U HU x instance of_stalk_of_rings_res_open.is_ring_hom (F : presheaf_of_rings.{u v} X) (U : opens X) (x : U) : is_ring_hom (of_stalk_of_rings_res_open F U x) := { map_one := show to_stalk _ _ _ _ 1 = 1, from is_ring_hom.map_one (to_stalk _ _ _ _), map_mul := λ s t, stalk_of_rings.induction_on₂ s t $ λ V HV p q, by rw [← is_ring_hom.map_mul (to_stalk (presheaf_of_rings.res_open F U) x V HV), of_stalk_of_rings_res_open_to_stalk, of_stalk_of_rings_res_open_to_stalk, of_stalk_of_rings_res_open_to_stalk, is_ring_hom.map_mul (to_stalk F x.1 V.map_subtype_val (set.mem_image_of_mem _ HV))], map_add := λ s t, stalk_of_rings.induction_on₂ s t $ λ V HV p q, by rw [← is_ring_hom.map_add (to_stalk (presheaf_of_rings.res_open F U) x V HV), of_stalk_of_rings_res_open_to_stalk, of_stalk_of_rings_res_open_to_stalk, of_stalk_of_rings_res_open_to_stalk, is_ring_hom.map_add (to_stalk F x.1 V.map_subtype_val (set.mem_image_of_mem _ HV))] } def to_stalk_of_rings_res_open (F : presheaf_of_rings X) (U : opens X) (x : U) (s : stalk_of_rings F x.1) : stalk_of_rings (F.res_open U) x := quotient.lift_on s (λ g, to_stalk (F.res_open U) x (opens.comap continuous_subtype_val g.1) g.2 $ F.1.res _ _ (set.image_preimage_subset _ _) g.3) $ λ g1 g2 ⟨V, hxV, HV1, HV2, hv⟩, quotient.sound ⟨opens.comap continuous_subtype_val V, hxV, opens.comap_mono _ _ _ HV1, opens.comap_mono _ _ _ HV2, have _ := congr_arg (F.res V (opens.comap continuous_subtype_val V).map_subtype_val (set.image_preimage_subset (subtype.val : U → X) _)) hv, by dsimp only [presheaf_of_rings.res_open, presheaf.res_open]; rw [← presheaf.Hcomp', ← presheaf.Hcomp'] at this ⊢; exact this⟩ theorem to_stalk_of_rings_res_open_to_stalk (F : presheaf_of_rings X) (U : opens X) (x : U) (V : opens X) (HV : x.1 ∈ V) (s) : to_stalk_of_rings_res_open F U x (to_stalk F x.1 V HV s) = to_stalk (F.res_open U) x (opens.comap continuous_subtype_val V) HV (F.1.res _ _ (set.image_preimage_subset _ _) s) := rfl def presheaf_of_rings.res_open.stalk_of_rings (F : presheaf_of_rings X) (U : opens X) (x : U) : stalk_of_rings (F.res_open U) x ≃+* stalk_of_rings F x.1 := ring_equiv.of' { to_fun := of_stalk_of_rings_res_open F U x, inv_fun := to_stalk_of_rings_res_open F U x, left_inv := λ s, stalk_of_rings.induction_on s $ λ V HV s, by rw [of_stalk_of_rings_res_open_to_stalk, to_stalk_of_rings_res_open_to_stalk]; apply to_stalk_res; show subtype.val ⁻¹' (subtype.val '' V.1) ⊆ V.1; rw [set.preimage_image_eq _ subtype.val_injective], right_inv := λ s, stalk_of_rings.induction_on s $ λ V HV s, by rw [to_stalk_of_rings_res_open_to_stalk, of_stalk_of_rings_res_open_to_stalk]; apply to_stalk_res } instance to_stalk_of_rings_res_open.hom (F : presheaf_of_rings X) (U : opens X) (x : U) : is_ring_hom (to_stalk_of_rings_res_open F U x) := (presheaf_of_rings.res_open.stalk_of_rings F U x).symm.hom /- theorem is_local_ring_iff : is_local_ring R ↔ ((0:R) ≠ 1 ∧ ∀ x y : R, is_unit (x + y) → is_unit x ∨ is_unit y) := ⟨λ hr, ⟨hr.1, λ x y hxy, classical.or_iff_not_imp_left.2 $ λ hnx, classical.by_contradiction $ λ hny, absurd hxy $ (@local_ring.nonunits_ideal R (local_of_is_local_ring hr)).add_mem hnx hny⟩, λ hr, is_local_of_nonunits_ideal hr.1 $ λ x y hx hy hxy, or.cases_on (hr.2 x y hxy) hx hy⟩ -/ theorem is_unit_congr {A : Type u} [comm_ring A] {B : Type v} [comm_ring B] (e : A ≃+* B) (x : A) : is_unit (e x) ↔ is_unit x := ⟨λ hx, e.left_inv x ▸ @@is_unit.map' _ _ e.symm hx _, λ hx, @@is_unit.map' _ _ e hx _⟩ theorem is_local_ring_congr {A : Type u} [comm_ring A] {B : Type v} [comm_ring B] (e : A ≃+* B) : is_local_ring A ↔ is_local_ring B := by unfold is_local_ring; exact ⟨λ ⟨h1, h2⟩, ⟨is_ring_hom.map_zero e ▸ is_ring_hom.map_one e ▸ λ h3, h1 (e.to_equiv.bijective.1 h3), λ x, let ⟨r, hr⟩ := e.bijective.2 x in by rw [← hr, ← is_ring_hom.map_one e, ← is_ring_hom.map_sub e, is_unit_congr, is_unit_congr]; apply h2⟩, λ ⟨h1, h2⟩, ⟨is_ring_hom.map_zero e.symm ▸ is_ring_hom.map_one e.symm ▸ λ h3, h1 (e.symm.bijective.1 h3), λ x, let ⟨r, hr⟩ := e.symm.bijective.2 x in by rw [← hr, ← is_ring_hom.map_one e.symm, ← is_ring_hom.map_sub e.symm, is_unit_congr, is_unit_congr]; apply h2⟩⟩ def locally_ringed_space.res_open (OX : locally_ringed_space X) (U : opens X) : locally_ringed_space U := { O := OX.O.res_open U, Hstalks := λ x, (is_local_ring_congr $ presheaf_of_rings.res_open.stalk_of_rings OX.O.F U x).2 (OX.Hstalks x.1) } -- def covering.univ.res_open (cov : covering.univ X) (U : opens X) : covering.univ U := -- { γ := cov.γ, -- Uis := λ i, opens.comap continuous_subtype_val (cov.Uis i), -- Hcov := opens.ext $ set.eq_univ_of_forall $ λ x, -- let ⟨_, ⟨_, ⟨i, rfl⟩, rfl⟩, hxi⟩ := set.mem_sUnion.1 (((set.ext_iff _ _).1 (congr_arg subtype.val cov.Hcov) x.1).2 trivial) in -- set.mem_sUnion.2 ⟨_, ⟨_, ⟨i, rfl⟩, rfl⟩, hxi⟩ } -- def scheme.res_open (O : scheme X) (U : opens X) : scheme U := -- { carrier := O.carrier.res_open U, -- cov := O.cov.res_open U } end res_open def Zariski.coinduced (x : R) (p : Spec.DO R x) : Spec (localization.away x) := ⟨p.1.1.map localization.of, localization.prime_map_away x p.1.1 p.1.2 p.2⟩ theorem coinduced_induced (x : R) (p : Spec (localization.away x)) (hp : Zariski.induced localization.of p ∈ Spec.DO R x) : Zariski.coinduced x ⟨Zariski.induced localization.of p, hp⟩ = p := subtype.eq $ localization.map_comap R p.1 theorem induced_coinduced (x : R) (p : Spec R) (hp : p ∈ Spec.DO R x) : Zariski.induced localization.of (Zariski.coinduced x ⟨p, hp⟩) = p := subtype.eq $ localization.comap_map_away x p.1 p.2 hp theorem Zariski.coinduced.continuous (x : R) : continuous (Zariski.coinduced x) := λ U HU, ⟨Zariski.induced localization.of '' U, open_Zariski_induced_localization_of x U HU, set.ext $ λ p, ⟨λ ⟨q, hqU, hqp⟩, have q = (⟨p.1.1.map localization.of, localization.prime_map_away x p.1.1 p.1.2 p.2⟩ : Spec (localization.away x)), from subtype.eq $ by dsimp only; rw ← hqp; dsimp only [Zariski.induced]; erw localization.map_comap, show (⟨p.1.1.map localization.of, localization.prime_map_away x p.1.1 p.1.2 p.2⟩ : Spec (localization.away x)) ∈ U, from this ▸ hqU, λ hp, ⟨_, hp, subtype.eq $ by dsimp only [Zariski.induced, Zariski.coinduced]; rw localization.comap_map_away x p.1.1 p.1.2 p.2⟩⟩⟩ theorem of_mem_map_subtype_val {x : R} {U : opens (Spec.DO R x)} {p : Spec R} (hp : p ∈ U.map_subtype_val) : x ∉ p.1 := let ⟨q, hqU, hqp⟩ := hp in hqp ▸ q.2 theorem mem_of_mem_map_subtype_val {x : R} {U : opens (Spec.DO R x)} {p : Spec R} (hp : p ∈ U.map_subtype_val) : (⟨p, of_mem_map_subtype_val hp⟩ : Spec.DO R x) ∈ U := let ⟨q, hqU, hqp⟩ := hp in have q = ⟨p, of_mem_map_subtype_val hp⟩, from subtype.eq hqp, this ▸ hqU theorem Spec.D'_eq_D (x : R) : Spec.D' x = Spec.D {x} := set.ext $ λ r, not_congr $ iff.symm $ set.singleton_subset_iff def Zariski.map_away {x : R} (U : opens (Spec (localization.away x))) : opens (Spec R) := opens.map (λ U, open_Zariski_induced_localization_of x U.1 U.2) U theorem localization.map_DO {x : R} (r : R) (s : powers x) : Zariski.map_away (Spec.DO (localization.away x) (localization.mk r s)) = Spec.DO R (r * x) := opens.ext $ show Zariski.induced localization.of '' Spec.D' (localization.mk r s) = Spec.D' (r * x), by rw [Spec.D'_eq_D, Zariski_induced_localization_of_D, range_Zariski_induced_localization_away_of, Spec.D'.product_eq_inter]; exact set.ext (λ p, ⟨λ ⟨hp1, hp2⟩, ⟨λ hrp, hp1 $ λ r1 ⟨s1, hs1⟩, localization.comap_map_away x p.1 p.2 hp2 ▸ (localization.mk_mem_iff _ _ _ s1).1 ((set.mem_singleton_iff.1 hs1).symm ▸ (localization.mk_mem_iff _ _ _ s).2 (ideal.mem_map_of_mem hrp)), hp2⟩, λ ⟨hp1, hp2⟩, ⟨λ hp3, hp1 $ hp3 ⟨s, set.mem_singleton _⟩, hp2⟩⟩) theorem localization.map_away_mem_D_fs {x : R} {U : opens (Spec (localization.away x))} (HU : U ∈ D_fs (localization.away x)) : Zariski.map_away U ∈ D_fs R := let ⟨y, hy⟩ := HU in localization.induction_on y (λ r s hrs, ⟨r * x, hrs.symm ▸ localization.map_DO r s⟩) hy theorem powers_subset_S_map_away {x : R} {U : opens (Spec (localization.away x))} : powers x ⊆ S (Zariski.map_away U) := λ r hr, set.image_subset_iff.2 $ λ p hpU hrp, p.2.1 $ p.1.eq_top_of_is_unit_mem hrp ⟨localization.to_units ⟨r, hr⟩, rfl⟩ theorem mul_comm4 {α : Type u} [comm_semigroup α] (a b c d : α) : (a * b) * (c * d) = (a * c) * (b * d) := by rw [mul_assoc, mul_assoc, mul_left_comm b c d] theorem mul_sub_mul {α : Type u} [ring α] (a b c d : α) : a * b - c * d = (a - c) * (b - d) + c * (b - d) + (a - c) * d := by rw [sub_mul, mul_sub, mul_sub, sub_mul, ← sub_add, ← add_sub_assoc, ← add_sub_assoc]; simp [add_right_comm] theorem mem_S_map_away_of_mem_S {x : R} {p : R × powers x} {U : opens (Spec (localization.away x))} (hp : ⟦p⟧ ∈ S U) : p.1 ∈ S (Zariski.map_away U) := set.image_subset_iff.2 $ λ q hqU hpq, hp hqU $ prod.cases_on p (λ p1 p2, (localization.mk_mem_iff _ _ _ _).2) hpq attribute [elab_as_eliminator] quotient.hrec_on₂ def Zariski.coinduced.presheaf_on_basis {x : R} (U : opens (Spec (localization.away x))) (HUB : U ∈ D_fs (localization.away x)) (g : (structure_presheaf_on_basis (localization.away x)).to_presheaf_on_basis HUB) : (structure_presheaf_on_basis R).to_presheaf_on_basis (localization.map_away_mem_D_fs HUB) := quotient.lift_on g (λ r : localization.away x × S U, (quotient.hrec_on₂ r.1 r.2.1 (λ s t ht, localization.mk (s.1 * t.2.1) ⟨s.2.1 * t.1, is_submonoid.mul_mem (powers_subset_S_map_away s.2.2) (mem_S_map_away_of_mem_S ht)⟩) (λ s1 s2 s3 s4 ⟨t1, hts1, ht1⟩ ⟨t2, hts2, ht2⟩, function.hfunext (congr_arg _ $ quotient.sound ⟨t2, hts2, ht2⟩) $ λ _ _ _, heq_of_eq $ quotient.sound $ ⟨t1 * t2, powers_subset_S_map_away $ is_submonoid.mul_mem hts1 hts2, show (((s1.2 : R) * s2.1) * (s3.1 * s4.2) - (s3.2 * s4.1) * (s1.1 * s2.2)) * (t1 * t2) = 0, by rw [mul_comm4, mul_comm4 (s3.2 : R), mul_sub_mul, add_mul, add_mul, mul_comm4, ht1, zero_mul, zero_add, mul_comm4, ← neg_sub, neg_mul_eq_neg_mul_symm, mul_comm s4.1, mul_comm s2.1, ht2, neg_zero, mul_zero, zero_add, mul_comm4, ht1, zero_mul]⟩) r.2.2 : (structure_presheaf_on_basis R).to_presheaf_on_basis (localization.map_away_mem_D_fs HUB))) $ λ ⟨s1, s2, hs2⟩ ⟨s3, s4, hs4⟩, localization.induction_on s1 $ λ r1 d1, localization.induction_on s2 (λ r2 d2 hrd2, localization.induction_on s3 $ λ r3 d3, localization.induction_on s4 (λ r4 d4 hrd4 ⟨t, hts, ht⟩, localization.induction_on t (λ rt dt hrdts hrdt, begin show localization.mk (r1 * d2.1) ⟨d1.1 * r2, _⟩ = localization.mk (r3 * d4.1) ⟨d3.1 * r4, _⟩, change (localization.mk r2 d2 * localization.mk r3 d3 - localization.mk r4 d4 * localization.mk r1 d1) * localization.mk rt dt = 0 at hrdt, rw [localization.mk_mul_mk, localization.mk_mul_mk, sub_mul, sub_eq_zero, localization.mk_mul_mk, localization.mk_mul_mk] at hrdt, rcases quotient.exact hrdt.symm with ⟨t1, hts1, ht1⟩, refine quotient.sound ⟨dt.1 * rt * t1, is_submonoid.mul_mem (is_submonoid.mul_mem (powers_subset_S_map_away dt.2) (mem_S_map_away_of_mem_S hrdts)) (powers_subset_S_map_away hts1), _⟩, change ((d4.1 * d1.1 * dt.1) * (r2 * r3 * rt) - (d2.1 * d3.1 * dt.1) * (r4 * r1 * rt)) * t1 = 0 at ht1, change ((d1.1 * r2) * (r3 * d4.1) - (d3.1 * r4) * (r1 * d2.1)) * (dt.1 * rt * t1) = 0, rw [← ht1, sub_mul, sub_mul], simp only [mul_assoc, mul_left_comm] end) hts ht) hs4) hs2 theorem Zariski.coinduced.presheaf_on_basis_def {x : R} (U : opens (Spec (localization.away x))) (HUB : U ∈ D_fs (localization.away x)) (p q r s h) : Zariski.coinduced.presheaf_on_basis U HUB ⟦(⟦(p, q)⟧, ⟨⟦(r, s)⟧, h⟩)⟧ = ⟦(p * s.1, ⟨q.1 * r, is_submonoid.mul_mem (powers_subset_S_map_away q.2) (mem_S_map_away_of_mem_S h)⟩)⟧ := rfl instance Zariski.coinduced.presheaf_on_basis_hom {x : R} (U : opens (Spec (localization.away x))) (HUB : U ∈ D_fs (localization.away x)) : is_ring_hom (Zariski.coinduced.presheaf_on_basis U HUB) := { map_one := quotient.sound ⟨1, is_submonoid.one_mem _, show (((1 * 1) * 1 - 1 * (1 * 1)) * 1 : R) = 0, by simp only [mul_one, sub_self]⟩, map_mul := λ s t, quotient.induction_on₂ s t $ λ ⟨p1, p2, p3⟩ ⟨q1, q2, q3⟩, quotient.induction_on₂ p1 q1 $ λ ⟨x1, x2, x3⟩ ⟨y1, y2, y3⟩, quotient.induction_on₂ p2 q2 (λ ⟨x4, x5, x6⟩ ⟨y4, y5, y6⟩ p3 q3, quotient.sound $ ⟨1, is_submonoid.one_mem _, show (((x2 * y2) * (x4 * y4)) * ((x1 * x5) * (y1 * y5)) - ((x2 * x4) * (y2 * y4)) * ((x1 * y1) * (x5 * y5))) * 1 = 0, by rw [mul_one, mul_comm4 x2 y2 x4 y4, mul_comm4 x1 x5 y1 y5, sub_self]⟩) p3 q3, map_add := λ s t, quotient.induction_on₂ s t $ λ ⟨p1, p2, p3⟩ ⟨q1, q2, q3⟩, quotient.induction_on₂ p1 q1 $ λ ⟨x1, x2, x3⟩ ⟨y1, y2, y3⟩, quotient.induction_on₂ p2 q2 (λ ⟨x4, x5, x6⟩ ⟨y4, y5, y6⟩ p3 q3, quotient.sound $ ⟨1, is_submonoid.one_mem _, show (((x5 * y2) * (y5 * x2)) * (x4 * y4) * ((x2 * x4) * (y1 * y5) + (y2 * y4) * (x1 * x5)) - ((x2 * x4) * (y2 * y4)) * (((x5 * y2) * (y4 * x1) + (y5 * x2) * (x4 * y1)) * (x5 * y5))) * 1 = 0, by rw [mul_one, sub_eq_zero]; simp only [mul_add, add_mul]; rw add_comm; simp only [mul_comm, mul_left_comm, mul_assoc]⟩) p3 q3 } theorem Zariski.coinduced.presheaf_on_basis_res {x : R} (U : opens (Spec (localization.away x))) (HUB : U ∈ D_fs (localization.away x)) (V : opens (Spec (localization.away x))) (HVB : V ∈ D_fs (localization.away x)) (HVU : V ⊆ U) (g : (structure_presheaf_on_basis (localization.away x)).to_presheaf_on_basis HUB) : Zariski.coinduced.presheaf_on_basis V HVB (presheaf_on_basis.res _ HUB HVB HVU g) = presheaf_on_basis.res _ (localization.map_away_mem_D_fs HUB) (localization.map_away_mem_D_fs HVB) (opens.map_mono _ _ _ HVU) (Zariski.coinduced.presheaf_on_basis U HUB g) := localization.induction_on g $ λ r ⟨s, hs⟩, localization.induction_on r $ λ r1 r2, localization.induction_on s (λ s1 s2 hs, rfl) hs def Zariski.coinduced.stalk_on_basis.elem {x : R} (p : Spec R) (V : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) V).map_subtype_val) (g : stalk_on_basis.elem ((structure_presheaf_on_basis (localization.away x)).to_presheaf_on_basis) (Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩)) : stalk_on_basis.elem ((structure_presheaf_on_basis R).to_presheaf_on_basis) p := ⟨Zariski.map_away g.1, localization.map_away_mem_D_fs g.2, ⟨Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩, g.3, subtype.eq $ localization.comap_map_away x p.1 p.2 (of_mem_map_subtype_val hp)⟩, Zariski.coinduced.presheaf_on_basis g.1 g.2 g.4⟩ def Zariski.coinduced.stalk_on_basis {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) (s : stalk_on_basis ((structure_presheaf_on_basis (localization.away x)).to_presheaf_on_basis) (Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩)) : stalk_on_basis ((structure_presheaf_on_basis R).to_presheaf_on_basis) p := quotient.lift_on s (λ g, ⟦Zariski.coinduced.stalk_on_basis.elem p U hp g⟧) $ λ ⟨V1, HVB1, hpV1, s1⟩ ⟨V2, HVB2, hpV2, s2⟩ ⟨V, HVB, hpV, HV1, HV2, HV⟩, quotient.sound ⟨Zariski.map_away V, localization.map_away_mem_D_fs HVB, ⟨Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩, hpV, subtype.eq $ localization.comap_map_away _ _ p.2 (of_mem_map_subtype_val hp)⟩, set.image_subset _ HV1, set.image_subset _ HV2, by dsimp only [Zariski.coinduced.stalk_on_basis.elem] at HV ⊢; erw [← Zariski.coinduced.presheaf_on_basis_res _ _ _ _ HV1, ← Zariski.coinduced.presheaf_on_basis_res _ _ _ _ HV2, HV]⟩ instance stalk_on_basis.comm_ring (p : Spec R) : comm_ring (stalk_on_basis ((structure_presheaf_on_basis R).to_presheaf_on_basis) p) := stalk_of_rings_on_standard_basis.comm_ring (D_fs_standard_basis _) _ _ theorem map_away_univ (x : R) : Zariski.map_away (opens.univ : opens (Spec (localization.away x))) = Spec.DO R x := by erw [show (opens.univ : opens (Spec (localization.away x))) = Spec.DO _ 1, from (Spec.DO_one).symm, localization.map_DO, one_mul] theorem mem_map_away_of_coinduced_mem {x : R} {p : Spec R} {hpx : p ∈ Spec.DO R x} {U : opens (Spec (localization.away x))} (hp : Zariski.coinduced x ⟨p, hpx⟩ ∈ U) : p ∈ Zariski.map_away U := ⟨Zariski.coinduced x ⟨p, hpx⟩, hp, induced_coinduced _ _ _⟩ theorem induced_mem_DO {x : R} {p : Spec (localization.away x)} : Zariski.induced localization.of p ∈ Spec.DO R x := have h1 : _ := Zariski.induced.preimage_D (localization.of : R → localization.away x) x, ((set.ext_iff _ _).1 h1 _).2 $ λ hxp, p.2.1 $ ideal.eq_top_of_is_unit_mem _ hxp $ localization.coe_is_unit' _ _ _ ⟨1, pow_one x⟩ theorem injective_induced (x : R) : function.injective (Zariski.induced (localization.of : R → localization.away x)) := λ p q hpq, by rw [← coinduced_induced x p induced_mem_DO, ← coinduced_induced x q induced_mem_DO]; congr' 2; exact hpq theorem map_away_inter {x : R} (U V : opens (Spec (localization.away x))) : Zariski.map_away (U ∩ V) = Zariski.map_away U ∩ Zariski.map_away V := subtype.eq $ eq.symm $ set.image_inter $ injective_induced x instance Zariski.coinduced.stalk_on_basis.hom {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) : is_ring_hom (Zariski.coinduced.stalk_on_basis p U hp) := { map_one := quotient.sound ⟨Spec.DO R x, D_fs.mem R x, of_mem_map_subtype_val hp, show Spec.DO R x ⊆ Zariski.map_away opens.univ, by rw map_away_univ; exact set.subset.refl _, set.subset_univ _, quotient.sound $ ⟨1, is_submonoid.one_mem _, show (((1 * 1) * 1 - 1 * (1 * 1)) * 1 : R) = 0, by simp only [mul_one, sub_self]⟩⟩, map_mul := λ s t, quotient.induction_on₂ s t $ λ σ τ, quotient.sound ⟨Zariski.map_away σ.U ∩ Zariski.map_away τ.U, (D_fs_standard_basis _).2 (localization.map_away_mem_D_fs σ.2) (localization.map_away_mem_D_fs τ.2), ⟨mem_map_away_of_coinduced_mem σ.3, mem_map_away_of_coinduced_mem τ.3⟩, by rw ← map_away_inter; refl, set.subset.refl _, by dsimp only [Zariski.coinduced.stalk_on_basis.elem]; rw [is_ring_hom.map_mul (((structure_presheaf_on_basis R).to_presheaf_on_basis).res _ _ _), is_ring_hom.map_mul (Zariski.coinduced.presheaf_on_basis (σ.U ∩ τ.U) _), is_ring_hom.map_mul (((structure_presheaf_on_basis R).to_presheaf_on_basis).res _ _ _), Zariski.coinduced.presheaf_on_basis_res, Zariski.coinduced.presheaf_on_basis_res, ← presheaf_on_basis.Hcomp', ← presheaf_on_basis.Hcomp', ← presheaf_on_basis.Hcomp', ← presheaf_on_basis.Hcomp']; apply_instance⟩, map_add := λ s t, quotient.induction_on₂ s t $ λ σ τ, quotient.sound ⟨Zariski.map_away σ.U ∩ Zariski.map_away τ.U, (D_fs_standard_basis _).2 (localization.map_away_mem_D_fs σ.2) (localization.map_away_mem_D_fs τ.2), ⟨mem_map_away_of_coinduced_mem σ.3, mem_map_away_of_coinduced_mem τ.3⟩, by rw ← map_away_inter; refl, set.subset.refl _, by dsimp only [Zariski.coinduced.stalk_on_basis.elem]; rw [is_ring_hom.map_add (((structure_presheaf_on_basis R).to_presheaf_on_basis).res _ _ _), is_ring_hom.map_add (Zariski.coinduced.presheaf_on_basis (σ.U ∩ τ.U) _), is_ring_hom.map_add (((structure_presheaf_on_basis R).to_presheaf_on_basis).res _ _ _), Zariski.coinduced.presheaf_on_basis_res, Zariski.coinduced.presheaf_on_basis_res, ← presheaf_on_basis.Hcomp', ← presheaf_on_basis.Hcomp', ← presheaf_on_basis.Hcomp', ← presheaf_on_basis.Hcomp']; apply_instance⟩ } theorem powers_subset {x : R} {p : Spec R} (hxp : x ∉ p.1) : powers x ⊆ -p.1 := by rintros _ ⟨n, rfl⟩; exact mt (p.2.mem_of_pow_mem n) hxp set_option class.instance_max_depth 50 def Zariski.coinduced.stalk_on_basis.algebraic {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) (s : localization.at_prime ((Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩).val)) : localization.at_prime p.val := begin refine quotient.lift_on s (λ r, _) _, { refine quotient.hrec_on₂ r.1 r.2.1 (λ s t h, _) _ r.2.2, { refine ⟦(s.1 * t.2.1, ⟨s.2.1 * t.1, is_submonoid.mul_mem (powers_subset (of_mem_map_subtype_val hp) s.2.2) (λ htp, h _)⟩)⟧, cases t with t1 t2, change localization.mk t1 t2 ∈ (Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩).val, rw localization.mk_mem_iff, exact ideal.subset_span ⟨t1, htp, rfl⟩ }, { rintros s1 s2 t1 t2 h1 h2, refine function.hfunext _ _, { exact congr_arg _ (quotient.sound h2) }, { intros h3 h4 h5, refine heq_of_eq (quotient.sound _), rcases h1 with ⟨s3, s4, h6⟩, rcases h2 with ⟨t3, t4, h7⟩, refine ⟨s3 * t3, powers_subset (of_mem_map_subtype_val hp) (powers.mul_mem s4 t4), _⟩, change (((s1.2 * s2.1) * (t1.1 * t2.2) - (t1.2 * t2.1) * (s1.1 * s2.2)) * (s3 * t3) : R) = 0, rw [sub_mul, sub_eq_zero] at h6 h7 ⊢, calc ((s1.2 * s2.1) * (t1.1 * t2.2) * (s3 * t3) : R) = ((s1.2 * t1.1 * s3) * (t2.2 * s2.1 * t3) : R) : by simp only [mul_assoc, mul_left_comm] ... = ((t1.2 * s1.1 * s3) * (s2.2 * t2.1 * t3) : R) : by rw [h6, ← h7] ... = ((t1.2 * t2.1) * (s1.1 * s2.2) * (s3 * t3)) : by simp only [mul_assoc, mul_left_comm] } } }, { rintros ⟨s1, s2, h1⟩ ⟨t1, t2, h2⟩ ⟨x1, hx1, hx2⟩, refine quotient.induction_on₂ s1 s2 (λ s3 s4 h5 hx3, _) h1 hx2, refine quotient.induction_on₂ t1 t2 (λ t3 t4 h6 hx4, _) h2 hx3, refine quotient.induction_on x1 (λ x2 hx5 hx6, _) hx1 hx4, rcases quotient.exact hx6 with ⟨x3, hx7, hx8⟩, change ((((s4.2 * t3.2) * (t4.2 * s3.2) * x2.2) * 0 - 1 * (((s4.2 * t3.2) * -(t4.1 * s3.1) + (t4.2 * s3.2) * (s4.1 * t3.1)) * x2.1)) * x3 : R) = 0 at hx8, rw [mul_zero, one_mul, zero_sub, mul_neg_eq_neg_mul_symm, neg_mul_eq_neg_mul_symm, neg_eq_zero, neg_add_eq_sub, sub_mul, sub_mul, sub_eq_zero] at hx8, refine quotient.sound ⟨x2.1 * x3, is_submonoid.mul_mem (λ H, hx5 _) (powers_subset (of_mem_map_subtype_val hp) hx7), _⟩, { cases x2 with x21 x22, change localization.mk x21 x22 ∈ (Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩).val, rw localization.mk_mem_iff, exact ideal.subset_span ⟨x21, H, rfl⟩ }, change (((s3.2 * s4.1) * (t3.1 * t4.2) - (t3.2 * t4.1) * (s3.1 * s4.2)) * (x2.1 * x3) : R) = 0, rw [sub_mul, sub_eq_zero], simpa only [mul_assoc, mul_left_comm] using hx8 } end instance Zariski.coinduced.stalk_on_basis.algebraic.hom {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) : is_ring_hom (Zariski.coinduced.stalk_on_basis.algebraic p U hp) := { map_one := quotient.sound ⟨1, is_submonoid.one_mem _, show (((1 * 1) * 1 - 1 * (1 * 1)) * 1 : R) = 0, by simp only [mul_one]; rw sub_self⟩, map_mul := λ x y, by rcases x with ⟨⟨x1, x2, h1⟩, ⟨x3, x4, h2⟩, h3⟩; rcases y with ⟨⟨y1, y2, h4⟩, ⟨y3, y4, h5⟩, h6⟩; exact quotient.sound ⟨1, is_submonoid.one_mem _, show (((x2 * y2) * (x3 * y3)) * ((x1 * x4) * (y1 * y4)) - ((x2 * x3) * (y2 * y3)) * ((x1 * y1) * (x4 * y4))) * 1 = 0, by rw [mul_one, mul_comm4 x2 y2, mul_comm4 x1 x4, sub_self]⟩, map_add := λ x y, by rcases x with ⟨⟨x1, x2, h1⟩, ⟨x3, x4, h2⟩, h3⟩; rcases y with ⟨⟨y1, y2, h4⟩, ⟨y3, y4, h5⟩, h6⟩; exact quotient.sound ⟨1, is_submonoid.one_mem _, show ((((x4 * y2) * (y4 * x2)) * (x3 * y3)) * ((x2 * x3) * (y1 * y4) + (y2 * y3) * (x1 * x4)) - ((x2 * x3) * (y2 * y3)) * (((x4 * y2) * (y3 * x1) + (y4 * x2) * (x3 * y1)) * (x4 * y4))) * 1 = 0, by rw [mul_one, sub_eq_zero]; simp only [add_mul, mul_add]; rw add_comm; congr' 1; simp only [mul_assoc, mul_left_comm, mul_comm]⟩ } def localization.to_superset {α : Type u} [comm_ring α] {S T : set α} [is_submonoid S] [is_submonoid T] (H : S ⊆ T) (x : localization α S) : localization α T := quotient.lift_on x (λ r, localization.mk r.1 ⟨r.2.1, H r.2.2⟩) $ λ s t ⟨x1, h1, h2⟩, quotient.sound ⟨x1, H h1, h2⟩ instance localization.to_superset.hom {α : Type u} [comm_ring α] {S T : set α} [is_submonoid S] [is_submonoid T] (H : S ⊆ T) : is_ring_hom (localization.to_superset H) := { map_one := rfl, map_mul := λ x y, localization.induction_on x $ λ r1 s1, localization.induction_on y $ λ r2 s2, rfl, map_add := λ x y, localization.induction_on x $ λ r1 s1, localization.induction_on y $ λ r2 s2, rfl } theorem localization.to_superset.of {α : Type u} [comm_ring α] {S T : set α} [is_submonoid S] [is_submonoid T] (H : S ⊆ T) (r : α) : localization.to_superset H (localization.of r) = localization.of r := rfl theorem localization.to_superset.coe {α : Type u} [comm_ring α] {S T : set α} [is_submonoid S] [is_submonoid T] (H : S ⊆ T) (r : α) : localization.to_superset H r = r := rfl theorem localization.to_superset.self {α : Type u} [comm_ring α] {S : set α} [is_submonoid S] (H : S ⊆ S) (r) : localization.to_superset H r = r := suffices localization.to_superset H = id, from congr_fun this r, localization.funext _ _ $ λ x, rfl theorem rec_eq_to_superset {p q : Spec R} (h : p = q) (s : localization.at_prime p.1) : (eq.rec s h : localization.at_prime q.1) = localization.to_superset (eq.rec (set.subset.refl _) h : (-p.1 : set R) ⊆ -q.1) s := eq.drec (localization.to_superset.self _ _).symm h def compl_coinduced_to_units {x : R} (p : Spec R) (hxp : x ∉ p.1) (s : (-↑(Zariski.coinduced x ⟨p, hxp⟩).1 : set (localization.away x))) : units (localization.at_prime p.1) := ⟨localization.to_superset (powers_subset hxp) s.1, quotient.hrec_on s.1 (λ r : R × powers x, λ hr, localization.mk r.2.1 ⟨r.1, λ h1, hr $ by cases r with r1 r2; change localization.mk r1 r2 ∈ (Zariski.coinduced x ⟨p, hxp⟩).1; rw localization.mk_mem_iff; exact ideal.subset_span ⟨r1, h1, rfl⟩⟩) (λ r1 r2 h, function.hfunext (congr_arg _ $ quotient.sound h) $ λ h1 h2 h3, heq_of_eq $ by rcases h with ⟨r3, h4, h5⟩; refine quotient.sound ⟨r3, powers_subset hxp h4, _⟩; rwa [← neg_sub, neg_mul_eq_neg_mul_symm, neg_eq_zero, mul_comm (r2.2 : R), mul_comm (r1.2 : R)] at h5) s.2, localization.induction_on s.1 (λ r s h, quotient.sound ⟨1, is_submonoid.one_mem _, show ((s.1 * r) * 1 - 1 * (r * s.1)) * 1 = 0, by rw [mul_one, mul_one, one_mul, mul_comm, sub_self]⟩) s.2, localization.induction_on s.1 (λ r s h, quotient.sound ⟨1, is_submonoid.one_mem _, show ((r * s.1) * 1 - 1 * (s.1 * r)) * 1 = 0, by rw [mul_one, mul_one, one_mul, mul_comm, sub_self]⟩) s.2⟩ @[simp] lemma compl_coinduced_to_units_coe {x : R} (p : Spec R) (hxp : x ∉ p.1) (s : (-↑(Zariski.coinduced x ⟨p, hxp⟩).1 : set (localization.away x))) : ↑(compl_coinduced_to_units p hxp s) = localization.to_superset (powers_subset hxp) s.1 := rfl instance compl_coinduced_to_units.hom {x : R} (p : Spec R) (hxp : x ∉ p.1) : is_monoid_hom (compl_coinduced_to_units p hxp) := { map_one := units.ext $ by erw [compl_coinduced_to_units_coe, is_ring_hom.map_one (localization.to_superset (powers_subset hxp))], map_mul := λ s t, units.ext $ by rw units.coe_mul; iterate 3 { rw compl_coinduced_to_units_coe }; erw is_ring_hom.map_mul (localization.to_superset (powers_subset hxp)) } theorem Zariski.coinduced.stalk_on_basis.algebraic.def {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) (r s) : Zariski.coinduced.stalk_on_basis.algebraic p U hp (localization.mk r s) = (localization.to_superset (powers_subset (of_mem_map_subtype_val hp)) r) * ((compl_coinduced_to_units p (of_mem_map_subtype_val hp) s)⁻¹ : units (localization.at_prime p.1)) := by cases s with s hs; refine localization.induction_on r (λ r1 r2, _); refine localization.induction_on s (λ r2 s2 h, _) hs; refl theorem Zariski.coinduced.stalk_on_basis.algebraic.of {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) (r) : Zariski.coinduced.stalk_on_basis.algebraic p U hp (localization.of r) = (localization.to_superset (powers_subset (of_mem_map_subtype_val hp)) r) := (Zariski.coinduced.stalk_on_basis.algebraic.def p U hp r 1).trans $ by rw [is_monoid_hom.map_one (compl_coinduced_to_units p (of_mem_map_subtype_val hp))]; rw [one_inv, units.coe_one, mul_one] theorem Zariski.coinduced.stalk_on_basis.algebraic.coe {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) (r : localization.away x) : Zariski.coinduced.stalk_on_basis.algebraic p U hp r = (localization.to_superset (powers_subset (of_mem_map_subtype_val hp)) r) := Zariski.coinduced.stalk_on_basis.algebraic.of _ _ _ _ theorem Zariski.coinduced.stalk_on_basis.algebraic.hlocal {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) (s) (hs : is_unit (Zariski.coinduced.stalk_on_basis.algebraic p U hp s)) : is_unit s := begin refine localization.induction_on s (λ r s, _) hs, rw is_unit_localization_mk, refine localization.induction_on r (λ x1 x2, _), cases s with s h1, refine localization.induction_on s (λ x3 x4 h1, _) h1, change is_unit (localization.mk (x1 * x4) ⟨x2 * x3, _⟩) → _, rw is_unit_localization_mk, rintros ⟨t, ht⟩, refine ⟨localization.mk (x4 * t) 1, _⟩, change _ ∉ (Zariski.coinduced x ⟨p, _⟩).1, rw [localization.mk_mul_mk, localization.mk_mem_iff], change _ ∉ (Zariski.induced localization.of (Zariski.coinduced x ⟨p, _⟩)).1, rw [induced_coinduced, ← mul_assoc], exact ht end theorem Zariski.coinduced.stalk_on_basis.stalk_on_basis_of {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) (r : R) : Zariski.coinduced.stalk_on_basis p U hp (stalk_on_basis_of (Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩) r) = stalk_on_basis_of p r := quotient.sound ⟨Zariski.map_away (opens.univ : opens (Spec (localization.away x))), localization.map_away_mem_D_fs (D_fs_standard_basis _).1, mem_map_away_of_coinduced_mem (by trivial : Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩ ∈ opens.univ), set.subset.refl _, set.subset_univ _, quotient.sound ⟨1, is_submonoid.one_mem _, show ((1 * 1) * r - 1 * (r * 1)) * 1 = 0, by rw [mul_one, one_mul, one_mul, one_mul, mul_one, sub_self]⟩⟩ theorem Zariski.coinduced.stalk_on_basis.stalk_on_basis_of_localization {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) (s : localization.at_prime ((Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩).val)) : Zariski.coinduced.stalk_on_basis p U hp (stalk_on_basis_of_localization (Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩) s) = stalk_on_basis_of_localization p (Zariski.coinduced.stalk_on_basis.algebraic p U hp s) := begin refine congr_fun _ s, refine @@localization.funext _ _ _ _ _ (is_ring_hom.comp _ _) (is_ring_hom.comp _ _) (λ s, _), change (Zariski.coinduced.stalk_on_basis p U hp ∘ stalk_on_basis_of_localization (Zariski.coinduced x ⟨p, _⟩) ∘ localization.of) s = (stalk_on_basis_of_localization p ∘ Zariski.coinduced.stalk_on_basis.algebraic p U hp ∘ localization.of) s, refine congr_fun _ s, refine @@localization.funext _ _ _ _ _ (@@is_ring_hom.comp _ _ _ (is_ring_hom.comp _ _) _ _ _) (@@is_ring_hom.comp _ _ _ (is_ring_hom.comp _ _) _ _ _) (λ s, _), change Zariski.coinduced.stalk_on_basis p U hp (stalk_on_basis_of_localization (Zariski.coinduced x ⟨p, _⟩) (localization.of (localization.of s))) = stalk_on_basis_of_localization p (Zariski.coinduced.stalk_on_basis.algebraic p U hp (localization.of (localization.of s))), rw [Zariski.coinduced.stalk_on_basis.algebraic.of, localization.to_superset.of], unfold stalk_on_basis_of_localization, rw [localization.lift'_of, localization.lift'_of], exact Zariski.coinduced.stalk_on_basis.stalk_on_basis_of p U hp s end theorem Zariski.coinduced.stalk_on_basis.hlocal {x : R} (p : Spec R) (U : opens (Spec (localization.away x))) (hp : p ∈ (opens.comap (Zariski.coinduced.continuous x) U).map_subtype_val) (s) (hs : is_unit (Zariski.coinduced.stalk_on_basis p U hp s)) : is_unit s := by rcases (stalk_on_basis_of_localization.bijective _).2 s with ⟨σ, rfl⟩; rw Zariski.coinduced.stalk_on_basis.stalk_on_basis_of_localization at hs; rw stalk_on_basis_of_localization.unit at hs ⊢; exact Zariski.coinduced.stalk_on_basis.algebraic.hlocal p U hp σ hs def Zariski.coinduced.Fext {x : R} (U : opens (Spec (localization.away x))) (s : ((((Spec.locally_ringed_space (localization.away x)).O).F).to_presheaf : presheaf (Spec (localization.away x))) U) : ((((locally_ringed_space.res_open (Spec.locally_ringed_space R) (Spec.DO R x)).O).F).to_presheaf) (opens.comap (Zariski.coinduced.continuous x) U) := ⟨λ p hp, Zariski.coinduced.stalk_on_basis p U hp $ s.1 (Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩) (mem_of_mem_map_subtype_val hp), λ p hp, let ⟨V, HVB, hxV, σ, hσ⟩ := s.2 (Zariski.coinduced x ⟨p, of_mem_map_subtype_val hp⟩) (mem_of_mem_map_subtype_val hp) in ⟨Zariski.map_away V, localization.map_away_mem_D_fs HVB, ⟨_, hxV, subtype.eq $ localization.comap_map_away _ _ p.2 (of_mem_map_subtype_val hp)⟩, Zariski.coinduced.presheaf_on_basis V HVB σ, λ q hq1, funext $ λ hq2, by rcases hq1.2 with ⟨r, hrV, rfl⟩; rw hσ (Zariski.coinduced x ⟨Zariski.induced localization.of r, of_mem_map_subtype_val hq2⟩) ⟨mem_of_mem_map_subtype_val hq1.1, by rw coinduced_induced; exact hrV⟩; refl⟩⟩ instance Zariski.coinduced.Fext.hom {x : R} (U : opens (Spec (localization.away x))) : is_ring_hom (Zariski.coinduced.Fext U) := { map_one := subtype.eq $ by ext p hp; exact is_ring_hom.map_one (Zariski.coinduced.stalk_on_basis p U hp), map_mul := by rintros ⟨q, hq⟩ ⟨r, hr⟩; apply subtype.eq; ext p hp; exact is_ring_hom.map_mul (Zariski.coinduced.stalk_on_basis p U hp), map_add := by rintros ⟨q, hq⟩ ⟨r, hr⟩; apply subtype.eq; ext p hp; exact is_ring_hom.map_add (Zariski.coinduced.stalk_on_basis p U hp) } def D_f_to_Spec (x : R) : locally_ringed_space.morphism ((Spec.locally_ringed_space R).res_open (Spec.DO R x)) (Spec.locally_ringed_space (localization.away x)) := { f := Zariski.coinduced x, Hf := Zariski.coinduced.continuous x, fO := { map := λ U s, Zariski.coinduced.Fext U s, commutes := λ U V HVU, funext $ λ s, subtype.eq $ funext $ λ p, funext $ λ hp, rfl }, hom := λ U, Zariski.coinduced.Fext.hom U, Hstalks := λ p s, begin refine quotient.induction_on s (λ g, _), cases g with U hp σ, intro h, change is_unit (to_stalk (presheaf_of_rings.res_open _ _) _ _ _ _) at h, replace h := is_unit.map' (of_stalk_of_rings_res_open _ _ _) h, erw [of_stalk_of_rings_res_open_to_stalk, is_unit_to_stalk_on_basis] at h, change is_unit (to_stalk _ _ _ _ _), erw is_unit_to_stalk_on_basis, cases p with p hp1, have := Zariski.coinduced.stalk_on_basis.hlocal _ _ _ _ h, change is_unit (σ.val (Zariski.coinduced x ⟨p, hp1⟩) hp) at this, exact this end } def Zariski.induced' (x : R) (p : Spec (localization.away x)) : Spec.DO R x := ⟨Zariski.induced localization.of p, λ hxp, p.2.1 $ p.1.eq_top_of_is_unit_mem hxp $ localization.of_is_unit' _ _ _ ⟨1, pow_one x⟩⟩ theorem Zariski.induced'.continuous (x : R) : continuous (Zariski.induced' x) := continuous_induced_rng $ Zariski.induced.continuous localization.of def Spec_to_D_f (x : R) : locally_ringed_space.morphism (Spec.locally_ringed_space (localization.away x)) ((Spec.locally_ringed_space R).res_open (Spec.DO R x)) := { f := Zariski.induced' x, Hf := Zariski.induced'.continuous x, fO := { map := λ U s, (Spec.locally_ringed_space (localization.away x)).O.F.res (opens.comap ((Zariski.induced.locally_ringed_space localization.of).Hf) (topological_space.opens.map_subtype_val U)) (opens.comap (Zariski.induced'.continuous x) U) (λ p hpU, ⟨_, hpU, rfl⟩) ((Zariski.induced.locally_ringed_space localization.of).fO.map U.map_subtype_val s), commutes := λ U V HVU, rfl }, hom := λ U, @@is_ring_hom.comp _ _ _ ((Zariski.induced.locally_ringed_space localization.of).hom _) _ _ _, Hstalks := λ p s, begin refine quotient.induction_on s (λ g, _), cases g with U hp σ, intro h, change is_unit (to_stalk _ _ _ _ _) at h, dsimp only at h, rw to_stalk_res _ p (opens.comap (((Zariski.induced.locally_ringed_space localization.of).to_morphism).Hf) (topological_space.opens.map_subtype_val U)) _ ⟨_, hp, rfl⟩ at h, erw is_unit_to_stalk_on_basis at h, dsimp only at h, change is_unit (to_stalk _ _ _ _ _), --erw is_unit_to_stalk_on_basis, have := Zariski.induced.stalk_on_basis.hlocal localization.of p _ h, erw ← is_unit_to_stalk_on_basis at this, replace this := is_unit.map' (to_stalk_of_rings_res_open _ _ (Zariski.induced' x p)) this, erw [to_stalk_of_rings_res_open_to_stalk, to_stalk_res] at this, exact this, { rintros q ⟨r, hrU, hrq⟩, rwa ← subtype.eq hrq } end } protected theorem polynomial.funext {α : Type u} [comm_ring α] {β : Type v} [ring β] (f g : polynomial α → β) [is_ring_hom f] [is_ring_hom g] (p : polynomial α) (h1 : ∀ x, f (polynomial.C x) = g (polynomial.C x)) (h2 : f polynomial.X = g polynomial.X) : f p = g p := polynomial.induction_on p h1 (λ p q ihp ihq, by rw [is_ring_hom.map_add f, is_ring_hom.map_add g, ihp, ihq]) (λ n x ih, by rw [pow_add, pow_one, ← mul_assoc, is_ring_hom.map_mul f, is_ring_hom.map_mul g, ih, h2]) theorem localization.away.inv_self_eq (x : R) : localization.away.inv_self x = ↑(localization.to_units ⟨x, 1, pow_one x⟩ : units (localization.away x))⁻¹ := rfl namespace projective_line variables (R) noncomputable def inr_aux : polynomial R → localization.away (polynomial.X : polynomial R) := polynomial.eval₂ (localization.of ∘ polynomial.C) (localization.away.inv_self (polynomial.X)) instance is_ring_hom_inr_aux : is_ring_hom (inr_aux R) := polynomial.eval₂.is_ring_hom _ theorem inr_aux_C (x : R) : inr_aux R (polynomial.C x) = localization.of (polynomial.C x) := polynomial.eval₂_C _ _ theorem inr_aux_X : inr_aux R polynomial.X = localization.away.inv_self (polynomial.X) := polynomial.eval₂_X _ _ noncomputable def inverse : localization.away (polynomial.X : polynomial R) → localization.away (polynomial.X : polynomial R) := localization.lift' (inr_aux R) (λ p, ⟨inr_aux R p.1, localization.of p.1, by rcases p with ⟨_, n, rfl⟩; rw [inr_aux, polynomial.eval₂_pow, polynomial.eval₂_X, localization.of_pow, ← mul_pow, localization.away.inv_self_mul_of, one_pow], by rcases p with ⟨_, n, rfl⟩; rw [inr_aux, polynomial.eval₂_pow, polynomial.eval₂_X, localization.of_pow, ← mul_pow, localization.away.of_mul_inv_self, one_pow]⟩) (λ p, rfl) instance is_ring_hom_inverse : is_ring_hom (inverse R) := localization.lift'.is_ring_hom _ _ _ theorem inverse_inverse : inverse R ∘ inverse R = id := @@localization.funext _ _ _ (inverse R ∘ inverse R) _ (is_ring_hom.comp _ _) is_ring_hom.id $ λ p, polynomial.induction_on p (λ r, by simp only [inverse, function.comp_apply, localization.lift'_coe, localization.lift'_of, inr_aux, polynomial.eval₂_C]; refl) (λ p q hp hq, by rw [localization.coe_add, is_ring_hom.map_add (inverse R ∘ inverse R), hp, hq]; refl) (λ n r ih, by rw [pow_add, pow_one, ← mul_assoc, localization.coe_mul, is_ring_hom.map_mul (inverse R ∘ inverse R), ih]; simp only [inverse, function.comp_apply, localization.lift'_coe, localization.lift'_of, inr_aux, polynomial.eval₂_X, localization.away.lift'_inv_self]; refl) theorem inverse_inverse' (p) : inverse R (inverse R p) = p := congr_fun (inverse_inverse R) p theorem Zariski_induced_inverse (p : Spec (localization.away (polynomial.X : polynomial R))) : Zariski.induced (inverse R) (Zariski.induced (inverse R) p) = p := calc Zariski.induced (inverse R) (Zariski.induced (inverse R) p) = Zariski.induced (inverse R ∘ inverse R) p : (Zariski_induced_comp (inverse R) (inverse R) p).symm ... = Zariski.induced id p : congr_arg_Zariski (inverse_inverse R) p ... = p : Zariski_induced_id p set_option class.instance_max_depth 32 inductive r : Spec (polynomial R) ⊕ Spec (polynomial R) → Spec (polynomial R) ⊕ Spec (polynomial R) → Prop | inv : ∀ p : Spec (localization.away (polynomial.X : polynomial R)), r (sum.inl $ Zariski.induced localization.of p) (sum.inr $ Zariski.induced (inr_aux R) p) end projective_line def projective_line (R : Type u) [comm_ring R] [decidable_eq R] : Type u := quot (projective_line.r R) namespace projective_line variables (R) [decidable_eq R] def inl (p : Spec (polynomial R)) : projective_line R := quot.mk _ $ sum.inl p def inr (p : Spec (polynomial R)) : projective_line R := quot.mk _ $ sum.inr p instance : topological_space (projective_line R) := { is_open := λ s, is_open (inl R ⁻¹' s) ∧ is_open (inr R ⁻¹' s), is_open_univ := ⟨is_open_univ, is_open_univ⟩, is_open_inter := λ s t hs ht, ⟨is_open_inter hs.1 ht.1, is_open_inter hs.2 ht.2⟩, is_open_sUnion := λ S HS, ⟨by rw set.preimage_sUnion; exact is_open_bUnion (λ i his, (HS i his).1), by rw set.preimage_sUnion; exact is_open_bUnion (λ i his, (HS i his).2)⟩ } theorem continuous_inl : continuous (inl R) := λ s hs, hs.1 theorem continuous_inr : continuous (inr R) := λ s hs, hs.2 theorem inj_indl : function.injective (Zariski.induced localization.of : Spec (localization.away (polynomial.X : polynomial R)) → Spec (polynomial R)) := localization.inj_Zariski_induced_localization_of (powers polynomial.X) theorem inverse_comp_localization_of : inverse R ∘ localization.of = inr_aux R := funext $ λ p, by rw [inverse, function.comp_apply, localization.lift'_of] theorem inl_induced (p : Spec (localization.away (polynomial.X : polynomial R))) : inl R (Zariski.induced (inr_aux R) p) = inr R (Zariski.induced localization.of p) := have h1 : Zariski.induced (inr_aux R) p = Zariski.induced localization.of (Zariski.induced (inverse R) p), from subtype.eq $ ideal.ext $ λ x, show _ ∈ p.1 ↔ _ ∈ p.1, by rw [← inverse_comp_localization_of], have h2 : Zariski.induced localization.of p = Zariski.induced (inr_aux R) (Zariski.induced (inverse R) p), from subtype.eq $ ideal.ext $ λ x, show _ ∈ p.1 ↔ _ ∈ p.1, by rw [← inverse_comp_localization_of, function.comp_apply, inverse_inverse'], quot.sound $ by rw [h1, h2]; apply r.inv theorem inr_induced (p : Spec (localization.away (polynomial.X : polynomial R))) : inr R (Zariski.induced (inr_aux R) p) = inl R (Zariski.induced localization.of p) := eq.symm $ quot.sound $ r.inv p theorem inj_indr : function.injective (Zariski.induced (inr_aux R) : Spec (localization.away (polynomial.X : polynomial R)) → Spec (polynomial R)) := have h2 : function.injective (Zariski.induced (inverse R)), from (equiv.bijective { to_fun := Zariski.induced (inverse R), inv_fun := Zariski.induced (inverse R), left_inv := λ p, by rw [← Zariski_induced_comp, @@congr_arg_Zariski _ _ (inverse R ∘ inverse R) id (is_ring_hom.comp _ _) is_ring_hom.id (inverse_inverse R), Zariski_induced_id], right_inv := λ p, by rw [← Zariski_induced_comp, @@congr_arg_Zariski _ _ (inverse R ∘ inverse R) id (is_ring_hom.comp _ _) is_ring_hom.id (inverse_inverse R), Zariski_induced_id] }).1, λ p1 p2 H, h2 $ inj_indl R $ by haveI : is_ring_hom (inverse R ∘ localization.of) := is_ring_hom.comp _ _; calc Zariski.induced localization.of (Zariski.induced (inverse R) p1) = Zariski.induced (inverse R ∘ localization.of) p1 : (Zariski_induced_comp _ _ _).symm ... = Zariski.induced (inr_aux R) p1 : congr_arg_Zariski (inverse_comp_localization_of R) p1 ... = Zariski.induced (inr_aux R) p2 : H ... = Zariski.induced (inverse R ∘ localization.of) p2 : congr_arg_Zariski (inverse_comp_localization_of R).symm p2 ... = Zariski.induced localization.of (Zariski.induced (inverse R) p2) : Zariski_induced_comp _ _ _ theorem exact (s t) (H : (quot.mk _ s : projective_line R) = quot.mk _ t) : s = t ∨ (∃ p, s = sum.inl (Zariski.induced localization.of p) ∧ t = sum.inr (Zariski.induced (inr_aux R) p)) ∨ ∃ p, s = sum.inr (Zariski.induced (inr_aux R) p) ∧ t = sum.inl (Zariski.induced localization.of p) := begin replace H := quot.exact _ H, induction H, case eqv_gen.rel : _ _ h { cases h, exact or.inr (or.inl ⟨_, rfl, rfl⟩) }, case eqv_gen.refl { left, refl }, case eqv_gen.symm : _ _ _ ih { rcases ih with rfl | ⟨p, rfl, rfl⟩ | ⟨p, rfl, rfl⟩, { exact or.inl rfl }, { exact or.inr (or.inr ⟨p, rfl, rfl⟩) }, { exact or.inr (or.inl ⟨p, rfl, rfl⟩) } }, case eqv_gen.trans : _ _ _ _ _ ih1 ih2 { rcases ih1 with rfl | ⟨p, rfl, rfl⟩ | ⟨p, rfl, rfl⟩, { exact ih2 }, { rcases ih2 with rfl | ⟨q, ih2, rfl⟩ | ⟨q, ih2, rfl⟩, { exact or.inr (or.inl ⟨p, rfl, rfl⟩) }, { cases ih2 }, { replace ih2 := inj_indr R (sum.inr.inj ih2), subst ih2, exact or.inl rfl } }, { rcases ih2 with rfl | ⟨q, ih2, rfl⟩ | ⟨q, ih2, rfl⟩, { exact or.inr (or.inr ⟨p, rfl, rfl⟩) }, { replace ih2 := inj_indl R (sum.inl.inj ih2), subst ih2, exact or.inl rfl }, { cases ih2 } } } end theorem inl_preimage_range_inr : inl R ⁻¹' set.range (inr R) = (Spec.DO (polynomial R) polynomial.X).1 := begin ext p, split, { rintros ⟨q, hq⟩ hp, rcases exact R _ _ hq with h | ⟨s, h1, h2⟩ | ⟨s, h1, h2⟩, { cases h }, { cases h1 }, cases h2, exact s.2.1 (s.1.eq_top_of_is_unit_mem hp $ is_unit_of_mul_one _ _ $ localization.away.of_mul_inv_self _) }, { rintros hp, rcases exists_Zariski_induced_of_not_mem _ _ hp with ⟨q, rfl⟩, use Zariski.induced (inr_aux R) q, symmetry, apply quot.sound, constructor } end theorem open_preimagelr : is_open (inl R ⁻¹' set.range (inr R)) := by rw inl_preimage_range_inr; exact D_fs_open _ _ theorem inr_preimage_range_inl : inr R ⁻¹' set.range (inl R) = (Spec.DO (polynomial R) polynomial.X).1 := begin ext p, split, { rintros ⟨q, hq⟩ hp, rcases exact R _ _ hq with h | ⟨s, h1, h2⟩ | ⟨s, h1, h2⟩, { cases h }, { cases h2, refine s.2.1 (s.1.eq_top_of_is_unit_mem hp $ is_unit_of_mul_one _ (localization.of polynomial.X) _), rw [inr_aux, polynomial.eval₂_X, localization.away.inv_self_mul_of] }, { cases h1 } }, { rintros hp, rcases exists_Zariski_induced_of_not_mem _ _ hp with ⟨q, rfl⟩, rw [← Zariski_induced_inverse R q, ← Zariski_induced_comp, congr_arg_Zariski.{u u} (inverse_comp_localization_of R)], split, apply quot.sound, constructor } end theorem inj_inl : function.injective (inl R) := λ x y h, by rcases exact R _ _ h with h | ⟨s, h1, ⟨⟩⟩ | ⟨s, ⟨⟩, h2⟩; exact sum.inl.inj h theorem inj_inr : function.injective (inr R) := λ x y h, by rcases exact R _ _ h with h | ⟨s, ⟨⟩, h2⟩ | ⟨s, h1, ⟨⟩⟩; exact sum.inr.inj h theorem open_preimagerl : is_open (inr R ⁻¹' set.range (inl R)) := by rw inr_preimage_range_inl; exact D_fs_open _ _ theorem set.preimage_range {α : Type u} {β : Type v} {f : α → β} : f ⁻¹' set.range f = set.univ := set.eq_univ_of_forall $ λ x, ⟨x, rfl⟩ def opl : opens (projective_line R) := ⟨set.range (inl R), by rw set.preimage_range; exact is_open_univ, open_preimagerl R⟩ def opr : opens (projective_line R) := ⟨set.range (inr R), open_preimagelr R, by rw set.preimage_range; exact is_open_univ⟩ inductive pbool : Type u | ff | tt. protected def covering : covering (⊤ : opens (projective_line R)) := { γ := pbool, Uis := λ b, pbool.rec_on b (opl R) (opr R), Hcov := opens.ext $ set.eq_univ_of_forall $ λ x, quot.induction_on x $ λ p, sum.cases_on p (λ v, set.mem_sUnion.2 ⟨_, ⟨_, ⟨pbool.ff, rfl⟩, rfl⟩, v, rfl⟩) (λ v, set.mem_sUnion.2 ⟨_, ⟨_, ⟨pbool.tt, rfl⟩, rfl⟩, v, rfl⟩) } noncomputable def soropl : sheaf_of_rings_on_opens (projective_line R) (opl R) := sheaf_of_rings.pushforward (continuous_inl R) (structure_sheaf (polynomial R)) noncomputable def soropr : sheaf_of_rings_on_opens (projective_line R) (opr R) := sheaf_of_rings.pushforward (continuous_inr R) (structure_sheaf (polynomial R)) theorem sorope1.aux (V : opens (projective_line R)) (HV : V ≤ opl R ⊓ opr R) : opens.comap (continuous_inr R) V ⊆ topological_space.opens.map_subtype_val (opens.comap (((D_f_to_Spec polynomial.X).to_morphism).Hf) (opens.comap (((Zariski.induced.locally_ringed_space (inr_aux R)).to_morphism).Hf) (opens.comap (continuous_inl R) V))) := λ p (hp : _ ∈ V), ⟨⟨p, ((set.ext_iff _ _).1 (inr_preimage_range_inl R) p).1 (HV hp).1⟩, show inl R (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, _⟩)) ∈ V, by rwa [inl_induced, induced_coinduced], rfl⟩ noncomputable def sorope1 : sheaf_of_rings_on_opens.morphism (sheaf_of_rings_on_opens.res_subset (soropl R) (opl R ⊓ opr R) lattice.inf_le_left) (sheaf_of_rings_on_opens.res_subset (soropr R) (opl R ⊓ opr R) lattice.inf_le_right) := { η := { map := λ V HV, (by exact (Spec.locally_ringed_space (polynomial R)).O.F.res _ _ (sorope1.aux R V HV)) ∘ (D_f_to_Spec (polynomial.X : polynomial R)).fO.map _ ∘ (Zariski.induced.locally_ringed_space (inr_aux R)).fO.map (opens.comap (continuous_inl R) V), commutes := λ V HV W HW HWV s, rfl }, hom := λ V HV, @@is_ring_hom.comp _ _ _ (is_ring_hom.comp _ _) _ _ _ } theorem sorope2.aux (V : opens (projective_line R)) (HV : V ≤ opl R ⊓ opr R) : opens.comap (continuous_inl R) V ⊆ topological_space.opens.map_subtype_val (opens.comap (((D_f_to_Spec polynomial.X).to_morphism).Hf) (opens.comap (((Zariski.induced.locally_ringed_space (inr_aux R)).to_morphism).Hf) (opens.comap (continuous_inr R) V))) := λ p (hp : _ ∈ V), ⟨⟨p, ((set.ext_iff _ _).1 (inl_preimage_range_inr R) p).1 (HV hp).2⟩, show inr R (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, _⟩)) ∈ V, by rwa [inr_induced, induced_coinduced], rfl⟩ noncomputable def sorope2 : sheaf_of_rings_on_opens.morphism (sheaf_of_rings_on_opens.res_subset (soropr R) (opl R ⊓ opr R) lattice.inf_le_right) (sheaf_of_rings_on_opens.res_subset (soropl R) (opl R ⊓ opr R) lattice.inf_le_left) := { η := { map := λ V HV, (by exact (Spec.locally_ringed_space (polynomial R)).O.F.res _ _ (sorope2.aux R V HV)) ∘ (D_f_to_Spec (polynomial.X : polynomial R)).fO.map _ ∘ (Zariski.induced.locally_ringed_space (inr_aux R)).fO.map (opens.comap (continuous_inr R) V), commutes := λ V HV W HW HWV s, rfl }, hom := λ V HV, @@is_ring_hom.comp _ _ _ (is_ring_hom.comp _ _) _ _ _ } set_option class.instance_max_depth 100 -- TODO: cleanup theorem sorope21 (V HV s) : (sorope2 R).η.map V HV ((sorope1 R).η.map V HV s) = s := begin refine subtype.eq (funext $ λ p, funext $ λ hp, _), change Zariski.coinduced.stalk_on_basis p (opens.comap _ (opens.comap _ V)) _ (Zariski.induced.stalk_on_basis (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, _⟩) (Zariski.coinduced.stalk_on_basis (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, _⟩)) (opens.comap _ (opens.comap _ V)) _ (Zariski.induced.stalk_on_basis (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, _⟩), _⟩) (s.val (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, _⟩), _⟩)) _)))) = s.val p hp, generalize : Zariski.coinduced.stalk_on_basis._proof_3 p (opens.comap (sorope2._proof_7 R) (opens.comap (sorope2._proof_8 R) V)) (sorope2._proof_13 R V HV hp) = h2, generalize : Zariski.coinduced.stalk_on_basis._proof_3 (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩)) _ _ = h3, generalize : sorope2._proof_13 R V HV hp = h4, generalize : Zariski.coinduced.Fext._proof_12 (opens.comap (sorope1._proof_7 R) (opens.comap (sorope1._proof_8 R) V)) _ _ = h1, generalize : sorope1._proof_13 R V HV _ = h9, change Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩), h3⟩) ∈ _ at h1, have : Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩), h3⟩) = p, { revert h3, rw [← congr_arg_Zariski.{u u} (inverse_comp_localization_of R), Zariski_induced_comp], intros h3 _, rw [coinduced_induced, ← Zariski_induced_comp], have : inverse R ∘ inr_aux R = localization.of, { ext s, rw ← inverse_comp_localization_of, dsimp only [(∘)], rw inverse_inverse' }, rw [congr_arg_Zariski.{u u} this, induced_coinduced] }, generalize h5 : s.val (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩), h3⟩)) h1 = x, rcases (stalk_on_basis_of_localization.bijective _).2 x with ⟨x, rfl⟩, rw Zariski.induced.stalk_on_basis.stalk_on_basis_of_localization, rw Zariski.coinduced.stalk_on_basis.stalk_on_basis_of_localization, rw Zariski.induced.stalk_on_basis.stalk_on_basis_of_localization, rw Zariski.coinduced.stalk_on_basis.stalk_on_basis_of_localization, have h6 : s.1 p hp = stalk_on_basis_of_localization p (eq.rec x this), { revert this h5 h1 hp x, clear h9 h4, generalize : Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩), h3⟩) = q, intros, subst this, exact h5 }, rw [h6, rec_eq_to_superset], congr' 1, refine congr_fun _ x, have : is_ring_hom ((Zariski.coinduced.stalk_on_basis.algebraic p (opens.comap (((Zariski.induced.locally_ringed_space (inr_aux R)).to_morphism).Hf) (opens.comap (continuous_inr R) V)) h4 ∘ Zariski.induced.stalk_on_basis.algebraic (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩) ∘ Zariski.coinduced.stalk_on_basis.algebraic (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩)) (opens.comap (sorope1._proof_7 R) (opens.comap (sorope1._proof_8 R) V)) h9 ∘ Zariski.induced.stalk_on_basis.algebraic (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩), h3⟩))), convert (@@is_ring_hom.comp _ _ _ _ _ _ (Zariski.coinduced.stalk_on_basis.algebraic.hom _ _ _)), convert (@@is_ring_hom.comp _ _ _ _ _ _ (Zariski.induced.stalk_on_basis.algebraic.hom _ _)), convert (@@is_ring_hom.comp _ _ _ _ _ _ (Zariski.coinduced.stalk_on_basis.algebraic.hom _ _ _)), convert (Zariski.induced.stalk_on_basis.algebraic.hom _ _), refine @@localization.funext _ _ _ _ _ this (localization.to_superset.hom _) (λ r, _), clear this h6 h5 h1 x, dsimp only [(∘)], simp only [Zariski.induced.stalk_on_basis.algebraic.coe, Zariski.coinduced.stalk_on_basis.algebraic.coe, localization.to_superset.coe], clear this h3 hp, refine @@polynomial.funext _ _ (Zariski.coinduced.stalk_on_basis.algebraic p (opens.comap (((Zariski.induced.locally_ringed_space (inr_aux R)).to_morphism).Hf) (opens.comap (continuous_inr R) V)) h4 ∘ Zariski.induced.stalk_on_basis.algebraic (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩) ∘ localization.to_superset (powers_subset (of_mem_map_subtype_val h9)) ∘ inr_aux R) localization.of (by convert @@is_ring_hom.comp _ _ _ _ _ _ (Zariski.coinduced.stalk_on_basis.algebraic.hom _ _ _); convert @@is_ring_hom.comp _ _ _ _ _ _ (Zariski.induced.stalk_on_basis.algebraic.hom _ _); convert @@is_ring_hom.comp _ _ _ _ _ _ (localization.to_superset.hom _); convert projective_line.is_ring_hom_inr_aux R) _ r (λ x, _) _, { dsimp only [(∘)], rw [inr_aux_C, localization.to_superset.of, Zariski.induced.stalk_on_basis.algebraic.of, Zariski.coinduced.stalk_on_basis.algebraic.of, inr_aux_C, localization.to_superset.of] }, { dsimp only [(∘)], rw [inr_aux_X, localization.away.inv_self_eq, ← units.coe_map' (localization.to_superset (powers_subset (of_mem_map_subtype_val h9))), ← units.coe_map' (Zariski.induced.stalk_on_basis.algebraic (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩)), ← units.coe_map' (Zariski.coinduced.stalk_on_basis.algebraic p (opens.comap (((Zariski.induced.locally_ringed_space (inr_aux R)).to_morphism).Hf) (opens.comap (continuous_inr R) V)) h4), monoid_hom.map_inv, monoid_hom.map_inv, monoid_hom.map_inv], refine eq.trans (one_mul _).symm _, rw units.mul_inv_eq_iff_eq_mul, rw [units.coe_map', units.coe_map', units.coe_map', localization.to_units_coe, coe_coe, localization.to_superset.coe, Zariski.induced.stalk_on_basis.algebraic.coe, Zariski.coinduced.stalk_on_basis.algebraic.coe, subtype.coe_mk, inr_aux_X, localization.away.inv_self_eq, ← units.coe_map' (localization.to_superset (powers_subset (of_mem_map_subtype_val h4))), monoid_hom.map_inv], symmetry, rw units.mul_inv_eq_iff_eq_mul, rw [one_mul, units.coe_map', localization.to_units_coe, coe_coe, localization.to_superset.coe], refl } end theorem sorope12 (V HV s) : (sorope1 R).η.map V HV ((sorope2 R).η.map V HV s) = s := begin refine subtype.eq (funext $ λ p, funext $ λ hp, _), change Zariski.coinduced.stalk_on_basis p (opens.comap _ (opens.comap _ V)) _ (Zariski.induced.stalk_on_basis (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, _⟩) (Zariski.coinduced.stalk_on_basis (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, _⟩)) (opens.comap _ (opens.comap _ V)) _ (Zariski.induced.stalk_on_basis (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, _⟩), _⟩) (s.val (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, _⟩), _⟩)) _)))) = s.val p hp, generalize : Zariski.coinduced.stalk_on_basis._proof_3 p (opens.comap (sorope1._proof_7 R) (opens.comap (sorope1._proof_8 R) V)) (sorope1._proof_13 R V HV hp) = h2, generalize : Zariski.coinduced.stalk_on_basis._proof_3 (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩)) _ _ = h3, generalize : sorope1._proof_13 R V HV hp = h4, generalize : Zariski.coinduced.Fext._proof_12 (opens.comap (sorope2._proof_7 R) (opens.comap (sorope2._proof_8 R) V)) _ _ = h1, generalize : sorope2._proof_13 R V HV _ = h9, change Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩), h3⟩) ∈ _ at h1, have : Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩), h3⟩) = p, { revert h3, rw [← congr_arg_Zariski.{u u} (inverse_comp_localization_of R), Zariski_induced_comp], intros h3 _, rw [coinduced_induced, ← Zariski_induced_comp], have : inverse R ∘ inr_aux R = localization.of, { ext s, rw ← inverse_comp_localization_of, dsimp only [(∘)], rw inverse_inverse' }, rw [congr_arg_Zariski.{u u} this, induced_coinduced] }, generalize h5 : s.val (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩), h3⟩)) h1 = x, rcases (stalk_on_basis_of_localization.bijective _).2 x with ⟨x, rfl⟩, rw Zariski.induced.stalk_on_basis.stalk_on_basis_of_localization, rw Zariski.coinduced.stalk_on_basis.stalk_on_basis_of_localization, rw Zariski.induced.stalk_on_basis.stalk_on_basis_of_localization, rw Zariski.coinduced.stalk_on_basis.stalk_on_basis_of_localization, have h6 : s.1 p hp = stalk_on_basis_of_localization p (eq.rec x this), { revert this h5 h1 hp x, clear h9 h4, generalize : Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩), h3⟩) = q, intros, subst this, exact h5 }, rw [h6, rec_eq_to_superset], congr' 1, refine congr_fun _ x, have : is_ring_hom ((Zariski.coinduced.stalk_on_basis.algebraic p (opens.comap (((Zariski.induced.locally_ringed_space (inr_aux R)).to_morphism).Hf) (opens.comap (continuous_inl R) V)) h4 ∘ Zariski.induced.stalk_on_basis.algebraic (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩) ∘ Zariski.coinduced.stalk_on_basis.algebraic (Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩)) (opens.comap (sorope2._proof_7 R) (opens.comap (sorope2._proof_8 R) V)) h9 ∘ Zariski.induced.stalk_on_basis.algebraic (inr_aux R) (Zariski.coinduced polynomial.X ⟨Zariski.induced (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩), h3⟩))), convert (@@is_ring_hom.comp _ _ _ _ _ _ (Zariski.coinduced.stalk_on_basis.algebraic.hom _ _ _)), convert (@@is_ring_hom.comp _ _ _ _ _ _ (Zariski.induced.stalk_on_basis.algebraic.hom _ _)), convert (@@is_ring_hom.comp _ _ _ _ _ _ (Zariski.coinduced.stalk_on_basis.algebraic.hom _ _ _)), convert (Zariski.induced.stalk_on_basis.algebraic.hom _ _), refine @@localization.funext _ _ _ _ _ this (localization.to_superset.hom _) (λ r, _), clear this h6 h5 h1 x, dsimp only [(∘)], simp only [Zariski.induced.stalk_on_basis.algebraic.coe, Zariski.coinduced.stalk_on_basis.algebraic.coe, localization.to_superset.coe], clear this h3 hp, refine @@polynomial.funext _ _ (Zariski.coinduced.stalk_on_basis.algebraic p (opens.comap (((Zariski.induced.locally_ringed_space (inr_aux R)).to_morphism).Hf) (opens.comap (continuous_inl R) V)) h4 ∘ Zariski.induced.stalk_on_basis.algebraic (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩) ∘ localization.to_superset (powers_subset (of_mem_map_subtype_val h9)) ∘ inr_aux R) localization.of (by convert @@is_ring_hom.comp _ _ _ _ _ _ (Zariski.coinduced.stalk_on_basis.algebraic.hom _ _ _); convert @@is_ring_hom.comp _ _ _ _ _ _ (Zariski.induced.stalk_on_basis.algebraic.hom _ _); convert @@is_ring_hom.comp _ _ _ _ _ _ (localization.to_superset.hom _); convert projective_line.is_ring_hom_inr_aux R) _ r (λ x, _) _, { dsimp only [(∘)], rw [inr_aux_C, localization.to_superset.of, Zariski.induced.stalk_on_basis.algebraic.of, Zariski.coinduced.stalk_on_basis.algebraic.of, inr_aux_C, localization.to_superset.of] }, { dsimp only [(∘)], rw [inr_aux_X, localization.away.inv_self_eq, ← units.coe_map' (localization.to_superset (powers_subset (of_mem_map_subtype_val h9))), ← units.coe_map' (Zariski.induced.stalk_on_basis.algebraic (inr_aux R) (Zariski.coinduced polynomial.X ⟨p, h2⟩)), ← units.coe_map' (Zariski.coinduced.stalk_on_basis.algebraic p (opens.comap (((Zariski.induced.locally_ringed_space (inr_aux R)).to_morphism).Hf) (opens.comap (continuous_inl R) V)) h4), monoid_hom.map_inv, monoid_hom.map_inv, monoid_hom.map_inv], refine eq.trans (one_mul _).symm _, rw units.mul_inv_eq_iff_eq_mul, rw [units.coe_map', units.coe_map', units.coe_map', localization.to_units_coe, coe_coe, localization.to_superset.coe, Zariski.induced.stalk_on_basis.algebraic.coe, Zariski.coinduced.stalk_on_basis.algebraic.coe, subtype.coe_mk, inr_aux_X, localization.away.inv_self_eq, ← units.coe_map' (localization.to_superset (powers_subset (of_mem_map_subtype_val h4))), monoid_hom.map_inv], symmetry, rw units.mul_inv_eq_iff_eq_mul, rw [one_mul, units.coe_map', localization.to_units_coe, coe_coe, localization.to_superset.coe], refl } end noncomputable def sorope : sheaf_of_rings_on_opens.equiv (sheaf_of_rings_on_opens.res_subset (soropl R) (opl R ⊓ opr R) lattice.inf_le_left) (sheaf_of_rings_on_opens.res_subset (soropr R) (opl R ⊓ opr R) lattice.inf_le_right) := { to_fun := sorope1 R, inv_fun := (sorope2 R).η, left_inv := λ V HV s, sorope21 R V HV s, right_inv := λ V HV s, sorope12 R V HV s } noncomputable def sor : sheaf_of_rings (projective_line R) := sheaf_of_rings_on_opens.sheaf_glue (projective_line.covering R).Uis (λ b, pbool.rec_on b (soropl R) (soropr R)) (λ b₁ b₂, pbool.rec_on b₁ (pbool.rec_on b₂ (sheaf_of_rings_on_opens.equiv.refl _) (sorope R)) (pbool.rec_on b₂ ((sorope R).symm.res_subset _ $ le_of_eq lattice.inf_comm) (sheaf_of_rings_on_opens.equiv.refl _))) end projective_line
deea45788effb2762d037e049b22bf0eb4fc0468
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/simp_tactic_auto.lean
81ac3513d3dc3eedbfce1dc93890f68ca74c5326
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,873
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.tactic import Mathlib.Lean3Lib.init.meta.attribute import Mathlib.Lean3Lib.init.meta.constructor_tactic import Mathlib.Lean3Lib.init.meta.relation_tactics import Mathlib.Lean3Lib.init.meta.occurrences import Mathlib.Lean3Lib.init.data.option.basic universes l namespace Mathlib def simp.default_max_steps : ℕ := bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit1 (bit0 (bit1 (bit1 (bit0 (bit1 (bit0 (bit0 (bit1 (bit0 (bit0 (bit0 (bit1 (bit1 (bit0 (bit0 1)))))))))))))))))))))) /-- Prefix the given `attr_name` with `"simp_attr"`. -/ /-- Simp lemmas are used by the "simplifier" family of tactics. `simp_lemmas` is essentially a pair of tables `rb_map (expr_type × name) (priority_list simp_lemma)`. One of the tables is for congruences and one is for everything else. An individual simp lemma is: - A kind which can be `Refl`, `Simp` or `Congr`. - A pair of `expr`s `l ~> r`. The rb map is indexed by the name of `get_app_fn(l)`. - A proof that `l = r` or `l ↔ r`. - A list of the metavariables that must be filled before the proof can be applied. - A priority number -/ /-- Make a new table of simp lemmas -/ /-- Merge the simp_lemma tables. -/ /-- Remove the given lemmas from the table. Use the names of the lemmas. -/ /-- Makes the default simp_lemmas table which is composed of all lemmas tagged with `simp`. -/ /-- Add a simplification lemma by an expression `p`. Some conditions on `p` must hold for it to be added, see list below. If your lemma is not being added, you can see the reasons by setting `set_option trace.simp_lemmas true`. - `p` must have the type `Π (h₁ : _) ... (hₙ : _), LHS ~ RHS` for some reflexive, transitive relation (usually `=`). - Any of the hypotheses `hᵢ` should either be present in `LHS` or otherwise a `Prop` or a typeclass instance. - `LHS` should not occur within `RHS`. - `LHS` should not occur within a hypothesis `hᵢ`. -/ /-- Add a simplification lemma by it's declaration name. See `simp_lemmas.add` for more information.-/ /-- Adds a congruence simp lemma to simp_lemmas. A congruence simp lemma is a lemma that breaks the simplification down into separate problems. For example, to simplify `a ∧ b` to `c ∧ d`, we should try to simp `a` to `c` and `b` to `d`. For examples of congruence simp lemmas look for lemmas with the `@[congr]` attribute. ```lean lemma if_simp_congr ... (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := ... lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := ... lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := ... ``` -/ /-- Add expressions to a set of simp lemmas using `simp_lemmas.add`. This is the new version of `simp_lemmas.append`, which also allows you to set the `symm` flag. -/ /-- Add expressions to a set of simp lemmas using `simp_lemmas.add`. This is the backwards-compatibility version of `simp_lemmas.append_with_symm`, and sets all `symm` flags to `ff`. -/ /-- `simp_lemmas.rewrite s e prove R` apply a simplification lemma from 's' - 'e' is the expression to be "simplified" - 'prove' is used to discharge proof obligations. - 'r' is the equivalence relation being used (e.g., 'eq', 'iff') - 'md' is the transparency; how aggresively should the simplifier perform reductions. Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ /-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/ namespace tactic /- Remark: `transform` should not change the target. -/ /-- Revert a local constant, change its type using `transform`. -/ /-- `get_eqn_lemmas_for deps d` returns the automatically generated equational lemmas for definition d. If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/ structure dsimp_config where md : transparency max_steps : ℕ canonize_instances : Bool single_pass : Bool fail_if_unchanged : Bool eta : Bool zeta : Bool beta : Bool proj : Bool iota : Bool unfold_reducible : Bool memoize : Bool end tactic /-- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. The list `u` contains defintions to be delta-reduced, and projections to be reduced.-/ namespace tactic /- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/ /- Remark: we use transparency.instances by default to make sure that we can unfold projections of type classes. Example: (@has_add.add nat nat.has_add a b) -/ /-- Tries to unfold `e` if it is a constant or a constant application. Remark: this is not a recursive procedure. -/ structure dunfold_config extends dsimp_config where /- Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for performance reasons. -/ structure delta_config where max_steps : ℕ visit_instances : Bool /-- Delta reduce the given constant names -/ structure unfold_proj_config extends dsimp_config where /-- If `e` is a projection application, try to unfold it, otherwise fail. -/ structure simp_config where max_steps : ℕ contextual : Bool lift_eq : Bool canonize_instances : Bool canonize_proofs : Bool use_axioms : Bool zeta : Bool beta : Bool eta : Bool proj : Bool iota : Bool iota_eqn : Bool constructor_eq : Bool single_pass : Bool fail_if_unchanged : Bool memoize : Bool trace_lemmas : Bool /-- `simplify s e cfg r prove` simplify `e` using `s` using bottom-up traversal. `discharger` is a tactic for dischaging new subgoals created by the simplifier. If it fails, the simplifier tries to discharge the subgoal by simplifying it to `true`. The parameter `to_unfold` specifies definitions that should be delta-reduced, and projection applications that should be unfolded. -/ /-- `ext_simplify_core a c s discharger pre post r e`: - `a : α` - initial user data - `c : simp_config` - simp configuration options - `s : simp_lemmas` - the set of simp_lemmas to use. Remark: the simplification lemmas are not applied automatically like in the simplify tactic. The caller must use them at pre/post. - `discharger : α → tactic α` - tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user data. - `pre a s r p e` is invoked before visiting the children of subterm 'e'. + arguments: - `a` is the current user data - `s` is the updated set of lemmas if 'contextual' is `tt`, - `r` is the simplification relation being used, - `p` is the "parent" expression (if there is one). - `e` is the current subexpression in question. + if it succeeds the result is `(new_a, new_e, new_pr, flag)` where - `new_a` is the new value for the user data - `new_e` is a new expression s.t. `r e new_e` - `new_pr` is a proof for `r e new_e`, If it is none, the proof is assumed to be by reflexivity - `flag` if tt `new_e` children should be visited, and `post` invoked. - `(post a s r p e)` is invoked after visiting the children of subterm `e`, The output is similar to `(pre a r s p e)`, but the 'flag' indicates whether the new expression should be revisited or not. - `r` is the simplification relation. Usually `=` or `↔`. - `e` is the input expression to be simplified. The method returns `(a,e,pr)` where - `a` is the final user data - `e` is the new expression - `pr` is the proof that the given expression equals the input expression. Note that `ext_simplify_core` will succeed even if `pre` and `post` fail, as failures are used to indicate that the method should move on to the next subterm. If it is desirable to propagate errors from `pre`, they can be propagated through the "user data". An easy way to do this is to call `tactic.capture (do ...)` in the parts of `pre`/`post` where errors matter, and then use `tactic.unwrap a` on the result. Additionally, `ext_simplify_core` does not propagate changes made to the tactic state by `pre` and `post. If it is desirable to propagate changes to the tactic state in addition to errors, use `tactic.resume` instead of `tactic.unwrap`. -/ structure simp_intros_config extends simp_config where use_hyps : Bool end Mathlib
f69f1fbe320ce50412207f5ee1896c78dd5c4bef
682dc1c167e5900ba3168b89700ae1cf501cfa29
/src/del/semantics/translationdefs.lean
d389c9ffee32caa7203404e28528818972f32e90
[]
no_license
paulaneeley/modal
834558c87f55cdd6d8a29bb46c12f4d1de3239bc
ee5d149d4ecb337005b850bddf4453e56a5daf04
refs/heads/master
1,675,911,819,093
1,609,785,144,000
1,609,785,144,000
270,388,715
13
1
null
null
null
null
UTF-8
Lean
false
false
963
lean
/- Copyright (c) 2021 Paula Neeley. All rights reserved. Author: Paula Neeley Following the textbook "Dynamic Epistemic Logic" by Hans van Ditmarsch, Wiebe van der Hoek, and Barteld Kooi -/ import del.languageDEL variables {agents : Type} -- Subformulas def subformulas : formPA agents → set (formPA agents) | (⊥) := {⊥} | (p n) := {(p n)} | (φ & ψ) := {(φ & ψ)} ∪ (subformulas φ) ∪ (subformulas ψ) | (φ ⊃ ψ) := {(φ ⊃ ψ)} ∪ (subformulas φ) ∪ (subformulas ψ) | (K a φ) := {(K a φ)} ∪ (subformulas φ) | (U φ ψ) := {(U φ ψ)} ∪ (subformulas φ) ∪ (subformulas ψ) -- Def 7.21, pg. 187, Complexity function c @[simp] def complexity : formPA agents → ℕ | (⊥) := 1 | (p n) := 1 | (φ & ψ) := 1 + max (complexity φ) (complexity ψ) | (φ ⊃ ψ) := 1 + max (complexity φ) (complexity ψ) | (K a φ) := 1 + (complexity φ) | (U φ ψ) := (4 + (complexity φ)) * (complexity ψ)
14e4505c5d4f93f9d7704e152badf598a2814d07
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/graded_algebra/radical.lean
8c72570374cc151b590ec1913c77badca15b105a
[ "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
8,934
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang, Eric Wieser -/ import ring_theory.graded_algebra.homogeneous_ideal /-! This file contains a proof that the radical of any homogeneous ideal is a homogeneous ideal ## Main statements * `ideal.is_homogeneous.is_prime_iff`: for any `I : ideal A`, if `I` is homogeneous, then `I` is prime if and only if `I` is homogeneously prime, i.e. `I ≠ ⊤` and if `x, y` are homogeneous elements such that `x * y ∈ I`, then at least one of `x,y` is in `I`. * `ideal.is_prime.homogeneous_core`: for any `I : ideal A`, if `I` is prime, then `I.homogeneous_core 𝒜` (i.e. the largest homogeneous ideal contained in `I`) is also prime. * `ideal.is_homogeneous.radical`: for any `I : ideal A`, if `I` is homogeneous, then the radical of `I` is homogeneous as well. * `homogeneous_ideal.radical`: for any `I : homogeneous_ideal 𝒜`, `I.radical` is the the radical of `I` as a `homogeneous_ideal 𝒜` ## Implementation details Throughout this file, the indexing type `ι` of grading is assumed to be a `linear_ordered_cancel_add_comm_monoid`. This might be stronger than necessary but cancelling property is strictly necessary; for a counterexample of how `ideal.is_homogeneous.is_prime_iff` fails for a non-cancellative set see `counterexample/homogeneous_prime_not_prime.lean`. ## Tags homogeneous, radical -/ open graded_algebra set_like finset open_locale big_operators variables {ι R A : Type*} variables [comm_semiring R] [comm_ring A] [algebra R A] variables [linear_ordered_cancel_add_comm_monoid ι] variables {𝒜 : ι → submodule R A} [graded_algebra 𝒜] lemma ideal.is_homogeneous.is_prime_of_homogeneous_mem_or_mem {I : ideal A} (hI : I.is_homogeneous 𝒜) (I_ne_top : I ≠ ⊤) (homogeneous_mem_or_mem : ∀ {x y : A}, is_homogeneous 𝒜 x → is_homogeneous 𝒜 y → (x * y ∈ I → x ∈ I ∨ y ∈ I)) : ideal.is_prime I := ⟨I_ne_top, begin intros x y hxy, by_contradiction rid, obtain ⟨rid₁, rid₂⟩ := not_or_distrib.mp rid, /- The idea of the proof is the following : since `x * y ∈ I` and `I` homogeneous, then `proj i (x * y) ∈ I` for any `i : ι`. Then consider two sets `{i ∈ x.support | xᵢ ∉ I}` and `{j ∈ y.support | yⱼ ∉ J}`; let `max₁, max₂` be the maximum of the two sets, then `proj (max₁ + max₂) (x * y) ∈ I`. Then, `proj max₁ x ∉ I` and `proj max₂ j ∉ I` but `proj i x ∈ I` for all `max₁ < i` and `proj j y ∈ I` for all `max₂ < j`. ` proj (max₁ + max₂) (x * y)` `= ∑ {(i, j) ∈ supports | i + j = max₁ + max₂}, xᵢ * yⱼ` `= proj max₁ x * proj max₂ y` ` + ∑ {(i, j) ∈ supports \ {(max₁, max₂)} | i + j = max₁ + max₂}, xᵢ * yⱼ`. This is a contradiction, because both `proj (max₁ + max₂) (x * y) ∈ I` and the sum on the right hand side is in `I` however `proj max₁ x * proj max₂ y` is not in `I`. -/ letI : Π (x : A), decidable_pred (λ (i : ι), proj 𝒜 i x ∉ I) := λ x, classical.dec_pred _, letI : Π i (x : 𝒜 i), decidable (x ≠ 0) := λ i x, classical.dec _, set set₁ := (support 𝒜 x).filter (λ i, proj 𝒜 i x ∉ I) with set₁_eq, set set₂ := (support 𝒜 y).filter (λ i, proj 𝒜 i y ∉ I) with set₂_eq, have nonempty : ∀ (x : A), (x ∉ I) → ((support 𝒜 x).filter (λ i, proj 𝒜 i x ∉ I)).nonempty, { intros x hx, rw filter_nonempty_iff, contrapose! hx, rw ← sum_support_decompose 𝒜 x, apply ideal.sum_mem _ hx, }, set max₁ := set₁.max' (nonempty x rid₁) with max₁_eq, set max₂ := set₂.max' (nonempty y rid₂) with max₂_eq, have mem_max₁ : max₁ ∈ set₁ := max'_mem set₁ (nonempty x rid₁), have mem_max₂ : max₂ ∈ set₂ := max'_mem set₂ (nonempty y rid₂), replace hxy : proj 𝒜 (max₁ + max₂) (x * y) ∈ I := hI _ hxy, have mem_I : proj 𝒜 max₁ x * proj 𝒜 max₂ y ∈ I, { set antidiag := ((support 𝒜 x).product (support 𝒜 y)).filter (λ z : ι × ι, z.1 + z.2 = max₁ + max₂) with ha, have mem_antidiag : (max₁, max₂) ∈ antidiag, { simp only [add_sum_erase, mem_filter, mem_product], exact ⟨⟨mem_of_mem_filter _ mem_max₁, mem_of_mem_filter _ mem_max₂⟩, rfl⟩ }, have eq_add_sum := calc proj 𝒜 (max₁ + max₂) (x * y) = ∑ ij in antidiag, proj 𝒜 ij.1 x * proj 𝒜 ij.2 y : by simp_rw [ha, proj_apply, map_mul, support, direct_sum.coe_mul_apply_submodule] ... = proj 𝒜 max₁ x * proj 𝒜 max₂ y + ∑ ij in antidiag.erase (max₁, max₂), proj 𝒜 ij.1 x * proj 𝒜 ij.2 y : (add_sum_erase _ _ mem_antidiag).symm, rw eq_sub_of_add_eq eq_add_sum.symm, refine ideal.sub_mem _ hxy (ideal.sum_mem _ (λ z H, _)), rcases z with ⟨i, j⟩, simp only [mem_erase, prod.mk.inj_iff, ne.def, mem_filter, mem_product] at H, rcases H with ⟨H₁, ⟨H₂, H₃⟩, H₄⟩, have max_lt : max₁ < i ∨ max₂ < j, { rcases lt_trichotomy max₁ i with h | rfl | h, { exact or.inl h }, { refine false.elim (H₁ ⟨rfl, add_left_cancel H₄⟩), }, { apply or.inr, have := add_lt_add_right h j, rw H₄ at this, exact lt_of_add_lt_add_left this, }, }, cases max_lt, { -- in this case `max₁ < i`, then `xᵢ ∈ I`; for otherwise `i ∈ set₁` then `i ≤ max₁`. have not_mem : i ∉ set₁ := λ h, lt_irrefl _ ((max'_lt_iff set₁ (nonempty x rid₁)).mp max_lt i h), rw set₁_eq at not_mem, simp only [not_and, not_not, ne.def, dfinsupp.mem_support_to_fun, mem_filter] at not_mem, exact ideal.mul_mem_right _ I (not_mem H₂), }, { -- in this case `max₂ < j`, then `yⱼ ∈ I`; for otherwise `j ∈ set₂`, then `j ≤ max₂`. have not_mem : j ∉ set₂ := λ h, lt_irrefl _ ((max'_lt_iff set₂ (nonempty y rid₂)).mp max_lt j h), rw set₂_eq at not_mem, simp only [not_and, not_not, ne.def, dfinsupp.mem_support_to_fun, mem_filter] at not_mem, exact ideal.mul_mem_left I _ (not_mem H₃), }, }, have not_mem_I : proj 𝒜 max₁ x * proj 𝒜 max₂ y ∉ I, { have neither_mem : proj 𝒜 max₁ x ∉ I ∧ proj 𝒜 max₂ y ∉ I, { rw mem_filter at mem_max₁ mem_max₂, exact ⟨mem_max₁.2, mem_max₂.2⟩, }, intro rid, cases homogeneous_mem_or_mem ⟨max₁, submodule.coe_mem _⟩ ⟨max₂, submodule.coe_mem _⟩ mem_I, { apply neither_mem.1 h }, { apply neither_mem.2 h }, }, exact not_mem_I mem_I, end⟩ lemma ideal.is_homogeneous.is_prime_iff {I : ideal A} (h : I.is_homogeneous 𝒜) : I.is_prime ↔ (I ≠ ⊤) ∧ ∀ {x y : A}, set_like.is_homogeneous 𝒜 x → set_like.is_homogeneous 𝒜 y → (x * y ∈ I → x ∈ I ∨ y ∈ I) := ⟨λ HI, ⟨ne_of_apply_ne _ HI.ne_top, λ x y hx hy hxy, ideal.is_prime.mem_or_mem HI hxy⟩, λ ⟨I_ne_top, homogeneous_mem_or_mem⟩, h.is_prime_of_homogeneous_mem_or_mem I_ne_top @homogeneous_mem_or_mem⟩ lemma ideal.is_prime.homogeneous_core {I : ideal A} (h : I.is_prime) : (I.homogeneous_core 𝒜).to_ideal.is_prime := begin apply (ideal.homogeneous_core 𝒜 I).is_homogeneous.is_prime_of_homogeneous_mem_or_mem, { exact ne_top_of_le_ne_top h.ne_top (ideal.to_ideal_homogeneous_core_le 𝒜 I) }, rintros x y hx hy hxy, have H := h.mem_or_mem (ideal.to_ideal_homogeneous_core_le 𝒜 I hxy), refine H.imp _ _, { exact ideal.mem_homogeneous_core_of_is_homogeneous_of_mem hx, }, { exact ideal.mem_homogeneous_core_of_is_homogeneous_of_mem hy, }, end lemma ideal.is_homogeneous.radical_eq {I : ideal A} (hI : I.is_homogeneous 𝒜) : I.radical = Inf { J | J.is_homogeneous 𝒜 ∧ I ≤ J ∧ J.is_prime } := begin rw ideal.radical_eq_Inf, apply le_antisymm, { exact Inf_le_Inf (λ J, and.right), }, { refine Inf_le_Inf_of_forall_exists_le _, rintros J ⟨HJ₁, HJ₂⟩, refine ⟨(J.homogeneous_core 𝒜).to_ideal, _, J.to_ideal_homogeneous_core_le _⟩, refine ⟨homogeneous_ideal.is_homogeneous _, _, HJ₂.homogeneous_core⟩, refine hI.to_ideal_homogeneous_core_eq_self.symm.trans_le (ideal.homogeneous_core_mono _ HJ₁), } end lemma ideal.is_homogeneous.radical {I : ideal A} (h : I.is_homogeneous 𝒜) : I.radical.is_homogeneous 𝒜 := by { rw h.radical_eq, exact ideal.is_homogeneous.Inf (λ _, and.left) } /-- The radical of a homogenous ideal, as another homogenous ideal. -/ def homogeneous_ideal.radical (I : homogeneous_ideal 𝒜) : homogeneous_ideal 𝒜 := ⟨I.to_ideal.radical, I.is_homogeneous.radical⟩ @[simp] lemma homogeneous_ideal.coe_radical (I : homogeneous_ideal 𝒜) : I.radical.to_ideal = I.to_ideal.radical := rfl
c2663262ed5bffe7d0a1735eac6f7311a8173315
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/extra/616c.hlean
2ddee385526d6a656cb11a1b4ea844e77674a2c3
[ "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
235
hlean
open eq definition my_elim {A P : Type} {R : A → A → Type} (Pc : A → P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (x : quotient R) : P := begin induction x, exact (Pc a), refine (pathover_of_eq _ (Pp H)) end
dd19588fd83d35cc90d084219792c6542165e1d2
f57749ca63d6416f807b770f67559503fdb21001
/hott/hit/trunc.hlean
c003079dc3ecd8be14294ee30278d29c08263d7e
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,747
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn n-truncation of types. Ported from Coq HoTT -/ /- The hit n-truncation is primitive, declared in init.hit. -/ import types.sigma types.pointed open is_trunc eq equiv is_equiv function prod sum sigma namespace trunc protected definition elim [recursor 6] {n : trunc_index} {A : Type} {P : Type} [Pt : is_trunc n P] (H : A → P) : trunc n A → P := trunc.rec H protected definition elim_on {n : trunc_index} {A : Type} {P : Type} (aa : trunc n A) [Pt : is_trunc n P] (H : A → P) : P := trunc.elim H aa /- there are no theorems to eliminate to the universe here, because the universe is generally not a set -/ --export is_trunc variables {X Y Z : Type} {P : X → Type} (A B : Type) (n : trunc_index) local attribute is_trunc_eq [instance] definition is_equiv_tr [instance] [H : is_trunc n A] : is_equiv (@tr n A) := adjointify _ (trunc.rec id) (λaa, trunc.rec_on aa (λa, idp)) (λa, idp) definition equiv_trunc [H : is_trunc n A] : A ≃ trunc n A := equiv.mk tr _ definition is_trunc_of_is_equiv_tr [H : is_equiv (@tr n A)] : is_trunc n A := is_trunc_is_equiv_closed n (@tr n _)⁻¹ definition untrunc_of_is_trunc [reducible] [H : is_trunc n A] : trunc n A → A := tr⁻¹ /- Functoriality -/ definition trunc_functor [unfold 5] (f : X → Y) : trunc n X → trunc n Y := λxx, trunc.rec_on xx (λx, tr (f x)) definition trunc_functor_compose (f : X → Y) (g : Y → Z) : trunc_functor n (g ∘ f) ~ trunc_functor n g ∘ trunc_functor n f := λxx, trunc.rec_on xx (λx, idp) definition trunc_functor_id : trunc_functor n (@id A) ~ id := λxx, trunc.rec_on xx (λx, idp) definition is_equiv_trunc_functor (f : X → Y) [H : is_equiv f] : is_equiv (trunc_functor n f) := adjointify _ (trunc_functor n f⁻¹) (λyy, trunc.rec_on yy (λy, ap tr !right_inv)) (λxx, trunc.rec_on xx (λx, ap tr !left_inv)) section open equiv.ops definition trunc_equiv_trunc (f : X ≃ Y) : trunc n X ≃ trunc n Y := equiv.mk _ (is_equiv_trunc_functor n f) end section open prod.ops definition trunc_prod_equiv : trunc n (X × Y) ≃ trunc n X × trunc n Y := begin fapply equiv.MK, {exact (λpp, trunc.rec_on pp (λp, (tr p.1, tr p.2)))}, {intro p, cases p with xx yy, apply (trunc.rec_on xx), intro x, apply (trunc.rec_on yy), intro y, exact (tr (x,y))}, {intro p, cases p with xx yy, apply (trunc.rec_on xx), intro x, apply (trunc.rec_on yy), intro y, apply idp}, {intro pp, apply (trunc.rec_on pp), intro p, cases p, apply idp} end end /- Propositional truncation -/ -- should this live in hprop? definition merely [reducible] (A : Type) : Type := trunc -1 A notation `||`:max A `||`:0 := merely A notation `∥`:max A `∥`:0 := merely A definition Exists [reducible] (P : X → Type) : Type := ∥ sigma P ∥ definition or [reducible] (A B : Type) : Type := ∥ A ⊎ B ∥ notation `exists` binders `,` r:(scoped P, Exists P) := r notation `∃` binders `,` r:(scoped P, Exists P) := r notation A `\/` B := or A B notation A ∨ B := or A B definition merely.intro [reducible] (a : A) : ∥ A ∥ := tr a definition exists.intro [reducible] (x : X) (p : P x) : ∃x, P x := tr ⟨x, p⟩ definition or.intro_left [reducible] (x : X) : X ∨ Y := tr (inl x) definition or.intro_right [reducible] (y : Y) : X ∨ Y := tr (inr y) definition is_contr_of_merely_hprop [H : is_hprop A] (aa : merely A) : is_contr A := is_contr_of_inhabited_hprop (trunc.rec_on aa id) section open sigma.ops definition trunc_sigma_equiv : trunc n (Σ x, P x) ≃ trunc n (Σ x, trunc n (P x)) := equiv.MK (λpp, trunc.rec_on pp (λp, tr ⟨p.1, tr p.2⟩)) (λpp, trunc.rec_on pp (λp, trunc.rec_on p.2 (λb, tr ⟨p.1, b⟩))) (λpp, trunc.rec_on pp (λp, sigma.rec_on p (λa bb, trunc.rec_on bb (λb, by esimp)))) (λpp, trunc.rec_on pp (λp, sigma.rec_on p (λa b, by esimp))) definition trunc_sigma_equiv_of_is_trunc [H : is_trunc n X] : trunc n (Σ x, P x) ≃ Σ x, trunc n (P x) := calc trunc n (Σ x, P x) ≃ trunc n (Σ x, trunc n (P x)) : trunc_sigma_equiv ... ≃ Σ x, trunc n (P x) : equiv.symm !equiv_trunc end end trunc attribute trunc.elim_on [unfold 4] attribute trunc.rec [recursor] attribute trunc.elim [recursor 6] [unfold 6]
bea6077c51ecdc9cf6e63e9f17fcb7a8fb10712c
82e44445c70db0f03e30d7be725775f122d72f3e
/src/combinatorics/hales_jewett.lean
47e62e3c183f60f92af517ab5c5465137f476583
[ "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
15,441
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import data.fintype.basic import algebra.big_operators.basic import data.equiv.fin /-! # The Hales-Jewett theorem We prove the Hales-Jewett theorem and deduce Van der Waerden's theorem as a corollary. The Hales-Jewett theorem is a result in Ramsey theory dealing with *combinatorial lines*. Given an 'alphabet' `α : Type*` and `a b : α`, an example of a combinatorial line in `α^5` is `{ (a, x, x, b, x) | x : α }`. See `combinatorics.line` for a precise general definition. The Hales-Jewett theorem states that for any fixed finite types `α` and `κ`, there exists a (potentially huge) finite type `ι` such that whenever `ι → α` is `κ`-colored (i.e. for any coloring `C : (ι → α) → κ`), there exists a monochromatic line. We prove the Hales-Jewett theorem using the idea of *color focusing* and a *product argument*. See the proof of `combinatorics.line.exists_mono_in_high_dimension'` for details. The version of Van der Waerden's theorem in this file states that whenever a commutative monoid `M` is finitely colored and `S` is a finite subset, there exists a monochromatic homothetic copy of `S`. This follows from the Hales-Jewett theorem by considering the map `(ι → S) → M` sending `v` to `∑ i : ι, v i`, which sends a combinatorial line to a homothetic copy of `S`. ## Main results - `combinatorics.line.exists_mono_in_high_dimension`: the Hales-Jewett theorem. - `combinatorics.exists_mono_homothetic_copy`: a generalization of Van der Waerden's theorem. ## Implementation details For convenience, we work directly with finite types instead of natural numbers. That is, we write `α, ι, κ` for (finite) types where one might traditionally use natural numbers `n, H, c`. This allows us to work directly with `α`, `option α`, `(ι → α) → κ`, and `ι ⊕ ι'` instead of `fin n`, `fin (n+1)`, `fin (c^(n^H))`, and `fin (H + H')`. ## Todo - Prove a finitary version of Van der Waerden's theorem (either by compactness or by modifying the current proof). - One could reformulate the proof of Hales-Jewett to give explicit upper bounds on the number of coordinates needed. ## Tags combinatorial line, Ramsey theory, arithmetic progession ### References * https://en.wikipedia.org/wiki/Hales%E2%80%93Jewett_theorem -/ open_locale classical open_locale big_operators universes u v namespace combinatorics /-- The type of combinatorial lines. A line `l : line α ι` in the hypercube `ι → α` defines a function `α → ι → α` from `α` to the hypercube, such that for each coordinate `i : ι`, the function `λ x, l x i` is either `id` or constant. We require lines to be nontrivial in the sense that `λ x, l x i` is `id` for at least one `i`. Formally, a line is represented by the function `l.idx_fun : ι → option α` which says whether `λ x, l x i` is `id` (corresponding to `l.idx_fun i = none`) or constantly `y` (corresponding to `l.idx_fun i = some y`). When `α` has size `1` there can be many elements of `line α ι` defining the same function. -/ structure line (α ι : Type*) := (idx_fun : ι → option α) (proper : ∃ i, idx_fun i = none) namespace line /- This lets us treat a line `l : line α ι` as a function `α → ι → α`. -/ instance (α ι) : has_coe_to_fun (line α ι) := ⟨λ _, α → ι → α, λ l x i, (l.idx_fun i).get_or_else x⟩ /-- A line is monochromatic if all its points are the same color. -/ def is_mono {α ι κ} (C : (ι → α) → κ) (l : line α ι) : Prop := ∃ c, ∀ x, C (l x) = c /-- The diagonal line. It is the identity at every coordinate. -/ def diagonal (α ι) [nonempty ι] : line α ι := { idx_fun := λ _, none, proper := ⟨classical.arbitrary ι, rfl⟩ } instance (α ι) [nonempty ι] : inhabited (line α ι) := ⟨diagonal α ι⟩ /-- The type of lines that are only one color except possibly at their endpoints. -/ structure almost_mono {α ι κ : Type*} (C : (ι → option α) → κ) := (line : line (option α) ι) (color : κ) (has_color : ∀ x : α, C (line (some x)) = color) instance {α ι κ : Type*} [nonempty ι] [inhabited κ] : inhabited (almost_mono (λ v : ι → option α, default κ)) := ⟨{ line := default _, color := default κ, has_color := λ _, rfl }⟩ /-- The type of collections of lines such that - each line is only one color except possibly at its endpoint - the lines all have the same endpoint - the colors of the lines are distinct. Used in the proof `exists_mono_in_high_dimension`. -/ structure color_focused {α ι κ : Type*} (C : (ι → option α) → κ) := (lines : multiset (almost_mono C)) (focus : ι → option α) (is_focused : ∀ p ∈ lines, almost_mono.line p none = focus) (distinct_colors : (lines.map almost_mono.color).nodup) instance {α ι κ} (C : (ι → option α) → κ) : inhabited (color_focused C) := ⟨⟨0, λ _, none, λ _, false.elim, multiset.nodup_zero⟩⟩ /-- A function `f : α → α'` determines a function `line α ι → line α' ι`. For a coordinate `i`, `l.map f` is the identity at `i` if `l` is, and constantly `f y` if `l` is constantly `y` at `i`. -/ def map {α α' ι} (f : α → α') (l : line α ι) : line α' ι := { idx_fun := λ i, (l.idx_fun i).map f, proper := ⟨l.proper.some, by rw [l.proper.some_spec, option.map_none'] ⟩ } /-- A point in `ι → α` and a line in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def vertical {α ι ι'} (v : ι → α) (l : line α ι') : line α (ι ⊕ ι') := { idx_fun := sum.elim (some ∘ v) l.idx_fun, proper := ⟨sum.inr l.proper.some, l.proper.some_spec⟩ } /-- A line in `ι → α` and a point in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def horizontal {α ι ι'} (l : line α ι) (v : ι' → α) : line α (ι ⊕ ι') := { idx_fun := sum.elim l.idx_fun (some ∘ v), proper := ⟨sum.inl l.proper.some, l.proper.some_spec⟩ } /-- One line in `ι → α` and one in `ι' → α` together determine a line in `ι ⊕ ι' → α`. -/ def prod {α ι ι'} (l : line α ι) (l' : line α ι') : line α (ι ⊕ ι') := { idx_fun := sum.elim l.idx_fun l'.idx_fun, proper := ⟨sum.inl l.proper.some, l.proper.some_spec⟩ } lemma apply {α ι} (l : line α ι) (x : α) : l x = λ i, (l.idx_fun i).get_or_else x := rfl lemma apply_none {α ι} (l : line α ι) (x : α) (i : ι) (h : l.idx_fun i = none) : l x i = x := by simp only [option.get_or_else_none, h, l.apply] lemma apply_of_ne_none {α ι} (l : line α ι) (x : α) (i : ι) (h : l.idx_fun i ≠ none) : some (l x i) = l.idx_fun i := by rw [l.apply, option.get_or_else_of_ne_none h] @[simp] lemma map_apply {α α' ι} (f : α → α') (l : line α ι) (x : α) : l.map f (f x) = f ∘ l x := by simp only [line.apply, line.map, option.get_or_else_map] @[simp] lemma vertical_apply {α ι ι'} (v : ι → α) (l : line α ι') (x : α) : l.vertical v x = sum.elim v (l x) := by { funext i, cases i; refl } @[simp] lemma horizontal_apply {α ι ι'} (l : line α ι) (v : ι' → α) (x : α) : l.horizontal v x = sum.elim (l x) v := by { funext i, cases i; refl } @[simp] lemma prod_apply {α ι ι'} (l : line α ι) (l' : line α ι') (x : α) : l.prod l' x = sum.elim (l x) (l' x) := by { funext i, cases i; refl } @[simp] lemma diagonal_apply {α ι} [nonempty ι] (x : α) : line.diagonal α ι x = λ i, x := by simp_rw [line.apply, line.diagonal, option.get_or_else_none] /-- The Hales-Jewett theorem. This version has a restriction on universe levels which is necessary for the proof. See `exists_mono_in_high_dimension` for a fully universe-polymorphic version. -/ private theorem exists_mono_in_high_dimension' : ∀ (α : Type u) [fintype α] (κ : Type (max v u)) [fintype κ], ∃ (ι : Type) [fintype ι], ∀ C : (ι → α) → κ, ∃ l : line α ι, l.is_mono C := -- The proof proceeds by induction on `α`. fintype.induction_empty_option -- We have to show that the theorem is invariant under `α ≃ α'` for the induction to work. (λ α α' e, forall_imp $ λ κ, forall_imp $ λ _, Exists.imp $ λ ι, Exists.imp $ λ _ h C, let ⟨l, c, lc⟩ := h (λ v, C (e ∘ v)) in ⟨l.map e, c, e.forall_congr_left.mp $ λ x, by rw [←lc x, line.map_apply]⟩) begin -- This deals with the degenerate case where `α` is empty. introsI κ _, by_cases h : nonempty κ, { resetI, exact ⟨unit, infer_instance, λ C, ⟨default _, classical.arbitrary _, pempty.rec _⟩⟩, }, { exact ⟨empty, infer_instance, λ C, (h ⟨C (empty.rec _)⟩).elim⟩, } end begin -- Now we have to show that the theorem holds for `option α` if it holds for `α`. introsI α _ ihα κ _, -- Later we'll need `α` to be nonempty. So we first deal with the trivial case where `α` is empty. -- Then `option α` has only one element, so any line is monochromatic. by_cases h : nonempty α, work_on_goal 1 { refine ⟨unit, infer_instance, λ C, ⟨diagonal _ _, C (λ _, none), _⟩⟩, rintros (_ | ⟨a⟩), refl, exact (h ⟨a⟩).elim, }, -- The key idea is to show that for every `r`, in high dimension we can either find -- `r` color focused lines or a monochromatic line. suffices key : ∀ r : ℕ, ∃ (ι : Type) [fintype ι], ∀ C : (ι → (option α)) → κ, (∃ s : color_focused C, s.lines.card = r) ∨ (∃ l, is_mono C l), -- Given the key claim, we simply take `r = |κ| + 1`. We cannot have this many distinct colors so -- we must be in the second case, where there is a monochromatic line. { obtain ⟨ι, _inst, hι⟩ := key (fintype.card κ + 1), refine ⟨ι, _inst, λ C, (hι C).resolve_left _⟩, rintro ⟨s, sr⟩, apply nat.not_succ_le_self (fintype.card κ), rw [←nat.add_one, ←sr, ←multiset.card_map, ←finset.card_mk], exact finset.card_le_univ ⟨_, s.distinct_colors⟩ }, -- We now prove the key claim, by induction on `r`. intro r, induction r with r ihr, -- The base case `r = 0` is trivial as the empty collection is color-focused. { exact ⟨empty, infer_instance, λ C, or.inl ⟨default _, multiset.card_zero⟩⟩, }, -- Supposing the key claim holds for `r`, we need to show it for `r+1`. First pick a high enough -- dimension `ι` for `r`. obtain ⟨ι, _inst, hι⟩ := ihr, resetI, -- Then since the theorem holds for `α` with any number of colors, pick a dimension `ι'` such that -- `ι' → α` always has a monochromatic line whenever it is `(ι → option α) → κ`-colored. specialize ihα ((ι → option α) → κ), obtain ⟨ι', _inst, hι'⟩ := ihα, resetI, -- We claim that `ι ⊕ ι'` works for `option α` and `κ`-coloring. refine ⟨ι ⊕ ι', infer_instance, _⟩, intro C, -- A `κ`-coloring of `ι ⊕ ι' → option α` induces an `(ι → option α) → κ`-coloring of `ι' → α`. specialize hι' (λ v' v, C (sum.elim v (some ∘ v'))), -- By choice of `ι'` this coloring has a monochromatic line `l'` with color class `C'`, where -- `C'` is a `κ`-coloring of `ι → α`. obtain ⟨l', C', hl'⟩ := hι', -- If `C'` has a monochromatic line, then so does `C`. We use this in two places below. have mono_of_mono : (∃ l, is_mono C' l) → (∃ l, is_mono C l), { rintro ⟨l, c, hl⟩, refine ⟨l.horizontal (some ∘ l' (classical.arbitrary α)), c, λ x, _⟩, rw [line.horizontal_apply, ←hl, ←hl'], }, -- By choice of `ι`, `C'` either has `r` color-focused lines or a monochromatic line. specialize hι C', rcases hι with ⟨s, sr⟩ | _, -- By above, we are done if `C'` has a monochromatic line. work_on_goal 1 { exact or.inr (mono_of_mono hι) }, -- Here we assume `C'` has `r` color focused lines. We split into cases depending on whether one of -- these `r` lines has the same color as the focus point. by_cases h : ∃ p ∈ s.lines, (p : almost_mono _).color = C' s.focus, -- If so then this is a `C'`-monochromatic line and we are done. { obtain ⟨p, p_mem, hp⟩ := h, refine or.inr (mono_of_mono ⟨p.line, p.color, _⟩), rintro (_ | _), rw [hp, s.is_focused p p_mem], apply p.has_color, }, -- If not, we get `r+1` color focused lines by taking the product of the `r` lines with `l'` and -- adding to this the vertical line obtained by the focus point and `l`. refine or.inl ⟨⟨(s.lines.map _).cons ⟨(l'.map some).vertical s.focus, C' s.focus, λ x, _⟩, sum.elim s.focus (l'.map some none), _, _⟩, _⟩, -- The vertical line is almost monochromatic. { rw [vertical_apply, ←congr_fun (hl' x), line.map_apply], }, { refine λ p, ⟨p.line.prod (l'.map some), p.color, λ x, _⟩, -- The product lines are almost monochromatic. rw [line.prod_apply, line.map_apply, ←p.has_color, ←congr_fun (hl' x)], }, -- Our `r+1` lines have the same endpoint. { simp_rw [multiset.mem_cons, multiset.mem_map], rintros _ (rfl | ⟨q, hq, rfl⟩), { rw line.vertical_apply, }, { rw [line.prod_apply, s.is_focused q hq], }, }, -- Our `r+1` lines have distinct colors (this is why we needed to split into cases above). { rw [multiset.map_cons, multiset.map_map, multiset.nodup_cons, multiset.mem_map], exact ⟨λ ⟨q, hq, he⟩, h ⟨q, hq, he⟩, s.distinct_colors⟩, }, -- Finally, we really do have `r+1` lines! { rw [multiset.card_cons, multiset.card_map, sr], }, end /-- The Hales-Jewett theorem: for any finite types `α` and `κ`, there exists a finite type `ι` such that whenever the hypercube `ι → α` is `κ`-colored, there is a monochromatic combinatorial line. -/ theorem exists_mono_in_high_dimension (α : Type u) [fintype α] (κ : Type v) [fintype κ] : ∃ (ι : Type) [fintype ι], ∀ C : (ι → α) → κ, ∃ l : line α ι, l.is_mono C := let ⟨ι, ιfin, hι⟩ := exists_mono_in_high_dimension' α (ulift κ) in ⟨ι, ιfin, λ C, let ⟨l, c, hc⟩ := hι (ulift.up ∘ C) in ⟨l, c.down, λ x, by rw ←hc⟩ ⟩ end line /-- A generalization of Van der Waerden's theorem: if `M` is a finitely colored commutative monoid, and `S` is a finite subset, then there exists a monochromatic homothetic copy of `S`. -/ theorem exists_mono_homothetic_copy {M κ} [add_comm_monoid M] (S : finset M) [fintype κ] (C : M → κ) : ∃ (a > 0) (b : M) (c : κ), ∀ s ∈ S, C (a • s + b) = c := begin obtain ⟨ι, _inst, hι⟩ := line.exists_mono_in_high_dimension S κ, resetI, specialize hι (λ v, C $ ∑ i, v i), obtain ⟨l, c, hl⟩ := hι, set s : finset ι := { i ∈ finset.univ | l.idx_fun i = none } with hs, refine ⟨s.card, finset.card_pos.mpr ⟨l.proper.some, _⟩, ∑ i in sᶜ, ((l.idx_fun i).map coe).get_or_else 0, c, _⟩, { rw [hs, finset.sep_def, finset.mem_filter], exact ⟨finset.mem_univ _, l.proper.some_spec⟩, }, intros x xs, rw ←hl ⟨x, xs⟩, clear hl, congr, rw ←finset.sum_add_sum_compl s, congr' 1, { rw ←finset.sum_const, apply finset.sum_congr rfl, intros i hi, rw [hs, finset.sep_def, finset.mem_filter] at hi, rw [l.apply_none _ _ hi.right, subtype.coe_mk], }, { apply finset.sum_congr rfl, intros i hi, rw [hs, finset.sep_def, finset.compl_filter, finset.mem_filter] at hi, obtain ⟨y, hy⟩ := option.ne_none_iff_exists.mp hi.right, simp_rw [line.apply, ←hy, option.map_some', option.get_or_else_some], }, end end combinatorics
56b159f0e32cad2f42774269291a13d2df674640
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/injection_tactic_auto.lean
6eaabbf74819ddec44c78e07656145245e36dd02
[]
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
1,202
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jannis Limperg -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.tactic namespace Mathlib namespace tactic /- Given a local constant `H : C x₁ ... xₙ = D y₁ ... yₘ`, where `C` and `D` are fully applied constructors, `injection_with H ns base offset` does the following: - If `C ≠ D`, it solves the goal (using the no-confusion rule). - If `C = D` (and thus `n = m`), it adds hypotheses `h₁ : x₁ = y₁, ..., hₙ : xₙ = yₙ` to the local context. Names for the `hᵢ` are taken from `ns`. If `ns` does not contain enough names, then the names are derived from `base` and `offset` (by default `h_1`, `h_2` etc.; see `intro_fresh`). - Special case: if `C = D` and `n = 0` (i.e. the constructors have no arguments), the hypothesis `h : true` is added to the context. `injection_with` returns the new hypotheses and the leftover names from `ns` (i.e. those names that were not used to name the new hypotheses). If (and only if) the goal was solved, the list of new hypotheses is empty. -/ end Mathlib
ac3c3ebd16daf2a7ac945e581be85aa3ab794818
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/polynomial/ring_division.lean
bd861c1787f46c41b74542775e68c10d2695760d
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
44,258
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, Johan Commelin -/ import algebra.char_zero.infinite import data.polynomial.algebra_map import data.polynomial.degree.lemmas import data.polynomial.div import ring_theory.localization.fraction_ring import algebra.polynomial.big_operators /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ ## Main definitions * `polynomial.roots p`: The multiset containing all the roots of `p`, including their multiplicities. * `polynomial.root_set p E`: The set of distinct roots of `p` in an algebra `E`. ## Main statements * `polynomial.C_leading_coeff_mul_prod_multiset_X_sub_C`: If a polynomial has as many roots as its degree, it can be written as the product of its leading coefficient with `∏ (X - a)` where `a` ranges through its roots. -/ noncomputable theory open_locale classical polynomial open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {a b : R} {n : ℕ} section comm_ring variables [comm_ring R] {p q : R[X]} section variables [semiring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : R[X]} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.nat_degree := nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj lemma degree_pos_of_aeval_root [algebra R S] {p : R[X]} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.degree := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj) lemma mod_by_monic_eq_of_dvd_sub (hq : q.monic) {p₁ p₂ : R[X]} (h : q ∣ (p₁ - p₂)) : p₁ %ₘ q = p₂ %ₘ q := begin nontriviality R, obtain ⟨f, sub_eq⟩ := h, refine (div_mod_by_monic_unique (p₂ /ₘ q + f) _ hq ⟨_, degree_mod_by_monic_lt _ hq⟩).2, rw [sub_eq_iff_eq_add.mp sub_eq, mul_add, ← add_assoc, mod_by_monic_add_div _ hq, add_comm] end lemma add_mod_by_monic (p₁ p₂ : R[X]) : (p₁ + p₂) %ₘ q = p₁ %ₘ q + p₂ %ₘ q := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (p₁ /ₘ q + p₂ /ₘ q) _ hq ⟨by rw [mul_add, add_left_comm, add_assoc, mod_by_monic_add_div _ hq, ← add_assoc, add_comm (q * _), mod_by_monic_add_div _ hq], (degree_add_le _ _).trans_lt (max_lt (degree_mod_by_monic_lt _ hq) (degree_mod_by_monic_lt _ hq))⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end lemma smul_mod_by_monic (c : R) (p : R[X]) : (c • p) %ₘ q = c • (p %ₘ q) := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (c • (p /ₘ q)) (c • (p %ₘ q)) hq ⟨by rw [mul_smul_comm, ← smul_add, mod_by_monic_add_div p hq], (degree_smul_le _ _).trans_lt (degree_mod_by_monic_lt _ hq)⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end /-- `_ %ₘ q` as an `R`-linear map. -/ @[simps] def mod_by_monic_hom (q : R[X]) : R[X] →ₗ[R] R[X] := { to_fun := λ p, p %ₘ q, map_add' := add_mod_by_monic, map_smul' := smul_mod_by_monic } end section variables [ring S] lemma aeval_mod_by_monic_eq_self_of_root [algebra R S] {p q : R[X]} (hq : q.monic) {x : S} (hx : aeval x q = 0) : aeval x (p %ₘ q) = aeval x p := -- `eval₂_mod_by_monic_eq_self_of_root` doesn't work here as it needs commutativity by rw [mod_by_monic_eq_sub_mul_div p hq, _root_.map_sub, _root_.map_mul, hx, zero_mul, sub_zero] end end comm_ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} instance : no_zero_divisors R[X] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], refine eq_zero_or_eq_zero_of_mul_eq_zero _, rw [← leading_coeff_zero, ← leading_coeff_mul, h], end } lemma nat_degree_mul (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] lemma trailing_degree_mul : (p * q).trailing_degree = p.trailing_degree + q.trailing_degree := begin by_cases hp : p = 0, { rw [hp, zero_mul, trailing_degree_zero, top_add] }, by_cases hq : q = 0, { rw [hq, mul_zero, trailing_degree_zero, add_top] }, rw [trailing_degree_eq_nat_trailing_degree hp, trailing_degree_eq_nat_trailing_degree hq, trailing_degree_eq_nat_trailing_degree (mul_ne_zero hp hq), nat_trailing_degree_mul hp hq, with_top.coe_add], end @[simp] lemma nat_degree_pow (p : R[X]) (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' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma degree_le_mul_left (p : R[X]) (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, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) theorem nat_degree_le_of_dvd {p q : R[X]} (h1 : p ∣ q) (h2 : q ≠ 0) : p.nat_degree ≤ q.nat_degree := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _ end lemma degree_le_of_dvd {p q : R[X]} (h1 : p ∣ q) (h2 : q ≠ 0) : degree p ≤ degree q := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, exact degree_le_mul_left p h2.2, end /-- This lemma is useful for working with the `int_degree` of a rational function. -/ lemma nat_degree_sub_eq_of_prod_eq {p₁ p₂ q₁ q₂ : R[X]} (hp₁ : p₁ ≠ 0) (hq₁ : q₁ ≠ 0) (hp₂ : p₂ ≠ 0) (hq₂ : q₂ ≠ 0) (h_eq : p₁ * q₂ = p₂ * q₁) : (p₁.nat_degree : ℤ) - q₁.nat_degree = (p₂.nat_degree : ℤ) - q₂.nat_degree := begin rw sub_eq_sub_iff_add_eq_add, norm_cast, rw [← nat_degree_mul hp₁ hq₂, ← nat_degree_mul hp₂ hq₁, h_eq] end lemma nat_degree_eq_zero_of_is_unit (h : is_unit p) : nat_degree p = 0 := begin nontriviality R, obtain ⟨q, hq⟩ := h.exists_right_inv, have := nat_degree_mul (left_ne_zero_of_mul_eq_one hq) (right_ne_zero_of_mul_eq_one hq), rw [hq, nat_degree_one, eq_comm, add_eq_zero_iff] at this, exact this.1, end lemma degree_eq_zero_of_is_unit [nontrivial R] (h : is_unit p) : degree p = 0 := (nat_degree_eq_zero_iff_degree_le_zero.mp $ nat_degree_eq_zero_of_is_unit h).antisymm (zero_le_degree_iff.mpr h.ne_zero) @[simp] lemma degree_coe_units [nontrivial R] (u : R[X]ˣ) : degree (u : R[X]) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ theorem is_unit_iff : is_unit p ↔ ∃ r : R, is_unit r ∧ C r = p := ⟨λ hp, ⟨p.coeff 0, let h := eq_C_of_nat_degree_eq_zero (nat_degree_eq_zero_of_is_unit hp) in ⟨is_unit_C.1 (h ▸ hp), h.symm⟩⟩, λ ⟨r, hr, hrp⟩, hrp ▸ is_unit_C.2 hr⟩ variables [char_zero R] @[simp] lemma degree_bit0_eq (p : R[X]) : degree (bit0 p) = degree p := by rw [bit0_eq_two_mul, degree_mul, (by simp : (2 : R[X]) = C 2), @polynomial.degree_C R _ _ two_ne_zero, zero_add] @[simp] lemma nat_degree_bit0_eq (p : R[X]) : nat_degree (bit0 p) = nat_degree p := nat_degree_eq_of_degree_eq $ degree_bit0_eq p @[simp] lemma nat_degree_bit1_eq (p : R[X]) : nat_degree (bit1 p) = nat_degree p := begin rw bit1, apply le_antisymm, convert nat_degree_add_le _ _, { simp, }, by_cases h : p.nat_degree = 0, { simp [h], }, apply le_nat_degree_of_ne_zero, intro hh, apply h, simp [*, coeff_one, if_neg (ne.symm h)] at *, end lemma degree_bit1_eq {p : R[X]} (hp : 0 < degree p) : degree (bit1 p) = degree p := begin rw [bit1, degree_add_eq_left_of_degree_lt, degree_bit0_eq], rwa [degree_one, degree_bit0_eq] end end no_zero_divisors section no_zero_divisors variables [comm_semiring R] [no_zero_divisors R] {p q : R[X]} lemma irreducible_of_monic (hp : p.monic) (hp1 : p ≠ 1) : irreducible p ↔ ∀ f g : R[X], f.monic → g.monic → f * g = p → f = 1 ∨ g = 1 := begin refine ⟨λ h f g hf hg hp, (h.2 f g hp.symm).imp hf.eq_one_of_is_unit hg.eq_one_of_is_unit, λ h, ⟨hp1 ∘ hp.eq_one_of_is_unit, λ f g hfg, (h (g * C f.leading_coeff) (f * C g.leading_coeff) _ _ _).symm.imp (is_unit_of_mul_eq_one f _) (is_unit_of_mul_eq_one g _)⟩⟩, { rwa [monic, leading_coeff_mul, leading_coeff_C, ←leading_coeff_mul, mul_comm, ←hfg, ←monic] }, { rwa [monic, leading_coeff_mul, leading_coeff_C, ←leading_coeff_mul, ←hfg, ←monic] }, { rw [mul_mul_mul_comm, ←C_mul, ←leading_coeff_mul, ←hfg, hp.leading_coeff, C_1, mul_one, mul_comm, ←hfg] }, end lemma monic.irreducible_iff_nat_degree (hp : p.monic) : irreducible p ↔ p ≠ 1 ∧ ∀ f g : R[X], f.monic → g.monic → f * g = p → f.nat_degree = 0 ∨ g.nat_degree = 0 := begin by_cases hp1 : p = 1, { simp [hp1] }, rw [irreducible_of_monic hp hp1, and_iff_right hp1], refine forall₄_congr (λ a b ha hb, _), rw [ha.nat_degree_eq_zero_iff_eq_one, hb.nat_degree_eq_zero_iff_eq_one], end lemma monic.irreducible_iff_nat_degree' (hp : p.monic) : irreducible p ↔ p ≠ 1 ∧ ∀ f g : R[X], f.monic → g.monic → f * g = p → g.nat_degree ∉ Ioc 0 (p.nat_degree / 2) := begin simp_rw [hp.irreducible_iff_nat_degree, mem_Ioc, nat.le_div_iff_mul_le zero_lt_two, mul_two], apply and_congr_right', split; intros h f g hf hg he; subst he, { rw [hf.nat_degree_mul hg, add_le_add_iff_right], exact λ ha, (h f g hf hg rfl).elim (ha.1.trans_le ha.2).ne' ha.1.ne' }, { simp_rw [hf.nat_degree_mul hg, pos_iff_ne_zero] at h, contrapose! h, obtain hl|hl := le_total f.nat_degree g.nat_degree, { exact ⟨g, f, hg, hf, mul_comm g f, h.1, add_le_add_left hl _⟩ }, { exact ⟨f, g, hf, hg, rfl, h.2, add_le_add_right hl _⟩ } }, end lemma monic.not_irreducible_iff_exists_add_mul_eq_coeff (hm : p.monic) (hnd : p.nat_degree = 2) : ¬ irreducible p ↔ ∃ c₁ c₂, p.coeff 0 = c₁ * c₂ ∧ p.coeff 1 = c₁ + c₂ := begin casesI subsingleton_or_nontrivial R, { simpa only [nat_degree_of_subsingleton] using hnd }, rw [hm.irreducible_iff_nat_degree', and_iff_right, hnd], push_neg, split, { rintros ⟨a, b, ha, hb, rfl, hdb|⟨⟨⟩⟩⟩, have hda := hnd, rw [ha.nat_degree_mul hb, hdb] at hda, use [a.coeff 0, b.coeff 0, mul_coeff_zero a b], simpa only [next_coeff, hnd, add_right_cancel hda, hdb] using ha.next_coeff_mul hb }, { rintros ⟨c₁, c₂, hmul, hadd⟩, refine ⟨X + C c₁, X + C c₂, monic_X_add_C _, monic_X_add_C _, _, or.inl $ nat_degree_X_add_C _⟩, rw [p.as_sum_range_C_mul_X_pow, hnd, finset.sum_range_succ, finset.sum_range_succ, finset.sum_range_one, ← hnd, hm.coeff_nat_degree, hnd, hmul, hadd, C_mul, C_add, C_1], ring }, { rintro rfl, simpa only [nat_degree_one] using hnd }, end lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a := by simp_rw [is_root, eval_mul, mul_eq_zero] lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := root_mul.1 h end no_zero_divisors section ring variables [ring R] [is_domain R] {p q : R[X]} instance : is_domain R[X] := no_zero_divisors.to_is_domain _ end ring section comm_ring variable [comm_ring R] /-- The multiplicity of `a` as root of a nonzero polynomial `p` is at least `n` iff `(X - a) ^ n` divides `p`. -/ lemma le_root_multiplicity_iff {p : R[X]} (p0 : p ≠ 0) {a : R} {n : ℕ} : n ≤ root_multiplicity a p ↔ (X - C a) ^ n ∣ p := begin simp_rw [root_multiplicity, dif_neg p0, nat.le_find_iff, not_not], refine ⟨λ h, _, λ h m hm, (pow_dvd_pow _ hm).trans h⟩, cases n, { rw pow_zero, apply one_dvd }, { exact h n n.lt_succ_self }, end lemma root_multiplicity_le_iff {p : R[X]} (p0 : p ≠ 0) (a : R) (n : ℕ) : root_multiplicity a p ≤ n ↔ ¬ (X - C a) ^ (n + 1) ∣ p := by rw [← (le_root_multiplicity_iff p0).not, not_le, nat.lt_add_one_iff] lemma pow_root_multiplicity_not_dvd {p : R[X]} (p0 : p ≠ 0) (a : R) : ¬ (X - C a) ^ (root_multiplicity a p + 1) ∣ p := by rw [← root_multiplicity_le_iff p0] /-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/ lemma root_multiplicity_add {p q : R[X]} (a : R) (hzero : p + q ≠ 0) : min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) := begin rw le_root_multiplicity_iff hzero, have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a, have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a, exact min_pow_dvd_add hdivp hdivq end variables [is_domain R] {p q : R[X]} section roots open multiset theorem prime_X_sub_C (r : R) : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C r, λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : R[X]) := by { convert (prime_X_sub_C (0 : R)), simp } lemma monic.prime_of_degree_eq_one (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, this.symm ▸ prime_X_sub_C _ theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) := (prime_X_sub_C r).irreducible theorem irreducible_X : irreducible (X : R[X]) := prime.irreducible prime_X lemma monic.irreducible_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : irreducible p := (hm.prime_of_degree_eq_one hp1).irreducible theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q := begin obtain ⟨u, hu⟩ := hpq, unfold monic at hp hq, rw eq_C_of_degree_le_zero (degree_coe_units _).le at hu, rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq, rwa [hq, C_1, mul_one] at hu, all_goals { apply_instance }, end lemma root_multiplicity_mul {p q : R[X]} {x : R} (hpq : p * q ≠ 0) : root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q := begin have hp : p ≠ 0 := left_ne_zero_of_mul hpq, have hq : q ≠ 0 := right_ne_zero_of_mul hpq, rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq, root_multiplicity_eq_multiplicity p, dif_neg hp, root_multiplicity_eq_multiplicity q, dif_neg hq, multiplicity.mul' (prime_X_sub_C x)], end lemma root_multiplicity_X_sub_C_self {x : R} : root_multiplicity x (X - C x) = 1 := by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x), multiplicity.get_multiplicity_self] lemma root_multiplicity_X_sub_C {x y : R} : root_multiplicity x (X - C y) = if x = y then 1 else 0 := begin split_ifs with hxy, { rw hxy, exact root_multiplicity_X_sub_C_self }, exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy)) end /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n := begin induction n with n hn, { refine root_multiplicity_eq_zero _, simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] }, have hzero := pow_ne_zero n.succ (X_sub_C_ne_zero a), rw pow_succ (X - C a) n at hzero ⊢, simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add] end lemma exists_multiset_roots : ∀ {p : R[X]} (hp : p ≠ 0), ∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p | 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_multiset_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)).1 $ not_lt.2 hdeg, ⟨x ::ₘ t, calc (card (x ::ₘ t) : with_bot ℕ) = t.card + 1 : by exact_mod_cast card_cons _ _ ... ≤ 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 a, conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx }, rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero x) hdiv0), root_multiplicity_X_sub_C, ← htr a], split_ifs with ha, { rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] }, { rw [count_cons_of_ne ha, zero_add] }, end⟩ else ⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a multiset containing all the roots of `p`, including their multiplicities. -/ noncomputable def roots (p : R[X]) : multiset R := if h : p = 0 then ∅ else classical.some (exists_multiset_roots h) @[simp] lemma roots_zero : (0 : R[X]).roots = 0 := dif_pos rfl 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_multiset_roots hp0)).1 end lemma card_roots' (p : R[X]) : p.roots.card ≤ nat_degree p := begin by_cases hp0 : p = 0, { simp [hp0], }, exact with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) end lemma card_roots_sub_C {p : R[X]} {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 : R[X]} {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 count_roots (p : R[X]) : p.roots.count a = root_multiplicity a p := begin by_cases hp : p = 0, { simp [hp], }, rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a end @[simp] lemma mem_roots' : a ∈ p.roots ↔ p ≠ 0 ∧ is_root p a := by rw [← count_pos, count_roots p, root_multiplicity_pos'] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := mem_roots'.trans $ and_iff_right hp lemma ne_zero_of_mem_roots (h : a ∈ p.roots) : p ≠ 0 := (mem_roots'.1 h).1 lemma is_root_of_mem_roots (h : a ∈ p.roots) : is_root p a := (mem_roots'.1 h).2 theorem card_le_degree_of_subset_roots {p : R[X]} {Z : finset R} (h : Z.val ⊆ p.roots) : Z.card ≤ p.nat_degree := (multiset.card_le_of_le (finset.val_le_iff_val_subset.2 h)).trans (polynomial.card_roots' p) lemma finite_set_of_is_root {p : R[X]} (hp : p ≠ 0) : set.finite {x | is_root p x} := by simpa only [← finset.set_of_mem, mem_to_finset, mem_roots hp] using p.roots.to_finset.finite_to_set lemma eq_zero_of_infinite_is_root (p : R[X]) (h : set.infinite {x | is_root p x}) : p = 0 := not_imp_comm.mp finite_set_of_is_root h lemma exists_max_root [linear_order R] (p : R[X]) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x ≤ x₀ := set.exists_upper_bound_image _ _ $ finite_set_of_is_root hp lemma exists_min_root [linear_order R] (p : R[X]) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x₀ ≤ x := set.exists_lower_bound_image _ _ $ finite_set_of_is_root hp lemma eq_of_infinite_eval_eq (p q : R[X]) (h : set.infinite {x | eval x p = eval x q}) : p = q := begin rw [← sub_eq_zero], apply eq_zero_of_infinite_is_root, simpa only [is_root, eval_sub, sub_eq_zero] end lemma roots_mul {p q : R[X]} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots := multiset.ext.mpr $ λ r, by rw [count_add, count_roots, count_roots, count_roots, root_multiplicity_mul hpq] lemma roots.le_of_dvd (h : q ≠ 0) : p ∣ q → roots p ≤ roots q := begin rintro ⟨k, rfl⟩, exact multiset.le_iff_exists_add.mpr ⟨k.roots, roots_mul h⟩ end lemma mem_roots_sub_C' {p : R[X]} {a x : R} : x ∈ (p - C a).roots ↔ p ≠ C a ∧ p.eval x = a := by rw [mem_roots', is_root.def, sub_ne_zero, eval_sub, sub_eq_zero, eval_C] lemma mem_roots_sub_C {p : R[X]} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := mem_roots_sub_C'.trans $ and_iff_right $ λ hp, hp0.not_le $ hp.symm ▸ degree_C_le @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = {r} := begin ext s, rw [count_roots, root_multiplicity_X_sub_C, count_singleton], end @[simp] lemma roots_X : roots (X : R[X]) = {0} := by rw [← roots_X_sub_C, C_0, sub_zero] @[simp] lemma roots_C (x : R) : (C x).roots = 0 := if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r, by rw [count_roots, count_zero, root_multiplicity_eq_zero (not_is_root_C _ _ H)] @[simp] lemma roots_one : (1 : R[X]).roots = ∅ := roots_C 1 @[simp] lemma roots_C_mul (p : R[X]) (ha : a ≠ 0) : (C a * p).roots = p.roots := by by_cases hp : p = 0; simp only [roots_mul, *, ne.def, mul_eq_zero, C_eq_zero, or_self, not_false_iff, roots_C, zero_add, mul_zero] @[simp] lemma roots_smul_nonzero (p : R[X]) (ha : a ≠ 0) : (a • p).roots = p.roots := by rw [smul_eq_C_mul, roots_C_mul _ ha] lemma roots_list_prod (L : list R[X]) : ((0 : R[X]) ∉ L) → L.prod.roots = (L : multiset R[X]).bind roots := list.rec_on L (λ _, roots_one) $ λ hd tl ih H, begin rw [list.mem_cons_iff, not_or_distrib] at H, rw [list.prod_cons, roots_mul (mul_ne_zero (ne.symm H.1) $ list.prod_ne_zero H.2), ← multiset.cons_coe, multiset.cons_bind, ih H.2] end lemma roots_multiset_prod (m : multiset R[X]) : (0 : R[X]) ∉ m → m.prod.roots = m.bind roots := by { rcases m with ⟨L⟩, simpa only [multiset.coe_prod, quot_mk_to_coe''] using roots_list_prod L } lemma roots_prod {ι : Type*} (f : ι → R[X]) (s : finset ι) : s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) := begin rcases s with ⟨m, hm⟩, simpa [multiset.prod_eq_zero_iff, bind_map] using roots_multiset_prod (m.map f) end @[simp] lemma roots_pow (p : R[X]) (n : ℕ) : (p ^ n).roots = n • p.roots := begin induction n with n ihn, { rw [pow_zero, roots_one, zero_smul, empty_eq_zero] }, { rcases eq_or_ne p 0 with rfl | hp, { rw [zero_pow n.succ_pos, roots_zero, smul_zero] }, { rw [pow_succ', roots_mul (mul_ne_zero (pow_ne_zero _ hp) hp), ihn, nat.succ_eq_add_one, add_smul, one_smul] } } end lemma roots_X_pow (n : ℕ) : (X ^ n : R[X]).roots = n • {0} := by rw [roots_pow, roots_X] lemma roots_C_mul_X_pow (ha : a ≠ 0) (n : ℕ) : (C a * X ^ n).roots = n • {0} := by rw [roots_C_mul _ ha, roots_X_pow] @[simp] lemma roots_monomial (ha : a ≠ 0) (n : ℕ) : (monomial n a).roots = n • {0} := by rw [← C_mul_X_pow_eq_monomial, roots_C_mul_X_pow ha] lemma roots_prod_X_sub_C (s : finset R) : (s.prod (λ a, X - C a)).roots = s.val := (roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans (by simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id']) @[simp] lemma roots_multiset_prod_X_sub_C (s : multiset R) : (s.map (λ a, X - C a)).prod.roots = s := begin rw [roots_multiset_prod, multiset.bind_map], { simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id'] }, { rw [multiset.mem_map], rintro ⟨a, -, h⟩, exact X_sub_C_ne_zero a h }, end @[simp] lemma nat_degree_multiset_prod_X_sub_C_eq_card (s : multiset R): (s.map (λ a, X - C a)).prod.nat_degree = s.card := begin rw [nat_degree_multiset_prod_of_monic, multiset.map_map], { convert multiset.sum_repeat 1 _, { convert multiset.map_const _ 1, ext, apply nat_degree_X_sub_C }, { simp } }, { intros f hf, obtain ⟨a, ha, rfl⟩ := multiset.mem_map.1 hf, exact monic_X_sub_C a }, end lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : R[X]) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : R[X]) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : R[X]) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a section nth_roots /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots (n : ℕ) (a : R) : multiset R := roots ((X : R[X]) ^ n - C a) @[simp] lemma mem_nth_roots {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] @[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 := by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C] lemma card_nth_roots (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : R[X]) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by { rw [hn, pow_zero, ← C_1, ← ring_hom.map_sub ], 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) @[simp] lemma nth_roots_two_eq_zero_iff {r : R} : nth_roots 2 r = 0 ↔ ¬ is_square r := by simp_rw [is_square_iff_exists_sq, eq_zero_iff_forall_not_mem, mem_nth_roots (by norm_num : 0 < 2), ← not_exists, eq_comm] /-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/ def nth_roots_finset (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : finset R := multiset.to_finset (nth_roots n (1 : R)) @[simp] lemma mem_nth_roots_finset {n : ℕ} (h : 0 < n) {x : R} : x ∈ nth_roots_finset n R ↔ x ^ (n : ℕ) = 1 := by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h] @[simp] lemma nth_roots_finset_zero : nth_roots_finset 0 R = ∅ := by simp [nth_roots_finset] end nth_roots lemma monic.comp (hp : p.monic) (hq : q.monic) (h : q.nat_degree ≠ 0) : (p.comp q).monic := by rw [monic.def, leading_coeff_comp h, monic.def.1 hp, monic.def.1 hq, one_pow, one_mul] lemma monic.comp_X_add_C (hp : p.monic) (r : R) : (p.comp (X + C r)).monic := begin refine hp.comp (monic_X_add_C _) (λ ha, _), rw [nat_degree_X_add_C] at ha, exact one_ne_zero ha end lemma monic.comp_X_sub_C (hp : p.monic) (r : R) : (p.comp (X - C r)).monic := by simpa using hp.comp_X_add_C (-r) lemma units_coeff_zero_smul (c : R[X]ˣ) (p : R[X]) : (c : R[X]).coeff 0 • p = c * p := by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)] @[simp] lemma nat_degree_coe_units (u : R[X]ˣ) : nat_degree (u : R[X]) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma comp_eq_zero_iff : p.comp q = 0 ↔ p = 0 ∨ (p.eval (q.coeff 0) = 0 ∧ q = C (q.coeff 0)) := begin split, { intro h, have key : p.nat_degree = 0 ∨ q.nat_degree = 0, { rw [←mul_eq_zero, ←nat_degree_comp, h, nat_degree_zero] }, replace key := or.imp eq_C_of_nat_degree_eq_zero eq_C_of_nat_degree_eq_zero key, cases key, { rw [key, C_comp] at h, exact or.inl (key.trans h) }, { rw [key, comp_C, C_eq_zero] at h, exact or.inr ⟨h, key⟩ }, }, { exact λ h, or.rec (λ h, by rw [h, zero_comp]) (λ h, by rw [h.2, comp_C, h.1, C_0]) h }, end lemma zero_of_eval_zero [infinite R] (p : R[X]) (h : ∀ x, p.eval x = 0) : p = 0 := by classical; by_contradiction hp; exact fintype.false ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩ lemma funext [infinite R] {p q : R[X]} (ext : ∀ r : R, p.eval r = q.eval r) : p = q := begin rw ← sub_eq_zero, apply zero_of_eval_zero, intro x, rw [eval_sub, sub_eq_zero, ext], end variables [comm_ring T] /-- The set of distinct roots of `p` in `E`. If you have a non-separable polynomial, use `polynomial.roots` for the multiset where multiple roots have the appropriate multiplicity. -/ def root_set (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : set S := (p.map (algebra_map T S)).roots.to_finset lemma root_set_def (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : p.root_set S = (p.map (algebra_map T S)).roots.to_finset := rfl @[simp] lemma root_set_C [comm_ring S] [is_domain S] [algebra T S] (a : T) : (C a).root_set S = ∅ := by rw [root_set_def, map_C, roots_C, multiset.to_finset_zero, finset.coe_empty] @[simp] lemma root_set_zero (S) [comm_ring S] [is_domain S] [algebra T S] : (0 : T[X]).root_set S = ∅ := by rw [← C_0, root_set_C] instance root_set_fintype (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : fintype (p.root_set S) := finset_coe.fintype _ lemma root_set_finite (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : (p.root_set S).finite := set.to_finite _ /-- The set of roots of all polynomials of bounded degree and having coefficients in a finite set is finite. -/ lemma bUnion_roots_finite {R S : Type*} [semiring R] [comm_ring S] [is_domain S] (m : R →+* S) (d : ℕ) {U : set R} (h : U.finite) : (⋃ (f : R[X]) (hf : f.nat_degree ≤ d ∧ ∀ i, (f.coeff i) ∈ U), ((f.map m).roots.to_finset : set S)).finite := set.finite.bUnion begin -- We prove that the set of polynomials under consideration is finite because its -- image by the injective map `π` is finite let π : R[X] → fin (d+1) → R := λ f i, f.coeff i, refine ((set.finite.pi $ λ e, h).subset $ _).of_finite_image (_ : set.inj_on π _), { exact set.image_subset_iff.2 (λ f hf i _, hf.2 i) }, { refine λ x hx y hy hxy, (ext_iff_nat_degree_le hx.1 hy.1).2 (λ i hi, _), exact id congr_fun hxy ⟨i, nat.lt_succ_of_le hi⟩ }, end $ λ i hi, finset.finite_to_set _ theorem mem_root_set' {p : T[X]} {S : Type*} [comm_ring S] [is_domain S] [algebra T S] {a : S} : a ∈ p.root_set S ↔ p.map (algebra_map T S) ≠ 0 ∧ aeval a p = 0 := by rw [root_set, finset.mem_coe, mem_to_finset, mem_roots', is_root.def, ← eval₂_eq_eval_map, aeval_def] theorem mem_root_set {p : T[X]} {S : Type*} [comm_ring S] [is_domain S] [algebra T S] [no_zero_smul_divisors T S] {a : S} : a ∈ p.root_set S ↔ p ≠ 0 ∧ aeval a p = 0 := by rw [mem_root_set', (map_injective _ (no_zero_smul_divisors.algebra_map_injective T S)).ne_iff' (polynomial.map_zero _)] theorem mem_root_set_of_ne {p : T[X]} {S : Type*} [comm_ring S] [is_domain S] [algebra T S] [no_zero_smul_divisors T S] (hp : p ≠ 0) {a : S} : a ∈ p.root_set S ↔ aeval a p = 0 := mem_root_set.trans $ and_iff_right hp lemma root_set_maps_to' {p : T[X]} {S S'} [comm_ring S] [is_domain S] [algebra T S] [comm_ring S'] [is_domain S'] [algebra T S'] (hp : p.map (algebra_map T S') = 0 → p.map (algebra_map T S) = 0) (f : S →ₐ[T] S') : (p.root_set S).maps_to f (p.root_set S') := λ x hx, begin rw [mem_root_set'] at hx ⊢, rw [aeval_alg_hom, alg_hom.comp_apply, hx.2, _root_.map_zero], exact ⟨mt hp hx.1, rfl⟩ end lemma ne_zero_of_mem_root_set {p : T[X]} [comm_ring S] [is_domain S] [algebra T S] {a : S} (h : a ∈ p.root_set S) : p ≠ 0 := λ hf, by rwa [hf, root_set_zero] at h lemma aeval_eq_zero_of_mem_root_set {p : T[X]} [comm_ring S] [is_domain S] [algebra T S] {a : S} (hx : a ∈ p.root_set S) : aeval a p = 0 := (mem_root_set'.1 hx).2 lemma root_set_maps_to {p : T[X]} {S S'} [comm_ring S] [is_domain S] [algebra T S] [comm_ring S'] [is_domain S'] [algebra T S'] [no_zero_smul_divisors T S'] (f : S →ₐ[T] S') : (p.root_set S).maps_to f (p.root_set S') := begin refine root_set_maps_to' (λ h₀, _) f, obtain rfl : p = 0 := map_injective _ (no_zero_smul_divisors.algebra_map_injective T S') (by rwa [polynomial.map_zero]), exact polynomial.map_zero _ end end roots lemma coeff_coe_units_zero_ne_zero (u : R[X]ˣ) : coeff (u : R[X]) 0 ≠ 0 := begin conv in (0) { rw [← nat_degree_coe_units u] }, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.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.is_unit_or_is_unit 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, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) /-- Division by a monic polynomial doesn't change the leading coefficient. -/ lemma leading_coeff_div_by_monic_of_monic {R : Type u} [comm_ring R] {p q : R[X]} (hmonic : q.monic) (hdegree : q.degree ≤ p.degree) : (p /ₘ q).leading_coeff = p.leading_coeff := begin nontriviality, have h : q.leading_coeff * (p /ₘ q).leading_coeff ≠ 0, { simpa [div_by_monic_eq_zero_iff hmonic, hmonic.leading_coeff, nat.with_bot.one_le_iff_zero_lt] using hdegree }, nth_rewrite_rhs 0 ←mod_by_monic_add_div p hmonic, rw [leading_coeff_add_of_degree_lt, leading_coeff_monic_mul hmonic], rw [degree_mul' h, degree_add_div_by_monic hmonic hdegree], exact (degree_mod_by_monic_lt p hmonic).trans_le hdegree end lemma leading_coeff_div_by_monic_X_sub_C (p : R[X]) (hp : degree p ≠ 0) (a : R) : leading_coeff (p /ₘ (X - C a)) = leading_coeff p := begin nontriviality, cases hp.lt_or_lt with hd hd, { rw [degree_eq_bot.mp $ (nat.with_bot.lt_zero_iff _).mp hd, zero_div_by_monic] }, refine leading_coeff_div_by_monic_of_monic (monic_X_sub_C a) _, rwa [degree_X_sub_C, nat.with_bot.one_le_iff_zero_lt] end lemma eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le {R} [comm_ring R] {p q : R[X]} (hp : p.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = C q.leading_coeff * p := begin obtain ⟨r, hr⟩ := hdiv, obtain (rfl|hq) := eq_or_ne q 0, {simp}, have rzero : r ≠ 0 := λ h, by simpa [h, hq] using hr, rw [hr, nat_degree_mul'] at hdeg, swap, { rw [hp.leading_coeff, one_mul, leading_coeff_ne_zero], exact rzero }, rw [mul_comm, @eq_C_of_nat_degree_eq_zero _ _ r] at hr, { convert hr, convert leading_coeff_C _ using 1, rw [hr, leading_coeff_mul_monic hp] }, { exact (add_right_inj _).1 (le_antisymm hdeg $ nat.le.intro rfl) }, end lemma eq_of_monic_of_dvd_of_nat_degree_le {R} [comm_ring R] {p q : R[X]} (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = p := begin convert eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le hp hdiv hdeg, rw [hq.leading_coeff, C_1, one_mul], end lemma is_coprime_X_sub_C_of_is_unit_sub {R} [comm_ring R] {a b : R} (h : is_unit (a - b)) : is_coprime (X - C a) (X - C b) := ⟨-C h.unit⁻¹.val, C h.unit⁻¹.val, by { rw [neg_mul_comm, ← left_distrib, neg_add_eq_sub, sub_sub_sub_cancel_left, ← C_sub, ← C_mul], convert C_1, exact h.coe_inv_mul }⟩ theorem pairwise_coprime_X_sub_C {K} [field K] {I : Type v} {s : I → K} (H : function.injective s) : pairwise (is_coprime on (λ i : I, X - C (s i))) := λ i j hij, is_coprime_X_sub_C_of_is_unit_sub (sub_ne_zero_of_ne $ H.ne hij).is_unit lemma monic_prod_multiset_X_sub_C : monic (p.roots.map (λ a, X - C a)).prod := monic_multiset_prod_of_monic _ _ (λ a _, monic_X_sub_C a) lemma prod_multiset_root_eq_finset_root : (p.roots.map (λ a, X - C a)).prod = p.roots.to_finset.prod (λ a, (X - C a) ^ root_multiplicity a p) := by simp only [count_roots, finset.prod_multiset_map_count] /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ lemma prod_multiset_X_sub_C_dvd (p : R[X]) : (p.roots.map (λ a, X - C a)).prod ∣ p := begin rw ← map_dvd_map _ (is_fraction_ring.injective R $ fraction_ring R) monic_prod_multiset_X_sub_C, rw [prod_multiset_root_eq_finset_root, polynomial.map_prod], refine finset.prod_dvd_of_coprime (λ a _ b _ h, _) (λ a _, _), { simp_rw [polynomial.map_pow, polynomial.map_sub, map_C, map_X], exact (pairwise_coprime_X_sub_C (is_fraction_ring.injective R $ fraction_ring R) h).pow }, { exact polynomial.map_dvd _ (pow_root_multiplicity_dvd p a) }, end /-- A Galois connection. -/ lemma _root_.multiset.prod_X_sub_C_dvd_iff_le_roots {p : R[X]} (hp : p ≠ 0) (s : multiset R) : (s.map (λ a, X - C a)).prod ∣ p ↔ s ≤ p.roots := ⟨λ h, multiset.le_iff_count.2 $ λ r, begin rw [count_roots, le_root_multiplicity_iff hp, ← multiset.prod_repeat, ← multiset.map_repeat (λ a, X - C a), ← multiset.filter_eq], exact (multiset.prod_dvd_prod_of_le $ multiset.map_le_map $ s.filter_le _).trans h, end, λ h, (multiset.prod_dvd_prod_of_le $ multiset.map_le_map h).trans p.prod_multiset_X_sub_C_dvd⟩ lemma exists_prod_multiset_X_sub_C_mul (p : R[X]) : ∃ q, (p.roots.map (λ a, X - C a)).prod * q = p ∧ p.roots.card + q.nat_degree = p.nat_degree ∧ q.roots = 0 := begin obtain ⟨q, he⟩ := p.prod_multiset_X_sub_C_dvd, use [q, he.symm], obtain (rfl|hq) := eq_or_ne q 0, { rw mul_zero at he, subst he, simp }, split, { conv_rhs { rw he }, rw [monic_prod_multiset_X_sub_C.nat_degree_mul' hq, nat_degree_multiset_prod_X_sub_C_eq_card] }, { replace he := congr_arg roots he.symm, rw [roots_mul, roots_multiset_prod_X_sub_C] at he, exacts [add_right_eq_self.1 he, mul_ne_zero monic_prod_multiset_X_sub_C.ne_zero hq] }, end /-- A polynomial `p` that has as many roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/ lemma C_leading_coeff_mul_prod_multiset_X_sub_C (hroots : p.roots.card = p.nat_degree) : C p.leading_coeff * (p.roots.map (λ a, X - C a)).prod = p := (eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le monic_prod_multiset_X_sub_C p.prod_multiset_X_sub_C_dvd ((nat_degree_multiset_prod_X_sub_C_eq_card _).trans hroots).ge).symm /-- A monic polynomial `p` that has as many roots as its degree can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/ lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq (hp : p.monic) (hroots : p.roots.card = p.nat_degree) : (p.roots.map (λ a, X - C a)).prod = p := by { convert C_leading_coeff_mul_prod_multiset_X_sub_C hroots, rw [hp.leading_coeff, C_1, one_mul] } end comm_ring section variables {A B : Type*} [comm_ring A] [comm_ring B] lemma le_root_multiplicity_map {p : A[X]} {f : A →+* B} (hmap : map f p ≠ 0) (a : A) : root_multiplicity a p ≤ root_multiplicity (f a) (p.map f) := begin rw [le_root_multiplicity_iff hmap], refine trans _ ((map_ring_hom f).map_dvd (pow_root_multiplicity_dvd p a)), rw [map_pow, map_sub, coe_map_ring_hom, map_X, map_C], end lemma eq_root_multiplicity_map {p : A[X]} {f : A →+* B} (hf : function.injective f) (a : A) : root_multiplicity a p = root_multiplicity (f a) (p.map f) := begin by_cases hp0 : p = 0, { simp only [hp0, root_multiplicity_zero, polynomial.map_zero], }, apply le_antisymm (le_root_multiplicity_map ((polynomial.map_ne_zero_iff hf).mpr hp0) a), rw [le_root_multiplicity_iff hp0, ← map_dvd_map f hf ((monic_X_sub_C a).pow _), polynomial.map_pow, polynomial.map_sub, map_X, map_C], apply pow_root_multiplicity_dvd, end lemma count_map_roots [is_domain A] {p : A[X]} {f : A →+* B} (hmap : map f p ≠ 0) (b : B) : (p.roots.map f).count b ≤ root_multiplicity b (p.map f) := begin rw [le_root_multiplicity_iff hmap, ← multiset.prod_repeat, ← multiset.map_repeat (λ a, X - C a)], rw ← multiset.filter_eq, refine (multiset.prod_dvd_prod_of_le $ multiset.map_le_map $ multiset.filter_le _ _).trans _, convert polynomial.map_dvd _ p.prod_multiset_X_sub_C_dvd, simp only [polynomial.map_multiset_prod, multiset.map_map], congr, ext1, simp only [function.comp_app, polynomial.map_sub, map_X, map_C], end lemma count_map_roots_of_injective [is_domain A] (p : A[X]) {f : A →+* B} (hf : function.injective f) (b : B) : (p.roots.map f).count b ≤ root_multiplicity b (p.map f) := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, multiset.map_zero, multiset.count_zero, polynomial.map_zero, root_multiplicity_zero] }, { exact count_map_roots ((polynomial.map_ne_zero_iff hf).mpr hp0) b }, end lemma map_roots_le [is_domain A] [is_domain B] {p : A[X]} {f : A →+* B} (h : p.map f ≠ 0) : p.roots.map f ≤ (p.map f).roots := multiset.le_iff_count.2 $ λ b, by { rw count_roots, apply count_map_roots h } lemma map_roots_le_of_injective [is_domain A] [is_domain B] (p : A[X]) {f : A →+* B} (hf : function.injective f) : p.roots.map f ≤ (p.map f).roots := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, multiset.map_zero, polynomial.map_zero], }, exact map_roots_le ((polynomial.map_ne_zero_iff hf).mpr hp0), end lemma card_roots_le_map [is_domain A] [is_domain B] {p : A[X]} {f : A →+* B} (h : p.map f ≠ 0) : p.roots.card ≤ (p.map f).roots.card := by { rw ← p.roots.card_map f, exact multiset.card_le_of_le (map_roots_le h) } lemma card_roots_le_map_of_injective [is_domain A] [is_domain B] {p : A[X]} {f : A →+* B} (hf : function.injective f) : p.roots.card ≤ (p.map f).roots.card := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, polynomial.map_zero, multiset.card_zero], }, exact card_roots_le_map ((polynomial.map_ne_zero_iff hf).mpr hp0), end lemma roots_map_of_injective_of_card_eq_nat_degree [is_domain A] [is_domain B] {p : A[X]} {f : A →+* B} (hf : function.injective f) (hroots : p.roots.card = p.nat_degree) : p.roots.map f = (p.map f).roots := begin apply multiset.eq_of_le_of_card_le (map_roots_le_of_injective p hf), simpa only [multiset.card_map, hroots] using (card_roots' _).trans (nat_degree_map_le f p), end end section variables [semiring R] [comm_ring S] [is_domain S] (φ : R →+* S) lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map {f : R[X]} (hf : is_unit f.leading_coeff) (H : is_unit (map φ f)) : is_unit f := begin have dz := degree_eq_zero_of_is_unit H, rw degree_map_eq_of_leading_coeff_ne_zero at dz, { rw eq_C_of_degree_eq_zero dz, refine is_unit.map C _, convert hf, rw (degree_eq_iff_nat_degree_eq _).1 dz, rintro rfl, simpa using H, }, { intro h, have u : is_unit (φ f.leading_coeff) := is_unit.map φ hf, rw h at u, simpa using u, } end end section variables [comm_ring R] [is_domain R] [comm_ring S] [is_domain S] (φ : R →+* S) /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `ℤ` is irreducible if it is monic and irreducible over `ℤ/pℤ` for some prime `p`. -/ lemma monic.irreducible_of_irreducible_map (f : R[X]) (h_mon : monic f) (h_irr : irreducible (map φ f)) : irreducible f := begin refine ⟨h_irr.not_unit ∘ is_unit.map (map_ring_hom φ), λ a b h, _⟩, dsimp [monic] at h_mon, have q := (leading_coeff_mul a b).symm, rw [←h, h_mon] at q, refine (h_irr.is_unit_or_is_unit $ (congr_arg (map φ) h).trans (polynomial.map_mul φ)).imp _ _; apply is_unit_of_is_unit_leading_coeff_of_is_unit_map; apply is_unit_of_mul_eq_one, { exact q }, { rw mul_comm, exact q }, end end end polynomial
00ca8d537c6060892119849ff54a3f7b163d4466
5ee26964f602030578ef0159d46145dd2e357ba5
/src/prime.lean
00d36a6009ae2680e4eeed6a2093661650cf30b7
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
459
lean
import algebra.char_p import ring_theory.ideals def Prime := { p : ℕ // nat.prime p} instance : has_coe Prime ℕ := ⟨subtype.val⟩ instance monoid.prime_pow {α : Type*} [monoid α]: has_pow α Prime := ⟨λ x p, x^p.val⟩ noncomputable def Frobenius (α : Type*) [semiring α] : α → α := λ x, x^(ring_char α) notation `Frob` R `∕` x := Frobenius (ideal.quotient (ideal.span ({x} : set R))) notation x `∣` y `in` R := (x : R) ∣ (y : R)
f88fc31b969311809ccb577e6eaa2117062b8c11
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/algebra/ordered_field.lean
69b13aebbd586604efd6e43d56368e7f6f99c010
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
9,229
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import algebra.ordered_ring algebra.field section linear_ordered_field variables {α : Type*} [linear_ordered_field α] {a b c d : α} lemma div_pos : 0 < a → 0 < b → 0 < a / b := div_pos_of_pos_of_pos @[simp] lemma inv_pos : ∀ {a : α}, 0 < a⁻¹ ↔ 0 < a := suffices ∀ a : α, 0 < a → 0 < a⁻¹, from λ a, ⟨λ h, inv_inv'' a ▸ this _ h, this a⟩, λ a, one_div_eq_inv a ▸ one_div_pos_of_pos @[simp] lemma inv_lt_zero : ∀ {a : α}, a⁻¹ < 0 ↔ a < 0 := suffices ∀ a : α, a < 0 → a⁻¹ < 0, from λ a, ⟨λ h, inv_inv'' a ▸ this _ h, this a⟩, λ a, one_div_eq_inv a ▸ one_div_neg_of_neg @[simp] lemma inv_nonneg {a : α} : 0 ≤ a⁻¹ ↔ 0 ≤ a := le_iff_le_iff_lt_iff_lt.2 inv_lt_zero @[simp] lemma inv_nonpos {a : α} : a⁻¹ ≤ 0 ↔ a ≤ 0 := le_iff_le_iff_lt_iff_lt.2 inv_pos lemma one_le_div_iff_le (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a := ⟨le_of_one_le_div a hb, one_le_div_of_le a hb⟩ lemma one_lt_div_iff_lt (hb : 0 < b) : 1 < a / b ↔ b < a := ⟨lt_of_one_lt_div a hb, one_lt_div_of_lt a hb⟩ lemma div_le_one_iff_le (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 (one_lt_div_iff_lt hb) lemma div_lt_one_iff_lt (hb : 0 < b) : a / b < 1 ↔ a < b := lt_iff_lt_of_le_iff_le (one_le_div_iff_le hb) lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b := ⟨mul_le_of_le_div hc, le_div_of_mul_le hc⟩ lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b := by rw [mul_comm, le_div_iff hc] lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b := ⟨le_mul_of_div_le hb, by rw [mul_comm]; exact div_le_of_le_mul hb⟩ lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c := by rw [mul_comm, div_le_iff hb] lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b := ⟨mul_lt_of_lt_div hc, lt_div_of_mul_lt hc⟩ lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b := by rw [mul_comm, lt_div_iff hc] lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b := ⟨mul_le_of_div_le_of_neg hc, div_le_of_mul_le_of_neg hc⟩ lemma le_div_iff_of_neg (hc : c < 0) : a ≤ b / c ↔ b ≤ a * c := by rw [← neg_neg c, mul_neg_eq_neg_mul_symm, div_neg, le_neg, div_le_iff (neg_pos.2 hc), neg_mul_eq_neg_mul_symm] lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c := lt_iff_lt_of_le_iff_le (le_div_iff hc) lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a := by rw [mul_comm, div_lt_iff hc] lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b := ⟨mul_lt_of_gt_div_of_neg hc, div_lt_of_mul_gt_of_neg hc⟩ lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by rw [inv_eq_one_div, div_le_iff ha, ← div_eq_inv_mul, one_le_div_iff_le hb] lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by rw [← inv_le_inv hb (inv_pos.2 ha), inv_inv'] lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by rw [← inv_le_inv (inv_pos.2 hb) ha, inv_inv'] lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a := by simpa [one_div_eq_inv] using inv_le_inv ha hb lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a := lt_iff_lt_of_le_iff_le (inv_le_inv hb ha) lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a := lt_iff_lt_of_le_iff_le (le_inv hb ha) lemma one_div_lt (ha : 0 < a) (hb : 0 < b) : 1 / a < b ↔ 1 / b < a := (one_div_eq_inv a).symm ▸ (one_div_eq_inv b).symm ▸ inv_lt ha hb lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ := lt_iff_lt_of_le_iff_le (inv_le hb ha) lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a := lt_iff_lt_of_le_iff_le (one_div_le_one_div hb ha) lemma div_nonneg : 0 ≤ a → 0 < b → 0 ≤ a / b := div_nonneg_of_nonneg_of_pos lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b := ⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_pos h hc), λ h, div_lt_div_of_lt_of_pos h hc⟩ lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right hc) lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a := ⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_neg h hc), λ h, div_lt_div_of_lt_of_neg h hc⟩ lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right_of_neg hc) lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b := (mul_lt_mul_left ha).trans (inv_lt_inv hb hc) lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b := le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb) lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b < c / d ↔ a * d < c * b := by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0] lemma div_le_div_iff (b0 : 0 < b) (d0 : 0 < d) : a / b ≤ c / d ↔ a * d ≤ c * b := by rw [le_div_iff d0, div_mul_eq_mul_div, div_le_iff b0] lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (lt_of_lt_of_le d0 hbd) d0).2 (mul_lt_mul hac hbd d0 c0) lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) : a / b < c / d := (div_lt_div_iff (lt_trans d0 hbd) d0).2 (mul_lt_mul' hac hbd (le_of_lt d0) c0) lemma half_pos {a : α} (h : 0 < a) : 0 < a / 2 := div_pos h two_pos lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one lemma half_lt_self : 0 < a → a / 2 < a := div_two_lt_of_pos lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_densely_ordered : densely_ordered α := { dense := assume a₁ a₂ h, ⟨(a₁ + a₂) / 2, calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm ... < (a₁ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_left h _) two_pos, calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_right h _) two_pos ... = a₂ : add_self_div_two a₂⟩ } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_no_top_order : no_top_order α := { no_top := assume a, ⟨a + 1, lt_add_of_le_of_pos (le_refl a) zero_lt_one ⟩ } @[priority 100] -- see Note [lower instance priority] instance linear_ordered_field.to_no_bot_order : no_bot_order α := { no_bot := assume a, ⟨a + -1, add_lt_of_le_of_neg (le_refl _) (neg_lt_of_neg_lt $ by simp [zero_lt_one]) ⟩ } lemma inv_lt_one {a : α} (ha : 1 < a) : a⁻¹ < 1 := by rw [inv_eq_one_div]; exact div_lt_of_mul_lt_of_pos (lt_trans zero_lt_one ha) (by simp *) lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ := by rw [inv_eq_one_div, lt_div_iff h₁]; simp [h₂] lemma inv_le_one {a : α} (ha : 1 ≤ a) : a⁻¹ ≤ 1 := by rw [inv_eq_one_div]; exact div_le_of_le_mul (lt_of_lt_of_le zero_lt_one ha) (by simp *) lemma one_le_inv {x : α} (hx0 : 0 < x) (hx : x ≤ 1) : 1 ≤ x⁻¹ := le_of_mul_le_mul_left (by simpa [mul_inv_cancel (ne.symm (ne_of_lt hx0))]) hx0 lemma mul_self_inj_of_nonneg {a b : α} (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b := (mul_self_eq_mul_self_iff a b).trans $ or_iff_left_of_imp $ λ h, by subst a; rw [le_antisymm (neg_nonneg.1 a0) b0, neg_zero] lemma div_le_div_of_le_left {a b c : α} (ha : 0 ≤ a) (hc : 0 < c) (h : c ≤ b) : a / b ≤ a / c := by haveI := classical.dec_eq α; exact if ha0 : a = 0 then by simp [ha0] else (div_le_div_left (lt_of_le_of_ne ha (ne.symm ha0)) (lt_of_lt_of_le hc h) hc).2 h lemma inv_neg : (-a)⁻¹ = -(a⁻¹) := by rwa [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div] lemma inv_le_inv_of_le {a b : α} (hb : 0 < b) (h : b ≤ a) : a⁻¹ ≤ b⁻¹ := begin rw [inv_eq_one_div, inv_eq_one_div], exact one_div_le_one_div_of_le hb h end lemma div_nonneg' {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b := (lt_or_eq_of_le hb).elim (div_nonneg ha) (λ h, by simp [h.symm]) lemma div_le_div_of_le_of_nonneg {a b c : α} (hab : a ≤ b) (hc : 0 ≤ c) : a / c ≤ b / c := mul_le_mul_of_nonneg_right hab (inv_nonneg.2 hc) end linear_ordered_field namespace nat variables {α : Type*} [linear_ordered_field α] lemma inv_pos_of_nat {n : ℕ} : 0 < ((n : α) + 1)⁻¹ := inv_pos.2 $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one lemma one_div_pos_of_nat {n : ℕ} : 0 < 1 / ((n : α) + 1) := by { rw one_div_eq_inv, exact inv_pos_of_nat } lemma one_div_le_one_div {n m : ℕ} (h : n ≤ m) : 1 / ((m : α) + 1) ≤ 1 / ((n : α) + 1) := by { refine one_div_le_one_div_of_le _ _, exact nat.cast_add_one_pos _, simpa } lemma one_div_lt_one_div {n m : ℕ} (h : n < m) : 1 / ((m : α) + 1) < 1 / ((n : α) + 1) := by { refine one_div_lt_one_div_of_lt _ _, exact nat.cast_add_one_pos _, simpa } end nat section variables {α : Type*} [discrete_linear_ordered_field α] (a b c : α) lemma abs_inv : abs a⁻¹ = (abs a)⁻¹ := have h : abs (1 / a) = 1 / abs a, begin rw [abs_div, abs_of_nonneg], exact zero_le_one end, by simp [*] at * end
d4e9103101b1e30fcc7a00e95c184938aa766bc7
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/order/filter/basic.lean
e88ddf35800066f04928f7b8a1a476ae6015f955
[ "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
117,281
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad -/ import data.set.finite import order.copy import order.zorn import tactic.monotonicity /-! # Theory of filters on sets ## Main definitions * `filter` : filters on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `prod` : operations on filters; * `tendsto` : limit with respect to filters; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `ne_bot f` : an utility class stating that `f` is a non-trivial filter. Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to abstract two related kinds of ideas: * *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions at a point or at infinity, etc... * *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough a point `x`, or for close enough pairs of points, or things happening almost everywhere in the sense of measure theory. Dually, filters can also express the idea of *things happening often*: for arbitrarily large `n`, or at a point in any neighborhood of given a point etc... In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to the smallest filter containing it in the other direction. We also prove `filter` is a monadic functor, with a push-forward operation `filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the order on filters. Finally we describe a product operation `filter X → filter Y → filter (X × Y)`. The examples of filters appearing in the description of the two motivating ideas are: * `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N` * `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic) * `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces defined in topology.uniform_space.basic) * `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in `measure_theory.measure_space`) The general notion of limit of a map with respect to filters on the source and target types is `filter.tendsto`. It is defined in terms of the order and the push-forward operation. The predicate "happening eventually" is `filter.eventually`, and "happening often" is `filter.frequently`, whose definitions are immediate after `filter` is defined (but they come rather late in this file in order to immediately relate them to the lattice structure). For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of `M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`, which is a special case of `mem_closure_of_tendsto` from topology.basic. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`; * `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`; * `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`; * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`; * `𝓟 s` : `principal s`, localized in `filter`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which we do *not* require. This gives `filter X` better formal properties, in particular a bottom element `⊥` for its lattice structure, at the cost of including the assumption `[ne_bot f]` in a number of lemmas and definitions. -/ open set universes u v w x y open_locale classical /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection. We do not forbid this collection to be all sets of `α`. -/ structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} @[simp] protected lemma mem_mk {t : set (set α)} {h₁ h₂ h₃} : s ∈ mk t h₁ h₂ h₃ ↔ s ∈ t := iff.rfl @[simp] protected lemma mem_sets : s ∈ f.sets ↔ s ∈ f := iff.rfl instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩ lemma filter_eq : ∀ {f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by simp only [filter_eq_iff, ext_iff, filter.mem_sets] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 @[simp] lemma univ_mem : univ ∈ f := f.univ_sets lemma mem_of_superset : ∀ {x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem : ∀ {s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets @[simp] lemma inter_mem_iff {s t} : s ∩ t ∈ f ↔ s ∈ f ∧ t ∈ f := ⟨λ h, ⟨mem_of_superset h (inter_subset_left s t), mem_of_superset h (inter_subset_right s t)⟩, and_imp.2 inter_mem⟩ lemma univ_mem' (h : ∀ a, a ∈ s) : s ∈ f := mem_of_superset univ_mem (λ x _, h x) lemma mp_mem (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_of_superset (inter_mem hs h) $ λ x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_mem hs (mem_of_superset h (λ x, iff.mp)), λ hs, mp_mem hs (mem_of_superset h (λ x, iff.mpr))⟩ @[simp] lemma bInter_mem {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := finite.induction_on hf (by simp) (λ i s hi _ hs, by simp [hs]) @[simp] lemma bInter_finset_mem {β : Type v} {s : β → set α} (is : finset β) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := bInter_mem is.finite_to_set alias bInter_finset_mem ← finset.Inter_mem_sets attribute [protected] finset.Inter_mem_sets @[simp] lemma sInter_mem {s : set (set α)} (hfin : finite s) : ⋂₀ s ∈ f ↔ ∀ U ∈ s, U ∈ f := by rw [sInter_eq_bInter, bInter_mem hfin] @[simp] lemma Inter_mem {β : Type v} {s : β → set α} [fintype β] : (⋂ i, s i) ∈ f ↔ ∀ i, s i ∈ f := by simpa using bInter_mem finite_univ lemma exists_mem_subset_iff : (∃ t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨λ ⟨t, ht, ts⟩, mem_of_superset ht ts, λ hs, ⟨s, hs, subset.rfl⟩⟩ lemma monotone_mem {f : filter α} : monotone (λ s, s ∈ f) := λ s t hst h, mem_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀ x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_mem >> eapply e), eapplyc `filter.univ_mem', `[dsimp only [set.mem_set_of_eq]], match e' with | some e := interactive.exact e | none := skip end add_tactic_doc { name := "filter_upwards", category := doc_category.tactic, decl_names := [`tactic.interactive.filter_upwards], tags := ["goal management", "lemma application"] } end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := λ x y hx, subset.trans hx, inter_sets := λ x y, subset_inter } localized "notation `𝓟` := filter.principal" in filter instance : inhabited (filter α) := ⟨𝓟 ∅⟩ @[simp] lemma mem_principal {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.rfl end principal open_locale filter section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [mem_set_of_eq, univ_sets, ← filter.mem_sets, set_of_true], sets_of_superset := λ x y hx xy, mem_of_superset hx $ λ f h, mem_of_superset h xy, inter_sets := λ x y hx hy, mem_of_superset (inter_mem hx hy) $ λ f ⟨h₁, h₂⟩, inter_mem h₁ h₂ } @[simp] lemma mem_join {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λ f g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := λ a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := λ a, subset.rfl, le_trans := λ a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := λ x y, generate_sets.superset, inter_sets := λ s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (λ h u hu, h $ generate_sets.basic $ hu) (λ h u hu, hu.rec_on h univ_mem (λ x y _ hxy hx, mem_of_superset hx hxy) (λ x y _ _ hx hy, inter_mem hx hy)) lemma mem_generate_iff {s : set $ set α} {U : set α} : U ∈ generate s ↔ ∃ t ⊆ s, finite t ∧ ⋂₀ t ⊆ U := begin split ; intro h, { induction h with V V_in V W V_in hVW hV V W V_in W_in hV hW, { use {V}, simp [V_in] }, { use ∅, simp [subset.refl, univ] }, { rcases hV with ⟨t, hts, htfin, hinter⟩, exact ⟨t, hts, htfin, hinter.trans hVW⟩ }, { rcases hV with ⟨t, hts, htfin, htinter⟩, rcases hW with ⟨z, hzs, hzfin, hzinter⟩, refine ⟨t ∪ z, union_subset hts hzs, htfin.union hzfin, _⟩, rw sInter_union, exact inter_subset_inter htinter hzinter } }, { rcases h with ⟨t, ts, tfin, h⟩, apply generate_sets.superset _ h, revert ts, apply finite.induction_on tfin, { intro h, rw sInter_empty, exact generate_sets.univ }, { intros V r hV rfin hinter h, cases insert_subset.mp h with V_in r_sub, rw [insert_eq V r, sInter_union], apply generate_sets.inter _ (hinter r_sub), rw sInter_singleton, exact generate_sets.basic V_in } }, end /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem : univ ∈ generate s), sets_of_superset := λ x y, hs ▸ (mem_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := λ x y, hs ▸ (inter_mem : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ λ u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := λ s f, sets_iff_generate, le_l_u := λ f u h, generate_sets.basic h, choice := λ s hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_rfl), choice_eq := λ s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), s = a ∩ b }, univ_sets := ⟨_, univ_mem, _, univ_mem, by simp⟩, sets_of_superset := begin rintro x y ⟨a, ha, b, hb, rfl⟩ xy, refine ⟨a ∪ y, mem_of_superset ha (subset_union_left a y), b ∪ y, mem_of_superset hb (subset_union_left b y), _⟩, rw [← inter_union_distrib_right, union_eq_self_of_subset_left xy] end, inter_sets := begin rintro x y ⟨a, ha, b, hb, rfl⟩ ⟨c, hc, d, hd, rfl⟩, refine ⟨a ∩ c, inter_mem ha hc, b ∩ d, inter_mem hb hd, _⟩, ac_refl end }⟩ lemma mem_inf_iff {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, s = t₁ ∩ t₂ := iff.rfl lemma mem_inf_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem, (inter_univ s).symm⟩ lemma mem_inf_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem, s, h, (univ_inter s).symm⟩ lemma inter_mem_inf {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := ⟨s, hs, t, ht, rfl⟩ lemma mem_inf_of_inter {f g : filter α} {s t u : set α} (hs : s ∈ f) (ht : t ∈ g) (h : s ∩ t ⊆ u) : u ∈ f ⊓ g := mem_of_superset (inter_mem_inf hs ht) h lemma mem_inf_iff_superset {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃ t₁ ∈ f, ∃ t₂ ∈ g, t₁ ∩ t₂ ⊆ s := ⟨λ ⟨t₁, h₁, t₂, h₂, eq⟩, ⟨t₁, h₁, t₂, h₂, eq ▸ subset.rfl⟩, λ ⟨t₁, h₁, t₂, h₂, sub⟩, mem_inf_of_inter h₁ h₂ sub⟩ instance : has_top (filter α) := ⟨{ sets := {s | ∀ x, x ∈ s}, univ_sets := λ x, mem_univ x, sets_of_superset := λ x y hx hxy a, hxy (hx a), inter_sets := λ x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀ x, x ∈ s) := iff.rfl @[simp] lemma mem_top {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.has_top).1 (top_unique $ λ s hs, by simp [mem_top.1 hs]) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (λ s, mem_inf_of_left) (λ s, mem_inf_of_right)) (begin rintro s ⟨a, ha, b, hb, rfl⟩, exact inter_sets _ (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb) end) end /- Sup -/ (join ∘ 𝓟) (by { ext s x, exact (@mem_bInter_iff _ _ s filter.sets x).symm.trans (set.ext_iff.1 (sInter_image _ _) x).symm}) /- Inf -/ _ rfl end complete_lattice /-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set does not belong to the filter. Bourbaki include this assumption in the definition of a filter but we prefer to have a `complete_lattice` structure on filter, so we use a typeclass argument in lemmas instead. -/ class ne_bot (f : filter α) : Prop := (ne' : f ≠ ⊥) lemma ne_bot_iff {f : filter α} : ne_bot f ↔ f ≠ ⊥ := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := ne_bot.ne' @[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ := not_iff_comm.1 ne_bot_iff.symm lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g := ⟨ne_bot_of_le_ne_bot hf.1 hg⟩ lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g := hf.mono hg @[simp] lemma sup_ne_bot {f g : filter α} : ne_bot (f ⊔ g) ↔ ne_bot f ∨ ne_bot g := by simp [ne_bot_iff, not_and_distrib] lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂ f ∈ s, (f : filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂ i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∪ t ∈ f ⊔ g := ⟨mem_of_superset hs (subset_union_left s t), mem_of_superset ht (subset_union_right s t)⟩ @[simp] lemma mem_Sup {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀ f ∈ s, x ∈ (f : filter α)) := iff.rfl @[simp] lemma mem_supr {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀ i, x ∈ f i) := by simp only [← filter.mem_sets, supr_sets_eq, iff_self, mem_Inter] @[simp] lemma supr_ne_bot {f : ι → filter α} : (⨆ i, f i).ne_bot ↔ ∃ i, (f i).ne_bot := by simp [ne_bot_iff] lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) := show generate _ = generate _, from congr_arg _ $ congr_arg Sup $ (range_comp _ _).symm lemma mem_infi_of_mem {f : ι → filter α} (i : ι) : ∀ {s}, s ∈ f i → s ∈ ⨅ i, f i := show (⨅ i, f i) ≤ f i, from infi_le _ _ lemma mem_infi_of_Inter {ι} {s : ι → filter α} {U : set α} {I : set ι} (I_fin : finite I) {V : I → set α} (hV : ∀ i, V i ∈ s i) (hU : (⋂ i, V i) ⊆ U) : U ∈ ⨅ i, s i := begin haveI := I_fin.fintype, refine mem_of_superset (Inter_mem.2 $ λ i, _) hU, exact mem_infi_of_mem i (hV _) end lemma mem_infi {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : I → set α, (∀ i, V i ∈ s i) ∧ U = ⋂ i, V i := begin split, { rw [infi_eq_generate, mem_generate_iff], rintro ⟨t, tsub, tfin, tinter⟩, rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩, rw sInter_Union at tinter, set V := λ i, U ∪ ⋂₀ σ i with hV, have V_in : ∀ i, V i ∈ s i, { rintro i, have : (⋂₀ σ i) ∈ s i, { rw sInter_mem (σfin _), apply σsub }, exact mem_of_superset this (subset_union_right _ _) }, refine ⟨I, Ifin, V, V_in, _⟩, rwa [hV, ← union_Inter, union_eq_self_of_subset_right] }, { rintro ⟨I, Ifin, V, V_in, rfl⟩, exact mem_infi_of_Inter Ifin V_in subset.rfl } end lemma mem_infi' {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : ι → set α, (∀ i, V i ∈ s i) ∧ (∀ i ∉ I, V i = univ) ∧ (U = ⋂ i ∈ I, V i) ∧ U = ⋂ i, V i := begin simp only [mem_infi, set_coe.forall', bInter_eq_Inter], refine ⟨_, λ ⟨I, If, V, hVs, _, hVU, _⟩, ⟨I, If, λ i, V i, λ i, hVs i, hVU⟩⟩, rintro ⟨I, If, V, hV, rfl⟩, refine ⟨I, If, λ i, if hi : i ∈ I then V ⟨i, hi⟩ else univ, λ i, _, λ i hi, _, _⟩, { split_ifs, exacts [hV _, univ_mem] }, { exact dif_neg hi }, { simp [Inter_dite, bInter_eq_Inter] } end lemma exists_Inter_of_mem_infi {ι : Type*} {α : Type*} {f : ι → filter α} {s} (hs : s ∈ ⨅ i, f i) : ∃ t : ι → set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i := let ⟨I, If, V, hVs, hV', hVU, hVU'⟩ := mem_infi'.1 hs in ⟨V, hVs, hVU'⟩ lemma mem_infi_of_fintype {ι : Type*} [fintype ι] {α : Type*} {f : ι → filter α} (s) : s ∈ (⨅ i, f i) ↔ ∃ t : ι → set α, (∀ i, t i ∈ f i) ∧ s = ⋂ i, t i := begin refine ⟨exists_Inter_of_mem_infi, _⟩, rintro ⟨t, ht, rfl⟩, exact Inter_mem.2 (λ i, mem_infi_of_mem i (ht i)) end @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f := show (∀ {t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨λ h, h (subset.refl s), λ hs t ht, mem_of_superset hs ht⟩ lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal] @[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (𝓟 s) = Sup s := rfl @[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top, eq_self_iff_true] @[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ := bot_unique $ λ s _, empty_subset _ /-! ### Lattice equations -/ lemma empty_mem_iff_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨λ h, bot_unique $ λ s _, mem_of_superset h (empty_subset s), λ h, h.symm ▸ mem_bot⟩ lemma nonempty_of_mem {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_mem_iff_bot.mp hf.1)) id lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) : s.nonempty := @nonempty_of_mem α f hf s hs @[simp] lemma empty_not_mem (f : filter α) [ne_bot f] : ¬(∅ ∈ f) := λ h, (nonempty_of_mem h).ne_empty rfl lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α := nonempty_of_exists $ nonempty_of_mem (univ_mem : univ ∈ f) lemma compl_not_mem {f : filter α} {s : set α} [ne_bot f] (h : s ∈ f) : sᶜ ∉ f := λ hsc, (nonempty_of_mem (inter_mem h hsc)).ne_empty $ inter_compl_self s lemma filter_eq_bot_of_is_empty [is_empty α] (f : filter α) : f = ⊥ := empty_mem_iff_bot.mp $ univ_mem' is_empty_elim /-- There is exactly one filter on an empty type. --/ -- TODO[gh-6025]: make this globally an instance once safe to do so local attribute [instance] protected def unique [is_empty α] : unique (filter α) := { default := ⊥, uniq := filter_eq_bot_of_is_empty } lemma forall_mem_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f := ⟨λ h, ⟨λ hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot)⟩, @nonempty_of_mem _ _⟩ lemma nontrivial_iff_nonempty : nontrivial (filter α) ↔ nonempty α := ⟨λ ⟨⟨f, g, hfg⟩⟩, by_contra $ λ h, hfg $ by haveI : is_empty α := not_nonempty_iff.1 h; exact subsingleton.elim _ _, λ ⟨x⟩, ⟨⟨⊤, ⊥, ne_bot.ne $ forall_mem_nonempty_iff_ne_bot.1 $ λ s hs, by rwa [mem_top.1 hs, ← nonempty_iff_univ_nonempty]⟩⟩⟩ lemma eq_Inf_of_mem_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) [ne : nonempty ι] : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], intros x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_iff_exists_mem (λ s, by simp only [filter.mem_mk, mem_Union, filter.mem_sets]), congr_arg filter.sets this.symm lemma mem_infi_of_directed {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [← filter.mem_sets, infi_sets_eq h, mem_Union] lemma mem_binfi_of_directed {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i ∈ s, f i) ↔ ∃ i ∈ s, t ∈ f i := by haveI : nonempty {x // x ∈ s} := ne.to_subtype; erw [infi_subtype', mem_infi_of_directed h.directed_coe, subtype.exists]; refl lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i ∈ s, f i).sets = ⋃ i ∈ s, (f i).sets := ext $ λ t, by simp [mem_binfi_of_directed h ne] lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) : (⨅ i, f i).sets = (⋃ t : finset ι, (⨅ i ∈ t, f i).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λ s₁ s₂ hs, infi_le_infi $ λ i, infi_le_infi_const $ λ h, hs h), end lemma infi_sets_eq_finite' (f : ι → filter α) : (⨅ i, f i).sets = (⋃ t : finset (plift ι), (⨅ i ∈ t, f (plift.down i)).sets) := by { rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp], refl } lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t : finset ι, s ∈ ⨅ i ∈ t, f i := (set.ext_iff.1 (infi_sets_eq_finite f) s).trans mem_Union lemma mem_infi_finite' {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t : finset (plift ι), s ∈ ⨅ i ∈ t, f (plift.down i) := (set.ext_iff.1 (infi_sets_eq_finite' f) s).trans mem_Union @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter.ext $ λ x, by simp only [mem_sup, mem_join] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆ x, join (f x)) = join (⨆ x, f x) := filter.ext $ λ x, by simp only [mem_supr, mem_join] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin intros x y z s, simp only [and_assoc, mem_inf_iff, mem_sup, exists_prop, exists_imp_distrib, and_imp], rintro hs t₁ ht₁ t₂ ht₂ rfl, exact ⟨t₁, x.sets_of_superset hs (inter_subset_left t₁ t₂), ht₁, t₂, x.sets_of_superset hs (inter_subset_right t₁ t₂), ht₂, rfl⟩ end, ..filter.complete_lattice } /- the complementary version with ⨆ i, f ⊓ g i does not hold! -/ lemma infi_sup_left {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ λ i, sup_le_sup_left (infi_le _ _) _), rintro t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite'] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅ i, f ⊔ g i) ≤ f ⊔ s.inf (λ i, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_of_le_right le_top }, { rintro ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma infi_sup_right {f : filter α} {g : ι → filter α} : (⨅ x, g x ⊔ f) = infi g ⊔ f := by simp [sup_comm, ← infi_sup_left] lemma binfi_sup_right (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (f i ⊔ g)) = (⨅ i (h : p i), f i) ⊔ g := by rw [infi_subtype', infi_sup_right, infi_subtype'] lemma binfi_sup_left (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (g ⊔ f i)) = g ⊔ (⨅ i (h : p i), f i) := by rw [infi_subtype', infi_sup_left, infi_subtype'] lemma mem_infi_finset {s : finset α} {f : α → filter β} : ∀ t, t ∈ (⨅ a ∈ s, f a) ↔ (∃ p : α → set β, (∀ a ∈ s, p a ∈ f a) ∧ t = ⋂ a ∈ s, p a) := show ∀ t, t ∈ (⨅ a ∈ s, f a) ↔ (∃ p : α → set β, (∀ a ∈ s, p a ∈ f a) ∧ t = ⨅ a ∈ s, p a), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_iff, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { rintro t₁ ht₁ t₂ p hp ht₂ rfl, use function.update p a t₁, have : ∀ a' ∈ s, function.update p a t₁ a' = p a', from λ a' ha', have a' ≠ a, from λ h, has $ h ▸ ha', function.update_noteq this _ _, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, refl }, rintro p hpa hp rfl, exact ⟨p a, hpa, s.inf p, ⟨p, hp, rfl⟩, rfl⟩ } end /-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) (hb : ∀ i, ne_bot (f i)) : ne_bot (infi f) := ⟨begin intro h, have he : ∅ ∈ (infi f), from h.symm ▸ (mem_bot : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃ i, ∅ ∈ f i, from (mem_infi_of_directed hd ∅).1 he, exact (hb i).ne (empty_mem_iff_bot.1 hi) end⟩ /-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} [hn : nonempty α] (hd : directed (≥) f) (hb : ∀ i, ne_bot (f i)) : ne_bot (infi f) := if hι : nonempty ι then @infi_ne_bot_of_directed' _ _ _ hι hd hb else ⟨λ h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ λ i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x)⟩ lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) : ne_bot (infi f) ↔ ∀ i, ne_bot (f i) := ⟨λ H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) : ne_bot (infi f) ↔ (∀ i, ne_bot (f i)) := ⟨λ H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀ {i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) : p s := begin rw [mem_infi_finite'] at hs, simp only [← finset.inf_eq_infi] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { intros s hs, rwa [mem_top.1 hs] }, { rintro ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_iff] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, rfl⟩, exact ins hs₁ (ih hs₂) } end /-! #### `principal` equations -/ @[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (s ∩ t) := le_antisymm (by simp only [le_principal_iff, mem_inf_iff]; exact ⟨s, subset.rfl, t, subset.rfl, rfl⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) := filter.ext $ λ u, by simp only [union_subset_iff, mem_sup, mem_principal] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆ x, 𝓟 (s x)) = 𝓟 (⋃ i, s i) := filter.ext $ λ x, by simp only [mem_supr, mem_principal, Union_subset_iff] @[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ := empty_mem_iff_bot.symm.trans $ mem_principal.trans subset_empty_iff @[simp] lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty := ne_bot_iff.trans $ (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) := ⟨by simp only [inf_principal, inter_compl_self, principal_empty, le_refl], by simp only [sup_principal, union_compl_self, principal_univ, le_refl]⟩ theorem mem_inf_principal {f : filter α} {s t : set α} : s ∈ f ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f := begin simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint, inf_assoc, inf_principal, imp_iff_not_or], rw [← disjoint, ← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl], refl end lemma supr_inf_principal (f : ι → filter α) (s : set α) : (⨆ i, f i ⊓ 𝓟 s) = (⨆ i, f i) ⊓ 𝓟 s := by { ext, simp only [mem_supr, mem_inf_principal] } lemma inf_principal_eq_bot {f : filter α} {s : set α} : f ⊓ 𝓟 s = ⊥ ↔ sᶜ ∈ f := by { rw [← empty_mem_iff_bot, mem_inf_principal], refl } lemma mem_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f := by rwa [inf_principal_eq_bot, compl_compl] at h lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) : s \ t ∈ f ⊓ 𝓟 tᶜ := begin rw mem_inf_principal, filter_upwards [hs], intros a has hat, exact ⟨has, hat⟩ end lemma principal_le_iff {s : set α} {f : filter α} : 𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V := begin change (∀ V, V ∈ f → V ∈ _) ↔ _, simp_rw mem_principal, end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅ i ∈ s, 𝓟 (f i)) = 𝓟 (⋂ i ∈ s, f i) := begin induction s using finset.induction_on with i s hi hs, { simp }, { rw [finset.infi_insert, finset.set_bInter_insert, hs, inf_principal] }, end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅ i, 𝓟 (f i)) = 𝓟 (⋂ i, f i) := by simpa using infi_principal_finset finset.univ f lemma infi_principal_finite {ι : Type w} {s : set ι} (hs : finite s) (f : ι → set α) : (⨅ i ∈ s, 𝓟 (f i)) = 𝓟 (⋂ i ∈ s, f i) := begin lift s to finset ι using hs, exact_mod_cast infi_principal_finset s f end end lattice @[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) : join f₁ ≤ join f₂ := λ s hs, h hs /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f := iff.rfl protected lemma ext' {f₁ f₂ : filter α} (h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) : f₁ = f₂ := filter.ext h lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop} (hp : ∀ᶠ x in f₂, p x) : ∀ᶠ x in f₁, p x := h hp lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) : ∀ᶠ x in f, P x := mem_of_superset hU h protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem' hp @[simp] lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_mem_iff_bot @[simp] lemma eventually_const {f : filter α} [t : ne_bot f] {p : Prop} : (∀ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h] using t.ne) lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} : (∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y := exists_mem_subset_iff.symm lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) : ∃ v ∈ f, ∀ y ∈ v, p y := eventually_iff_exists_mem.1 hp lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_mem hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (eventually_of_forall hq) @[simp] lemma eventually_and {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := inter_mem_iff lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x) (h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x := h'.mp (h.mono $ λ x hx, hx.mp) lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) : (∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) := ⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩ @[simp] lemma eventually_all {ι} [fintype ι] {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i, p i x) ↔ ∀ i, ∀ᶠ x in l, p i x := by simpa only [filter.eventually, set_of_forall] using Inter_mem @[simp] lemma eventually_all_finite {ι} {I : set ι} (hI : I.finite) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ (∀ i ∈ I, ∀ᶠ x in l, p i x) := by simpa only [filter.eventually, set_of_forall] using bInter_mem hI alias eventually_all_finite ← set.finite.eventually_all attribute [protected] set.finite.eventually_all @[simp] lemma eventually_all_finset {ι} (I : finset ι) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x := I.finite_to_set.eventually_all alias eventually_all_finset ← finset.eventually_all attribute [protected] finset.eventually_all @[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) := classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h]) @[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) := by simp only [or_comm _ q, eventually_or_distrib_left] @[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) := by simp only [imp_iff_not_or, eventually_or_distrib_left] @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl @[simp] lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl lemma eventually_inf {f g : filter α} {p : α → Prop} : (∀ᶠ x in f ⊓ g, p x) ↔ ∃ (s ∈ f) (t ∈ g), ∀ x ∈ s ∩ t, p x := mem_inf_iff_superset theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} : (∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x := mem_inf_principal /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := compl_not_mem h lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) : ∃ᶠ x in f, p x := eventually.frequently (eventually_of_forall h) lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.filter_mono {p : α → Prop} {f g : filter α} (h : ∃ᶠ x in f, p x) (hle : f ≤ g) : ∃ᶠ x in g, p x := mt (λ h', h'.filter_mono hle) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, exact λ x hpq hq hp, hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) : ∃ x, p x := hp.frequently.exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨λ hp q hq, (hp.and_eventually hq).exists, λ H hp, by simpa only [and_not_self, exists_false] using H hp⟩ lemma frequently_iff {f : filter α} {P : α → Prop} : (∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x := begin rw frequently_iff_forall_eventually_exists_and, split ; intro h, { intros U U_in, simpa [exists_prop, and_comm] using h U_in }, { intros H H', simpa [and_comm] using h H' }, end @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] @[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot_iff] @[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp @[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} : (∃ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h]) @[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) := by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and] lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) := by simp lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q := by simp @[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) := by simp [imp_iff_not_or, not_eventually, frequently_or_distrib] lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) := by simp lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) := by simp @[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) := by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently] @[simp] lemma frequently_and_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∧ q x) ↔ (p ∧ ∃ᶠ x in f, q x) := by simp only [filter.frequently, not_and, eventually_imp_distrib_left, not_imp] @[simp] lemma frequently_and_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∧ q) ↔ ((∃ᶠ x in f, p x) ∧ q) := by simp only [and_comm _ q, frequently_and_distrib_left] @[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /-! ### Relation “eventually equal” -/ /-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that `f x = g x` belongs to `l`. -/ def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∀ᶠ x in l, f x = g x := h lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop) (hf : ∀ᶠ x in l, p x (f x)) : ∀ᶠ x in l, p x (g x) := hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl lemma eventually_eq_set {s t : set α} {l : filter α} : s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t := eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩ alias eventually_eq_set ↔ filter.eventually_eq.mem_iff filter.eventually.set_eq lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∃ s ∈ l, eq_on f g s := h.exists_mem lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α} (hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g := eventually_of_mem hs h lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} : (f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s := eventually_iff_exists_mem lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) : f =ᶠ[l'] g := h₂ h₁ @[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) : f =ᶠ[l] f := eventually_of_forall $ λ x, rfl lemma eventually_eq.rfl {l : filter α} {f : α → β} : f =ᶠ[l] f := eventually_eq.refl l f @[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) : g =ᶠ[l] f := H.mono $ λ _, eq.symm @[trans] lemma eventually_eq.trans {f g h : α → β} {l : filter α} (H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h := H₂.rw (λ x y, f x = y) H₁ lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') : (λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) := hf.mp $ hg.mono $ by { intros, simp only * } lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) : (h ∘ f) =ᶠ[l] (h ∘ g) := H.mono $ λ x hx, congr_arg h hx lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ) (Hg : g =ᶠ[l] g') : (λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) := (Hf.prod_mk Hg).fun_comp (function.uncurry h) @[to_additive] lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) := h.comp₂ (*) h' @[to_additive] lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : ((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) := h.fun_comp has_inv.inv lemma eventually_eq.div [group_with_zero β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.div' [group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.sub [add_group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x - f' x) =ᶠ[l] (λ x, g x - g' x)) := by simpa only [sub_eq_add_neg] using h.add h'.neg lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) := h.comp₂ (∧) h' lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) := h.comp₂ (∨) h' lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) : (sᶜ : set α) =ᶠ[l] (tᶜ : set α) := h.fun_comp not lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s \ s' : set α) =ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma eventually_eq_empty {s : set α} {l : filter α} : s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s := eventually_eq_set.trans $ by simp lemma inter_eventually_eq_left {s t : set α} {l : filter α} : (s ∩ t : set α) =ᶠ[l] s ↔ ∀ᶠ x in l, x ∈ s → x ∈ t := by simp only [eventually_eq_set, mem_inter_eq, and_iff_left_iff_imp] lemma inter_eventually_eq_right {s t : set α} {l : filter α} : (s ∩ t : set α) =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ t → x ∈ s := by rw [inter_comm, inter_eventually_eq_left] @[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} : f =ᶠ[𝓟 s] g ↔ eq_on f g s := iff.rfl lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} : (f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x := eventually_inf_principal lemma eventually_eq.sub_eq [add_group β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : f - g =ᶠ[l] 0 := by simpa using (eventually_eq.sub (eventually_eq.refl l f) h).symm lemma eventually_eq_iff_sub [add_group β] {f g : α → β} {l : filter α} : f =ᶠ[l] g ↔ f - g =ᶠ[l] 0 := ⟨λ h, h.sub_eq, λ h, by simpa using h.add (eventually_eq.refl l g)⟩ section has_le variables [has_le β] {l : filter α} /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f' ≤ᶠ[l] g' := H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' := ⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder β] {l : filter α} {f g h : α → β} lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq @[refl] lemma eventually_le.refl (l : filter α) (f : α → β) : f ≤ᶠ[l] f := eventually_eq.rfl.le lemma eventually_le.rfl : f ≤ᶠ[l] f := eventually_le.refl l f @[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₂.mp $ H₁.mono $ λ x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₁.le.trans H₂ @[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h := H₁.trans H₂.le end preorder lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β} (h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) : f =ᶠ[l] g := h₂.mp $ h₁.mono $ λ x, le_antisymm lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} : f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f := by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and] lemma eventually_le.le_iff_eq [partial_order β] {l : filter α} {f g : α → β} (h : f ≤ᶠ[l] g) : g ≤ᶠ[l] f ↔ g =ᶠ[l] f := ⟨λ h', h'.antisymm h, eventually_eq.le⟩ lemma eventually.ne_of_lt [preorder β] {l : filter α} {f g : α → β} (h : ∀ᶠ x in l, f x < g x) : ∀ᶠ x in l, f x ≠ g x := h.mono (λ x hx, hx.ne) lemma eventually.ne_top_of_lt [order_top β] {l : filter α} {f g : α → β} (h : ∀ᶠ x in l, f x < g x) : ∀ᶠ x in l, f x ≠ ⊤ := h.mono (λ x hx, hx.ne_top) lemma eventually.lt_top_of_ne [order_top β] {l : filter α} {f : α → β} (h : ∀ᶠ x in l, f x ≠ ⊤) : ∀ᶠ x in l, f x < ⊤ := h.mono (λ x hx, hx.lt_top) lemma eventually.lt_top_iff_ne_top [order_top β] {l : filter α} {f : α → β} : (∀ᶠ x in l, f x < ⊤) ↔ ∀ᶠ x in l, f x ≠ ⊤ := ⟨eventually.ne_of_lt, eventually.lt_top_of_ne⟩ @[mono] lemma eventually_le.inter {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∩ s' : set α) ≤ᶠ[l] (t ∩ t' : set α) := h'.mp $ h.mono $ λ x, and.imp @[mono] lemma eventually_le.union {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∪ s' : set α) ≤ᶠ[l] (t ∪ t' : set α) := h'.mp $ h.mono $ λ x, or.imp @[mono] lemma eventually_le.compl {s t : set α} {l : filter α} (h : s ≤ᶠ[l] t) : (tᶜ : set α) ≤ᶠ[l] (sᶜ : set α) := h.mono $ λ x, mt @[mono] lemma eventually_le.diff {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : t' ≤ᶠ[l] s') : (s \ s' : set α) ≤ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l := λ s hs, h.mono $ λ m hm, hm hs /-! ### Push-forwards, pull-backs, and the monad structure -/ section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem, sets_of_superset := λ s t hs st, mem_of_superset hs $ preimage_mono st, inter_sets := λ s t hs ht, inter_mem hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (𝓟 s) = 𝓟 (set.image f s) := filter.ext $ λ a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma eventually_map {P : β → Prop} : (∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) := iff.rfl @[simp] lemma frequently_map {P : β → Prop} : (∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) := iff.rfl @[simp] lemma mem_map : t ∈ map m f ↔ m ⁻¹' t ∈ f := iff.rfl lemma mem_map' : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma image_mem_map_iff (hf : function.injective m) : m '' s ∈ map m f ↔ s ∈ f := ⟨λ h, by rwa [← preimage_image_eq s hf], image_mem_map⟩ lemma range_mem_map : range m ∈ map m f := by { rw ←image_univ, exact image_mem_map univ_mem } lemma mem_map_iff_exists_image : t ∈ map m f ↔ (∃ s ∈ f, m '' s ⊆ t) := ⟨λ ht, ⟨m ⁻¹' t, ht, image_preimage_subset _ _⟩, λ ⟨s, hs, ht⟩, mem_of_superset (image_mem_map hs) ht⟩ @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_id' : filter.map (λ x, x) f = f := map_id @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ λ _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f /-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then they map this filter to the same filter. -/ lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) : map m₁ f = map m₂ f := filter.ext' $ λ p, by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) } end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃ t ∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := λ a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', ma'a.trans ab⟩, inter_sets := λ a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } lemma eventually_comap' {f : filter β} {φ : α → β} {p : β → Prop} (hf : ∀ᶠ b in f, p b) : ∀ᶠ a in comap φ f, p (φ a) := ⟨_, hf, (λ a h, h)⟩ @[simp] lemma eventually_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∀ᶠ a in comap φ f, P a) ↔ ∀ᶠ b in f, ∀ a, φ a = b → P a := begin split ; intro h, { rcases h with ⟨t, t_in, ht⟩, apply mem_of_superset t_in, rintro y y_in _ rfl, apply ht y_in }, { exact ⟨_, h, λ _ x_in, x_in _ rfl⟩ } end @[simp] lemma frequently_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∃ᶠ a in comap φ f, P a) ↔ ∃ᶠ b in f, ∃ a, φ a = b ∧ P a := by simp only [filter.frequently, eventually_comap, not_exists, not_and] end comap /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃ u ∈ f, ∃ t ∈ g, (∀ m ∈ u, ∀ x ∈ t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem, univ, univ_mem, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, λ s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, λ x hx y hy, hst $ h _ hx _ hy⟩, λ s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem ht₀ hu₀, t₁ ∩ u₁, inter_mem ht₁ hu₁, λ x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl @[simp] lemma eventually_pure {a : α} {p : α → Prop} : (∀ᶠ x in pure a, p x) ↔ p a := iff.rfl @[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a := filter.ext $ λ s, by simp only [mem_pure, mem_principal, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := λ α f, filter_eq rfl, pure_bind := λ α β, pure_bind, bind_assoc := λ α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := λ α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map', mem_join, mem_set_of_eq, function.comp, mem_pure] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λ α, ⊥, orelse := λ α x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /-! #### `map` and `comap` equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap : s ∈ comap m g ↔ ∃ t ∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.rfl⟩ lemma comap_id : comap id f = f := le_antisymm (λ s, preimage_mem_comap) (λ s ⟨t, ht, hst⟩, mem_of_superset ht hst) lemma comap_const_of_not_mem {x : α} {f : filter α} {V : set α} (hV : V ∈ f) (hx : x ∉ V) : comap (λ y : α, x) f = ⊥ := begin ext W, suffices : ∃ t ∈ f, (λ (y : α), x) ⁻¹' t ⊆ W, by simpa, use [V, hV], simp [preimage_const_of_not_mem hx], end lemma comap_const_of_mem {x : α} {f : filter α} (h : ∀ V ∈ f, x ∈ V) : comap (λ y : α, x) f = ⊤ := begin ext W, suffices : (∃ (t : set α), t ∈ f ∧ (λ (y : α), x) ⁻¹' t ⊆ W) ↔ W = univ, by simpa, split, { rintro ⟨V, V_in, hW⟩, simpa [preimage_const_of_mem (h V V_in), univ_subset_iff] using hW }, { rintro rfl, use univ, simp [univ_mem] }, end lemma comap_comap {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (λ c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (λ c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from (preimage_mono h₁).trans h₂⟩) section comm variables {δ : Type*} /-! The variables in the following lemmas are used as in this diagram: ``` φ α → β θ ↓ ↓ ψ γ → δ ρ ``` -/ variables {φ : α → β} {θ : α → γ} {ψ : β → δ} {ρ : γ → δ} (H : ψ ∘ φ = ρ ∘ θ) include H lemma map_comm (F : filter α) : map ψ (map φ F) = map ρ (map θ F) := by rw [filter.map_map, H, ← filter.map_map] lemma comap_comm (G : filter δ) : comap φ (comap ψ G) = comap θ (comap ρ G) := by rw [filter.comap_comap, H, ← filter.comap_comap] end comm @[simp] theorem comap_principal {t : set β} : comap m (𝓟 t) = 𝓟 (m ⁻¹' t) := filter.ext $ λ s, ⟨λ ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, (preimage_mono hu).trans b, λ h, ⟨t, subset.refl t, h⟩⟩ @[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) := by rw [← principal_singleton, comap_principal] lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨λ h s ⟨t, ht, hts⟩, mem_of_superset (h ht) hts, λ h s ht, h ⟨_, ht, subset.rfl⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := λ f g, map_le_iff_le_comap @[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l @[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆ i, f i) = (⨆ i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅ i, f i) = (⨅ i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by { rw [comap_top], exact le_top } lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ λ s _, ⟨∅, by simp only [mem_bot], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆ i, comap m (f i)) := le_antisymm (λ s hs, have ∀ i, ∃ t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap, exists_prop, mem_supr] using mem_supr.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃ i, t i, mem_supr.2 $ λ i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], exact λ i, (ht i).2 end⟩) (supr_le $ λ i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆ f ∈ s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := by rw [sup_eq_supr, comap_supr, supr_bool_eq, bool.cond_tt, bool.cond_ff] lemma map_comap (f : filter β) (m : α → β) : (f.comap m).map m = f ⊓ 𝓟 (range m) := begin refine le_antisymm (le_inf map_comap_le $ le_principal_iff.2 range_mem_map) _, rintro t' ⟨t, ht, sub⟩, refine mem_inf_principal.2 (mem_of_superset ht _), rintro _ hxt ⟨x, rfl⟩, exact sub hxt end lemma map_comap_of_mem {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := by rw [map_comap, inf_eq_left.2 (le_principal_iff.2 hf)] lemma comap_le_comap_iff {f g : filter β} {m : α → β} (hf : range m ∈ f) : comap m f ≤ comap m g ↔ f ≤ g := ⟨λ h, map_comap_of_mem hf ▸ (map_mono h).trans map_comap_le, λ h, comap_mono h⟩ theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := map_comap_of_mem $ by simp only [hf.range_eq, univ_mem] lemma subtype_coe_map_comap (s : set α) (f : filter α) : map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s := by rw [map_comap, subtype.range_coe] lemma subtype_coe_map_comap_prod (s : set α) (f : filter (α × α)) : map (coe : s × s → α × α) (comap (coe : s × s → α × α) f) = f ⊓ 𝓟 (s.prod s) := have (coe : s × s → α × α) = (λ x, (x.1, x.2)), by ext ⟨x, y⟩; refl, by simp [this, map_comap, ← prod_range_range_eq] lemma image_mem_of_mem_comap {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β} (W_in : W ∈ comap c f) : c '' W ∈ f := begin rw ← map_comap_of_mem h, exact image_mem_map W_in end lemma image_coe_mem_of_mem_comap {f : filter α} {U : set α} (h : U ∈ f) {W : set U} (W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f := image_mem_of_mem_comap (by simp [h]) W_in lemma comap_map {f : filter α} {m : α → β} (h : function.injective m) : comap m (map m f) = f := le_antisymm (λ s hs, mem_of_superset (preimage_mem_comap $ image_mem_map hs) $ by simp only [preimage_image_eq s h]) le_comap_map lemma mem_comap_iff {f : filter β} {m : α → β} (inj : function.injective m) (large : set.range m ∈ f) {S : set α} : S ∈ comap m f ↔ m '' S ∈ f := by rw [← image_mem_map_iff inj, map_comap_of_mem large] lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := λ t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem hsg ht)] λ a has ⟨b, ⟨hbs, hb⟩, h⟩, hm _ hbs _ has h ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀ x ∈ s, ∀ y ∈ s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : function.injective m) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin rw ← forall_mem_nonempty_iff_ne_bot, exact ⟨λ h t t_in, h (m ⁻¹' t) ⟨t, t_in, subset.rfl⟩, λ h s ⟨u, u_in, hu⟩, let ⟨x, hx⟩ := h u u_in in ⟨x, hu hx⟩⟩, end lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀ t ∈ f, ∃ a, m a ∈ t) : ne_bot (comap m f) := comap_ne_bot_iff.mpr hm lemma comap_ne_bot_iff_frequently {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∃ᶠ y in f, y ∈ range m := by simp [comap_ne_bot_iff, frequently_iff, ← exists_and_distrib_left, and.comm] lemma comap_ne_bot_iff_compl_range {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ (range m)ᶜ ∉ f := comap_ne_bot_iff_frequently lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β} (hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) := comap_ne_bot_iff_frequently.2 $ eventually.frequently hm @[simp] lemma comap_fst_ne_bot_iff {f : filter α} : (f.comap (prod.fst : α × β → α)).ne_bot ↔ f.ne_bot ∧ nonempty β := begin casesI is_empty_or_nonempty β, { rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [simp *, apply_instance] }, { simp [comap_ne_bot_iff_frequently, h] } end @[instance] lemma comap_fst_ne_bot [nonempty β] {f : filter α} [ne_bot f] : (f.comap (prod.fst : α × β → α)).ne_bot := comap_fst_ne_bot_iff.2 ⟨‹_›, ‹_›⟩ @[simp] lemma comap_snd_ne_bot_iff {f : filter β} : (f.comap (prod.snd : α × β → β)).ne_bot ↔ nonempty α ∧ f.ne_bot := begin casesI is_empty_or_nonempty α with hα hα, { rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [simpa using hα.elim, apply_instance] }, { simp [comap_ne_bot_iff_frequently, hα] } end @[instance] lemma comap_snd_ne_bot [nonempty α] {f : filter β} [ne_bot f] : (f.comap (prod.snd : α × β → β)).ne_bot := comap_snd_ne_bot_iff.2 ⟨‹_›, ‹_›⟩ lemma comap_eval_ne_bot_iff' {ι : Type*} {α : ι → Type*} {i : ι} {f : filter (α i)} : (comap (function.eval i) f).ne_bot ↔ (∀ j, nonempty (α j)) ∧ ne_bot f := begin casesI is_empty_or_nonempty (Π j, α j) with H H, { rw [filter_eq_bot_of_is_empty (f.comap _), ← not_iff_not]; [skip, assumption], simpa [← classical.nonempty_pi] using H.elim }, { haveI : ∀ j, nonempty (α j), from classical.nonempty_pi.1 H, simp [comap_ne_bot_iff_frequently, *] } end @[simp] lemma comap_eval_ne_bot_iff {ι : Type*} {α : ι → Type*} [∀ j, nonempty (α j)] {i : ι} {f : filter (α i)} : (comap (function.eval i) f).ne_bot ↔ ne_bot f := by simp [comap_eval_ne_bot_iff', *] @[instance] lemma comap_eval_ne_bot {ι : Type*} {α : ι → Type*} [∀ j, nonempty (α j)] (i : ι) (f : filter (α i)) [ne_bot f] : (comap (function.eval i) f).ne_bot := comap_eval_ne_bot_iff.2 ‹_› lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f ⊓ 𝓟 s) := begin refine ⟨compl_compl s ▸ mt mem_of_eq_bot _⟩, rintro ⟨t, ht, hts⟩, rcases hf.nonempty_of_mem (inter_mem hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma comap_coe_ne_bot_of_le_principal {s : set γ} {l : filter γ} [h : ne_bot l] (h' : l ≤ 𝓟 s) : ne_bot (comap (coe : s → γ) l) := h.comap_of_range_mem $ (@subtype.range_coe γ s).symm ▸ h' (mem_principal_self s) lemma ne_bot.comap_of_surj {f : filter β} {m : α → β} (hf : ne_bot f) (hm : function.surjective m) : ne_bot (comap m f) := hf.comap_of_range_mem $ univ_mem' hm lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f) := hf.comap_of_range_mem $ mem_of_superset hs (image_subset_range _ _) @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by { rw [←empty_mem_iff_bot, ←empty_mem_iff_bot], exact id }, λ h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F := by simp only [ne_bot_iff, ne, map_eq_bot_iff] lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) := (map_ne_bot_iff m).2 hf instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀ (comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, filter.mem_sets, mem_comap, this, and_imp, exists_prop, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ λ i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) [nonempty ι] : map m (infi f) = (⨅ i, map m (f i)) := map_infi_le.antisymm (λ s (hs : preimage m s ∈ infi f), let ⟨i, hi⟩ := (mem_infi_of_directed hf _).1 hs in have (⨅ i, map m (f i)) ≤ 𝓟 s, from infi_le_of_le i $ by { simp only [le_principal_iff, mem_map], assumption }, filter.le_principal_iff.1 this) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃ i, p i) : map m (⨅ i (h : p i), f i) = (⨅ i (h : p i), map m (f i)) := begin haveI := nonempty_subtype.2 ne, simp only [infi_subtype'], exact map_infi_eq h.directed_coe end lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀ x ∈ t, ∀ y ∈ t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (λ s hs, _), simp only [mem_inf_iff, exists_prop, mem_map, mem_preimage, mem_inf_iff] at hs, rcases hs with ⟨t₁, h₁, t₂, h₂, hs : m ⁻¹' s = t₁ ∩ t₂⟩, have : m '' (t₁ ∩ t) ∩ m '' (t₂ ∩ t) ∈ map m f ⊓ map m g, { apply inter_mem_inf ; apply image_mem_map, exacts [inter_mem h₁ htf, inter_mem h₂ htg] }, apply mem_of_superset this, { rw [image_inter_on], { refine image_subset_iff.2 _, rw hs, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem univ_mem (λ x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (λ b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (λ b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀ s ∈ f, m '' s ∈ g) : g ≤ f.map m := λ s hs, mem_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le }, { rintro U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, apply mem_inf_of_inter (image_mem_map V_in) Z_in, calc f '' V ∩ Z = f '' (V ∩ f ⁻¹' Z) : by rw image_inter_preimage ... ⊆ f '' (V ∩ W) : image_subset _ (inter_subset_inter_right _ ‹_›) ... = f '' (f ⁻¹' U) : by rw h ... ⊆ U : image_preimage_subset f U } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_injective : function.injective (pure : α → filter α) := λ a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) := ⟨mt empty_mem_iff_bot.2 $ not_mem_empty a⟩ @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure, λ h s hs, mem_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃ u ∈ f, ∃ t ∈ g, ∀ x ∈ u, ∀ y ∈ t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃ u ∈ f, ∃ t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃ t u, t ∈ g ∧ u ∈ f ∧ ∀ x ∈ u, ∀ y ∈ t, m x y ∈ s) := iff.intro (λ ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, λ a, hts _⟩) (λ ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, λ f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, λ f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀ t ∈ f, ∀ u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := λ s ⟨t, ht, u, hu, hs⟩, mem_of_superset (hh _ ht _ hu) $ λ b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha @[mono] lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ λ s hs t ht, seq_mem_seq (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ λ s hs, _) (le_seq $ λ s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq _ hs, exact singleton_mem_pure }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintro b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λ g : α → β, g a) f := begin refine le_antisymm (le_map $ λ s hs, _) (le_seq $ λ s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq hs singleton_mem_pure }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintro b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ λ s hs t ht, _) (le_seq $ λ s hs t ht, _), { rcases mem_seq_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_iff_exists_image.1 hu with ⟨w, hw, hu⟩, refine mem_of_superset _ (set.seq_mono ((set.seq_mono hu subset.rfl).trans hs) subset.rfl), rw ← set.seq_seq, exact seq_mem_seq hw (seq_mem_seq hv ht) }, { rcases mem_seq_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_of_superset _ (set.seq_mono subset.rfl ht), rw set.seq_seq, exact seq_mem_seq (seq_mem_seq (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λ b a, (a, b)) g) f := begin refine le_antisymm (le_seq $ λ s hs t ht, _) (le_seq $ λ s hs t ht, _), { rcases mem_map_iff_exists_image.1 hs with ⟨u, hu, hs⟩, refine mem_of_superset _ (set.seq_mono hs subset.rfl), rw ← set.prod_image_seq_comm, exact seq_mem_seq (image_mem_map ht) hu }, { rcases mem_map_iff_exists_image.1 hs with ⟨u, hu, hs⟩, refine mem_of_superset _ (set.seq_mono hs subset.rfl), rw set.prod_image_seq_comm, exact seq_mem_seq (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := λ α f, map_id, comp_map := λ α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := λ α β, pure_seq_eq_map, map_pure := λ α β, map_pure, seq_pure := λ α β, seq_pure, seq_assoc := λ α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨λ α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /-! #### `bind` equations -/ section bind @[simp] lemma eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} : (∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y := iff.rfl @[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ := iff.rfl @[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ := iff.rfl lemma mem_bind' {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ {a | s ∈ m a} ∈ f := iff.rfl @[simp] lemma mem_bind {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃ t ∈ f, ∀ x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl ... ↔ (∃ t ∈ f, t ⊆ {a | s ∈ m a}) : exists_mem_subset_iff.symm ... ↔ (∃ t ∈ f, ∀ x ∈ t, s ∈ m x) : iff.rfl lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) : f.bind g ≤ l := join_le $ eventually_map.2 h @[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ᶠ[f₁] g₂) : bind f₁ g₁ ≤ bind f₂ g₂ := begin refine le_trans (λ s hs, _) (join_mono $ map_mono hf), simp only [mem_join, mem_bind', mem_map] at hs ⊢, filter_upwards [hg, hs], exact λ x hx hs, hx hs end lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} : f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s := filter.ext $ λ s, by simp only [mem_bind, mem_inf_principal] lemma sup_bind {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma principal_bind {s : set α} {f : α → filter β} : (bind (𝓟 s) f) = (⨆ x ∈ s, f x) := show join (map f (𝓟 s)) = (⨆ x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind section list_traverse /- This is a separate section in order to open `list`, but mostly because of universe equality requirements in `traverse` -/ open list lemma sequence_mono : ∀ (as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_rfl | (a :: as) (b :: bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'} lemma mem_traverse : ∀ (fs : list β') (us : list γ'), forall₂ (λ b c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure.2 $ mem_singleton _ | (f :: fs) (u :: us) (forall₂.cons h hs) := seq_mem_seq (image_mem_map h) (mem_traverse fs us hs) lemma mem_traverse_iff (fs : list β') (t : set (list α')) : t ∈ traverse f fs ↔ (∃ us : list (set α'), forall₂ (λ b (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { intro ht, rcases mem_seq_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_iff_exists_image.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, (set.seq_mono hwu hu).trans ht⟩ } }, { rintro ⟨us, hus, hs⟩, exact mem_of_superset (mem_traverse _ _ hus) hs } end end list_traverse /-! ### Limits -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) := iff.rfl lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) : ∀ᶠ x in l₁, p (f x) := hf h lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) : ∃ᶠ y in l₂, p y := mt hf.eventually h lemma tendsto.frequently_map {l₁ : filter α} {l₂ : filter β} {p : α → Prop} {q : β → Prop} (f : α → β) (c : filter.tendsto f l₁ l₂) (w : ∀ x, p x → q (f x)) (h : ∃ᶠ x in l₁, p x) : ∃ᶠ y in l₂, q y := c.frequently (h.mono w) @[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto] @[simp] lemma tendsto_top {f : α → β} {l : filter α} : tendsto f l ⊤ := le_top lemma le_map_of_right_inverse {mab : α → β} {mba : β → α} {f : filter α} {g : filter β} (h₁ : mab ∘ mba =ᶠ[g] id) (h₂ : tendsto mba g f) : g ≤ map mab f := by { rw [← @map_id _ g, ← map_congr h₁, ← map_map], exact map_mono h₂ } lemma tendsto_of_is_empty [is_empty α] {f : α → β} {la : filter α} {lb : filter β} : tendsto f la lb := by simp only [filter_eq_bot_of_is_empty la, tendsto_bot] lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α} {fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y) (htendsto : tendsto g₂ fb fa) : g₁ =ᶠ[fb] g₂ := (htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap alias tendsto_iff_comap ↔ filter.tendsto.le_comap _ lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_congr hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto.mono_left {f : α → β} {x y : filter α} {z : filter β} (hx : tendsto f x z) (h : y ≤ x) : tendsto f y z := (map_mono h).trans hx lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β} (hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z := le_trans hy hz lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] : ne_bot y := (hx.map _).mono h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] @[simp] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by { rw [tendsto, map_map], refl } lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le @[simp] lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨λ h, tendsto_comap.comp h, λ h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by { rw [tendsto, ← map_compose], simp only [(∘), map_comap_of_mem h, tendsto] } lemma tendsto.of_tendsto_comp {f : α → β} {g : β → γ} {a : filter α} {b : filter β} {c : filter γ} (hfg : tendsto (g ∘ f) a c) (hg : comap g c ≤ b) : tendsto f a b := begin rw tendsto_iff_comap at hfg ⊢, calc a ≤ comap (g ∘ f) c : hfg ... ≤ comap f b : by simpa [comap_comap] using comap_mono hg end lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine ((comap_mono $ map_le_iff_le_comap.1 hψ).trans _).antisymm (map_le_iff_le_comap.1 hφ), rw [comap_comap, eq, comap_id], exact le_rfl end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_rfl end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ @[simp] lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅ i, y i) ↔ ∀ i, tendsto f x (y i) := by simp only [tendsto, iff_self, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) : tendsto f (⨅ i, x i) y := hi.mono_left $ infi_le _ _ @[simp] lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y := by simp only [tendsto, map_sup, sup_le_iff] lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y := λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩ @[simp] lemma tendsto_supr {f : α → β} {x : ι → filter α} {y : filter β} : tendsto f (⨆ i, x i) y ↔ ∀ i, tendsto f (x i) y := by simp only [tendsto, map_supr, supr_le_iff] @[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map', filter.eventually] @[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (𝓟 s) (𝓟 t) ↔ ∀ a ∈ s, f a ∈ t := by simp only [tendsto_principal, eventually_principal] @[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b := by simp only [tendsto, le_pure_iff, mem_map', mem_singleton_iff, filter.eventually] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λ x, b) a (pure b) := tendsto_pure.2 $ univ_mem' $ λ _, rfl lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s := iff.rfl lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} : tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s := iff.rfl @[simp] lemma map_inf_principal_preimage {f : α → β} {s : set β} {l : filter α} : map f (l ⊓ 𝓟 (f ⁻¹' s)) = map f l ⊓ 𝓟 s := filter.ext $ λ t, by simp only [mem_map', mem_inf_principal, mem_set_of_eq, mem_preimage] /-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial filter. -/ lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁) [ne_bot a] (hb : disjoint b₁ b₂) : ¬ tendsto f a b₂ := λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot.ne hb.eq_bot lemma tendsto.if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [∀ x, decidable (p x)] (h₀ : tendsto f (l₁ ⊓ 𝓟 {x | p x}) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin simp only [tendsto_def, mem_inf_principal] at *, intros s hs, filter_upwards [h₀ s hs, h₁ s hs], simp only [mem_preimage], intros x hp₀ hp₁, split_ifs, exacts [hp₀ h, hp₁ h] end lemma tendsto.piecewise {l₁ : filter α} {l₂ : filter β} {f g : α → β} {s : set α} [∀ x, decidable (x ∈ s)] (h₀ : tendsto f (l₁ ⊓ 𝓟 s) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 sᶜ) l₂) : tendsto (piecewise s f g) l₁ l₂ := h₀.if h₁ /-! ### Products of filters -/ section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃ n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀ i:ℕ, ∃ n, [n..∞] × {i} ⊆ s Now ⋃ i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ f ×ᶠ g := inter_mem_inf (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, { rintro ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, rfl⟩, exact ⟨s₁, hs₁, s₂, hs₂, λ p ⟨h, h'⟩, ⟨hts₁ h, hts₂ h'⟩⟩ }, { rintro ⟨t₁, ht₁, t₂, ht₂, h⟩, exact mem_inf_of_inter (preimage_mem_comap ht₁) (preimage_mem_comap ht₂) h } end @[simp] lemma prod_mem_prod_iff {s : set α} {t : set β} {f : filter α} {g : filter β} [f.ne_bot] [g.ne_bot] : s.prod t ∈ f ×ᶠ g ↔ s ∈ f ∧ t ∈ g := ⟨λ h, let ⟨s', hs', t', ht', H⟩ := mem_prod_iff.1 h in (prod_subset_prod_iff.1 H).elim (λ ⟨hs's, ht't⟩, ⟨mem_of_superset hs' hs's, mem_of_superset ht' ht't⟩) (λ h, h.elim (λ hs'e, absurd hs'e (nonempty_of_mem hs').ne_empty) (λ ht'e, absurd ht'e (nonempty_of_mem ht').ne_empty)), λ h, prod_mem_prod h.1 h.2⟩ lemma comap_prod (f : α → β × γ) (b : filter β) (c : filter γ) : comap f (b ×ᶠ c) = (comap (prod.fst ∘ f) b) ⊓ (comap (prod.snd ∘ f) c) := by erw [comap_inf, filter.comap_comap, filter.comap_comap] lemma sup_prod (f₁ f₂ : filter α) (g : filter β) : (f₁ ⊔ f₂) ×ᶠ g = (f₁ ×ᶠ g) ⊔ (f₂ ×ᶠ g) := by rw [filter.prod, comap_sup, inf_sup_right, ← filter.prod, ← filter.prod] lemma prod_sup (f : filter α) (g₁ g₂ : filter β) : f ×ᶠ (g₁ ⊔ g₂) = (f ×ᶠ g₁) ⊔ (f ×ᶠ g₂) := by rw [filter.prod, comap_sup, inf_sup_left, ← filter.prod, ← filter.prod] lemma eventually_prod_iff {p : α × β → Prop} {f : filter α} {g : filter β} : (∀ᶠ x in f ×ᶠ g, p x) ↔ ∃ (pa : α → Prop) (ha : ∀ᶠ x in f, pa x) (pb : β → Prop) (hb : ∀ᶠ y in g, pb y), ∀ {x}, pa x → ∀ {y}, pb y → p (x, y) := by simpa only [set.prod_subset_iff] using @mem_prod_iff α β p f g lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (f ×ᶠ g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λ x, (m₁ x, m₂ x)) f (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma eventually.prod_inl {la : filter α} {p : α → Prop} (h : ∀ᶠ x in la, p x) (lb : filter β) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).1 := tendsto_fst.eventually h lemma eventually.prod_inr {lb : filter β} {p : β → Prop} (h : ∀ᶠ x in lb, p x) (la : filter α) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).2 := tendsto_snd.eventually h lemma eventually.prod_mk {la : filter α} {pa : α → Prop} (ha : ∀ᶠ x in la, pa x) {lb : filter β} {pb : β → Prop} (hb : ∀ᶠ y in lb, pb y) : ∀ᶠ p in la ×ᶠ lb, pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl lb).and (hb.prod_inr la) lemma eventually.curry {la : filter α} {lb : filter β} {p : α × β → Prop} (h : ∀ᶠ x in la ×ᶠ lb, p x) : ∀ᶠ x in la, ∀ᶠ y in lb, p (x, y) := begin rcases eventually_prod_iff.1 h with ⟨pa, ha, pb, hb, h⟩, exact ha.mono (λ a ha, hb.mono $ λ b hb, h ha hb) end lemma prod_infi_left [nonempty ι] {f : ι → filter α} {g : filter β}: (⨅ i, f i) ×ᶠ g = (⨅ i, (f i) ×ᶠ g) := by { rw [filter.prod, comap_infi, infi_inf], simp only [filter.prod, eq_self_iff_true] } lemma prod_infi_right [nonempty ι] {f : filter α} {g : ι → filter β} : f ×ᶠ (⨅ i, g i) = (⨅ i, f ×ᶠ (g i)) := by { rw [filter.prod, comap_infi, inf_infi], simp only [filter.prod, eq_self_iff_true] } @[mono] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ f₂ ×ᶠ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λ p : β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λ p : β×α, (p.2, p.1)) (g ×ᶠ f) := by { rw [prod_comm', ← map_swap_eq_comap_swap], refl } lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λ p : α₁×α₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := le_antisymm (λ s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λ p : α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp le_rfl tendsto_fst).prod_mk (tendsto.comp le_rfl tendsto_snd)) lemma prod_map_map_eq' {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ → α₂) (g : β₁ → β₂) (F : filter α₁) (G : filter β₁) : (map f F) ×ᶠ (map g G) = map (prod.map f g) (F ×ᶠ G) := prod_map_map_eq lemma tendsto.prod_map {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a ×ᶠ b) (c ×ᶠ d) := begin erw [tendsto, ← prod_map_map_eq], exact filter.prod_mono hf hg, end lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f ×ᶠ g) = (f.map (λ a b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], intro s, split, exact λ ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, λ x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact λ ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, λ ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f ×ᶠ g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (𝓟 s) ×ᶠ (𝓟 t) = 𝓟 (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma pure_prod {a : α} {f : filter β} : pure a ×ᶠ f = map (prod.mk a) f := by rw [prod_eq, map_pure, pure_seq_eq_map] @[simp] lemma prod_pure {f : filter α} {b : β} : f ×ᶠ pure b = map (λ a, (a, b)) f := by rw [prod_eq, seq_pure, map_map] lemma prod_pure_pure {a : α} {b : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { intro h, rcases mem_prod_iff.1 (empty_mem_iff_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_mem_iff_bot.1 (s_eq ▸ hs) }, { right, exact empty_mem_iff_bot.1 (t_eq ▸ ht) } }, { rintro (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : ne_bot (f ×ᶠ g) ↔ (ne_bot f ∧ ne_bot g) := by simp only [ne_bot_iff, ne, prod_eq_bot, not_or_distrib] lemma ne_bot.prod {f : filter α} {g : filter β} (hf : ne_bot f) (hg : ne_bot g) : ne_bot (f ×ᶠ g) := prod_ne_bot.2 ⟨hf, hg⟩ instance prod_ne_bot' {f : filter α} {g : filter β} [hf : ne_bot f] [hg : ne_bot g] : ne_bot (f ×ᶠ g) := hf.prod hg lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod /-! ### Coproducts of filters -/ section coprod variables {f : filter α} {g : filter β} /-- Coproduct of filters. -/ protected def coprod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊔ g.comap prod.snd lemma mem_coprod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f.coprod g ↔ ((∃ t₁ ∈ f, prod.fst ⁻¹' t₁ ⊆ s) ∧ (∃ t₂ ∈ g, prod.snd ⁻¹' t₂ ⊆ s)) := by simp [filter.coprod] @[mono] lemma coprod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.coprod g₁ ≤ f₂.coprod g₂ := sup_le_sup (comap_mono hf) (comap_mono hg) lemma coprod_ne_bot_iff : (f.coprod g).ne_bot ↔ f.ne_bot ∧ nonempty β ∨ nonempty α ∧ g.ne_bot := by simp [filter.coprod] @[instance] lemma coprod_ne_bot_left [ne_bot f] [nonempty β] : (f.coprod g).ne_bot := coprod_ne_bot_iff.2 (or.inl ⟨‹_›, ‹_›⟩) @[instance] lemma coprod_ne_bot_right [ne_bot g] [nonempty α] : (f.coprod g).ne_bot := coprod_ne_bot_iff.2 (or.inr ⟨‹_›, ‹_›⟩) lemma principal_coprod_principal (s : set α) (t : set β) : (𝓟 s).coprod (𝓟 t) = 𝓟 (sᶜ.prod tᶜ)ᶜ := begin rw [filter.coprod, comap_principal, comap_principal, sup_principal], congr, ext x, simp ; tauto, end -- this inequality can be strict; see `map_const_principal_coprod_map_id_principal` and -- `map_prod_map_const_id_principal_coprod_principal` below. lemma map_prod_map_coprod_le {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : map (prod.map m₁ m₂) (f₁.coprod f₂) ≤ (map m₁ f₁).coprod (map m₂ f₂) := begin intros s, simp only [mem_map, mem_coprod_iff], rintro ⟨⟨u₁, hu₁, h₁⟩, u₂, hu₂, h₂⟩, refine ⟨⟨m₁ ⁻¹' u₁, hu₁, λ _ hx, h₁ _⟩, ⟨m₂ ⁻¹' u₂, hu₂, λ _ hx, h₂ _⟩⟩; convert hx end /-- Characterization of the coproduct of the `filter.map`s of two principal filters `𝓟 {a}` and `𝓟 {i}`, the first under the constant function `λ a, b` and the second under the identity function. Together with the next lemma, `map_prod_map_const_id_principal_coprod_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_const_principal_coprod_map_id_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : (map (λ _ : α, b) (𝓟 {a})).coprod (map id (𝓟 {i})) = 𝓟 (({b} : set β).prod (univ : set ι) ∪ (univ : set β).prod {i}) := begin rw [map_principal, map_principal, principal_coprod_principal], congr, ext ⟨b', i'⟩, simp, tauto, end /-- Characterization of the `filter.map` of the coproduct of two principal filters `𝓟 {a}` and `𝓟 {i}`, under the `prod.map` of two functions, respectively the constant function `λ a, b` and the identity function. Together with the previous lemma, `map_const_principal_coprod_map_id_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_prod_map_const_id_principal_coprod_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : map (prod.map (λ _ : α, b) id) ((𝓟 {a}).coprod (𝓟 {i})) = 𝓟 (({b} : set β).prod (univ : set ι)) := begin rw [principal_coprod_principal, map_principal], congr, ext ⟨b', i'⟩, split, { rintro ⟨⟨a'', i''⟩, h₁, h₂, h₃⟩, simp }, { rintro ⟨h₁, h₂⟩, use (a, i'), simpa using h₁.symm } end lemma tendsto.prod_map_coprod {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a.coprod b) (c.coprod d) := map_prod_map_coprod_le.trans (coprod_mono hf hg) end coprod /-! ### `n`-ary coproducts of filters -/ section Coprod variables {δ : Type*} {κ : δ → Type*} -- {f : Π d, filter (κ d)} /-- Coproduct of filters. -/ protected def Coprod (f : Π d, filter (κ d)) : filter (Π d, κ d) := ⨆ d : δ, (f d).comap (λ k, k d) lemma mem_Coprod_iff {s : set (Π d, κ d)} {f : Π d, filter (κ d)} : (s ∈ (filter.Coprod f)) ↔ (∀ d : δ, (∃ t₁ ∈ f d, (λ k : (Π d, κ d), k d) ⁻¹' t₁ ⊆ s)) := by simp [filter.Coprod] lemma Coprod_ne_bot_iff' {f : Π d, filter (κ d)} : ne_bot (filter.Coprod f) ↔ (∀ d, nonempty (κ d)) ∧ ∃ d, ne_bot (f d) := by simp only [filter.Coprod, supr_ne_bot, ← exists_and_distrib_left, ← comap_eval_ne_bot_iff'] @[simp] lemma Coprod_ne_bot_iff [∀ d, nonempty (κ d)] {f : Π d, filter (κ d)} : ne_bot (filter.Coprod f) ↔ ∃ d, ne_bot (f d) := by simp [Coprod_ne_bot_iff', *] lemma ne_bot.Coprod [∀ d, nonempty (κ d)] {f : Π d, filter (κ d)} {d : δ} (h : ne_bot (f d)) : ne_bot (filter.Coprod f) := Coprod_ne_bot_iff.2 ⟨d, h⟩ @[instance] lemma Coprod_ne_bot [∀ d, nonempty (κ d)] [nonempty δ] (f : Π d, filter (κ d)) [H : ∀ d, ne_bot (f d)] : ne_bot (filter.Coprod f) := (H (classical.arbitrary δ)).Coprod @[mono] lemma Coprod_mono {f₁ f₂ : Π d, filter (κ d)} (hf : ∀ d, f₁ d ≤ f₂ d) : filter.Coprod f₁ ≤ filter.Coprod f₂ := supr_le_supr $ λ d, comap_mono (hf d) lemma map_pi_map_Coprod_le {μ : δ → Type*} {f : Π d, filter (κ d)} {m : Π d, κ d → μ d} : map (λ (k : Π d, κ d), λ d, m d (k d)) (filter.Coprod f) ≤ filter.Coprod (λ d, map (m d) (f d)) := begin intros s h, rw [mem_map', mem_Coprod_iff], intros d, rw mem_Coprod_iff at h, obtain ⟨t, H, hH⟩ := h d, rw mem_map at H, refine ⟨{x : κ d | m d x ∈ t}, H, _⟩, intros x hx, simp only [mem_set_of_eq, preimage_set_of_eq] at hx, rw mem_set_of_eq, exact set.mem_of_subset_of_mem hH (mem_preimage.mpr hx), end lemma tendsto.pi_map_Coprod {μ : δ → Type*} {f : Π d, filter (κ d)} {m : Π d, κ d → μ d} {g : Π d, filter (μ d)} (hf : ∀ d, tendsto (m d) (f d) (g d)) : tendsto (λ (k : Π d, κ d), λ d, m d (k d)) (filter.Coprod f) (filter.Coprod g) := map_pi_map_Coprod_le.trans (Coprod_mono hf) end Coprod end filter open_locale filter lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) : f =ᶠ[𝓟 s] g := h lemma set.eq_on.eventually_eq_of_mem {α β} {s : set α} {l : filter α} {f g : α → β} (h : eq_on f g s) (hl : s ∈ l) : f =ᶠ[l] g := h.eventually_eq.filter_mono $ filter.le_principal_iff.2 hl lemma set.subset.eventually_le {α} {l : filter α} {s t : set α} (h : s ⊆ t) : s ≤ᶠ[l] t := filter.eventually_of_forall h lemma set.maps_to.tendsto {α β} {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) : filter.tendsto f (𝓟 s) (𝓟 t) := filter.tendsto_principal_principal.2 h
de1c947076c866bde7ecba92c9f4ea80498488dc
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/simplifier_norm_num.lean
92d10e46fc3967629ff94c7708a5cc0e0263773f
[ "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
1,885
lean
import algebra.ring set_option simplify.max_steps 5000000 -- TODO(dhs): we need to create the simplifier.numeral namespace incrementally. -- Once it exists, we can uncomment the following line to use it simplify. set_option simplify.numerals true universe l constants (A : Type.{l}) (A_comm_ring : comm_ring A) attribute A_comm_ring [instance] #simplify eq env 0 (0:A) + 1 #simplify eq env 0 (1:A) + 0 #simplify eq env 0 (1:A) + 1 #simplify eq env 0 (0:A) + 2 #simplify eq env 0 (1:A) + 2 #simplify eq env 0 (2:A) + 1 #simplify eq env 0 (3:A) + 1 #simplify eq env 0 (2:A) + 2 #simplify eq env 0 (4:A) + 1 #simplify eq env 0 (3:A) + 2 #simplify eq env 0 (2:A) + 3 #simplify eq env 0 (0:A) + 6 #simplify eq env 0 (3:A) + 3 #simplify eq env 0 (4:A) + 2 #simplify eq env 0 (5:A) + 1 #simplify eq env 0 (4:A) + 3 #simplify eq env 0 (1:A) + 6 #simplify eq env 0 (6:A) + 1 #simplify eq env 0 (5:A) + 28 #simplify eq env 0 (0 : A) + (2 + 3) + 7 #simplify eq env 0 (70 : A) + (33 + 2) #simplify eq env 0 (23000000000 : A) + 22000000000 #simplify eq env 0 (0 : A) * 0 #simplify eq env 0 (0 : A) * 1 #simplify eq env 0 (0 : A) * 2 #simplify eq env 0 (2 : A) * 0 #simplify eq env 0 (1 : A) * 0 #simplify eq env 0 (1 : A) * 1 #simplify eq env 0 (2 : A) * 1 #simplify eq env 0 (1 : A) * 2 #simplify eq env 0 (2 : A) * 2 #simplify eq env 0 (3 : A) * 2 #simplify eq env 0 (2 : A) * 3 #simplify eq env 0 (4 : A) * 1 #simplify eq env 0 (1 : A) * 4 #simplify eq env 0 (3 : A) * 3 #simplify eq env 0 (3 : A) * 4 #simplify eq env 0 (4 : A) * 4 #simplify eq env 0 (11 : A) * 2 #simplify eq env 0 (15 : A) * 6 #simplify eq env 0 (123456 : A) * 123456 #simplify eq env 0 (0 + 45343453:A) * (53653343 + 1) * (53453 + 2) + (0 + 1 + 2 + 2200000000034733) #simplify eq env 0 (23000000000343434534345316:A) * (53653343563534534 + 5367536453653573573453) * 53453756475777536 + 2200000000034733531531531534536
03ade03fde78f2d26b945fe973f11c0f548e9000
70f8755415fa7a17f87402cde4651e9f4db1b5bb
/src/mvfunctor.lean
74d0a3418b1ccb39e08f2fb25c38815ad5075b7f
[ "Apache-2.0" ]
permissive
shingarov/qpf
ab935dc2298db12c87ac011a2e4d2c27e0bdef4b
debe2eacb8cf46b21aba2eaf3f2e20940da0263b
refs/heads/master
1,653,705,576,607
1,570,136,035,000
1,570,136,035,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,851
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Mario Carneiro Tuples of types, and their categorical structure. Features: `typevec n` : n-tuples of types `α ⟹ β` : n-tuples of maps `f ⊚ g` : composition `mvfunctor n` : the type class of multivariate functors `f <$$> x` : notation for map Also, support functions for operating with n-tuples of types, such as: `append1 α β` : append type `β` to n-tuple `α` to obtain an (n+1)-tuple `drop α` : drops the last element of an (n+1)-tuple `last α` : returns the last element of an (n+1)-tuple `append_fun f g` : appends a function g to an n-tuple of functions `drop_fun f` : drops the last function from an n+1-tuple `last_fun f` : returns the last function of a tuple. Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal to it, we need support functions and lemmas to mediate between constructions. -/ import for_mathlib /- n-tuples of types, as a category -/ universes u v w inductive fin' : ℕ → Type | raise {n : ℕ} : fin' n → fin' n.succ | last {n : ℕ} : fin' n.succ def fin'.elim0 {α} : fin' 0 → α . def typevec (n : ℕ) := fin' n → Type* namespace typevec variable {n : ℕ} def arrow (α β : typevec n) := Π i : fin' n, α i → β i infixl ` ⟹ `:40 := arrow def id {α : typevec n} : α ⟹ α := λ i x, x def comp {α β γ : typevec n} (g : β ⟹ γ) (f : α ⟹ β) : α ⟹ γ := λ i x, g i (f i x) infixr ` ⊚ `:80 := typevec.comp -- type as \oo @[simp] theorem id_comp {α β : typevec n} (f : α ⟹ β) : id ⊚ f = f := rfl @[simp] theorem comp_id {α β : typevec n} (f : α ⟹ β) : f ⊚ id = f := rfl theorem comp_assoc {α β γ δ : typevec n} (h : γ ⟹ δ) (g : β ⟹ γ) (f : α ⟹ β) : (h ⊚ g) ⊚ f = h ⊚ g ⊚ f := rfl end typevec class mvfunctor {n : ℕ} (F : typevec n → Type*) := (map : Π {α β : typevec n}, (α ⟹ β) → (F α → F β)) infixr ` <$$> `:100 := mvfunctor.map namespace mvfunctor variables {n : ℕ} {α β γ : typevec.{u} n} {F : typevec.{u} n → Type v} [mvfunctor F] def liftp {α : typevec n} (p : Π i, α i → Prop) : F α → Prop := λ x, ∃ u : F (λ i, subtype (p i)), (λ i, @subtype.val _ (p i)) <$$> u = x def liftr {α β : typevec n} (r : Π {i}, α i → β i → Prop) : F α → F β → Prop := λ x y, ∃ u : F (λ i, {p : α i × β i // r p.fst p.snd}), (λ i (t : {p : α i × β i // r p.fst p.snd}), t.val.fst) <$$> u = x ∧ (λ i (t : {p : α i × β i // r p.fst p.snd}), t.val.snd) <$$> u = y def supp {α : typevec n} (x : F α) (i : fin' n) : set (α i) := { y : α i | ∀ {p}, liftp p x → p i y } theorem of_mem_supp {α : typevec n} {x : F α} {p : Π ⦃i⦄, α i → Prop} (h : liftp p x) (i : fin' n): ∀ y ∈ supp x i, p y := λ y hy, hy h end mvfunctor namespace mvfunctor class is_lawful {n : ℕ} (F : typevec n → Type*) [mvfunctor F] : Prop := (id_map : Π {α : typevec n} (x : F α), typevec.id <$$> x = x) (comp_map : Π {α β γ : typevec n} (g : α ⟹ β) (h : β ⟹ γ) (x : F α), (h ⊚ g) <$$> x = h <$$> g <$$> x) export is_lawful (id_map comp_map) attribute [simp] id_map variables {n : ℕ} {α β γ : typevec.{u} n} variables {F : typevec.{u} n → Type v} [mvfunctor F] [is_lawful F] @[simp] lemma id_map' (x : F α) : (λ i a, a) <$$> x = x := id_map n x lemma map_map (g : α ⟹ β) (h : β ⟹ γ) (x : F α) : h <$$> g <$$> x = (h ⊚ g) <$$> x := eq.symm $ comp_map _ _ _ end mvfunctor /- Support for extending a typevec by one element. -/ namespace eq theorem mp_mpr {α β : Type*} (h : α = β) (x : β) : eq.mp h (eq.mpr h x) = x := by induction h; reflexivity theorem mpr_mp {α β : Type*} (h : α = β) (x : α) : eq.mpr h (eq.mp h x) = x := by induction h; reflexivity end eq namespace fin def succ_cases {n : ℕ} (i : fin (n + 1)) : psum {j : fin n // i = j.cast_succ} (i = fin.last n) := begin cases i with i h, by_cases h' : i < n, { left, refine ⟨⟨i, h'⟩, _⟩, apply eq_of_veq, reflexivity }, right, apply eq_of_veq, show i = n, from le_antisymm (nat.le_of_lt_succ h) (le_of_not_lt h') end end fin namespace typevec variable {n : ℕ} def append1 (α : typevec n) (β : Type*) : typevec (n+1) | (fin'.raise i) := α i | fin'.last := β infixl ` ::: `:67 := append1 def drop (α : typevec (n+1)) : typevec n := λ i, α i.raise def last (α : typevec (n+1)) : Type* := α fin'.last theorem drop_append1 {α : typevec n} {β : Type*} {i : fin' n} : drop (append1 α β) i = α i := rfl theorem drop_append1' {α : typevec n} {β : Type*} : drop (append1 α β) = α := by ext; apply drop_append1 theorem last_append1 {α : typevec n} {β : Type*} : last (append1 α β) = β := rfl @[simp] theorem append1_drop_last (α : typevec (n+1)) : append1 (drop α) (last α) = α := funext $ λ i, by cases i; refl @[elab_as_eliminator] def append1_cases {C : typevec (n+1) → Sort u} (H : ∀ α β, C (append1 α β)) (γ) : C γ := by rw [← @append1_drop_last _ γ]; apply H @[simp] theorem append1_cases_append1 {C : typevec (n+1) → Sort u} (H : ∀ α β, C (append1 α β)) (α β) : @append1_cases _ C H (append1 α β) = H α β := rfl def split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : α ⟹ α' | (fin'.raise i) := f i | fin'.last := g def append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : append1 α β ⟹ append1 α' β' := split_fun f g infixl ` ::: ` := append_fun def drop_fun {α β : typevec (n+1)} (f : α ⟹ β) : drop α ⟹ drop β := λ i, f i.raise def last_fun {α β : typevec (n+1)} (f : α ⟹ β) : last α → last β := f fin'.last theorem eq_of_drop_last_eq {α β : typevec (n+1)} {f g : α ⟹ β} (h₀ : ∀ j, drop_fun f j = drop_fun g j) (h₁ : last_fun f = last_fun g) : f = g := by ext1 i; rcases i with ⟨j, ieq⟩ | ieq; [apply h₀, apply h₁] @[simp] theorem drop_fun_split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : drop_fun (split_fun f g) = f := rfl def arrow.mp {α β : typevec n} (h : α = β) : α ⟹ β | i := eq.mp (congr_fun h _) def arrow.mpr {α β : typevec n} (h : α = β) : β ⟹ α | i := eq.mpr (congr_fun h _) def to_append1_drop_last {α : typevec (n+1)} : α ⟹ drop α ::: last α := arrow.mpr (append1_drop_last _) @[simp] theorem last_fun_split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : last_fun (split_fun f g) = g := rfl @[simp] theorem drop_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : drop_fun (f ::: g) = f := rfl @[simp] theorem last_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : last_fun (f ::: g) = g := rfl theorem split_drop_fun_last_fun {α α' : typevec (n+1)} (f : α ⟹ α') : split_fun (drop_fun f) (last_fun f) = f := eq_of_drop_last_eq (λ _, rfl) rfl theorem split_fun_inj {α α' : typevec (n+1)} {f f' : drop α ⟹ drop α'} {g g' : last α → last α'} (H : split_fun f g = split_fun f' g') : f = f' ∧ g = g' := by rw [← drop_fun_split_fun f g, H, ← last_fun_split_fun f g, H]; simp def nil_fun : fin'.elim0 ⟹ fin'.elim0 := λ i, fin'.elim0 i theorem append_fun_inj {α α' : typevec n} {β β' : Type*} {f f' : α ⟹ α'} {g g' : β → β'} : f ::: g = f' ::: g' → f = f' ∧ g = g' := split_fun_inj theorem split_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : drop α₀ ⟹ drop α₁) (f₁ : drop α₁ ⟹ drop α₂) (g₀ : last α₀ → last α₁) (g₁ : last α₁ → last α₂) : split_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) = split_fun f₁ g₁ ⊚ split_fun f₀ g₀ := eq_of_drop_last_eq (λ _, rfl) rfl theorem append_fun_comp_split_fun {α γ : typevec n} {β δ : Type*} {ε : typevec (n + 1)} (f₀ : drop ε ⟹ α) (f₁ : α ⟹ γ) (g₀ : last ε → β) (g₁ : β → δ) : append_fun f₁ g₁ ⊚ split_fun f₀ g₀ = split_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) := (split_fun_comp _ _ _ _).symm lemma append_fun_comp {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : f₁ ⊚ f₀ ::: g₁ ∘ g₀ = (f₁ ::: g₁) ⊚ (f₀ ::: g₀) := eq_of_drop_last_eq (λ _, rfl) rfl lemma append_fun_comp' {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : (f₁ ::: g₁) ⊚ (f₀ ::: g₀) = f₁ ⊚ f₀ ::: g₁ ∘ g₀ := eq_of_drop_last_eq (λ _, rfl) rfl lemma nil_fun_comp {α₀ : typevec 0} (f₀ : α₀ ⟹ fin'.elim0) : nil_fun ⊚ f₀ = f₀ := funext $ λ x, fin'.elim0 x theorem append_fun_comp_id {α : typevec n} {β₀ β₁ β₂ : Type*} (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : @id _ α ::: g₁ ∘ g₀ = (id ::: g₁) ⊚ (id ::: g₀) := eq_of_drop_last_eq (λ _, rfl) rfl @[simp] theorem drop_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) : drop_fun (f₁ ⊚ f₀) = drop_fun f₁ ⊚ drop_fun f₀ := rfl @[simp] theorem last_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) : last_fun (f₁ ⊚ f₀) = last_fun f₁ ∘ last_fun f₀ := rfl theorem append_fun_aux {α α' : typevec n} {β β' : Type*} (f : α ::: β ⟹ α' ::: β') : drop_fun f ::: last_fun f = f := eq_of_drop_last_eq (λ _, rfl) rfl theorem append_fun_id_id {α : typevec n} {β : Type*} : @id n α ::: @_root_.id β = id := eq_of_drop_last_eq (λ _, rfl) rfl instance subsingleton0 : subsingleton (typevec 0) := ⟨ λ a b, funext $ λ a, fin'.elim0 a ⟩ run_cmd mk_simp_attr `typevec -- attribute [typevec] local prefix `♯`:0 := cast (by try { simp }; congr' 1; try { simp }) def typevec_cases_nil {β : typevec 0 → Sort*} (f : β fin'.elim0) : Π v, β v := λ v, ♯ f def typevec_cases_cons (n : ℕ) {β : typevec (n+1) → Sort*} (f : Π t (v : typevec n), β (v ::: t)) : Π v, β v := λ v, ♯ f v.last v.drop lemma typevec_cases_nil_append1 {β : typevec 0 → Sort*} (f : β fin'.elim0) : typevec_cases_nil f fin'.elim0 = f := rfl lemma typevec_cases_cons_append1 (n : ℕ) {β : typevec (n+1) → Sort*} (f : Π t (v : typevec n), β (v ::: t)) (v : typevec n) (α) : typevec_cases_cons n f (v ::: α) = f α v := rfl open typevec def typevec_cases_nil₃ {β : Π v v' : typevec 0, v ⟹ v' → Sort*} (f : β fin'.elim0 fin'.elim0 nil_fun) : Π v v' f, β v v' f := λ v v' fs, begin refine cast _ f; congr; ext; try { intros; exact fin'.elim0 ‹ fin' 0 › }; refl end def typevec_cases_cons₃ (n : ℕ) {β : Π v v' : typevec (n+1), v ⟹ v' → Sort*} (F : Π t t' (f : t → t') (v v' : typevec n) (fs : v ⟹ v'), β (v ::: t) (v' ::: t') (fs ::: f)) : Π v v' fs, β v v' fs := begin intros v v', rw [←append1_drop_last v, ←append1_drop_last v'], intro fs, rw [←split_drop_fun_last_fun fs], apply F end def typevec_cases_nil₂ {β : fin'.elim0 ⟹ fin'.elim0 → Sort*} (f : β nil_fun) : Π f, β f := begin intro g, have : g = nil_fun, ext ⟨ ⟩, rw this, exact f end def typevec_cases_cons₂ (n : ℕ) (t t' : Type*) (v v' : typevec (n)) {β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : Π (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) : Π fs, β fs := begin intro fs, rw [←split_drop_fun_last_fun fs], apply F end lemma typevec_cases_nil₂_append_fun {β : fin'.elim0 ⟹ fin'.elim0 → Sort*} (f : β nil_fun) : typevec_cases_nil₂ f nil_fun = f := rfl lemma typevec_cases_cons₂_append_fun (n : ℕ) (t t' : Type*) (v v' : typevec (n)) {β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : Π (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) (f fs) : typevec_cases_cons₂ n t t' v v' F (fs ::: f) = F f fs := rfl /- for lifting predicates and relations -/ /-- `pred_last α p x` predicates `p` of the last element of `x : α.append1 β`. -/ def pred_last (α : typevec n) {β : Type*} (p : β → Prop) : Π ⦃i⦄, (α.append1 β) i → Prop | (fin'.raise i) := λ x, true | fin'.last := p /-- `rel_last α r x y` says that `p` the last elements of `x y : α.append1 β` are related by `r` and all the other elements are equal. -/ def rel_last (α : typevec n) {β γ : Type*} (r : β → γ → Prop) : Π ⦃i⦄, (α.append1 β) i → (α.append1 γ) i → Prop | (fin'.raise i) := eq | fin'.last := r end typevec
f91957f2cfff2ea6adb496bb6d642c4420c40502
bdb33f8b7ea65f7705fc342a178508e2722eb851
/tests/wlog.lean
faba42cdec71e468541b9eb2ded2db7c2f4a0c26
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
1,857
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic example {a b : Prop} (h₀ : a → b) (h₁ : a) : b := begin apply_assumption, apply_assumption, end example {a b : Prop} (h₀ : a → b) (h₁ : a) : b := by solve_by_elim example {α : Type} {p : α → Prop} (h₀ : ∀ x, p x) (y : α) : p y := begin apply_assumption, end section tauto₀ variables p q r : Prop variables h : p ∧ q ∨ p ∧ r include h example : p ∧ p := by tauto end tauto₀ section tauto₁ variables α : Type variables p q r : α → Prop variables h : (∃ x, p x ∧ q x) ∨ (∃ x, p x ∧ r x) include h example : ∃ x, p x := by tauto end tauto₁ section tauto₂ variables α : Type variables x : α variables p q r : α → Prop variables h₀ : (∀ x, p x → q x → r x) ∨ r x variables h₁ : p x variables h₂ : q x include h₀ h₁ h₂ example : ∃ x, r x := by tauto end tauto₂ example {x y : ℕ} : true := begin suffices : x = 1 → false, trivial, intros a, wlog h : x = y, { guard_target x = y ∨ y = x, admit }, { guard_hyp h := x = y, guard_hyp a := x = 1, admit }, end example {x y : ℕ} : true := begin suffices : false, trivial, wlog h : x ≤ y, { guard_hyp h := x ≤ y, guard_target false, admit }, end example {x y z : ℕ} : true := begin suffices : false, trivial, wlog h : x ≤ y + z, { guard_target x ≤ y + z ∨ x ≤ z + y, admit }, { guard_hyp h := x ≤ y + z, guard_target false, admit }, end example {x y z : ℕ} : true := begin suffices : false, trivial, wlog : x ≤ y + z using x y, { guard_target x ≤ y + z ∨ y ≤ x + z, admit }, { guard_hyp a := x ≤ y + z, guard_target false, admit }, end
82d5b625475288229a85aaa44cf3bd20962bd15c
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/nat/sqrt.lean
4d35d6e6a4b1d7506e0b9d116e9eab6c3f6931fe
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,952
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura Very simple (sqrt n) function that returns s s.t. s*s ≤ n ≤ s*s + s + s -/ import data.nat.order data.nat.sub namespace nat open decidable open algebra -- This is the simplest possible function that just performs a linear search definition sqrt_aux : nat → nat → nat | 0 n := 0 | (succ s) n := if (succ s)*(succ s) ≤ n then succ s else sqrt_aux s n theorem sqrt_aux_succ_of_pos {s n} : (succ s)*(succ s) ≤ n → sqrt_aux (succ s) n = (succ s) := assume h, if_pos h theorem sqrt_aux_succ_of_neg {s n} : ¬ (succ s)*(succ s) ≤ n → sqrt_aux (succ s) n = sqrt_aux s n := assume h, if_neg h theorem sqrt_aux_of_le : ∀ {s n : nat}, s * s ≤ n → sqrt_aux s n = s | 0 n h := rfl | (succ s) n h := by rewrite [sqrt_aux_succ_of_pos h] theorem sqrt_aux_le : ∀ (s n), sqrt_aux s n ≤ s | 0 n := !zero_le | (succ s) n := or.elim (em ((succ s)*(succ s) ≤ n)) (λ h, begin unfold sqrt_aux, rewrite [if_pos h] end) (λ h, assert sqrt_aux s n ≤ succ s, from le.step (sqrt_aux_le s n), begin unfold sqrt_aux, rewrite [if_neg h], assumption end) definition sqrt (n : nat) : nat := sqrt_aux n n theorem sqrt_aux_lower : ∀ {s n : nat}, s ≤ n → sqrt_aux s n * sqrt_aux s n ≤ n | 0 n h := h | (succ s) n h := by_cases (λ h₁ : (succ s)*(succ s) ≤ n, by rewrite [sqrt_aux_succ_of_pos h₁]; exact h₁) (λ h₂ : ¬ (succ s)*(succ s) ≤ n, assert aux : s ≤ n, from le_of_succ_le h, by rewrite [sqrt_aux_succ_of_neg h₂]; exact (sqrt_aux_lower aux)) theorem sqrt_lower (n : nat) : sqrt n * sqrt n ≤ n := sqrt_aux_lower (le.refl n) theorem sqrt_aux_upper : ∀ {s n : nat}, n ≤ s*s + s + s → n ≤ sqrt_aux s n * sqrt_aux s n + sqrt_aux s n + sqrt_aux s n | 0 n h := h | (succ s) n h := by_cases (λ h₁ : (succ s)*(succ s) ≤ n, by rewrite [sqrt_aux_succ_of_pos h₁]; exact h) (λ h₂ : ¬ (succ s)*(succ s) ≤ n, assert h₃ : n < (succ s) * (succ s), from lt_of_not_ge h₂, assert h₄ : n ≤ s * s + s + s, by rewrite [succ_mul_succ_eq at h₃]; exact le_of_lt_succ h₃, by rewrite [sqrt_aux_succ_of_neg h₂]; exact (sqrt_aux_upper h₄)) theorem sqrt_upper (n : nat) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := have aux : n ≤ n*n + n + n, from le_add_of_le_right (le_add_of_le_left (le.refl n)), sqrt_aux_upper aux private theorem le_squared : ∀ (n : nat), n ≤ n*n | 0 := !le.refl | (succ n) := have aux₁ : 1 ≤ succ n, from succ_le_succ !zero_le, assert aux₂ : 1 * succ n ≤ succ n * succ n, from nat.mul_le_mul aux₁ !le.refl, by rewrite [one_mul at aux₂]; exact aux₂ private theorem lt_squared : ∀ {n : nat}, n > 1 → n < n * n | 0 h := absurd h dec_trivial | 1 h := absurd h dec_trivial | (succ (succ n)) h := have 1 < succ (succ n), from dec_trivial, assert succ (succ n) * 1 < succ (succ n) * succ (succ n), from mul_lt_mul_of_pos_left this dec_trivial, by rewrite [mul_one at this]; exact this theorem sqrt_le (n : nat) : sqrt n ≤ n := calc sqrt n ≤ sqrt n * sqrt n : le_squared ... ≤ n : sqrt_lower theorem eq_zero_of_sqrt_eq_zero {n : nat} : sqrt n = 0 → n = 0 := suppose sqrt n = 0, assert n ≤ sqrt n * sqrt n + sqrt n + sqrt n, from !sqrt_upper, have n ≤ 0, by rewrite [*`sqrt n = 0` at this]; exact this, eq_zero_of_le_zero this theorem le_three_of_sqrt_eq_one {n : nat} : sqrt n = 1 → n ≤ 3 := suppose sqrt n = 1, assert n ≤ sqrt n * sqrt n + sqrt n + sqrt n, from !sqrt_upper, show n ≤ 3, by rewrite [*`sqrt n = 1` at this]; exact this theorem sqrt_lt : ∀ {n : nat}, n > 1 → sqrt n < n | 0 h := absurd h dec_trivial | 1 h := absurd h dec_trivial | 2 h := dec_trivial | 3 h := dec_trivial | (n+4) h := have sqrt (n+4) > 1, from by_contradiction (suppose ¬ sqrt (n+4) > 1, have sqrt (n+4) ≤ 1, from le_of_not_gt this, or.elim (eq_or_lt_of_le this) (suppose sqrt (n+4) = 1, have n+4 ≤ 3, from le_three_of_sqrt_eq_one this, absurd this dec_trivial) (suppose sqrt (n+4) < 1, have sqrt (n+4) = 0, from eq_zero_of_le_zero (le_of_lt_succ this), have n + 4 = 0, from eq_zero_of_sqrt_eq_zero this, absurd this dec_trivial)), calc sqrt (n+4) < sqrt (n+4) * sqrt (n+4) : lt_squared this ... ≤ n+4 : sqrt_lower theorem sqrt_pos_of_pos {n : nat} : n > 0 → sqrt n > 0 := suppose n > 0, have sqrt n ≠ 0, from suppose sqrt n = 0, assert n = 0, from eq_zero_of_sqrt_eq_zero this, by subst n; exact absurd `0 > 0` !lt.irrefl, pos_of_ne_zero this theorem sqrt_aux_offset_eq {n k : nat} (h₁ : k ≤ n + n) : ∀ {s}, s ≥ n → sqrt_aux s (n*n + k) = n | 0 h₂ := assert neqz : n = 0, from eq_zero_of_le_zero h₂, by rewrite neqz | (succ s) h₂ := by_cases (λ hl : (succ s)*(succ s) ≤ n*n + k, have l₁ : n*n + k ≤ n*n + n + n, from by rewrite [add.assoc]; exact (add_le_add_left h₁ (n*n)), assert l₂ : n*n + k < n*n + n + n + 1, from lt_succ_of_le l₁, have l₃ : n*n + k < (succ n)*(succ n), by rewrite [-succ_mul_succ_eq at l₂]; exact l₂, assert l₄ : (succ s)*(succ s) < (succ n)*(succ n), from lt_of_le_of_lt hl l₃, have ng : ¬ succ s > (succ n), from assume g : succ s > succ n, have g₁ : (succ s)*(succ s) > (succ n)*(succ n), from mul_lt_mul_of_le_of_le g g, absurd (lt.trans g₁ l₄) !lt.irrefl, have sslesn : succ s ≤ succ n, from le_of_not_gt ng, have ssnesn : succ s ≠ succ n, from assume sseqsn : succ s = succ n, by rewrite [sseqsn at l₄]; exact (absurd l₄ !lt.irrefl), have sslen : s < n, from lt_of_succ_lt_succ (lt_of_le_of_ne sslesn ssnesn), assert sseqn : succ s = n, from le.antisymm sslen h₂, by rewrite [sqrt_aux_succ_of_pos hl]; exact sseqn) (λ hg : ¬ (succ s)*(succ s) ≤ n*n + k, or.elim (eq_or_lt_of_le h₂) (λ neqss : n = succ s, have p : n*n ≤ n*n + k, from !le_add_right, have n : ¬ n*n ≤ n*n + k, by rewrite [-neqss at hg]; exact hg, absurd p n) (λ sgen : succ s > n, by rewrite [sqrt_aux_succ_of_neg hg]; exact (sqrt_aux_offset_eq (le_of_lt_succ sgen)))) theorem sqrt_offset_eq {n k : nat} : k ≤ n + n → sqrt (n*n + k) = n := assume h, have h₁ : n ≤ n*n + k, from le.trans !le_squared !le_add_right, sqrt_aux_offset_eq h h₁ theorem sqrt_eq (n : nat) : sqrt (n*n) = n := sqrt_offset_eq !zero_le theorem mul_square_cancel {a b : nat} : a*a = b*b → a = b := assume h, assert aux : sqrt (a*a) = sqrt (b*b), by rewrite h, by rewrite [*sqrt_eq at aux]; exact aux end nat
7febbdf6a6d5a268ef525038aa4cbfcfef1a66e4
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/nat/parity.lean
9d899182a0ad44ebb5d45f61969381b78df66542
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
8,008
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Benjamin Davidson -/ import data.nat.modeq import algebra.parity /-! # Parity of natural numbers This file contains theorems about the `even` and `odd` predicates on the natural numbers. ## Tags even, odd -/ namespace nat variables {m n : ℕ} @[simp] theorem mod_two_ne_one : ¬ n % 2 = 1 ↔ n % 2 = 0 := by cases mod_two_eq_zero_or_one n with h h; simp [h] @[simp] theorem mod_two_ne_zero : ¬ n % 2 = 0 ↔ n % 2 = 1 := by cases mod_two_eq_zero_or_one n with h h; simp [h] theorem even_iff : even n ↔ n % 2 = 0 := ⟨λ ⟨m, hm⟩, by simp [← two_mul, hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [← two_mul, h])⟩⟩ theorem odd_iff : odd n ↔ n % 2 = 1 := ⟨λ ⟨m, hm⟩, by norm_num [hm, add_mod], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by rw [h, add_comm])⟩⟩ lemma not_even_iff : ¬ even n ↔ n % 2 = 1 := by rw [even_iff, mod_two_ne_zero] lemma not_odd_iff : ¬ odd n ↔ n % 2 = 0 := by rw [odd_iff, mod_two_ne_one] lemma even_iff_not_odd : even n ↔ ¬ odd n := by rw [not_odd_iff, even_iff] @[simp] lemma odd_iff_not_even : odd n ↔ ¬ even n := by rw [not_even_iff, odd_iff] lemma is_compl_even_odd : is_compl {n : ℕ | even n} {n | odd n} := by simp only [←set.compl_set_of, is_compl_compl, odd_iff_not_even] lemma even_or_odd (n : ℕ) : even n ∨ odd n := or.imp_right odd_iff_not_even.2 $ em $ even n lemma even_or_odd' (n : ℕ) : ∃ k, n = 2 * k ∨ n = 2 * k + 1 := by simpa only [← two_mul, exists_or_distrib, ← odd, ← even] using even_or_odd n lemma even_xor_odd (n : ℕ) : xor (even n) (odd n) := begin cases even_or_odd n with h, { exact or.inl ⟨h, even_iff_not_odd.mp h⟩ }, { exact or.inr ⟨h, odd_iff_not_even.mp h⟩ }, end lemma even_xor_odd' (n : ℕ) : ∃ k, xor (n = 2 * k) (n = 2 * k + 1) := begin rcases even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; use k, { simpa only [← two_mul, xor, true_and, eq_self_iff_true, not_true, or_false, and_false] using (succ_ne_self (2*k)).symm }, { simp only [xor, add_right_eq_self, false_or, eq_self_iff_true, not_true, not_false_iff, one_ne_zero, and_self] }, end @[simp] theorem two_dvd_ne_zero : ¬ 2 ∣ n ↔ n % 2 = 1 := even_iff_two_dvd.symm.not.trans not_even_iff instance : decidable_pred (even : ℕ → Prop) := λ n, decidable_of_iff _ even_iff.symm instance : decidable_pred (odd : ℕ → Prop) := λ n, decidable_of_iff _ odd_iff_not_even.symm mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`" @[simp] theorem not_even_one : ¬ even 1 := by rw even_iff; norm_num @[parity_simps] theorem even_add : even (m + n) ↔ (even m ↔ even n) := by cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, nat.add_mod]; norm_num theorem even_add' : even (m + n) ↔ (odd m ↔ odd n) := by rw [even_add, even_iff_not_odd, even_iff_not_odd, not_iff_not] @[parity_simps] theorem even_add_one : even (n + 1) ↔ ¬ even n := by simp [even_add] @[simp] theorem not_even_bit1 (n : ℕ) : ¬ even (bit1 n) := by simp [bit1] with parity_simps lemma two_not_dvd_two_mul_add_one (n : ℕ) : ¬(2 ∣ 2 * n + 1) := by simp [add_mod] lemma two_not_dvd_two_mul_sub_one : Π {n} (w : 0 < n), ¬(2 ∣ 2 * n - 1) | (n + 1) _ := two_not_dvd_two_mul_add_one n @[parity_simps] theorem even_sub (h : n ≤ m) : even (m - n) ↔ (even m ↔ even n) := begin conv { to_rhs, rw [←tsub_add_cancel_of_le h, even_add] }, by_cases h : even n; simp [h] end theorem even_sub' (h : n ≤ m) : even (m - n) ↔ (odd m ↔ odd n) := by rw [even_sub h, even_iff_not_odd, even_iff_not_odd, not_iff_not] theorem odd.sub_odd (hm : odd m) (hn : odd n) : even (m - n) := (le_total n m).elim (λ h, by simp only [even_sub' h, *]) (λ h, by simp only [tsub_eq_zero_iff_le.mpr h, even_zero]) @[parity_simps] theorem even_mul : even (m * n) ↔ even m ∨ even n := by cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, nat.mul_mod]; norm_num theorem odd_mul : odd (m * n) ↔ odd m ∧ odd n := by simp [not_or_distrib] with parity_simps theorem odd.of_mul_left (h : odd (m * n)) : odd m := (odd_mul.mp h).1 theorem odd.of_mul_right (h : odd (m * n)) : odd n := (odd_mul.mp h).2 /-- If `m` and `n` are natural numbers, then the natural number `m^n` is even if and only if `m` is even and `n` is positive. -/ @[parity_simps] theorem even_pow : even (m ^ n) ↔ even m ∧ n ≠ 0 := by { induction n with n ih; simp [*, pow_succ', even_mul], tauto } theorem even_pow' (h : n ≠ 0) : even (m ^ n) ↔ even m := even_pow.trans $ and_iff_left h theorem even_div : even (m / n) ↔ m % (2 * n) / n = 0 := by rw [even_iff_two_dvd, dvd_iff_mod_eq_zero, nat.div_mod_eq_mod_mul_div, mul_comm] @[parity_simps] theorem odd_add : odd (m + n) ↔ (odd m ↔ even n) := by rw [odd_iff_not_even, even_add, not_iff, odd_iff_not_even] theorem odd_add' : odd (m + n) ↔ (odd n ↔ even m) := by rw [add_comm, odd_add] lemma ne_of_odd_add (h : odd (m + n)) : m ≠ n := λ hnot, by simpa [hnot] with parity_simps using h @[parity_simps] theorem odd_sub (h : n ≤ m) : odd (m - n) ↔ (odd m ↔ even n) := by rw [odd_iff_not_even, even_sub h, not_iff, odd_iff_not_even] theorem odd.sub_even (h : n ≤ m) (hm : odd m) (hn : even n) : odd (m - n) := (odd_sub h).mpr $ iff_of_true hm hn theorem odd_sub' (h : n ≤ m) : odd (m - n) ↔ (odd n ↔ even m) := by rw [odd_iff_not_even, even_sub h, not_iff, not_iff_comm, odd_iff_not_even] theorem even.sub_odd (h : n ≤ m) (hm : even m) (hn : odd n) : odd (m - n) := (odd_sub' h).mpr $ iff_of_true hn hm lemma even_mul_succ_self (n : ℕ) : even (n * (n + 1)) := begin rw even_mul, convert n.even_or_odd, simp with parity_simps end lemma even_mul_self_pred (n : ℕ) : even (n * (n - 1)) := begin cases n, { exact even_zero }, { rw mul_comm, apply even_mul_succ_self } end lemma even_sub_one_of_prime_ne_two {p : ℕ} (hp : prime p) (hodd : p ≠ 2) : even (p - 1) := odd.sub_odd (odd_iff.2 $ hp.eq_two_or_odd.resolve_left hodd) (odd_iff.2 rfl) lemma two_mul_div_two_of_even : even n → 2 * (n / 2) = n := λ h, nat.mul_div_cancel_left' (even_iff_two_dvd.mp h) lemma div_two_mul_two_of_even : even n → n / 2 * 2 = n := --nat.div_mul_cancel λ h, nat.div_mul_cancel (even_iff_two_dvd.mp h) lemma two_mul_div_two_add_one_of_odd (h : odd n) : 2 * (n / 2) + 1 = n := by { rw mul_comm, convert nat.div_add_mod' n 2, rw odd_iff.mp h } lemma div_two_mul_two_add_one_of_odd (h : odd n) : n / 2 * 2 + 1 = n := by { convert nat.div_add_mod' n 2, rw odd_iff.mp h } lemma one_add_div_two_mul_two_of_odd (h : odd n) : 1 + n / 2 * 2 = n := by { rw add_comm, convert nat.div_add_mod' n 2, rw odd_iff.mp h } lemma bit0_div_two : bit0 n / 2 = n := by rw [←nat.bit0_eq_bit0, bit0_eq_two_mul, two_mul_div_two_of_even (even_bit0 n)] lemma bit1_div_two : bit1 n / 2 = n := by rw [←nat.bit1_eq_bit1, bit1, bit0_eq_two_mul, nat.two_mul_div_two_add_one_of_odd (odd_bit1 n)] @[simp] lemma bit0_div_bit0 : bit0 n / bit0 m = n / m := by rw [bit0_eq_two_mul m, ←nat.div_div_eq_div_mul, bit0_div_two] @[simp] lemma bit1_div_bit0 : bit1 n / bit0 m = n / m := by rw [bit0_eq_two_mul, ←nat.div_div_eq_div_mul, bit1_div_two] -- Here are examples of how `parity_simps` can be used with `nat`. example (m n : ℕ) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) := by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps example : ¬ even 25394535 := by simp end nat open nat variables {R : Type*} [monoid R] [has_distrib_neg R] {n : ℕ} lemma neg_one_pow_eq_one_iff_even (h : (-1 : R) ≠ 1) : (-1 : R) ^ n = 1 ↔ even n := ⟨λ h', of_not_not $ λ hn, h $ (odd.neg_one_pow $ odd_iff_not_even.mpr hn).symm.trans h', even.neg_one_pow⟩
317d6191729670d98fc2598b1a6943278193e863
4fa118f6209450d4e8d058790e2967337811b2b5
/src/Spa/rational_open_data.lean
9566a5a4b536e9271eadc2a37123f9c5b44d8d40
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
11,602
lean
import for_mathlib.group -- some stupid lemma about units import Spa.space import Huber_ring.localization /-! # Rational open subsets and their properties We define a preorder on `rational_open_data` that will be used when constructing the valuations on the stalks of the structure presheaf. -/ open_locale classical local attribute [instance] set.pointwise_mul_comm_semiring local attribute [instance] set.smul_set_action local postfix `⁺` : 66 := λ A : Huber_pair, A.plus namespace spa open set algebra variables {A : Huber_pair} namespace rational_open_data variables (r : rational_open_data A) /-- The preorder on rational open data. Due to limitations in the existing mathematical library, we cannot work with the “correct” preorder on rational open data. The “correct” preorder on rational open data would be: def correct_preorder : preorder (rational_open_data A) := { le := λ r1 r2, rational_open r1 ⊆ rational_open r2, le_refl := λ _ _, id, le_trans := λ _ _ _, subset.trans } One can prove (in maths) that r1 ≤ r2 iff there's a continuous R-algebra morphism of Huber pairs localization r2 → localization r1. I think the ← direction of this iff is straightforward (but I didn't think about it too carefully). However we definitely cannot prove the → direction of this iff in this repo yet because we don't have enough API for cont. Here is an indication of part of the problem. localization r2 is just A[1/r2.s]. But we cannot prove yet r2.s is invertible in localization.r1, even though we know it doesn't vanish anywhere on rational_open r2 and hence on rational_open r1, because the fact that it doesn't vanish anywhere on rational_open r1 only means that it's not in any prime ideal corresponding to a *continuous* valuation on localization r1 which is bounded by 1 on some + subring; one would now need to prove, at least, that every maximal ideal is the support of a continuous valuation, which is Wedhorn 7.52(2). This is not too bad -- but it is work that we have not yet done. However this is by no means the whole story; we would also need that r1.T is power-bounded in localization.r2 and this looks much worse: it's Wedhorn 7.52(1). Everything is do-able, but it's just *long*. Long as in "thousands more lines of code". We will need a good theory of primary and secondary specialisation of valuations and so on and so on. None of this is there at the time of writing, although I see no obstruction to putting it there, other than the fact that it would take weeks of work. We have to work with a weaker preorder then, because haven't made a good enough API for continuous valuations. We basically work with the preorder r1 ≤ r2 iff there's a continuous R-algebra map localization r2 → localization r1, i.e, we define our way around the problem. We are fortunate in that we can prove (in maths) that the projective limit over this preorder agrees with the projective limit over the correct preorder. -/ instance : preorder (rational_open_data A) := { le := λ r1 r2, ∃ k : A, r1.s * k = r2.s ∧ ∀ t₁ ∈ r1.T, ∃ t₂ ∈ r2.T, ∃ N : ℕ, r2.s ^ N * t₂ = r2.s ^ N * (t₁ * k), le_refl := λ r, ⟨1, mul_one _, λ t ht, ⟨t, ht, 0, by rw mul_one⟩⟩, le_trans := λ a b c ⟨k, hk, hab⟩ ⟨l, hl, hbc⟩, ⟨k * l, by rw [←mul_assoc, hk, hl], λ ta hta, begin rcases hab ta hta with ⟨tb, htb, Nab, h1⟩, rcases hbc tb htb with ⟨hc, htc, Nbc, h2⟩, refine ⟨hc, htc, (Nab + Nbc), _⟩, rw [←mul_assoc, pow_add, mul_assoc, h2, ←hl, mul_pow, mul_pow], rw (show b.s ^ Nab * l ^ Nab * (b.s ^ Nbc * l ^ Nbc * (tb * l)) = b.s ^ Nab * tb * (l ^ Nab * (b.s ^ Nbc * l ^ Nbc * l)), by ring), rw h1, ring end⟩ } lemma le_inter_left (r1 r2 : rational_open_data A) : r1 ≤ (inter r1 r2) := begin refine ⟨r2.s, rfl, _⟩, intros t1 ht1, refine ⟨t1 * r2.s, ⟨t1, mem_insert_of_mem _ ht1, r2.s, mem_insert_s _, rfl⟩, 0, by simp⟩, end lemma le_inter_right (r1 r2 : rational_open_data A) : r2 ≤ (inter r1 r2) := by { rw inter_symm, apply le_inter_left, } -- The preorder defined above is weaker than the preorder we're supposed to have but don't. -- However the projective limit we take over our preorder is provably (in maths) equal to -- the projective limit that we cannot even formalise. The thing we definitely need -- is that if r1 ≤ r2 then there's a map localization r1 → localization r2 /-- The localization of a Huber pair A at the rational open subset r = D(T,s) ⊆ spa(A). -/ def localization (r : rational_open_data A) := Huber_ring.away r.T r.s namespace localization /-- The ring structure on the localization at the rational open subset r = D(T,s) ⊆ spa(A). -/ instance : comm_ring (localization r) := by unfold localization; apply_instance /-- The basis of open subgroups of the localization at the rational open subset r = D(T,s) ⊆ spa(A). -/ instance : subgroups_basis (localization r) := Huber_ring.away.top_loc_basis r.T r.s r.Hopen /-- The topology on the localization at the rational open subset r = D(T,s) ⊆ spa(A). -/ instance : topological_space (localization r) := subgroups_basis.topology _ /-- The localization at the rational open subset r = D(T,s) ⊆ spa(A) is a topological ring. -/ instance : topological_ring (localization r) := ring_filter_basis.is_topological_ring _ rfl /-- The uniform structure on the localization at the rational open subset r = D(T,s) ⊆ spa(A). -/ instance (r : rational_open_data A) : uniform_space (rational_open_data.localization r) := topological_add_group.to_uniform_space _ /-- The localization at the rational open subset r = D(T,s) ⊆ spa(A) is a uniform additive group. -/ instance (rd : rational_open_data A): uniform_add_group (rational_open_data.localization rd) := topological_add_group_is_uniform /-- The localization at the rational open subset r = D(T,s) ⊆ spa(A) is a an algebra over A. -/ instance : algebra A (localization r) := Huber_ring.away.algebra r.T r.s /-- The coercion from a Huber pair A to the localization at the rational open subset r = D(T,s) ⊆ spa(A). -/ instance : has_coe A (localization r) := ⟨λ a, (of_id A (localization r) : A → localization r) a⟩ lemma nonarchimedean (r : rational_open_data A) : topological_add_group.nonarchimedean (localization r) := subgroups_basis.nonarchimedean set_option class.instance_max_depth 38 /--If A is a Huber pair, and r = D(T,s) a rational open subset of Spa(A), and coe is the localization map A → A(T/s), then `power_bounded_data r` is the set { coe(t)/s | t ∈ T } ⊆ A(T/s).-/ def power_bounded_data (r : rational_open_data A) : set (localization r) := let s_inv : localization r := ((localization.to_units ⟨r.s, ⟨1, by simp⟩⟩)⁻¹ : units (localization r)) in (s_inv • (coe : A → localization r) '' r.T) theorem power_bounded (r : rational_open_data A) : is_power_bounded_subset (power_bounded_data r) := begin suffices : is_bounded (ring.closure (power_bounded_data r)), { exact is_bounded.subset add_group.subset_closure this }, intros U hU, rcases subgroups_basis.mem_nhds_zero.mp hU with ⟨_, ⟨V, rfl⟩, hV⟩, refine ⟨_, mem_nhds_sets (subgroups_basis.is_op _ rfl (set.mem_range_self _)) _, _⟩, { exact V }, { erw submodule.mem_coe, convert submodule.zero_mem _ }, { intros v hv b hb, apply hV, rw [mul_comm, ← smul_eq_mul], rw submodule.mem_coe at hv ⊢, convert submodule.smul_mem _ _ hv, swap, { exact ⟨b, hb⟩ }, { refl } } end end localization /-- This auxilliary function produces r1.s as a unit in localization r2 -/ noncomputable def s_inv_aux (r1 r2 : rational_open_data A) (h : r1 ≤ r2) : units (localization r2) := @units.unit_of_mul_left_eq_unit _ _ ((of_id A (localization r2) : A → r2.localization) r1.s) ((of_id A (localization r2) : A → r2.localization) (classical.some h)) (localization.to_units (⟨r2.s, 1, by simp⟩ : powers r2.s)) begin rw [← alg_hom.map_mul, (classical.some_spec h).1], refl, end /-- The map A(T1/s1) -> A(T2/s2) coming from the inequality r1 ≤ r2 -/ noncomputable def localization_map {r1 r2 : rational_open_data A} (h : r1 ≤ r2) : localization r1 → localization r2 := Huber_ring.away.lift r1.T r1.s (of_id A (localization r2)) (s_inv_aux r1 r2 h) rfl /-- The induced map A(T1/s1) -> A(T2/s2) coming from the inequality r1 ≤ r2 is a ring homomorphism. -/ instance {r1 r2 : rational_open_data A} (h : r1 ≤ r2) : is_ring_hom (localization_map h) := by delta localization_map; apply_instance /- To prove continuity of the localisation map coming from r1 ≤ r2 we need to check that the image of T1/s1 under the localization map is power-bounded in the ring (localization r2). This is done in the following lemma. -/ local attribute [instance] set.pointwise_mul_comm_semiring local attribute [instance] set.smul_set_action set_option class.instance_max_depth 38 lemma localization_map_is_cts_aux {r1 r2 : rational_open_data A} (h : r1 ≤ r2) : is_power_bounded_subset ((s_inv_aux r1 r2 h)⁻¹.val • (λ (x : ↥A), to_fun (localization r2) x) '' r1.T) := begin refine power_bounded.subset _ (localization.power_bounded r2), intros x hx, rcases hx with ⟨_, ⟨t₁, ht₁, rfl⟩, rfl⟩, let h' := h, -- need it later rcases h with ⟨a, ha, h₂⟩, rcases h₂ t₁ ht₁ with ⟨t₂, ht₂, N, hN⟩, show ↑(s_inv_aux r1 r2 _)⁻¹ * to_fun (localization r2) t₁ ∈ localization.mk 1 ⟨r2.s, _⟩ • (of_id ↥A (localization r2)).to_fun '' r2.T, refine ⟨(of_id ↥A (localization r2)).to_fun t₂, ⟨t₂, ht₂, rfl⟩, _⟩, rw [←units.mul_left_inj (s_inv_aux r1 r2 h'), units.mul_inv_cancel_left], show to_fun (localization r2) t₁ = to_fun (localization r2) (r1.s) * (localization.mk 1 ⟨r2.s, _⟩ * to_fun (localization r2) t₂), rw [mul_comm, mul_assoc], rw ←units.mul_left_inj (localization.to_units (⟨r2.s, 1, by simp⟩ : powers r2.s)), rw ←mul_assoc, -- t1=s1*(1/s2 * t2) in r2 have : ↑(localization.to_units (⟨r2.s, 1, by simp⟩ : powers r2.s)) * localization.mk (1 : A) (⟨r2.s, 1, by simp⟩ : powers r2.s) = 1, convert units.mul_inv _, rw [this, one_mul], clear this, show to_fun (localization r2) r2.s * _ = _, rw ←units.mul_left_inj (localization.to_units (⟨r2.s ^ N, N, rfl⟩ : powers r2.s)), show to_fun (localization r2) (r2.s ^ N) * _ = to_fun (localization r2) (r2.s ^ N) * _, have hrh : is_ring_hom (to_fun (localization r2)) := begin change is_ring_hom ((of_id ↥A (localization r2)).to_fun), apply_instance, end, rw ←@is_ring_hom.map_mul _ _ _ _ (to_fun (localization r2)) hrh, rw ←@is_ring_hom.map_mul _ _ _ _ (to_fun (localization r2)) hrh, rw ←@is_ring_hom.map_mul _ _ _ _ (to_fun (localization r2)) hrh, rw ←@is_ring_hom.map_mul _ _ _ _ (to_fun (localization r2)) hrh, congr' 1, rw [←mul_assoc _ t₂, hN], rw ←ha, ring, end -- Continuity now follows from the universal property. lemma localization_map_is_cts {r1 r2 : rational_open_data A} (h : r1 ≤ r2) : continuous (localization_map h) := Huber_ring.away.lift_continuous r1.T r1.s (localization.nonarchimedean r2) (Huber_ring.away.of_continuous r2.T r2.s _) _ _ _ (localization_map_is_cts_aux h) lemma localization_map_is_uniform_continuous {r1 r2 : rational_open_data A} (h : r1 ≤ r2) : uniform_continuous (rational_open_data.localization_map h) := uniform_continuous_of_continuous (rational_open_data.localization_map_is_cts h) end rational_open_data -- namespace end spa
d89e7eaaaa0580e3aac5b2bf77543f80c47ac82f
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/game/world2/level6.lean
e6709ddc46099970217c9ab264f3f83758fb7e17
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
4,315
lean
import mynat.definition -- hide import mynat.add -- hide import game.world2.level5 -- hide import tactic.ring -- hide namespace mynat -- hide /- # World 2 -- Addition World ## Level 6 -- `add_right_comm` You have (amongst other things) these: * `add_assoc (a b c : mynat) : (a + b) + c = a + (b + c)` * `add_comm (a b : mynat) : a + b = b + a` Lean sometimes writes `a + b + c`. What does it mean? The convention is that if there are no brackets displayed in an addition formula, the brackets are around the left most `+` (Lean's addition is "left associative"). So the goal in this level is `(a + b) + c = (a + c) + b`. This isn't quite `add_assoc` or `add_comm`, it's something you'll have to prove by putting these two theorems together. If you hadn't picked up on this already, `rw add_assoc` will change `(x + y) + z` to `x + (y + z)`, but to change it back you will need `rw ← add_assoc`. Get the left arrow with \l . Similarly, if `h : a = b` then `rw h` will change `a`'s to `b`'s and `rw ← h` will change `b`'s to `a`'s. Also, you can be (and will need to be, in this level) more precise about where to rewrite theorems. `rw add_comm,` will just find the first `? + ?` it sees and swap it around. You can target more specific additions like this: `rw add_comm a` will swap around additions of the form `a + ?`, and `rw add_comm a b,` will only swap additions of the form `a + b`. ## Where next? There are ten more levels about addition after this one, but before you can attempt them you need to learn some more tactics. So after this level you have a choice -- either move on to world 3 (which you can solve with the tactics you know) or try world 5 (and learn some new ones). Use the "next world" and "previous world" buttons to move between worlds. Note that advanced addition world is not yet available in 1.07beta. Clicking "next world" once will take you to world 3, multiplication world. You won't need to know any new tactics to prove the big theorem `a * b = b * a` and get the `comm_semiring` collectible. -/ /- Lemma For all natural numbers $a, b$ and $c$, we have $$ a + b + c = a + c + b. $$ -/ lemma add_right_comm (a b c : mynat) : a + b + c = a + c + b := begin [less_leaky] rw add_assoc, rw add_comm b c, rw ←add_assoc, refl, end /- If you have got this far, then you have become very good at manipulating equalities in Lean. You have also collected four collectibles: ``` mynat.add_semigroup -- (after world 2-2) mynat.add_monoid -- (after world 2-2) mynat.add_comm_semigroup mynat (after world 2-4) mynat.add_comm_monoid -- (after world 2-4) ``` In Multiplication World you will be able to collect such advanced collectibles as `mynat.comm_semiring` and `mynat.distrib`, and then move on to power world and the famous collectible at the end of it. One last thing -- didn't you think that solving this level `add_right_comm` was boring? check out this AI that can do it for us. First we have to get the `add_comm_monoid` collectible, which we do by saying the magic words which make Lean's type class inference system give it to us. -/ instance : add_comm_monoid mynat := by structure_helper /- Tactic : simp The `simp` tactic does basic automation. By level 2-6 you have proved enough about addition for `simp` to be able to solve all equalities whose proofs involve a tedious number of rewrites of `add_assoc` and `add_comm`, and by level 3-9 the same is true of `mul_assoc` and `mul_comm`. ### Example: If our goal is this: ``` ⊢ a + b + c + d + e = c + (b + e + a) + d ``` and you are after level 2-6, then you've proved enough about addition to solve this level with `simp`. Note however that you can't prove `add_assoc` with `simp`, because `add_assoc` is an ingredient to get `simp` working. ### Example: If our goal is this: ``` ⊢ a * b * c = c * b * a ``` then as long as you're after 3-9, `simp` will close this goal. -/ /- Now the `simp` AI becomes accessible (it's just an advanced tactic really), and can nail some really tedious-for-a-human-to-solve goals. -/ example (a b c d e : mynat) : (((a+b)+c)+d)+e=(c+((b+e)+a))+d := begin simp end /- Imagine having to do that one by hand! The AI closes the goal because it knows how to use associativity and commutativity sensibly in a commutative monoid. -/ end mynat -- hide
3310e901735ef60644681b22aeef8508a1d00308
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/imo/imo2011_q5.lean
5bb51b977d729c2c110d5fdd9cac04baed31c59a
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,198
lean
/- Copyright (c) 2021 Alain Verberkmoes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alain Verberkmoes -/ import data.int.dvd.basic /-! # IMO 2011 Q5 > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Let `f` be a function from the set of integers to the set of positive integers. Suppose that, for any two integers `m` and `n`, the difference `f(m) - f(n)` is divisible by `f(m - n)`. Prove that, for all integers `m` and `n` with `f(m) ≤ f(n)`, the number `f(n)` is divisible by `f(m)`. -/ open int theorem imo2011_q5 (f : ℤ → ℤ) (hpos : ∀ n : ℤ, 0 < f n) (hdvd : ∀ m n : ℤ, f (m - n) ∣ f m - f n) : ∀ m n : ℤ, f m ≤ f n → f m ∣ f n := begin intros m n h_fm_le_fn, cases lt_or_eq_of_le h_fm_le_fn with h_fm_lt_fn h_fm_eq_fn, { -- m < n let d := f m - f (m - n), have h_fn_dvd_d : f n ∣ d, { rw ←sub_sub_self m n, exact hdvd m (m - n) }, have h_d_lt_fn : d < f n, { calc d < f m : sub_lt_self _ (hpos (m - n)) ... < f n : h_fm_lt_fn }, have h_neg_d_lt_fn : -d < f n, { calc -d = f (m - n) - f m : neg_sub _ _ ... < f (m - n) : sub_lt_self _ (hpos m) ... ≤ f n - f m : le_of_dvd (sub_pos.mpr h_fm_lt_fn) _ ... < f n : sub_lt_self _ (hpos m), -- ⊢ f (m - n) ∣ f n - f m rw [←dvd_neg, neg_sub], exact hdvd m n }, have h_d_eq_zero : d = 0, { obtain (hd | hd | hd) : d > 0 ∨ d = 0 ∨ d < 0 := trichotomous d 0, { -- d > 0 have h₁ : f n ≤ d, from le_of_dvd hd h_fn_dvd_d, have h₂ : ¬ f n ≤ d, from not_le.mpr h_d_lt_fn, contradiction }, { -- d = 0 exact hd }, { -- d < 0 have h₁ : f n ≤ -d, from le_of_dvd (neg_pos.mpr hd) h_fn_dvd_d.neg_right, have h₂ : ¬ f n ≤ -d, from not_le.mpr h_neg_d_lt_fn, contradiction } }, have h₁ : f m = f (m - n), from sub_eq_zero.mp h_d_eq_zero, have h₂ : f (m - n) ∣ f m - f n, from hdvd m n, rw ←h₁ at h₂, exact (dvd_iff_dvd_of_dvd_sub h₂).mp dvd_rfl }, { -- m = n rw h_fm_eq_fn } end
31e294e7d82fa0e73ed0082a19b1f3c46555e928
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/subobject/factor_thru.lean
adf579d3ea797aef0facf85c74806bc40e97b42a
[ "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
7,177
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Scott Morrison -/ import category_theory.subobject.basic import category_theory.preadditive /-! # Factoring through subobjects The predicate `h : P.factors f`, for `P : subobject Y` and `f : X ⟶ Y` asserts the existence of some `P.factor_thru f : X ⟶ (P : C)` making the obvious diagram commute. -/ universes v₁ v₂ u₁ u₂ noncomputable theory open category_theory category_theory.category category_theory.limits variables {C : Type u₁} [category.{v₁} C] {X Y Z : C} variables {D : Type u₂} [category.{v₂} D] namespace category_theory namespace mono_over /-- When `f : X ⟶ Y` and `P : mono_over Y`, `P.factors f` expresses that there exists a factorisation of `f` through `P`. Given `h : P.factors f`, you can recover the morphism as `P.factor_thru f h`. -/ def factors {X Y : C} (P : mono_over Y) (f : X ⟶ Y) : Prop := ∃ g : X ⟶ (P : C), g ≫ P.arrow = f lemma factors_congr {X : C} {f g : mono_over X} {Y : C} (h : Y ⟶ X) (e : f ≅ g) : f.factors h ↔ g.factors h := ⟨λ ⟨u, hu⟩, ⟨u ≫ (((mono_over.forget _).map e.hom)).left, by simp [hu]⟩, λ ⟨u, hu⟩, ⟨u ≫ (((mono_over.forget _).map e.inv)).left, by simp [hu]⟩⟩ /-- `P.factor_thru f h` provides a factorisation of `f : X ⟶ Y` through some `P : mono_over Y`, given the evidence `h : P.factors f` that such a factorisation exists. -/ def factor_thru {X Y : C} (P : mono_over Y) (f : X ⟶ Y) (h : factors P f) : X ⟶ (P : C) := classical.some h end mono_over namespace subobject /-- When `f : X ⟶ Y` and `P : subobject Y`, `P.factors f` expresses that there exists a factorisation of `f` through `P`. Given `h : P.factors f`, you can recover the morphism as `P.factor_thru f h`. -/ def factors {X Y : C} (P : subobject Y) (f : X ⟶ Y) : Prop := quotient.lift_on' P (λ P, P.factors f) begin rintros P Q ⟨h⟩, apply propext, split, { rintro ⟨i, w⟩, exact ⟨i ≫ h.hom.left, by erw [category.assoc, over.w h.hom, w]⟩, }, { rintro ⟨i, w⟩, exact ⟨i ≫ h.inv.left, by erw [category.assoc, over.w h.inv, w]⟩, }, end @[simp] lemma mk_factors_iff {X Y Z : C} (f : Y ⟶ X) [mono f] (g : Z ⟶ X) : (subobject.mk f).factors g ↔ (mono_over.mk' f).factors g := iff.rfl lemma mk_factors_self (f : X ⟶ Y) [mono f] : (mk f).factors f := ⟨𝟙 _, by simp⟩ lemma factors_iff {X Y : C} (P : subobject Y) (f : X ⟶ Y) : P.factors f ↔ (representative.obj P).factors f := quot.induction_on P $ λ a, mono_over.factors_congr _ (representative_iso _).symm lemma factors_self {X : C} (P : subobject X) : P.factors P.arrow := (factors_iff _ _).mpr ⟨𝟙 P, (by simp)⟩ lemma factors_comp_arrow {X Y : C} {P : subobject Y} (f : X ⟶ P) : P.factors (f ≫ P.arrow) := (factors_iff _ _).mpr ⟨f, rfl⟩ lemma factors_of_factors_right {X Y Z : C} {P : subobject Z} (f : X ⟶ Y) {g : Y ⟶ Z} (h : P.factors g) : P.factors (f ≫ g) := begin revert P, refine quotient.ind' _, intro P, rintro ⟨g, rfl⟩, exact ⟨f ≫ g, by simp⟩, end lemma factors_zero [has_zero_morphisms C] {X Y : C} {P : subobject Y} : P.factors (0 : X ⟶ Y) := (factors_iff _ _).mpr ⟨0, by simp⟩ lemma factors_of_le {Y Z : C} {P Q : subobject Y} (f : Z ⟶ Y) (h : P ≤ Q) : P.factors f → Q.factors f := by { simp only [factors_iff], exact λ ⟨u, hu⟩, ⟨u ≫ of_le _ _ h, by simp [←hu]⟩ } /-- `P.factor_thru f h` provides a factorisation of `f : X ⟶ Y` through some `P : subobject Y`, given the evidence `h : P.factors f` that such a factorisation exists. -/ def factor_thru {X Y : C} (P : subobject Y) (f : X ⟶ Y) (h : factors P f) : X ⟶ P := classical.some ((factors_iff _ _).mp h) @[simp, reassoc] lemma factor_thru_arrow {X Y : C} (P : subobject Y) (f : X ⟶ Y) (h : factors P f) : P.factor_thru f h ≫ P.arrow = f := classical.some_spec ((factors_iff _ _).mp h) @[simp] lemma factor_thru_self {X : C} (P : subobject X) (h) : P.factor_thru P.arrow h = 𝟙 P := by { ext, simp, } @[simp] lemma factor_thru_mk_self (f : X ⟶ Y) [mono f] : (mk f).factor_thru f (mk_factors_self f) = (underlying_iso f).inv := by { ext, simp, } @[simp] lemma factor_thru_comp_arrow {X Y : C} {P : subobject Y} (f : X ⟶ P) (h) : P.factor_thru (f ≫ P.arrow) h = f := by { ext, simp, } @[simp] lemma factor_thru_eq_zero [has_zero_morphisms C] {X Y : C} {P : subobject Y} {f : X ⟶ Y} {h : factors P f} : P.factor_thru f h = 0 ↔ f = 0 := begin fsplit, { intro w, replace w := w =≫ P.arrow, simpa using w, }, { rintro rfl, ext, simp, }, end lemma factor_thru_right {X Y Z : C} {P : subobject Z} (f : X ⟶ Y) (g : Y ⟶ Z) (h : P.factors g) : f ≫ P.factor_thru g h = P.factor_thru (f ≫ g) (factors_of_factors_right f h) := begin apply (cancel_mono P.arrow).mp, simp, end @[simp] lemma factor_thru_zero [has_zero_morphisms C] {X Y : C} {P : subobject Y} (h : P.factors (0 : X ⟶ Y)) : P.factor_thru 0 h = 0 := by simp -- `h` is an explicit argument here so we can use -- `rw factor_thru_le h`, obtaining a subgoal `P.factors f`. -- (While the reverse direction looks plausible as a simp lemma, it seems to be unproductive.) lemma factor_thru_of_le {Y Z : C} {P Q : subobject Y} {f : Z ⟶ Y} (h : P ≤ Q) (w : P.factors f) : Q.factor_thru f (factors_of_le f h w) = P.factor_thru f w ≫ of_le P Q h := by { ext, simp, } section preadditive variables [preadditive C] lemma factors_add {X Y : C} {P : subobject Y} (f g : X ⟶ Y) (wf : P.factors f) (wg : P.factors g) : P.factors (f + g) := (factors_iff _ _).mpr ⟨P.factor_thru f wf + P.factor_thru g wg, by simp⟩ -- This can't be a `simp` lemma as `wf` and `wg` may not exist. -- However you can `rw` by it to assert that `f` and `g` factor through `P` separately. lemma factor_thru_add {X Y : C} {P : subobject Y} (f g : X ⟶ Y) (w : P.factors (f + g)) (wf : P.factors f) (wg : P.factors g) : P.factor_thru (f + g) w = P.factor_thru f wf + P.factor_thru g wg := by { ext, simp, } lemma factors_left_of_factors_add {X Y : C} {P : subobject Y} (f g : X ⟶ Y) (w : P.factors (f + g)) (wg : P.factors g) : P.factors f := (factors_iff _ _).mpr ⟨P.factor_thru (f + g) w - P.factor_thru g wg, by simp⟩ @[simp] lemma factor_thru_add_sub_factor_thru_right {X Y : C} {P : subobject Y} (f g : X ⟶ Y) (w : P.factors (f + g)) (wg : P.factors g) : P.factor_thru (f + g) w - P.factor_thru g wg = P.factor_thru f (factors_left_of_factors_add f g w wg) := by { ext, simp, } lemma factors_right_of_factors_add {X Y : C} {P : subobject Y} (f g : X ⟶ Y) (w : P.factors (f + g)) (wf : P.factors f) : P.factors g := (factors_iff _ _).mpr ⟨P.factor_thru (f + g) w - P.factor_thru f wf, by simp⟩ @[simp] lemma factor_thru_add_sub_factor_thru_left {X Y : C} {P : subobject Y} (f g : X ⟶ Y) (w : P.factors (f + g)) (wf : P.factors f) : P.factor_thru (f + g) w - P.factor_thru f wf = P.factor_thru g (factors_right_of_factors_add f g w wf) := by { ext, simp, } end preadditive end subobject end category_theory
067694aa5e7b8259ca77646b1ed432c914f91f4e
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/trace.lean
d03c295fd3b51643dfbd5e07440845d70bd889dc
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,488
lean
import Lean.CoreM open Lean structure MyState := (traceState : TraceState := {}) (s : Nat := 0) abbrev M := CoreM def tst1 : M Unit := do trace[module] (m!"hello" ++ MessageData.nest 9 (m!"\n" ++ "world")); trace[module.aux] "another message"; pure () def tst2 (b : Bool) : M Unit := traceCtx `module $ do tst1; trace[bughunt] "at test2"; if b then throwError "error"; tst1; pure () partial def ack : Nat → Nat → Nat | 0, n => n+1 | m+1, 0 => ack m 1 | m+1, n+1 => ack m (ack (m+1) n) def slow (b : Bool) : Nat := ack 4 (cond b 0 1) def tst3 (b : Bool) : M Unit := do traceCtx `module $ do { tst2 b; tst1 }; trace[bughunt] "at end of tst3"; -- Messages are computed lazily. The following message will only be computed -- if `trace.slow is active. trace[slow] (m!"slow message: " ++ toString (slow b)) -- This is true even if it is a monad computation: trace[slow] (m!"slow message: " ++ (← toString (slow b))) def run (x : M Unit) : M Unit := withReader (fun ctx => -- Try commeting/uncommeting the following `setBool`s let opts := ctx.options; let opts := opts.setBool `trace.module true; -- let opts := opts.setBool `trace.module.aux false; let opts := opts.setBool `trace.bughunt true; -- let opts := opts.setBool `trace.slow true; { ctx with options := opts }) (tryCatch (tryFinally x printTraces) (fun _ => IO.println "ERROR")) #eval run (tst3 true) #eval run (tst3 false)
99cdb740a00b0de0f4f17d368e53d6f9ebe68db4
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/limits/shapes/pullbacks.lean
1f0e6bc85aad4a4ec7591bc5a4466014ecc6fdab
[ "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
90,304
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Markus Himmel, Bhavik Mehta, Andrew Yang -/ import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.binary_products /-! # Pullbacks We define a category `walking_cospan` (resp. `walking_span`), which is the index category for the given data for a pullback (resp. pushout) diagram. Convenience methods `cospan f g` and `span f g` construct functors from the walking (co)span, hitting the given morphisms. We define `pullback f g` and `pushout f g` as limits and colimits of such functors. ## References * [Stacks: Fibre products](https://stacks.math.columbia.edu/tag/001U) * [Stacks: Pushouts](https://stacks.math.columbia.edu/tag/0025) -/ noncomputable theory open category_theory namespace category_theory.limits universes v₁ v₂ v u u₂ local attribute [tidy] tactic.case_bash /-- The type of objects for the diagram indexing a pullback, defined as a special case of `wide_pullback_shape`. -/ abbreviation walking_cospan : Type v := wide_pullback_shape walking_pair /-- The left point of the walking cospan. -/ @[pattern] abbreviation walking_cospan.left : walking_cospan := some walking_pair.left /-- The right point of the walking cospan. -/ @[pattern] abbreviation walking_cospan.right : walking_cospan := some walking_pair.right /-- The central point of the walking cospan. -/ @[pattern] abbreviation walking_cospan.one : walking_cospan := none /-- The type of objects for the diagram indexing a pushout, defined as a special case of `wide_pushout_shape`. -/ abbreviation walking_span : Type v := wide_pushout_shape walking_pair /-- The left point of the walking span. -/ @[pattern] abbreviation walking_span.left : walking_span := some walking_pair.left /-- The right point of the walking span. -/ @[pattern] abbreviation walking_span.right : walking_span := some walking_pair.right /-- The central point of the walking span. -/ @[pattern] abbreviation walking_span.zero : walking_span := none namespace walking_cospan /-- The type of arrows for the diagram indexing a pullback. -/ abbreviation hom : walking_cospan → walking_cospan → Type v := wide_pullback_shape.hom /-- The left arrow of the walking cospan. -/ @[pattern] abbreviation hom.inl : left ⟶ one := wide_pullback_shape.hom.term _ /-- The right arrow of the walking cospan. -/ @[pattern] abbreviation hom.inr : right ⟶ one := wide_pullback_shape.hom.term _ /-- The identity arrows of the walking cospan. -/ @[pattern] abbreviation hom.id (X : walking_cospan) : X ⟶ X := wide_pullback_shape.hom.id X instance (X Y : walking_cospan) : subsingleton (X ⟶ Y) := by tidy end walking_cospan namespace walking_span /-- The type of arrows for the diagram indexing a pushout. -/ abbreviation hom : walking_span → walking_span → Type v := wide_pushout_shape.hom /-- The left arrow of the walking span. -/ @[pattern] abbreviation hom.fst : zero ⟶ left := wide_pushout_shape.hom.init _ /-- The right arrow of the walking span. -/ @[pattern] abbreviation hom.snd : zero ⟶ right := wide_pushout_shape.hom.init _ /-- The identity arrows of the walking span. -/ @[pattern] abbreviation hom.id (X : walking_span) : X ⟶ X := wide_pushout_shape.hom.id X instance (X Y : walking_span) : subsingleton (X ⟶ Y) := by tidy end walking_span section open walking_cospan /-- The functor between two `walking_cospan`s in different universes. -/ def walking_cospan_functor : walking_cospan.{v₁} ⥤ walking_cospan.{v₂} := { obj := by { rintro (_|_|_), exacts [one, left, right] }, map := by { rintro _ _ (_|_|_), exacts [hom.id _, hom.inl, hom.inr] }, map_id' := λ X, rfl, map_comp' := λ _ _ _ _ _, subsingleton.elim _ _ } @[simp] lemma walking_cospan_functor_one : walking_cospan_functor.obj one = one := rfl @[simp] lemma walking_cospan_functor_left : walking_cospan_functor.obj left = left := rfl @[simp] lemma walking_cospan_functor_right : walking_cospan_functor.obj right = right := rfl @[simp] lemma walking_cospan_functor_id (X) : walking_cospan_functor.map (𝟙 X) = 𝟙 _ := rfl @[simp] lemma walking_cospan_functor_inl : walking_cospan_functor.map hom.inl = hom.inl := rfl @[simp] lemma walking_cospan_functor_inr : walking_cospan_functor.map hom.inr = hom.inr := rfl /-- The equivalence between two `walking_cospan`s in different universes. -/ def walking_cospan_equiv : walking_cospan.{v₁} ≌ walking_cospan.{v₂} := { functor := walking_cospan_functor, inverse := walking_cospan_functor, unit_iso := nat_iso.of_components (λ x, eq_to_iso (by { rcases x with (_|_|_); refl })) (by { rintros _ _ (_|_|_); simp }), counit_iso := nat_iso.of_components (λ x, eq_to_iso (by { rcases x with (_|_|_); refl })) (by { rintros _ _ (_|_|_); simp }) } end section open walking_span /-- The functor between two `walking_span`s in different universes. -/ def walking_span_functor : walking_span.{v₁} ⥤ walking_span.{v₂} := { obj := by { rintro (_|_|_), exacts [zero, left, right] }, map := by { rintro _ _ (_|_|_), exacts [hom.id _, hom.fst, hom.snd] }, map_id' := λ X, rfl, map_comp' := λ _ _ _ _ _, subsingleton.elim _ _ } @[simp] lemma walking_span_functor_zero : walking_span_functor.obj zero = zero := rfl @[simp] lemma walking_span_functor_left : walking_span_functor.obj left = left := rfl @[simp] lemma walking_span_functor_right : walking_span_functor.obj right = right := rfl @[simp] lemma walking_span_functor_id (X) : walking_span_functor.map (𝟙 X) = 𝟙 _ := rfl @[simp] lemma walking_span_functor_fst : walking_span_functor.map hom.fst = hom.fst := rfl @[simp] lemma walking_span_functor_snd : walking_span_functor.map hom.snd = hom.snd := rfl /-- The equivalence between two `walking_span`s in different universes. -/ def walking_span_equiv : walking_span.{v₁} ≌ walking_span.{v₂} := { functor := walking_span_functor, inverse := walking_span_functor, unit_iso := nat_iso.of_components (λ x, eq_to_iso (by { rcases x with (_|_|_); refl })) (by { rintros _ _ (_|_|_); simp }), counit_iso := nat_iso.of_components (λ x, eq_to_iso (by { rcases x with (_|_|_); refl })) (by { rintros _ _ (_|_|_); simp }) } end open walking_span.hom walking_cospan.hom wide_pullback_shape.hom wide_pushout_shape.hom variables {C : Type u} [category.{v} C] /-- `cospan f g` is the functor from the walking cospan hitting `f` and `g`. -/ def cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : walking_cospan ⥤ C := wide_pullback_shape.wide_cospan Z (λ j, walking_pair.cases_on j X Y) (λ j, walking_pair.cases_on j f g) /-- `span f g` is the functor from the walking span hitting `f` and `g`. -/ def span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : walking_span ⥤ C := wide_pushout_shape.wide_span X (λ j, walking_pair.cases_on j Y Z) (λ j, walking_pair.cases_on j f g) @[simp] lemma cospan_left {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.left = X := rfl @[simp] lemma span_left {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.left = Y := rfl @[simp] lemma cospan_right {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.right = Y := rfl @[simp] lemma span_right {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.right = Z := rfl @[simp] lemma cospan_one {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).obj walking_cospan.one = Z := rfl @[simp] lemma span_zero {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).obj walking_span.zero = X := rfl @[simp] lemma cospan_map_inl {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inl = f := rfl @[simp] lemma span_map_fst {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.fst = f := rfl @[simp] lemma cospan_map_inr {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : (cospan f g).map walking_cospan.hom.inr = g := rfl @[simp] lemma span_map_snd {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : (span f g).map walking_span.hom.snd = g := rfl lemma cospan_map_id {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) (w : walking_cospan) : (cospan f g).map (walking_cospan.hom.id w) = 𝟙 _ := rfl lemma span_map_id {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) (w : walking_span) : (span f g).map (walking_span.hom.id w) = 𝟙 _ := rfl /-- Every diagram indexing an pullback is naturally isomorphic (actually, equal) to a `cospan` -/ @[simps {rhs_md := semireducible}] def diagram_iso_cospan (F : walking_cospan ⥤ C) : F ≅ cospan (F.map inl) (F.map inr) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) /-- Every diagram indexing a pushout is naturally isomorphic (actually, equal) to a `span` -/ @[simps {rhs_md := semireducible}] def diagram_iso_span (F : walking_span ⥤ C) : F ≅ span (F.map fst) (F.map snd) := nat_iso.of_components (λ j, eq_to_iso (by tidy)) (by tidy) variables {D : Type*} [category.{v} D] /-- A functor applied to a cospan is a cospan. -/ def cospan_comp_iso (F : C ⥤ D) {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) : cospan f g ⋙ F ≅ cospan (F.map f) (F.map g) := nat_iso.of_components (by rintros (⟨⟩|⟨⟨⟩⟩); exact iso.refl _) (by rintros (⟨⟩|⟨⟨⟩⟩) (⟨⟩|⟨⟨⟩⟩) ⟨⟩; repeat { dsimp, simp, }) section variables (F : C ⥤ D) {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) @[simp] lemma cospan_comp_iso_app_left : (cospan_comp_iso F f g).app walking_cospan.left = iso.refl _ := rfl @[simp] lemma cospan_comp_iso_app_right : (cospan_comp_iso F f g).app walking_cospan.right = iso.refl _ := rfl @[simp] lemma cospan_comp_iso_app_one : (cospan_comp_iso F f g).app walking_cospan.one = iso.refl _ := rfl @[simp] lemma cospan_comp_iso_hom_app_left : (cospan_comp_iso F f g).hom.app walking_cospan.left = 𝟙 _ := rfl @[simp] lemma cospan_comp_iso_hom_app_right : (cospan_comp_iso F f g).hom.app walking_cospan.right = 𝟙 _ := rfl @[simp] lemma cospan_comp_iso_hom_app_one : (cospan_comp_iso F f g).hom.app walking_cospan.one = 𝟙 _ := rfl @[simp] lemma cospan_comp_iso_inv_app_left : (cospan_comp_iso F f g).inv.app walking_cospan.left = 𝟙 _ := rfl @[simp] lemma cospan_comp_iso_inv_app_right : (cospan_comp_iso F f g).inv.app walking_cospan.right = 𝟙 _ := rfl @[simp] lemma cospan_comp_iso_inv_app_one : (cospan_comp_iso F f g).inv.app walking_cospan.one = 𝟙 _ := rfl end /-- A functor applied to a span is a span. -/ def span_comp_iso (F : C ⥤ D) {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) : span f g ⋙ F ≅ span (F.map f) (F.map g) := nat_iso.of_components (by rintros (⟨⟩|⟨⟨⟩⟩); exact iso.refl _) (by rintros (⟨⟩|⟨⟨⟩⟩) (⟨⟩|⟨⟨⟩⟩) ⟨⟩; repeat { dsimp, simp, }) section variables (F : C ⥤ D) {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) @[simp] lemma span_comp_iso_app_left : (span_comp_iso F f g).app walking_span.left = iso.refl _ := rfl @[simp] lemma span_comp_iso_app_right : (span_comp_iso F f g).app walking_span.right = iso.refl _ := rfl @[simp] lemma span_comp_iso_app_zero : (span_comp_iso F f g).app walking_span.zero = iso.refl _ := rfl @[simp] lemma span_comp_iso_hom_app_left : (span_comp_iso F f g).hom.app walking_span.left = 𝟙 _ := rfl @[simp] lemma span_comp_iso_hom_app_right : (span_comp_iso F f g).hom.app walking_span.right = 𝟙 _ := rfl @[simp] lemma span_comp_iso_hom_app_zero : (span_comp_iso F f g).hom.app walking_span.zero = 𝟙 _ := rfl @[simp] lemma span_comp_iso_inv_app_left : (span_comp_iso F f g).inv.app walking_span.left = 𝟙 _ := rfl @[simp] lemma span_comp_iso_inv_app_right : (span_comp_iso F f g).inv.app walking_span.right = 𝟙 _ := rfl @[simp] lemma span_comp_iso_inv_app_zero : (span_comp_iso F f g).inv.app walking_span.zero = 𝟙 _ := rfl end section variables {X Y Z X' Y' Z' : C} (iX : X ≅ X') (iY : Y ≅ Y') (iZ : Z ≅ Z') section variables {f : X ⟶ Z} {g : Y ⟶ Z} {f' : X' ⟶ Z'} {g' : Y' ⟶ Z'} /-- Construct an isomorphism of cospans from components. -/ def cospan_ext (wf : iX.hom ≫ f' = f ≫ iZ.hom) (wg : iY.hom ≫ g' = g ≫ iZ.hom) : cospan f g ≅ cospan f' g' := nat_iso.of_components (by { rintros (⟨⟩|⟨⟨⟩⟩), exacts [iZ, iX, iY], }) (by rintros (⟨⟩|⟨⟨⟩⟩) (⟨⟩|⟨⟨⟩⟩) ⟨⟩; repeat { dsimp, simp [wf, wg], }) variables (wf : iX.hom ≫ f' = f ≫ iZ.hom) (wg : iY.hom ≫ g' = g ≫ iZ.hom) @[simp] lemma cospan_ext_app_left : (cospan_ext iX iY iZ wf wg).app walking_cospan.left = iX := by { dsimp [cospan_ext], simp, } @[simp] lemma cospan_ext_app_right : (cospan_ext iX iY iZ wf wg).app walking_cospan.right = iY := by { dsimp [cospan_ext], simp, } @[simp] lemma cospan_ext_app_one : (cospan_ext iX iY iZ wf wg).app walking_cospan.one = iZ := by { dsimp [cospan_ext], simp, } @[simp] lemma cospan_ext_hom_app_left : (cospan_ext iX iY iZ wf wg).hom.app walking_cospan.left = iX.hom := by { dsimp [cospan_ext], simp, } @[simp] lemma cospan_ext_hom_app_right : (cospan_ext iX iY iZ wf wg).hom.app walking_cospan.right = iY.hom := by { dsimp [cospan_ext], simp, } @[simp] lemma cospan_ext_hom_app_one : (cospan_ext iX iY iZ wf wg).hom.app walking_cospan.one = iZ.hom := by { dsimp [cospan_ext], simp, } @[simp] lemma cospan_ext_inv_app_left : (cospan_ext iX iY iZ wf wg).inv.app walking_cospan.left = iX.inv := by { dsimp [cospan_ext], simp, } @[simp] lemma cospan_ext_inv_app_right : (cospan_ext iX iY iZ wf wg).inv.app walking_cospan.right = iY.inv := by { dsimp [cospan_ext], simp, } @[simp] lemma cospan_ext_inv_app_one : (cospan_ext iX iY iZ wf wg).inv.app walking_cospan.one = iZ.inv := by { dsimp [cospan_ext], simp, } end section variables {f : X ⟶ Y} {g : X ⟶ Z} {f' : X' ⟶ Y'} {g' : X' ⟶ Z'} /-- Construct an isomorphism of spans from components. -/ def span_ext (wf : iX.hom ≫ f' = f ≫ iY.hom) (wg : iX.hom ≫ g' = g ≫ iZ.hom) : span f g ≅ span f' g' := nat_iso.of_components (by { rintros (⟨⟩|⟨⟨⟩⟩), exacts [iX, iY, iZ], }) (by rintros (⟨⟩|⟨⟨⟩⟩) (⟨⟩|⟨⟨⟩⟩) ⟨⟩; repeat { dsimp, simp [wf, wg], }) variables (wf : iX.hom ≫ f' = f ≫ iY.hom) (wg : iX.hom ≫ g' = g ≫ iZ.hom) @[simp] lemma span_ext_app_left : (span_ext iX iY iZ wf wg).app walking_span.left = iY := by { dsimp [span_ext], simp, } @[simp] lemma span_ext_app_right : (span_ext iX iY iZ wf wg).app walking_span.right = iZ := by { dsimp [span_ext], simp, } @[simp] lemma span_ext_app_one : (span_ext iX iY iZ wf wg).app walking_span.zero = iX := by { dsimp [span_ext], simp, } @[simp] lemma span_ext_hom_app_left : (span_ext iX iY iZ wf wg).hom.app walking_span.left = iY.hom := by { dsimp [span_ext], simp, } @[simp] lemma span_ext_hom_app_right : (span_ext iX iY iZ wf wg).hom.app walking_span.right = iZ.hom := by { dsimp [span_ext], simp, } @[simp] lemma span_ext_hom_app_zero : (span_ext iX iY iZ wf wg).hom.app walking_span.zero = iX.hom := by { dsimp [span_ext], simp, } @[simp] lemma span_ext_inv_app_left : (span_ext iX iY iZ wf wg).inv.app walking_span.left = iY.inv := by { dsimp [span_ext], simp, } @[simp] lemma span_ext_inv_app_right : (span_ext iX iY iZ wf wg).inv.app walking_span.right = iZ.inv := by { dsimp [span_ext], simp, } @[simp] lemma span_ext_inv_app_zero : (span_ext iX iY iZ wf wg).inv.app walking_span.zero = iX.inv := by { dsimp [span_ext], simp, } end end variables {W X Y Z : C} /-- A pullback cone is just a cone on the cospan formed by two morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`.-/ abbreviation pullback_cone (f : X ⟶ Z) (g : Y ⟶ Z) := cone (cospan f g) namespace pullback_cone variables {f : X ⟶ Z} {g : Y ⟶ Z} /-- The first projection of a pullback cone. -/ abbreviation fst (t : pullback_cone f g) : t.X ⟶ X := t.π.app walking_cospan.left /-- The second projection of a pullback cone. -/ abbreviation snd (t : pullback_cone f g) : t.X ⟶ Y := t.π.app walking_cospan.right /-- This is a slightly more convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content -/ def is_limit_aux (t : pullback_cone f g) (lift : Π (s : pullback_cone f g), s.X ⟶ t.X) (fac_left : ∀ (s : pullback_cone f g), lift s ≫ t.fst = s.fst) (fac_right : ∀ (s : pullback_cone f g), lift s ≫ t.snd = s.snd) (uniq : ∀ (s : pullback_cone f g) (m : s.X ⟶ t.X) (w : ∀ j : walking_cospan, m ≫ t.π.app j = s.π.app j), m = lift s) : is_limit t := { lift := lift, fac' := λ s j, option.cases_on j (by { rw [← s.w inl, ← t.w inl, ←category.assoc], congr, exact fac_left s, } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pullback cone is a limit cone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_limit_aux' (t : pullback_cone f g) (create : Π (s : pullback_cone f g), {l // l ≫ t.fst = s.fst ∧ l ≫ t.snd = s.snd ∧ ∀ {m}, m ≫ t.fst = s.fst → m ≫ t.snd = s.snd → m = l}) : limits.is_limit t := pullback_cone.is_limit_aux t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pullback cone on `f` and `g` is determined by morphisms `fst : W ⟶ X` and `snd : W ⟶ Y` such that `fst ≫ f = snd ≫ g`. -/ @[simps] def mk {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : pullback_cone f g := { X := W, π := { app := λ j, option.cases_on j (fst ≫ f) (λ j', walking_pair.cases_on j' fst snd) } } @[simp] lemma mk_π_app_left {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.left = fst := rfl @[simp] lemma mk_π_app_right {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.right = snd := rfl @[simp] lemma mk_π_app_one {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).π.app walking_cospan.one = fst ≫ f := rfl @[simp] lemma mk_fst {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).fst = fst := rfl @[simp] lemma mk_snd {W : C} (fst : W ⟶ X) (snd : W ⟶ Y) (eq : fst ≫ f = snd ≫ g) : (mk fst snd eq).snd = snd := rfl @[reassoc] lemma condition (t : pullback_cone f g) : fst t ≫ f = snd t ≫ g := (t.w inl).trans (t.w inr).symm /-- To check whether a morphism is equalized by the maps of a pullback cone, it suffices to check it for `fst t` and `snd t` -/ lemma equalizer_ext (t : pullback_cone f g) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : ∀ (j : walking_cospan), k ≫ t.π.app j = l ≫ t.π.app j | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w inl, reassoc_of h₀] lemma is_limit.hom_ext {t : pullback_cone f g} (ht : is_limit t) {W : C} {k l : W ⟶ t.X} (h₀ : k ≫ fst t = l ≫ fst t) (h₁ : k ≫ snd t = l ≫ snd t) : k = l := ht.hom_ext $ equalizer_ext _ h₀ h₁ lemma mono_snd_of_is_pullback_of_mono {t : pullback_cone f g} (ht : is_limit t) [mono f] : mono t.snd := ⟨λ W h k i, is_limit.hom_ext ht (by simp [←cancel_mono f, t.condition, reassoc_of i]) i⟩ lemma mono_fst_of_is_pullback_of_mono {t : pullback_cone f g} (ht : is_limit t) [mono g] : mono t.fst := ⟨λ W h k i, is_limit.hom_ext ht i (by simp [←cancel_mono g, ←t.condition, reassoc_of i])⟩ /-- If `t` is a limit pullback cone over `f` and `g` and `h : W ⟶ X` and `k : W ⟶ Y` are such that `h ≫ f = k ≫ g`, then we have `l : W ⟶ t.X` satisfying `l ≫ fst t = h` and `l ≫ snd t = k`. -/ def is_limit.lift' {t : pullback_cone f g} (ht : is_limit t) {W : C} (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ t.X // l ≫ fst t = h ∧ l ≫ snd t = k} := ⟨ht.lift $ pullback_cone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ /-- This is a more convenient formulation to show that a `pullback_cone` constructed using `pullback_cone.mk` is a limit cone. -/ def is_limit.mk {W : C} {fst : W ⟶ X} {snd : W ⟶ Y} (eq : fst ≫ f = snd ≫ g) (lift : Π (s : pullback_cone f g), s.X ⟶ W) (fac_left : ∀ (s : pullback_cone f g), lift s ≫ fst = s.fst) (fac_right : ∀ (s : pullback_cone f g), lift s ≫ snd = s.snd) (uniq : ∀ (s : pullback_cone f g) (m : s.X ⟶ W) (w_fst : m ≫ fst = s.fst) (w_snd : m ≫ snd = s.snd), m = lift s) : is_limit (mk fst snd eq) := is_limit_aux _ lift fac_left fac_right (λ s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pullback square is a pullback square. -/ def flip_is_limit {W : C} {h : W ⟶ X} {k : W ⟶ Y} {comm : h ≫ f = k ≫ g} (t : is_limit (mk _ _ comm.symm)) : is_limit (mk _ _ comm) := is_limit_aux' _ $ λ s, begin refine ⟨(is_limit.lift' t _ _ s.condition.symm).1, (is_limit.lift' t _ _ _).2.2, (is_limit.lift' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).equalizer_ext, { rwa (is_limit.lift' t _ _ _).2.1 }, { rwa (is_limit.lift' t _ _ _).2.2 }, end /-- The pullback cone `(𝟙 X, 𝟙 X)` for the pair `(f, f)` is a limit if `f` is a mono. The converse is shown in `mono_of_pullback_is_id`. -/ def is_limit_mk_id_id (f : X ⟶ Y) [mono f] : is_limit (mk (𝟙 X) (𝟙 X) rfl : pullback_cone f f) := is_limit.mk _ (λ s, s.fst) (λ s, category.comp_id _) (λ s, by rw [←cancel_mono f, category.comp_id, s.condition]) (λ s m m₁ m₂, by simpa using m₁) /-- `f` is a mono if the pullback cone `(𝟙 X, 𝟙 X)` is a limit for the pair `(f, f)`. The converse is given in `pullback_cone.is_id_of_mono`. -/ lemma mono_of_is_limit_mk_id_id (f : X ⟶ Y) (t : is_limit (mk (𝟙 X) (𝟙 X) rfl : pullback_cone f f)) : mono f := ⟨λ Z g h eq, by { rcases pullback_cone.is_limit.lift' t _ _ eq with ⟨_, rfl, rfl⟩, refl } ⟩ /-- Suppose `f` and `g` are two morphisms with a common codomain and `s` is a limit cone over the diagram formed by `f` and `g`. Suppose `f` and `g` both factor through a monomorphism `h` via `x` and `y`, respectively. Then `s` is also a limit cone over the diagram formed by `x` and `y`. -/ def is_limit_of_factors (f : X ⟶ Z) (g : Y ⟶ Z) (h : W ⟶ Z) [mono h] (x : X ⟶ W) (y : Y ⟶ W) (hxh : x ≫ h = f) (hyh : y ≫ h = g) (s : pullback_cone f g) (hs : is_limit s) : is_limit (pullback_cone.mk _ _ (show s.fst ≫ x = s.snd ≫ y, from (cancel_mono h).1 $ by simp only [category.assoc, hxh, hyh, s.condition])) := pullback_cone.is_limit_aux' _ $ λ t, ⟨hs.lift (pullback_cone.mk t.fst t.snd $ by rw [←hxh, ←hyh, reassoc_of t.condition]), ⟨hs.fac _ walking_cospan.left, hs.fac _ walking_cospan.right, λ r hr hr', begin apply pullback_cone.is_limit.hom_ext hs; simp only [pullback_cone.mk_fst, pullback_cone.mk_snd] at ⊢ hr hr'; simp only [hr, hr']; symmetry, exacts [hs.fac _ walking_cospan.left, hs.fac _ walking_cospan.right] end⟩⟩ /-- If `W` is the pullback of `f, g`, it is also the pullback of `f ≫ i, g ≫ i` for any mono `i`. -/ def is_limit_of_comp_mono (f : X ⟶ W) (g : Y ⟶ W) (i : W ⟶ Z) [mono i] (s : pullback_cone f g) (H : is_limit s) : is_limit (pullback_cone.mk _ _ (show s.fst ≫ f ≫ i = s.snd ≫ g ≫ i, by rw [← category.assoc, ← category.assoc, s.condition])) := begin apply pullback_cone.is_limit_aux', intro s, rcases pullback_cone.is_limit.lift' H s.fst s.snd ((cancel_mono i).mp (by simpa using s.condition)) with ⟨l, h₁, h₂⟩, refine ⟨l,h₁,h₂,_⟩, intros m hm₁ hm₂, exact (pullback_cone.is_limit.hom_ext H (hm₁.trans h₁.symm) (hm₂.trans h₂.symm) : _) end end pullback_cone /-- A pushout cocone is just a cocone on the span formed by two morphisms `f : X ⟶ Y` and `g : X ⟶ Z`.-/ abbreviation pushout_cocone (f : X ⟶ Y) (g : X ⟶ Z) := cocone (span f g) namespace pushout_cocone variables {f : X ⟶ Y} {g : X ⟶ Z} /-- The first inclusion of a pushout cocone. -/ abbreviation inl (t : pushout_cocone f g) : Y ⟶ t.X := t.ι.app walking_span.left /-- The second inclusion of a pushout cocone. -/ abbreviation inr (t : pushout_cocone f g) : Z ⟶ t.X := t.ι.app walking_span.right /-- This is a slightly more convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content -/ def is_colimit_aux (t : pushout_cocone f g) (desc : Π (s : pushout_cocone f g), t.X ⟶ s.X) (fac_left : ∀ (s : pushout_cocone f g), t.inl ≫ desc s = s.inl) (fac_right : ∀ (s : pushout_cocone f g), t.inr ≫ desc s = s.inr) (uniq : ∀ (s : pushout_cocone f g) (m : t.X ⟶ s.X) (w : ∀ j : walking_span, t.ι.app j ≫ m = s.ι.app j), m = desc s) : is_colimit t := { desc := desc, fac' := λ s j, option.cases_on j (by { simp [← s.w fst, ← t.w fst, fac_left s] } ) (λ j', walking_pair.cases_on j' (fac_left s) (fac_right s)), uniq' := uniq } /-- This is another convenient method to verify that a pushout cocone is a colimit cocone. It only asks for a proof of facts that carry any mathematical content, and allows access to the same `s` for all parts. -/ def is_colimit_aux' (t : pushout_cocone f g) (create : Π (s : pushout_cocone f g), {l // t.inl ≫ l = s.inl ∧ t.inr ≫ l = s.inr ∧ ∀ {m}, t.inl ≫ m = s.inl → t.inr ≫ m = s.inr → m = l}) : is_colimit t := is_colimit_aux t (λ s, (create s).1) (λ s, (create s).2.1) (λ s, (create s).2.2.1) (λ s m w, (create s).2.2.2 (w walking_cospan.left) (w walking_cospan.right)) /-- A pushout cocone on `f` and `g` is determined by morphisms `inl : Y ⟶ W` and `inr : Z ⟶ W` such that `f ≫ inl = g ↠ inr`. -/ @[simps] def mk {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : pushout_cocone f g := { X := W, ι := { app := λ j, option.cases_on j (f ≫ inl) (λ j', walking_pair.cases_on j' inl inr) } } @[simp] lemma mk_ι_app_left {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.left = inl := rfl @[simp] lemma mk_ι_app_right {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.right = inr := rfl @[simp] lemma mk_ι_app_zero {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).ι.app walking_span.zero = f ≫ inl := rfl @[simp] lemma mk_inl {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inl = inl := rfl @[simp] lemma mk_inr {W : C} (inl : Y ⟶ W) (inr : Z ⟶ W) (eq : f ≫ inl = g ≫ inr) : (mk inl inr eq).inr = inr := rfl @[reassoc] lemma condition (t : pushout_cocone f g) : f ≫ (inl t) = g ≫ (inr t) := (t.w fst).trans (t.w snd).symm /-- To check whether a morphism is coequalized by the maps of a pushout cocone, it suffices to check it for `inl t` and `inr t` -/ lemma coequalizer_ext (t : pushout_cocone f g) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : ∀ (j : walking_span), t.ι.app j ≫ k = t.ι.app j ≫ l | (some walking_pair.left) := h₀ | (some walking_pair.right) := h₁ | none := by rw [← t.w fst, category.assoc, category.assoc, h₀] lemma is_colimit.hom_ext {t : pushout_cocone f g} (ht : is_colimit t) {W : C} {k l : t.X ⟶ W} (h₀ : inl t ≫ k = inl t ≫ l) (h₁ : inr t ≫ k = inr t ≫ l) : k = l := ht.hom_ext $ coequalizer_ext _ h₀ h₁ /-- If `t` is a colimit pushout cocone over `f` and `g` and `h : Y ⟶ W` and `k : Z ⟶ W` are morphisms satisfying `f ≫ h = g ≫ k`, then we have a factorization `l : t.X ⟶ W` such that `inl t ≫ l = h` and `inr t ≫ l = k`. -/ def is_colimit.desc' {t : pushout_cocone f g} (ht : is_colimit t) {W : C} (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : t.X ⟶ W // inl t ≫ l = h ∧ inr t ≫ l = k } := ⟨ht.desc $ pushout_cocone.mk _ _ w, ht.fac _ _, ht.fac _ _⟩ lemma epi_inr_of_is_pushout_of_epi {t : pushout_cocone f g} (ht : is_colimit t) [epi f] : epi t.inr := ⟨λ W h k i, is_colimit.hom_ext ht (by simp [←cancel_epi f, t.condition_assoc, i]) i⟩ lemma epi_inl_of_is_pushout_of_epi {t : pushout_cocone f g} (ht : is_colimit t) [epi g] : epi t.inl := ⟨λ W h k i, is_colimit.hom_ext ht i (by simp [←cancel_epi g, ←t.condition_assoc, i])⟩ /-- This is a more convenient formulation to show that a `pushout_cocone` constructed using `pushout_cocone.mk` is a colimit cocone. -/ def is_colimit.mk {W : C} {inl : Y ⟶ W} {inr : Z ⟶ W} (eq : f ≫ inl = g ≫ inr) (desc : Π (s : pushout_cocone f g), W ⟶ s.X) (fac_left : ∀ (s : pushout_cocone f g), inl ≫ desc s = s.inl) (fac_right : ∀ (s : pushout_cocone f g), inr ≫ desc s = s.inr) (uniq : ∀ (s : pushout_cocone f g) (m : W ⟶ s.X) (w_inl : inl ≫ m = s.inl) (w_inr : inr ≫ m = s.inr), m = desc s) : is_colimit (mk inl inr eq) := is_colimit_aux _ desc fac_left fac_right (λ s m w, uniq s m (w walking_cospan.left) (w walking_cospan.right)) /-- The flip of a pushout square is a pushout square. -/ def flip_is_colimit {W : C} {h : Y ⟶ W} {k : Z ⟶ W} {comm : f ≫ h = g ≫ k} (t : is_colimit (mk _ _ comm.symm)) : is_colimit (mk _ _ comm) := is_colimit_aux' _ $ λ s, begin refine ⟨(is_colimit.desc' t _ _ s.condition.symm).1, (is_colimit.desc' t _ _ _).2.2, (is_colimit.desc' t _ _ _).2.1, λ m m₁ m₂, t.hom_ext _⟩, apply (mk k h _).coequalizer_ext, { rwa (is_colimit.desc' t _ _ _).2.1 }, { rwa (is_colimit.desc' t _ _ _).2.2 }, end /-- The pushout cocone `(𝟙 X, 𝟙 X)` for the pair `(f, f)` is a colimit if `f` is an epi. The converse is shown in `epi_of_is_colimit_mk_id_id`. -/ def is_colimit_mk_id_id (f : X ⟶ Y) [epi f] : is_colimit (mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f) := is_colimit.mk _ (λ s, s.inl) (λ s, category.id_comp _) (λ s, by rw [←cancel_epi f, category.id_comp, s.condition]) (λ s m m₁ m₂, by simpa using m₁) /-- `f` is an epi if the pushout cocone `(𝟙 X, 𝟙 X)` is a colimit for the pair `(f, f)`. The converse is given in `pushout_cocone.is_colimit_mk_id_id`. -/ lemma epi_of_is_colimit_mk_id_id (f : X ⟶ Y) (t : is_colimit (mk (𝟙 Y) (𝟙 Y) rfl : pushout_cocone f f)) : epi f := ⟨λ Z g h eq, by { rcases pushout_cocone.is_colimit.desc' t _ _ eq with ⟨_, rfl, rfl⟩, refl }⟩ /-- Suppose `f` and `g` are two morphisms with a common domain and `s` is a colimit cocone over the diagram formed by `f` and `g`. Suppose `f` and `g` both factor through an epimorphism `h` via `x` and `y`, respectively. Then `s` is also a colimit cocone over the diagram formed by `x` and `y`. -/ def is_colimit_of_factors (f : X ⟶ Y) (g : X ⟶ Z) (h : X ⟶ W) [epi h] (x : W ⟶ Y) (y : W ⟶ Z) (hhx : h ≫ x = f) (hhy : h ≫ y = g) (s : pushout_cocone f g) (hs : is_colimit s) : is_colimit (pushout_cocone.mk _ _ (show x ≫ s.inl = y ≫ s.inr, from (cancel_epi h).1 $ by rw [reassoc_of hhx, reassoc_of hhy, s.condition])) := pushout_cocone.is_colimit_aux' _ $ λ t, ⟨hs.desc (pushout_cocone.mk t.inl t.inr $ by rw [←hhx, ←hhy, category.assoc, category.assoc, t.condition]), ⟨hs.fac _ walking_span.left, hs.fac _ walking_span.right, λ r hr hr', begin apply pushout_cocone.is_colimit.hom_ext hs; simp only [pushout_cocone.mk_inl, pushout_cocone.mk_inr] at ⊢ hr hr'; simp only [hr, hr']; symmetry, exacts [hs.fac _ walking_span.left, hs.fac _ walking_span.right] end⟩⟩ /-- If `W` is the pushout of `f, g`, it is also the pushout of `h ≫ f, h ≫ g` for any epi `h`. -/ def is_colimit_of_epi_comp (f : X ⟶ Y) (g : X ⟶ Z) (h : W ⟶ X) [epi h] (s : pushout_cocone f g) (H : is_colimit s) : is_colimit (pushout_cocone.mk _ _ (show (h ≫ f) ≫ s.inl = (h ≫ g) ≫ s.inr, by rw [category.assoc, category.assoc, s.condition])) := begin apply pushout_cocone.is_colimit_aux', intro s, rcases pushout_cocone.is_colimit.desc' H s.inl s.inr ((cancel_epi h).mp (by simpa using s.condition)) with ⟨l, h₁, h₂⟩, refine ⟨l,h₁,h₂,_⟩, intros m hm₁ hm₂, exact (pushout_cocone.is_colimit.hom_ext H (hm₁.trans h₁.symm) (hm₂.trans h₂.symm) : _) end end pushout_cocone /-- This is a helper construction that can be useful when verifying that a category has all pullbacks. Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a pullback cone on `F.map inl` and `F.map inr`, we get a cone on `F`. If you're thinking about using this, have a look at `has_pullbacks_of_has_limit_cospan`, which you may find to be an easier way of achieving your goal. -/ @[simps] def cone.of_pullback_cone {F : walking_cospan ⥤ C} (t : pullback_cone (F.map inl) (F.map inr)) : cone F := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).inv } /-- This is a helper construction that can be useful when verifying that a category has all pushout. Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.mal snd)`, and a pushout cocone on `F.map fst` and `F.map snd`, we get a cocone on `F`. If you're thinking about using this, have a look at `has_pushouts_of_has_colimit_span`, which you may find to be an easiery way of achieving your goal. -/ @[simps] def cocone.of_pushout_cocone {F : walking_span ⥤ C} (t : pushout_cocone (F.map fst) (F.map snd)) : cocone F := { X := t.X, ι := (diagram_iso_span F).hom ≫ t.ι } /-- Given `F : walking_cospan ⥤ C`, which is really the same as `cospan (F.map inl) (F.map inr)`, and a cone on `F`, we get a pullback cone on `F.map inl` and `F.map inr`. -/ @[simps] def pullback_cone.of_cone {F : walking_cospan ⥤ C} (t : cone F) : pullback_cone (F.map inl) (F.map inr) := { X := t.X, π := t.π ≫ (diagram_iso_cospan F).hom } /-- A diagram `walking_cospan ⥤ C` is isomorphic to some `pullback_cone.mk` after composing with `diagram_iso_cospan`. -/ @[simps] def pullback_cone.iso_mk {F : walking_cospan ⥤ C} (t : cone F) : (cones.postcompose (diagram_iso_cospan.{v} _).hom).obj t ≅ pullback_cone.mk (t.π.app walking_cospan.left) (t.π.app walking_cospan.right) ((t.π.naturality inl).symm.trans (t.π.naturality inr : _)) := cones.ext (iso.refl _) $ by rintro (_|(_|_)); { dsimp, simp } /-- Given `F : walking_span ⥤ C`, which is really the same as `span (F.map fst) (F.map snd)`, and a cocone on `F`, we get a pushout cocone on `F.map fst` and `F.map snd`. -/ @[simps] def pushout_cocone.of_cocone {F : walking_span ⥤ C} (t : cocone F) : pushout_cocone (F.map fst) (F.map snd) := { X := t.X, ι := (diagram_iso_span F).inv ≫ t.ι } /-- A diagram `walking_span ⥤ C` is isomorphic to some `pushout_cocone.mk` after composing with `diagram_iso_span`. -/ @[simps] def pushout_cocone.iso_mk {F : walking_span ⥤ C} (t : cocone F) : (cocones.precompose (diagram_iso_span.{v} _).inv).obj t ≅ pushout_cocone.mk (t.ι.app walking_span.left) (t.ι.app walking_span.right) ((t.ι.naturality fst).trans (t.ι.naturality snd).symm) := cocones.ext (iso.refl _) $ by rintro (_|(_|_)); { dsimp, simp } /-- `has_pullback f g` represents a particular choice of limiting cone for the pair of morphisms `f : X ⟶ Z` and `g : Y ⟶ Z`. -/ abbreviation has_pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) := has_limit (cospan f g) /-- `has_pushout f g` represents a particular choice of colimiting cocone for the pair of morphisms `f : X ⟶ Y` and `g : X ⟶ Z`. -/ abbreviation has_pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) := has_colimit (span f g) /-- `pullback f g` computes the pullback of a pair of morphisms with the same target. -/ abbreviation pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] := limit (cospan f g) /-- `pushout f g` computes the pushout of a pair of morphisms with the same source. -/ abbreviation pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] := colimit (span f g) /-- The first projection of the pullback of `f` and `g`. -/ abbreviation pullback.fst {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : pullback f g ⟶ X := limit.π (cospan f g) walking_cospan.left /-- The second projection of the pullback of `f` and `g`. -/ abbreviation pullback.snd {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : pullback f g ⟶ Y := limit.π (cospan f g) walking_cospan.right /-- The first inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inl {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : Y ⟶ pushout f g := colimit.ι (span f g) walking_span.left /-- The second inclusion into the pushout of `f` and `g`. -/ abbreviation pushout.inr {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : Z ⟶ pushout f g := colimit.ι (span f g) walking_span.right /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `pullback.lift : W ⟶ pullback f g`. -/ abbreviation pullback.lift {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : W ⟶ pullback f g := limit.lift _ (pullback_cone.mk h k w) /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `pushout.desc : pushout f g ⟶ W`. -/ abbreviation pushout.desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout f g ⟶ W := colimit.desc _ (pushout_cocone.mk h k w) @[simp, reassoc] lemma pullback.lift_fst {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.fst = h := limit.lift_π _ _ @[simp, reassoc] lemma pullback.lift_snd {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : pullback.lift h k w ≫ pullback.snd = k := limit.lift_π _ _ @[simp, reassoc] lemma pushout.inl_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inl ≫ pushout.desc h k w = h := colimit.ι_desc _ _ @[simp, reassoc] lemma pushout.inr_desc {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : pushout.inr ≫ pushout.desc h k w = k := colimit.ι_desc _ _ /-- A pair of morphisms `h : W ⟶ X` and `k : W ⟶ Y` satisfying `h ≫ f = k ≫ g` induces a morphism `l : W ⟶ pullback f g` such that `l ≫ pullback.fst = h` and `l ≫ pullback.snd = k`. -/ def pullback.lift' {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] (h : W ⟶ X) (k : W ⟶ Y) (w : h ≫ f = k ≫ g) : {l : W ⟶ pullback f g // l ≫ pullback.fst = h ∧ l ≫ pullback.snd = k} := ⟨pullback.lift h k w, pullback.lift_fst _ _ _, pullback.lift_snd _ _ _⟩ /-- A pair of morphisms `h : Y ⟶ W` and `k : Z ⟶ W` satisfying `f ≫ h = g ≫ k` induces a morphism `l : pushout f g ⟶ W` such that `pushout.inl ≫ l = h` and `pushout.inr ≫ l = k`. -/ def pullback.desc' {W X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] (h : Y ⟶ W) (k : Z ⟶ W) (w : f ≫ h = g ≫ k) : {l : pushout f g ⟶ W // pushout.inl ≫ l = h ∧ pushout.inr ≫ l = k} := ⟨pushout.desc h k w, pushout.inl_desc _ _ _, pushout.inr_desc _ _ _⟩ @[reassoc] lemma pullback.condition {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] : (pullback.fst : pullback f g ⟶ X) ≫ f = pullback.snd ≫ g := pullback_cone.condition _ @[reassoc] lemma pushout.condition {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := pushout_cocone.condition _ /-- Given such a diagram, then there is a natural morphism `W ×ₛ X ⟶ Y ×ₜ Z`. W ⟶ Y ↘ ↘ S ⟶ T ↗ ↗ X ⟶ Z -/ abbreviation pullback.map {W X Y Z S T : C} (f₁ : W ⟶ S) (f₂ : X ⟶ S) [has_pullback f₁ f₂] (g₁ : Y ⟶ T) (g₂ : Z ⟶ T) [has_pullback g₁ g₂] (i₁ : W ⟶ Y) (i₂ : X ⟶ Z) (i₃ : S ⟶ T) (eq₁ : f₁ ≫ i₃ = i₁ ≫ g₁) (eq₂ : f₂ ≫ i₃ = i₂ ≫ g₂) : pullback f₁ f₂ ⟶ pullback g₁ g₂ := pullback.lift (pullback.fst ≫ i₁) (pullback.snd ≫ i₂) (by simp [← eq₁, ← eq₂, pullback.condition_assoc]) /-- Given such a diagram, then there is a natural morphism `W ⨿ₛ X ⟶ Y ⨿ₜ Z`. W ⟶ Y ↗ ↗ S ⟶ T ↘ ↘ X ⟶ Z -/ abbreviation pushout.map {W X Y Z S T : C} (f₁ : S ⟶ W) (f₂ : S ⟶ X) [has_pushout f₁ f₂] (g₁ : T ⟶ Y) (g₂ : T ⟶ Z) [has_pushout g₁ g₂] (i₁ : W ⟶ Y) (i₂ : X ⟶ Z) (i₃ : S ⟶ T) (eq₁ : f₁ ≫ i₁ = i₃ ≫ g₁) (eq₂ : f₂ ≫ i₂ = i₃ ≫ g₂) : pushout f₁ f₂ ⟶ pushout g₁ g₂ := pushout.desc (i₁ ≫ pushout.inl) (i₂ ≫ pushout.inr) (by { simp only [← category.assoc, eq₁, eq₂], simp [pushout.condition] }) /-- Two morphisms into a pullback are equal if their compositions with the pullback morphisms are equal -/ @[ext] lemma pullback.hom_ext {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] {W : C} {k l : W ⟶ pullback f g} (h₀ : k ≫ pullback.fst = l ≫ pullback.fst) (h₁ : k ≫ pullback.snd = l ≫ pullback.snd) : k = l := limit.hom_ext $ pullback_cone.equalizer_ext _ h₀ h₁ /-- The pullback cone built from the pullback projections is a pullback. -/ def pullback_is_pullback {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] : is_limit (pullback_cone.mk (pullback.fst : pullback f g ⟶ _) pullback.snd pullback.condition) := pullback_cone.is_limit.mk _ (λ s, pullback.lift s.fst s.snd s.condition) (by simp) (by simp) (by tidy) /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := pullback_cone.mono_fst_of_is_pullback_of_mono (limit.is_limit _) /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_pullback f g] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := pullback_cone.mono_snd_of_is_pullback_of_mono (limit.is_limit _) /-- The map `X ×[Z] Y ⟶ X × Y` is mono. -/ instance mono_pullback_to_prod {C : Type*} [category C] {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_binary_product X Y] : mono (prod.lift pullback.fst pullback.snd : pullback f g ⟶ _) := ⟨λ W i₁ i₂ h, begin ext, { simpa using congr_arg (λ f, f ≫ prod.fst) h }, { simpa using congr_arg (λ f, f ≫ prod.snd) h } end⟩ /-- Two morphisms out of a pushout are equal if their compositions with the pushout morphisms are equal -/ @[ext] lemma pushout.hom_ext {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] {W : C} {k l : pushout f g ⟶ W} (h₀ : pushout.inl ≫ k = pushout.inl ≫ l) (h₁ : pushout.inr ≫ k = pushout.inr ≫ l) : k = l := colimit.hom_ext $ pushout_cocone.coequalizer_ext _ h₀ h₁ /-- The pushout cocone built from the pushout coprojections is a pushout. -/ def pushout_is_pushout {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] : is_colimit (pushout_cocone.mk (pushout.inl : _ ⟶ pushout f g) pushout.inr pushout.condition) := pushout_cocone.is_colimit.mk _ (λ s, pushout.desc s.inl s.inr s.condition) (by simp) (by simp) (by tidy) /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := pushout_cocone.epi_inl_of_is_pushout_of_epi (colimit.is_colimit _) /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_pushout f g] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := pushout_cocone.epi_inr_of_is_pushout_of_epi (colimit.is_colimit _) /-- The map ` X ⨿ Y ⟶ X ⨿[Z] Y` is epi. -/ instance epi_coprod_to_pushout {C : Type*} [category C] {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] [has_binary_coproduct Y Z] : epi (coprod.desc pushout.inl pushout.inr : _ ⟶ pushout f g) := ⟨λ W i₁ i₂ h, begin ext, { simpa using congr_arg (λ f, coprod.inl ≫ f) h }, { simpa using congr_arg (λ f, coprod.inr ≫ f) h } end⟩ instance pullback.map_is_iso {W X Y Z S T : C} (f₁ : W ⟶ S) (f₂ : X ⟶ S) [has_pullback f₁ f₂] (g₁ : Y ⟶ T) (g₂ : Z ⟶ T) [has_pullback g₁ g₂] (i₁ : W ⟶ Y) (i₂ : X ⟶ Z) (i₃ : S ⟶ T) (eq₁ : f₁ ≫ i₃ = i₁ ≫ g₁) (eq₂ : f₂ ≫ i₃ = i₂ ≫ g₂) [is_iso i₁] [is_iso i₂] [is_iso i₃] : is_iso (pullback.map f₁ f₂ g₁ g₂ i₁ i₂ i₃ eq₁ eq₂) := begin refine ⟨⟨pullback.map _ _ _ _ (inv i₁) (inv i₂) (inv i₃) _ _, _, _⟩⟩, { rw [is_iso.comp_inv_eq, category.assoc, eq₁, is_iso.inv_hom_id_assoc] }, { rw [is_iso.comp_inv_eq, category.assoc, eq₂, is_iso.inv_hom_id_assoc] }, tidy end /-- If `f₁ = f₂` and `g₁ = g₂`, we may construct a canonical isomorphism `pullback f₁ g₁ ≅ pullback f₂ g₂` -/ @[simps hom] def pullback.congr_hom {X Y Z : C} {f₁ f₂ : X ⟶ Z} {g₁ g₂ : Y ⟶ Z} (h₁ : f₁ = f₂) (h₂ : g₁ = g₂) [has_pullback f₁ g₁] [has_pullback f₂ g₂] : pullback f₁ g₁ ≅ pullback f₂ g₂ := as_iso $ pullback.map _ _ _ _ (𝟙 _) (𝟙 _) (𝟙 _) (by simp [h₁]) (by simp [h₂]) @[simp] lemma pullback.congr_hom_inv {X Y Z : C} {f₁ f₂ : X ⟶ Z} {g₁ g₂ : Y ⟶ Z} (h₁ : f₁ = f₂) (h₂ : g₁ = g₂) [has_pullback f₁ g₁] [has_pullback f₂ g₂] : (pullback.congr_hom h₁ h₂).inv = pullback.map _ _ _ _ (𝟙 _) (𝟙 _) (𝟙 _) (by simp [h₁]) (by simp [h₂]) := begin apply pullback.hom_ext, { erw pullback.lift_fst, rw iso.inv_comp_eq, erw pullback.lift_fst_assoc, rw [category.comp_id, category.comp_id] }, { erw pullback.lift_snd, rw iso.inv_comp_eq, erw pullback.lift_snd_assoc, rw [category.comp_id, category.comp_id] }, end instance pushout.map_is_iso {W X Y Z S T : C} (f₁ : S ⟶ W) (f₂ : S ⟶ X) [has_pushout f₁ f₂] (g₁ : T ⟶ Y) (g₂ : T ⟶ Z) [has_pushout g₁ g₂] (i₁ : W ⟶ Y) (i₂ : X ⟶ Z) (i₃ : S ⟶ T) (eq₁ : f₁ ≫ i₁ = i₃ ≫ g₁) (eq₂ : f₂ ≫ i₂ = i₃ ≫ g₂) [is_iso i₁] [is_iso i₂] [is_iso i₃] : is_iso (pushout.map f₁ f₂ g₁ g₂ i₁ i₂ i₃ eq₁ eq₂) := begin refine ⟨⟨pushout.map _ _ _ _ (inv i₁) (inv i₂) (inv i₃) _ _, _, _⟩⟩, { rw [is_iso.comp_inv_eq, category.assoc, eq₁, is_iso.inv_hom_id_assoc] }, { rw [is_iso.comp_inv_eq, category.assoc, eq₂, is_iso.inv_hom_id_assoc] }, tidy end /-- If `f₁ = f₂` and `g₁ = g₂`, we may construct a canonical isomorphism `pushout f₁ g₁ ≅ pullback f₂ g₂` -/ @[simps hom] def pushout.congr_hom {X Y Z : C} {f₁ f₂ : X ⟶ Y} {g₁ g₂ : X ⟶ Z} (h₁ : f₁ = f₂) (h₂ : g₁ = g₂) [has_pushout f₁ g₁] [has_pushout f₂ g₂] : pushout f₁ g₁ ≅ pushout f₂ g₂ := as_iso $ pushout.map _ _ _ _ (𝟙 _) (𝟙 _) (𝟙 _) (by simp [h₁]) (by simp [h₂]) @[simp] lemma pushout.congr_hom_inv {X Y Z : C} {f₁ f₂ : X ⟶ Y} {g₁ g₂ : X ⟶ Z} (h₁ : f₁ = f₂) (h₂ : g₁ = g₂) [has_pushout f₁ g₁] [has_pushout f₂ g₂] : (pushout.congr_hom h₁ h₂).inv = pushout.map _ _ _ _ (𝟙 _) (𝟙 _) (𝟙 _) (by simp [h₁]) (by simp [h₂]) := begin apply pushout.hom_ext, { erw pushout.inl_desc, rw [iso.comp_inv_eq, category.id_comp], erw pushout.inl_desc, rw category.id_comp }, { erw pushout.inr_desc, rw [iso.comp_inv_eq, category.id_comp], erw pushout.inr_desc, rw category.id_comp } end section variables (G : C ⥤ D) /-- The comparison morphism for the pullback of `f,g`. This is an isomorphism iff `G` preserves the pullback of `f,g`; see `category_theory/limits/preserves/shapes/pullbacks.lean` -/ def pullback_comparison (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : G.obj (pullback f g) ⟶ pullback (G.map f) (G.map g) := pullback.lift (G.map pullback.fst) (G.map pullback.snd) (by simp only [←G.map_comp, pullback.condition]) @[simp, reassoc] lemma pullback_comparison_comp_fst (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : pullback_comparison G f g ≫ pullback.fst = G.map pullback.fst := pullback.lift_fst _ _ _ @[simp, reassoc] lemma pullback_comparison_comp_snd (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] : pullback_comparison G f g ≫ pullback.snd = G.map pullback.snd := pullback.lift_snd _ _ _ @[simp, reassoc] lemma map_lift_pullback_comparison (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] [has_pullback (G.map f) (G.map g)] {W : C} {h : W ⟶ X} {k : W ⟶ Y} (w : h ≫ f = k ≫ g) : G.map (pullback.lift _ _ w) ≫ pullback_comparison G f g = pullback.lift (G.map h) (G.map k) (by simp only [←G.map_comp, w]) := by { ext; simp [← G.map_comp] } /-- The comparison morphism for the pushout of `f,g`. This is an isomorphism iff `G` preserves the pushout of `f,g`; see `category_theory/limits/preserves/shapes/pullbacks.lean` -/ def pushout_comparison (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] [has_pushout (G.map f) (G.map g)] : pushout (G.map f) (G.map g) ⟶ G.obj (pushout f g) := pushout.desc (G.map pushout.inl) (G.map pushout.inr) (by simp only [←G.map_comp, pushout.condition]) @[simp, reassoc] lemma inl_comp_pushout_comparison (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] [has_pushout (G.map f) (G.map g)] : pushout.inl ≫ pushout_comparison G f g = G.map pushout.inl := pushout.inl_desc _ _ _ @[simp, reassoc] lemma inr_comp_pushout_comparison (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] [has_pushout (G.map f) (G.map g)] : pushout.inr ≫ pushout_comparison G f g = G.map pushout.inr := pushout.inr_desc _ _ _ @[simp, reassoc] lemma pushout_comparison_map_desc (f : X ⟶ Y) (g : X ⟶ Z) [has_pushout f g] [has_pushout (G.map f) (G.map g)] {W : C} {h : Y ⟶ W} {k : Z ⟶ W} (w : f ≫ h = g ≫ k) : pushout_comparison G f g ≫ G.map (pushout.desc _ _ w) = pushout.desc (G.map h) (G.map k) (by simp only [←G.map_comp, w]) := by { ext; simp [← G.map_comp] } end section pullback_symmetry open walking_cospan variables (f : X ⟶ Z) (g : Y ⟶ Z) /-- Making this a global instance would make the typeclass seach go in an infinite loop. -/ lemma has_pullback_symmetry [has_pullback f g] : has_pullback g f := ⟨⟨⟨pullback_cone.mk _ _ pullback.condition.symm, pullback_cone.flip_is_limit (pullback_is_pullback _ _)⟩⟩⟩ local attribute [instance] has_pullback_symmetry /-- The isomorphism `X ×[Z] Y ≅ Y ×[Z] X`. -/ def pullback_symmetry [has_pullback f g] : pullback f g ≅ pullback g f := is_limit.cone_point_unique_up_to_iso (pullback_cone.flip_is_limit (pullback_is_pullback f g) : is_limit (pullback_cone.mk _ _ pullback.condition.symm)) (limit.is_limit _) @[simp, reassoc] lemma pullback_symmetry_hom_comp_fst [has_pullback f g] : (pullback_symmetry f g).hom ≫ pullback.fst = pullback.snd := by simp [pullback_symmetry] @[simp, reassoc] lemma pullback_symmetry_hom_comp_snd [has_pullback f g] : (pullback_symmetry f g).hom ≫ pullback.snd = pullback.fst := by simp [pullback_symmetry] @[simp, reassoc] lemma pullback_symmetry_inv_comp_fst [has_pullback f g] : (pullback_symmetry f g).inv ≫ pullback.fst = pullback.snd := by simp [iso.inv_comp_eq] @[simp, reassoc] lemma pullback_symmetry_inv_comp_snd [has_pullback f g] : (pullback_symmetry f g).inv ≫ pullback.snd = pullback.fst := by simp [iso.inv_comp_eq] end pullback_symmetry section pushout_symmetry open walking_cospan variables (f : X ⟶ Y) (g : X ⟶ Z) /-- Making this a global instance would make the typeclass seach go in an infinite loop. -/ lemma has_pushout_symmetry [has_pushout f g] : has_pushout g f := ⟨⟨⟨pushout_cocone.mk _ _ pushout.condition.symm, pushout_cocone.flip_is_colimit (pushout_is_pushout _ _)⟩⟩⟩ local attribute [instance] has_pushout_symmetry /-- The isomorphism `Y ⨿[X] Z ≅ Z ⨿[X] Y`. -/ def pushout_symmetry [has_pushout f g] : pushout f g ≅ pushout g f := is_colimit.cocone_point_unique_up_to_iso (pushout_cocone.flip_is_colimit (pushout_is_pushout f g) : is_colimit (pushout_cocone.mk _ _ pushout.condition.symm)) (colimit.is_colimit _) @[simp, reassoc] lemma inl_comp_pushout_symmetry_hom [has_pushout f g] : pushout.inl ≫ (pushout_symmetry f g).hom = pushout.inr := (colimit.is_colimit (span f g)).comp_cocone_point_unique_up_to_iso_hom (pushout_cocone.flip_is_colimit (pushout_is_pushout g f)) _ @[simp, reassoc] lemma inr_comp_pushout_symmetry_hom [has_pushout f g] : pushout.inr ≫ (pushout_symmetry f g).hom = pushout.inl := (colimit.is_colimit (span f g)).comp_cocone_point_unique_up_to_iso_hom (pushout_cocone.flip_is_colimit (pushout_is_pushout g f)) _ @[simp, reassoc] lemma inl_comp_pushout_symmetry_inv [has_pushout f g] : pushout.inl ≫ (pushout_symmetry f g).inv = pushout.inr := by simp [iso.comp_inv_eq] @[simp, reassoc] lemma inr_comp_pushout_symmetry_inv [has_pushout f g] : pushout.inr ≫ (pushout_symmetry f g).inv = pushout.inl := by simp [iso.comp_inv_eq] end pushout_symmetry section pullback_left_iso open walking_cospan /-- The pullback of `f, g` is also the pullback of `f ≫ i, g ≫ i` for any mono `i`. -/ noncomputable def pullback_is_pullback_of_comp_mono (f : X ⟶ W) (g : Y ⟶ W) (i : W ⟶ Z) [mono i] [has_pullback f g] : is_limit (pullback_cone.mk pullback.fst pullback.snd _) := pullback_cone.is_limit_of_comp_mono f g i _ (limit.is_limit (cospan f g)) instance has_pullback_of_comp_mono (f : X ⟶ W) (g : Y ⟶ W) (i : W ⟶ Z) [mono i] [has_pullback f g] : has_pullback (f ≫ i) (g ≫ i) := ⟨⟨⟨_,pullback_is_pullback_of_comp_mono f g i⟩⟩⟩ variables (f : X ⟶ Z) (g : Y ⟶ Z) [is_iso f] /-- If `f : X ⟶ Z` is iso, then `X ×[Z] Y ≅ Y`. This is the explicit limit cone. -/ def pullback_cone_of_left_iso : pullback_cone f g := pullback_cone.mk (g ≫ inv f) (𝟙 _) $ by simp @[simp] lemma pullback_cone_of_left_iso_X : (pullback_cone_of_left_iso f g).X = Y := rfl @[simp] lemma pullback_cone_of_left_iso_fst : (pullback_cone_of_left_iso f g).fst = g ≫ inv f := rfl @[simp] lemma pullback_cone_of_left_iso_snd : (pullback_cone_of_left_iso f g).snd = 𝟙 _ := rfl @[simp] lemma pullback_cone_of_left_iso_π_app_none : (pullback_cone_of_left_iso f g).π.app none = g := by { delta pullback_cone_of_left_iso, simp } @[simp] lemma pullback_cone_of_left_iso_π_app_left : (pullback_cone_of_left_iso f g).π.app left = g ≫ inv f := rfl @[simp] lemma pullback_cone_of_left_iso_π_app_right : (pullback_cone_of_left_iso f g).π.app right = 𝟙 _ := rfl /-- Verify that the constructed limit cone is indeed a limit. -/ def pullback_cone_of_left_iso_is_limit : is_limit (pullback_cone_of_left_iso f g) := pullback_cone.is_limit_aux' _ (λ s, ⟨s.snd, by simp [← s.condition_assoc]⟩) lemma has_pullback_of_left_iso : has_pullback f g := ⟨⟨⟨_, pullback_cone_of_left_iso_is_limit f g⟩⟩⟩ local attribute [instance] has_pullback_of_left_iso instance pullback_snd_iso_of_left_iso : is_iso (pullback.snd : pullback f g ⟶ _) := begin refine ⟨⟨pullback.lift (g ≫ inv f) (𝟙 _) (by simp), _, by simp⟩⟩, ext, { simp [← pullback.condition_assoc] }, { simp [pullback.condition_assoc] }, end variables (i : Z ⟶ W) [mono i] instance has_pullback_of_right_factors_mono (f : X ⟶ Z) : has_pullback i (f ≫ i) := by { conv { congr, rw ←category.id_comp i, }, apply_instance } instance pullback_snd_iso_of_right_factors_mono (f : X ⟶ Z) : is_iso (pullback.snd : pullback i (f ≫ i) ⟶ _) := begin convert (congr_arg is_iso (show _ ≫ pullback.snd = _, from limit.iso_limit_cone_hom_π ⟨_,pullback_is_pullback_of_comp_mono (𝟙 _) f i⟩ walking_cospan.right)).mp infer_instance; exact (category.id_comp _).symm end end pullback_left_iso section pullback_right_iso open walking_cospan variables (f : X ⟶ Z) (g : Y ⟶ Z) [is_iso g] /-- If `g : Y ⟶ Z` is iso, then `X ×[Z] Y ≅ X`. This is the explicit limit cone. -/ def pullback_cone_of_right_iso : pullback_cone f g := pullback_cone.mk (𝟙 _) (f ≫ inv g) $ by simp @[simp] lemma pullback_cone_of_right_iso_X : (pullback_cone_of_right_iso f g).X = X := rfl @[simp] lemma pullback_cone_of_right_iso_fst : (pullback_cone_of_right_iso f g).fst = 𝟙 _ := rfl @[simp] lemma pullback_cone_of_right_iso_snd : (pullback_cone_of_right_iso f g).snd = f ≫ inv g := rfl @[simp] lemma pullback_cone_of_right_iso_π_app_none : (pullback_cone_of_right_iso f g).π.app none = f := category.id_comp _ @[simp] lemma pullback_cone_of_right_iso_π_app_left : (pullback_cone_of_right_iso f g).π.app left = 𝟙 _ := rfl @[simp] lemma pullback_cone_of_right_iso_π_app_right : (pullback_cone_of_right_iso f g).π.app right = f ≫ inv g := rfl /-- Verify that the constructed limit cone is indeed a limit. -/ def pullback_cone_of_right_iso_is_limit : is_limit (pullback_cone_of_right_iso f g) := pullback_cone.is_limit_aux' _ (λ s, ⟨s.fst, by simp [s.condition_assoc]⟩) lemma has_pullback_of_right_iso : has_pullback f g := ⟨⟨⟨_, pullback_cone_of_right_iso_is_limit f g⟩⟩⟩ local attribute [instance] has_pullback_of_right_iso instance pullback_snd_iso_of_right_iso : is_iso (pullback.fst : pullback f g ⟶ _) := begin refine ⟨⟨pullback.lift (𝟙 _) (f ≫ inv g) (by simp), _, by simp⟩⟩, ext, { simp }, { simp [pullback.condition_assoc] }, end variables (i : Z ⟶ W) [mono i] instance has_pullback_of_left_factors_mono (f : X ⟶ Z) : has_pullback (f ≫ i) i := by { conv { congr, skip, rw ←category.id_comp i, }, apply_instance } instance pullback_snd_iso_of_left_factors_mono (f : X ⟶ Z) : is_iso (pullback.fst : pullback (f ≫ i) i ⟶ _) := begin convert (congr_arg is_iso (show _ ≫ pullback.fst = _, from limit.iso_limit_cone_hom_π ⟨_,pullback_is_pullback_of_comp_mono f (𝟙 _) i⟩ walking_cospan.left)).mp infer_instance; exact (category.id_comp _).symm end end pullback_right_iso section pushout_left_iso open walking_span /-- The pushout of `f, g` is also the pullback of `h ≫ f, h ≫ g` for any epi `h`. -/ noncomputable def pushout_is_pushout_of_epi_comp (f : X ⟶ Y) (g : X ⟶ Z) (h : W ⟶ X) [epi h] [has_pushout f g] : is_colimit (pushout_cocone.mk pushout.inl pushout.inr _) := pushout_cocone.is_colimit_of_epi_comp f g h _ (colimit.is_colimit (span f g)) instance has_pushout_of_epi_comp (f : X ⟶ Y) (g : X ⟶ Z) (h : W ⟶ X) [epi h] [has_pushout f g] : has_pushout (h ≫ f) (h ≫ g) := ⟨⟨⟨_,pushout_is_pushout_of_epi_comp f g h⟩⟩⟩ variables (f : X ⟶ Y) (g : X ⟶ Z) [is_iso f] /-- If `f : X ⟶ Y` is iso, then `Y ⨿[X] Z ≅ Z`. This is the explicit colimit cocone. -/ def pushout_cocone_of_left_iso : pushout_cocone f g := pushout_cocone.mk (inv f ≫ g) (𝟙 _) $ by simp @[simp] lemma pushout_cocone_of_left_iso_X : (pushout_cocone_of_left_iso f g).X = Z := rfl @[simp] lemma pushout_cocone_of_left_iso_inl : (pushout_cocone_of_left_iso f g).inl = inv f ≫ g := rfl @[simp] lemma pushout_cocone_of_left_iso_inr : (pushout_cocone_of_left_iso f g).inr = 𝟙 _ := rfl @[simp] lemma pushout_cocone_of_left_iso_ι_app_none : (pushout_cocone_of_left_iso f g).ι.app none = g := by { delta pushout_cocone_of_left_iso, simp } @[simp] lemma pushout_cocone_of_left_iso_ι_app_left : (pushout_cocone_of_left_iso f g).ι.app left = inv f ≫ g := rfl @[simp] lemma pushout_cocone_of_left_iso_ι_app_right : (pushout_cocone_of_left_iso f g).ι.app right = 𝟙 _ := rfl /-- Verify that the constructed cocone is indeed a colimit. -/ def pushout_cocone_of_left_iso_is_limit : is_colimit (pushout_cocone_of_left_iso f g) := pushout_cocone.is_colimit_aux' _ (λ s, ⟨s.inr, by simp [← s.condition]⟩) lemma has_pushout_of_left_iso : has_pushout f g := ⟨⟨⟨_, pushout_cocone_of_left_iso_is_limit f g⟩⟩⟩ local attribute [instance] has_pushout_of_left_iso instance pushout_inr_iso_of_left_iso : is_iso (pushout.inr : _ ⟶ pushout f g) := begin refine ⟨⟨pushout.desc (inv f ≫ g) (𝟙 _) (by simp), (by simp), _⟩⟩, ext, { simp [← pushout.condition] }, { simp [pushout.condition_assoc] }, end variables (h : W ⟶ X) [epi h] instance has_pushout_of_right_factors_epi (f : X ⟶ Y) : has_pushout h (h ≫ f) := by { conv { congr, rw ←category.comp_id h, }, apply_instance } instance pushout_inr_iso_of_right_factors_epi (f : X ⟶ Y) : is_iso (pushout.inr : _ ⟶ pushout h (h ≫ f)) := begin convert (congr_arg is_iso (show pushout.inr ≫ _ = _, from colimit.iso_colimit_cocone_ι_inv ⟨_, pushout_is_pushout_of_epi_comp (𝟙 _) f h⟩ walking_span.right)).mp infer_instance; exact (category.comp_id _).symm end end pushout_left_iso section pushout_right_iso open walking_span variables (f : X ⟶ Y) (g : X ⟶ Z) [is_iso g] /-- If `f : X ⟶ Z` is iso, then `Y ⨿[X] Z ≅ Y`. This is the explicit colimit cocone. -/ def pushout_cocone_of_right_iso : pushout_cocone f g := pushout_cocone.mk (𝟙 _) (inv g ≫ f) $ by simp @[simp] lemma pushout_cocone_of_right_iso_X : (pushout_cocone_of_right_iso f g).X = Y := rfl @[simp] lemma pushout_cocone_of_right_iso_inl : (pushout_cocone_of_right_iso f g).inl = 𝟙 _ := rfl @[simp] lemma pushout_cocone_of_right_iso_inr : (pushout_cocone_of_right_iso f g).inr = inv g ≫ f := rfl @[simp] lemma pushout_cocone_of_right_iso_ι_app_none : (pushout_cocone_of_right_iso f g).ι.app none = f := by { delta pushout_cocone_of_right_iso, simp } @[simp] lemma pushout_cocone_of_right_iso_ι_app_left : (pushout_cocone_of_right_iso f g).ι.app left = 𝟙 _ := rfl @[simp] lemma pushout_cocone_of_right_iso_ι_app_right : (pushout_cocone_of_right_iso f g).ι.app right = inv g ≫ f := rfl /-- Verify that the constructed cocone is indeed a colimit. -/ def pushout_cocone_of_right_iso_is_limit : is_colimit (pushout_cocone_of_right_iso f g) := pushout_cocone.is_colimit_aux' _ (λ s, ⟨s.inl, by simp [←s.condition]⟩) lemma has_pushout_of_right_iso : has_pushout f g := ⟨⟨⟨_, pushout_cocone_of_right_iso_is_limit f g⟩⟩⟩ local attribute [instance] has_pushout_of_right_iso instance pushout_inl_iso_of_right_iso : is_iso (pushout.inl : _ ⟶ pushout f g) := begin refine ⟨⟨pushout.desc (𝟙 _) (inv g ≫ f) (by simp), (by simp), _⟩⟩, ext, { simp [←pushout.condition] }, { simp [pushout.condition] }, end variables (h : W ⟶ X) [epi h] instance has_pushout_of_left_factors_epi (f : X ⟶ Y) : has_pushout (h ≫ f) h := by { conv { congr, skip, rw ←category.comp_id h, }, apply_instance } instance pushout_inl_iso_of_left_factors_epi (f : X ⟶ Y) : is_iso (pushout.inl : _ ⟶ pushout (h ≫ f) h) := begin convert (congr_arg is_iso (show pushout.inl ≫ _ = _, from colimit.iso_colimit_cocone_ι_inv ⟨_, pushout_is_pushout_of_epi_comp f (𝟙 _) h⟩ walking_span.left)).mp infer_instance; exact (category.comp_id _).symm end end pushout_right_iso section open walking_cospan variable (f : X ⟶ Y) instance has_kernel_pair_of_mono [mono f] : has_pullback f f := ⟨⟨⟨_, pullback_cone.is_limit_mk_id_id f⟩⟩⟩ lemma fst_eq_snd_of_mono_eq [mono f] : (pullback.fst : pullback f f ⟶ _) = pullback.snd := ((pullback_cone.is_limit_mk_id_id f).fac (get_limit_cone (cospan f f)).cone left).symm.trans ((pullback_cone.is_limit_mk_id_id f).fac (get_limit_cone (cospan f f)).cone right : _) @[simp] lemma pullback_symmetry_hom_of_mono_eq [mono f] : (pullback_symmetry f f).hom = 𝟙 _ := by ext; simp [fst_eq_snd_of_mono_eq] instance fst_iso_of_mono_eq [mono f] : is_iso (pullback.fst : pullback f f ⟶ _) := begin refine ⟨⟨pullback.lift (𝟙 _) (𝟙 _) (by simp), _, by simp⟩⟩, ext, { simp }, { simp [fst_eq_snd_of_mono_eq] } end instance snd_iso_of_mono_eq [mono f] : is_iso (pullback.snd : pullback f f ⟶ _) := by { rw ← fst_eq_snd_of_mono_eq, apply_instance } end section open walking_span variable (f : X ⟶ Y) instance has_cokernel_pair_of_epi [epi f] : has_pushout f f := ⟨⟨⟨_, pushout_cocone.is_colimit_mk_id_id f⟩⟩⟩ lemma inl_eq_inr_of_epi_eq [epi f] : (pushout.inl : _ ⟶ pushout f f) = pushout.inr := ((pushout_cocone.is_colimit_mk_id_id f).fac (get_colimit_cocone (span f f)).cocone left).symm.trans ((pushout_cocone.is_colimit_mk_id_id f).fac (get_colimit_cocone (span f f)).cocone right : _) @[simp] lemma pullback_symmetry_hom_of_epi_eq [epi f] : (pushout_symmetry f f).hom = 𝟙 _ := by ext; simp [inl_eq_inr_of_epi_eq] instance inl_iso_of_epi_eq [epi f] : is_iso (pushout.inl : _ ⟶ pushout f f) := begin refine ⟨⟨pushout.desc (𝟙 _) (𝟙 _) (by simp), by simp, _⟩⟩, ext, { simp }, { simp [inl_eq_inr_of_epi_eq] } end instance inr_iso_of_epi_eq [epi f] : is_iso (pushout.inr : _ ⟶ pushout f f) := by { rw ← inl_eq_inr_of_epi_eq, apply_instance } end section paste_lemma variables {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ X₂) (f₂ : X₂ ⟶ X₃) (g₁ : Y₁ ⟶ Y₂) (g₂ : Y₂ ⟶ Y₃) variables (i₁ : X₁ ⟶ Y₁) (i₂ : X₂ ⟶ Y₂) (i₃ : X₃ ⟶ Y₃) variables (h₁ : i₁ ≫ g₁ = f₁ ≫ i₂) (h₂ : i₂ ≫ g₂ = f₂ ≫ i₃) /-- Given X₁ - f₁ -> X₂ - f₂ -> X₃ | | | i₁ i₂ i₃ ∨ ∨ ∨ Y₁ - g₁ -> Y₂ - g₂ -> Y₃ Then the big square is a pullback if both the small squares are. -/ def big_square_is_pullback (H : is_limit (pullback_cone.mk _ _ h₂)) (H' : is_limit (pullback_cone.mk _ _ h₁)) : is_limit (pullback_cone.mk _ _ (show i₁ ≫ g₁ ≫ g₂ = (f₁ ≫ f₂) ≫ i₃, by rw [← category.assoc, h₁, category.assoc, h₂, category.assoc])) := begin fapply pullback_cone.is_limit_aux', intro s, have : (s.fst ≫ g₁) ≫ g₂ = s.snd ≫ i₃ := by rw [← s.condition, category.assoc], rcases pullback_cone.is_limit.lift' H (s.fst ≫ g₁) s.snd this with ⟨l₁, hl₁, hl₁'⟩, rcases pullback_cone.is_limit.lift' H' s.fst l₁ hl₁.symm with ⟨l₂, hl₂, hl₂'⟩, use l₂, use hl₂, use show l₂ ≫ f₁ ≫ f₂ = s.snd, by { rw [← hl₁', ← hl₂', category.assoc], refl }, intros m hm₁ hm₂, apply pullback_cone.is_limit.hom_ext H', { erw [hm₁, hl₂] }, { apply pullback_cone.is_limit.hom_ext H, { erw [category.assoc, ← h₁, ← category.assoc, hm₁, ← hl₂, category.assoc, category.assoc, h₁], refl }, { erw [category.assoc, hm₂, ← hl₁', ← hl₂'] } } end /-- Given X₁ - f₁ -> X₂ - f₂ -> X₃ | | | i₁ i₂ i₃ ∨ ∨ ∨ Y₁ - g₁ -> Y₂ - g₂ -> Y₃ Then the big square is a pushout if both the small squares are. -/ def big_square_is_pushout (H : is_colimit (pushout_cocone.mk _ _ h₂)) (H' : is_colimit (pushout_cocone.mk _ _ h₁)) : is_colimit (pushout_cocone.mk _ _ (show i₁ ≫ g₁ ≫ g₂ = (f₁ ≫ f₂) ≫ i₃, by rw [← category.assoc, h₁, category.assoc, h₂, category.assoc])) := begin fapply pushout_cocone.is_colimit_aux', intro s, have : i₁ ≫ s.inl = f₁ ≫ (f₂ ≫ s.inr) := by rw [s.condition, category.assoc], rcases pushout_cocone.is_colimit.desc' H' s.inl (f₂ ≫ s.inr) this with ⟨l₁, hl₁, hl₁'⟩, rcases pushout_cocone.is_colimit.desc' H l₁ s.inr hl₁' with ⟨l₂, hl₂, hl₂'⟩, use l₂, use show (g₁ ≫ g₂) ≫ l₂ = s.inl, by { rw [← hl₁, ← hl₂, category.assoc], refl }, use hl₂', intros m hm₁ hm₂, apply pushout_cocone.is_colimit.hom_ext H, { apply pushout_cocone.is_colimit.hom_ext H', { erw [← category.assoc, hm₁, hl₂, hl₁] }, { erw [← category.assoc, h₂, category.assoc, hm₂, ← hl₂', ← category.assoc, ← category.assoc, ← h₂], refl } }, { erw [hm₂, hl₂'] } end /-- Given X₁ - f₁ -> X₂ - f₂ -> X₃ | | | i₁ i₂ i₃ ∨ ∨ ∨ Y₁ - g₁ -> Y₂ - g₂ -> Y₃ Then the left square is a pullback if the right square and the big square are. -/ def left_square_is_pullback (H : is_limit (pullback_cone.mk _ _ h₂)) (H' : is_limit (pullback_cone.mk _ _ (show i₁ ≫ g₁ ≫ g₂ = (f₁ ≫ f₂) ≫ i₃, by rw [← category.assoc, h₁, category.assoc, h₂, category.assoc]))) : is_limit (pullback_cone.mk _ _ h₁) := begin fapply pullback_cone.is_limit_aux', intro s, have : s.fst ≫ g₁ ≫ g₂ = (s.snd ≫ f₂) ≫ i₃ := by { rw [← category.assoc, s.condition, category.assoc, category.assoc, h₂] }, rcases pullback_cone.is_limit.lift' H' s.fst (s.snd ≫ f₂) this with ⟨l₁, hl₁, hl₁'⟩, use l₁, use hl₁, split, { apply pullback_cone.is_limit.hom_ext H, { erw [category.assoc, ← h₁, ← category.assoc, hl₁, s.condition], refl }, { erw [category.assoc, hl₁'], refl } }, { intros m hm₁ hm₂, apply pullback_cone.is_limit.hom_ext H', { erw [hm₁, hl₁] }, { erw [hl₁', ← hm₂], exact (category.assoc _ _ _).symm } } end /-- Given X₁ - f₁ -> X₂ - f₂ -> X₃ | | | i₁ i₂ i₃ ∨ ∨ ∨ Y₁ - g₁ -> Y₂ - g₂ -> Y₃ Then the right square is a pushout if the left square and the big square are. -/ def right_square_is_pushout (H : is_colimit (pushout_cocone.mk _ _ h₁)) (H' : is_colimit (pushout_cocone.mk _ _ (show i₁ ≫ g₁ ≫ g₂ = (f₁ ≫ f₂) ≫ i₃, by rw [← category.assoc, h₁, category.assoc, h₂, category.assoc]))) : is_colimit (pushout_cocone.mk _ _ h₂) := begin fapply pushout_cocone.is_colimit_aux', intro s, have : i₁ ≫ g₁ ≫ s.inl = (f₁ ≫ f₂) ≫ s.inr := by { rw [category.assoc, ← s.condition, ← category.assoc, ← category.assoc, h₁] }, rcases pushout_cocone.is_colimit.desc' H' (g₁ ≫ s.inl) s.inr this with ⟨l₁, hl₁, hl₁'⟩, dsimp at *, use l₁, refine ⟨_,_,_⟩, { apply pushout_cocone.is_colimit.hom_ext H, { erw [← category.assoc, hl₁], refl }, { erw [← category.assoc, h₂, category.assoc, hl₁', s.condition] } }, { exact hl₁' }, { intros m hm₁ hm₂, apply pushout_cocone.is_colimit.hom_ext H', { erw [hl₁, category.assoc, hm₁] }, { erw [hm₂, hl₁'] } } end end paste_lemma section variables (f : X ⟶ Z) (g : Y ⟶ Z) (f' : W ⟶ X) variables [has_pullback f g] [has_pullback f' (pullback.fst : pullback f g ⟶ _)] variables [has_pullback (f' ≫ f) g] /-- The canonical isomorphism `W ×[X] (X ×[Z] Y) ≅ W ×[Z] Y` -/ noncomputable def pullback_right_pullback_fst_iso : pullback f' (pullback.fst : pullback f g ⟶ _) ≅ pullback (f' ≫ f) g := begin let := big_square_is_pullback (pullback.snd : pullback f' (pullback.fst : pullback f g ⟶ _) ⟶ _) pullback.snd f' f pullback.fst pullback.fst g pullback.condition pullback.condition (pullback_is_pullback _ _) (pullback_is_pullback _ _), exact (this.cone_point_unique_up_to_iso (pullback_is_pullback _ _) : _) end @[simp, reassoc] lemma pullback_right_pullback_fst_iso_hom_fst : (pullback_right_pullback_fst_iso f g f').hom ≫ pullback.fst = pullback.fst := is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.left @[simp, reassoc] lemma pullback_right_pullback_fst_iso_hom_snd : (pullback_right_pullback_fst_iso f g f').hom ≫ pullback.snd = pullback.snd ≫ pullback.snd := is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.right @[simp, reassoc] lemma pullback_right_pullback_fst_iso_inv_fst : (pullback_right_pullback_fst_iso f g f').inv ≫ pullback.fst = pullback.fst := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ walking_cospan.left @[simp, reassoc] lemma pullback_right_pullback_fst_iso_inv_snd_snd : (pullback_right_pullback_fst_iso f g f').inv ≫ pullback.snd ≫ pullback.snd = pullback.snd := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ walking_cospan.right @[simp, reassoc] lemma pullback_right_pullback_fst_iso_inv_snd_fst : (pullback_right_pullback_fst_iso f g f').inv ≫ pullback.snd ≫ pullback.fst = pullback.fst ≫ f' := begin rw ← pullback.condition, exact pullback_right_pullback_fst_iso_inv_fst_assoc _ _ _ _ end end section variables (f : X ⟶ Y) (g : X ⟶ Z) (g' : Z ⟶ W) variables [has_pushout f g] [has_pushout (pushout.inr : _ ⟶ pushout f g) g'] variables [has_pushout f (g ≫ g')] /-- The canonical isomorphism `(Y ⨿[X] Z) ⨿[Z] W ≅ Y ×[X] W` -/ noncomputable def pushout_left_pushout_inr_iso : pushout (pushout.inr : _ ⟶ pushout f g) g' ≅ pushout f (g ≫ g') := ((big_square_is_pushout g g' _ _ f _ _ pushout.condition pushout.condition (pushout_is_pushout _ _) (pushout_is_pushout _ _)) .cocone_point_unique_up_to_iso (pushout_is_pushout _ _) : _) @[simp, reassoc] lemma inl_pushout_left_pushout_inr_iso_inv : pushout.inl ≫ (pushout_left_pushout_inr_iso f g g').inv = pushout.inl ≫ pushout.inl := ((big_square_is_pushout g g' _ _ f _ _ pushout.condition pushout.condition (pushout_is_pushout _ _) (pushout_is_pushout _ _)) .comp_cocone_point_unique_up_to_iso_inv (pushout_is_pushout _ _) walking_span.left : _) @[simp, reassoc] lemma inr_pushout_left_pushout_inr_iso_hom : pushout.inr ≫ (pushout_left_pushout_inr_iso f g g').hom = pushout.inr := ((big_square_is_pushout g g' _ _ f _ _ pushout.condition pushout.condition (pushout_is_pushout _ _) (pushout_is_pushout _ _)) .comp_cocone_point_unique_up_to_iso_hom (pushout_is_pushout _ _) walking_span.right : _) @[simp, reassoc] lemma inr_pushout_left_pushout_inr_iso_inv : pushout.inr ≫ (pushout_left_pushout_inr_iso f g g').inv = pushout.inr := by rw [iso.comp_inv_eq, inr_pushout_left_pushout_inr_iso_hom] @[simp, reassoc] lemma inl_inl_pushout_left_pushout_inr_iso_hom : pushout.inl ≫ pushout.inl ≫ (pushout_left_pushout_inr_iso f g g').hom = pushout.inl := by rw [← category.assoc, ← iso.eq_comp_inv, inl_pushout_left_pushout_inr_iso_inv] @[simp, reassoc] lemma inr_inl_pushout_left_pushout_inr_iso_hom : pushout.inr ≫ pushout.inl ≫ (pushout_left_pushout_inr_iso f g g').hom = g' ≫ pushout.inr := by rw [← category.assoc, ← iso.eq_comp_inv, category.assoc, inr_pushout_left_pushout_inr_iso_inv, pushout.condition] end section pullback_assoc /- The objects and morphisms are as follows: Z₂ - g₄ -> X₃ | | g₃ f₄ ∨ ∨ Z₁ - g₂ -> X₂ - f₃ -> Y₂ | | g₁ f₂ ∨ ∨ X₁ - f₁ -> Y₁ where the two squares are pullbacks. We can then construct the pullback squares W - l₂ -> Z₂ - g₄ -> X₃ | | l₁ f₄ ∨ ∨ Z₁ - g₂ -> X₂ - f₃ -> Y₂ and W' - l₂' -> Z₂ | | l₁' g₃ ∨ ∨ Z₁ X₂ | | g₁ f₂ ∨ ∨ X₁ - f₁ -> Y₁ We will show that both `W` and `W'` are pullbacks over `g₁, g₂`, and thus we may construct a canonical isomorphism between them. -/ variables {X₁ X₂ X₃ Y₁ Y₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₁) (f₃ : X₂ ⟶ Y₂) variables (f₄ : X₃ ⟶ Y₂) [has_pullback f₁ f₂] [has_pullback f₃ f₄] include f₁ f₂ f₃ f₄ local notation `Z₁` := pullback f₁ f₂ local notation `Z₂` := pullback f₃ f₄ local notation `g₁` := (pullback.fst : Z₁ ⟶ X₁) local notation `g₂` := (pullback.snd : Z₁ ⟶ X₂) local notation `g₃` := (pullback.fst : Z₂ ⟶ X₂) local notation `g₄` := (pullback.snd : Z₂ ⟶ X₃) local notation `W` := pullback (g₂ ≫ f₃) f₄ local notation `W'` := pullback f₁ (g₃ ≫ f₂) local notation `l₁` := (pullback.fst : W ⟶ Z₁) local notation `l₂` := (pullback.lift (pullback.fst ≫ g₂) pullback.snd ((category.assoc _ _ _).trans pullback.condition) : W ⟶ Z₂) local notation `l₁'`:= (pullback.lift pullback.fst (pullback.snd ≫ g₃) (pullback.condition.trans (category.assoc _ _ _).symm) : W' ⟶ Z₁) local notation `l₂'`:= (pullback.snd : W' ⟶ Z₂) /-- `(X₁ ×[Y₁] X₂) ×[Y₂] X₃` is the pullback `(X₁ ×[Y₁] X₂) ×[X₂] (X₂ ×[Y₂] X₃)`. -/ def pullback_pullback_left_is_pullback [has_pullback (g₂ ≫ f₃) f₄] : is_limit (pullback_cone.mk l₁ l₂ (show l₁ ≫ g₂ = l₂ ≫ g₃, from (pullback.lift_fst _ _ _).symm)) := begin apply left_square_is_pullback, exact pullback_is_pullback f₃ f₄, convert pullback_is_pullback (g₂ ≫ f₃) f₄, rw pullback.lift_snd end /-- `(X₁ ×[Y₁] X₂) ×[Y₂] X₃` is the pullback `X₁ ×[Y₁] (X₂ ×[Y₂] X₃)`. -/ def pullback_assoc_is_pullback [has_pullback (g₂ ≫ f₃) f₄] : is_limit (pullback_cone.mk (l₁ ≫ g₁) l₂ (show (l₁ ≫ g₁) ≫ f₁ = l₂ ≫ (g₃ ≫ f₂), by rw [pullback.lift_fst_assoc, category.assoc, category.assoc, pullback.condition])) := begin apply pullback_cone.flip_is_limit, apply big_square_is_pullback, { apply pullback_cone.flip_is_limit, exact pullback_is_pullback f₁ f₂ }, { apply pullback_cone.flip_is_limit, apply pullback_pullback_left_is_pullback }, { exact pullback.lift_fst _ _ _ }, { exact pullback.condition.symm } end lemma has_pullback_assoc [has_pullback (g₂ ≫ f₃) f₄] : has_pullback f₁ (g₃ ≫ f₂) := ⟨⟨⟨_, pullback_assoc_is_pullback f₁ f₂ f₃ f₄⟩⟩⟩ /-- `X₁ ×[Y₁] (X₂ ×[Y₂] X₃)` is the pullback `(X₁ ×[Y₁] X₂) ×[X₂] (X₂ ×[Y₂] X₃)`. -/ def pullback_pullback_right_is_pullback [has_pullback f₁ (g₃ ≫ f₂)] : is_limit (pullback_cone.mk l₁' l₂' (show l₁' ≫ g₂ = l₂' ≫ g₃, from pullback.lift_snd _ _ _)) := begin apply pullback_cone.flip_is_limit, apply left_square_is_pullback, { apply pullback_cone.flip_is_limit, exact pullback_is_pullback f₁ f₂ }, { apply pullback_cone.flip_is_limit, convert pullback_is_pullback f₁ (g₃ ≫ f₂), rw pullback.lift_fst }, { exact pullback.condition.symm } end /-- `X₁ ×[Y₁] (X₂ ×[Y₂] X₃)` is the pullback `(X₁ ×[Y₁] X₂) ×[Y₂] X₃`. -/ def pullback_assoc_symm_is_pullback [has_pullback f₁ (g₃ ≫ f₂)] : is_limit (pullback_cone.mk l₁' (l₂' ≫ g₄) (show l₁' ≫ (g₂ ≫ f₃) = (l₂' ≫ g₄) ≫ f₄, by rw [pullback.lift_snd_assoc, category.assoc, category.assoc, pullback.condition])) := begin apply big_square_is_pullback, exact pullback_is_pullback f₃ f₄, apply pullback_pullback_right_is_pullback end lemma has_pullback_assoc_symm [has_pullback f₁ (g₃ ≫ f₂)] : has_pullback (g₂ ≫ f₃) f₄ := ⟨⟨⟨_, pullback_assoc_symm_is_pullback f₁ f₂ f₃ f₄⟩⟩⟩ variables [has_pullback (g₂ ≫ f₃) f₄] [has_pullback f₁ (g₃ ≫ f₂)] /-- The canonical isomorphism `(X₁ ×[Y₁] X₂) ×[Y₂] X₃ ≅ X₁ ×[Y₁] (X₂ ×[Y₂] X₃)`. -/ noncomputable def pullback_assoc : pullback (pullback.snd ≫ f₃ : pullback f₁ f₂ ⟶ _) f₄ ≅ pullback f₁ (pullback.fst ≫ f₂ : pullback f₃ f₄ ⟶ _) := (pullback_pullback_left_is_pullback f₁ f₂ f₃ f₄).cone_point_unique_up_to_iso (pullback_pullback_right_is_pullback f₁ f₂ f₃ f₄) @[simp, reassoc] lemma pullback_assoc_inv_fst_fst : (pullback_assoc f₁ f₂ f₃ f₄).inv ≫ pullback.fst ≫ pullback.fst = pullback.fst := begin transitivity l₁' ≫ pullback.fst, rw ← category.assoc, congr' 1, exact is_limit.cone_point_unique_up_to_iso_inv_comp _ _ walking_cospan.left, exact pullback.lift_fst _ _ _, end @[simp, reassoc] lemma pullback_assoc_hom_fst : (pullback_assoc f₁ f₂ f₃ f₄).hom ≫ pullback.fst = pullback.fst ≫ pullback.fst := by rw [← iso.eq_inv_comp, pullback_assoc_inv_fst_fst] @[simp, reassoc] lemma pullback_assoc_hom_snd_fst : (pullback_assoc f₁ f₂ f₃ f₄).hom ≫ pullback.snd ≫ pullback.fst = pullback.fst ≫ pullback.snd := begin transitivity l₂ ≫ pullback.fst, rw ← category.assoc, congr' 1, exact is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.right, exact pullback.lift_fst _ _ _, end @[simp, reassoc] lemma pullback_assoc_hom_snd_snd : (pullback_assoc f₁ f₂ f₃ f₄).hom ≫ pullback.snd ≫ pullback.snd = pullback.snd := begin transitivity l₂ ≫ pullback.snd, rw ← category.assoc, congr' 1, exact is_limit.cone_point_unique_up_to_iso_hom_comp _ _ walking_cospan.right, exact pullback.lift_snd _ _ _, end @[simp, reassoc] lemma pullback_assoc_inv_fst_snd : (pullback_assoc f₁ f₂ f₃ f₄).inv ≫ pullback.fst ≫ pullback.snd = pullback.snd ≫ pullback.fst := by rw [iso.inv_comp_eq, pullback_assoc_hom_snd_fst] @[simp, reassoc] lemma pullback_assoc_inv_snd : (pullback_assoc f₁ f₂ f₃ f₄).inv ≫ pullback.snd = pullback.snd ≫ pullback.snd := by rw [iso.inv_comp_eq, pullback_assoc_hom_snd_snd] end pullback_assoc section pushout_assoc /- The objects and morphisms are as follows: Z₂ - g₄ -> X₃ | | g₃ f₄ ∨ ∨ Z₁ - g₂ -> X₂ - f₃ -> Y₂ | | g₁ f₂ ∨ ∨ X₁ - f₁ -> Y₁ where the two squares are pushouts. We can then construct the pushout squares Z₁ - g₂ -> X₂ - f₃ -> Y₂ | | g₁ l₂ ∨ ∨ X₁ - f₁ -> Y₁ - l₁ -> W and Z₂ - g₄ -> X₃ | | g₃ f₄ ∨ ∨ X₂ Y₂ | | f₂ l₂' ∨ ∨ Y₁ - l₁' -> W' We will show that both `W` and `W'` are pushouts over `f₂, f₃`, and thus we may construct a canonical isomorphism between them. -/ variables {X₁ X₂ X₃ Z₁ Z₂ : C} (g₁ : Z₁ ⟶ X₁) (g₂ : Z₁ ⟶ X₂) (g₃ : Z₂ ⟶ X₂) variables (g₄ : Z₂ ⟶ X₃) [has_pushout g₁ g₂] [has_pushout g₃ g₄] include g₁ g₂ g₃ g₄ local notation `Y₁` := pushout g₁ g₂ local notation `Y₂` := pushout g₃ g₄ local notation `f₁` := (pushout.inl : X₁ ⟶ Y₁) local notation `f₂` := (pushout.inr : X₂ ⟶ Y₁) local notation `f₃` := (pushout.inl : X₂ ⟶ Y₂) local notation `f₄` := (pushout.inr : X₃ ⟶ Y₂) local notation `W` := pushout g₁ (g₂ ≫ f₃) local notation `W'` := pushout (g₃ ≫ f₂) g₄ local notation `l₁` := (pushout.desc pushout.inl (f₃ ≫ pushout.inr) (pushout.condition.trans (category.assoc _ _ _)) : Y₁ ⟶ W) local notation `l₂` := (pushout.inr : Y₂ ⟶ W) local notation `l₁'`:= (pushout.inl : Y₁ ⟶ W') local notation `l₂'`:= (pushout.desc (f₂ ≫ pushout.inl) pushout.inr ((category.assoc _ _ _).symm.trans pushout.condition) : Y₂ ⟶ W') /-- `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃` is the pushout `(X₁ ⨿[Z₁] X₂) ×[X₂] (X₂ ⨿[Z₂] X₃)`. -/ def pushout_pushout_left_is_pushout [has_pushout (g₃ ≫ f₂) g₄] : is_colimit (pushout_cocone.mk l₁' l₂' (show f₂ ≫ l₁' = f₃ ≫ l₂', from (pushout.inl_desc _ _ _).symm)) := begin apply pushout_cocone.flip_is_colimit, apply right_square_is_pushout, { apply pushout_cocone.flip_is_colimit, exact pushout_is_pushout _ _ }, { apply pushout_cocone.flip_is_colimit, convert pushout_is_pushout (g₃ ≫ f₂) g₄, exact pushout.inr_desc _ _ _ }, { exact pushout.condition.symm } end /-- `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃` is the pushout `X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)`. -/ def pushout_assoc_is_pushout [has_pushout (g₃ ≫ f₂) g₄] : is_colimit (pushout_cocone.mk (f₁ ≫ l₁') l₂' (show g₁ ≫ (f₁ ≫ l₁') = (g₂ ≫ f₃) ≫ l₂', by rw [category.assoc, pushout.inl_desc, pushout.condition_assoc])) := begin apply big_square_is_pushout, { apply pushout_pushout_left_is_pushout }, { exact pushout_is_pushout _ _ } end lemma has_pushout_assoc [has_pushout (g₃ ≫ f₂) g₄] : has_pushout g₁ (g₂ ≫ f₃) := ⟨⟨⟨_, pushout_assoc_is_pushout g₁ g₂ g₃ g₄⟩⟩⟩ /-- `X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)` is the pushout `(X₁ ⨿[Z₁] X₂) ×[X₂] (X₂ ⨿[Z₂] X₃)`. -/ def pushout_pushout_right_is_pushout [has_pushout g₁ (g₂ ≫ f₃)] : is_colimit (pushout_cocone.mk l₁ l₂ (show f₂ ≫ l₁ = f₃ ≫ l₂, from pushout.inr_desc _ _ _)) := begin apply right_square_is_pushout, { exact pushout_is_pushout _ _ }, { convert pushout_is_pushout g₁ (g₂ ≫ f₃), rw pushout.inl_desc } end /-- `X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)` is the pushout `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃`. -/ def pushout_assoc_symm_is_pushout [has_pushout g₁ (g₂ ≫ f₃)] : is_colimit (pushout_cocone.mk l₁ (f₄ ≫ l₂) ((show (g₃ ≫ f₂) ≫ l₁ = g₄ ≫ (f₄ ≫ l₂), by rw [category.assoc, pushout.inr_desc, pushout.condition_assoc]))) := begin apply pushout_cocone.flip_is_colimit, apply big_square_is_pushout, { apply pushout_cocone.flip_is_colimit, apply pushout_pushout_right_is_pushout }, { apply pushout_cocone.flip_is_colimit, exact pushout_is_pushout _ _ }, { exact pushout.condition.symm }, { exact (pushout.inr_desc _ _ _).symm } end lemma has_pushout_assoc_symm [has_pushout g₁ (g₂ ≫ f₃)] : has_pushout (g₃ ≫ f₂) g₄ := ⟨⟨⟨_, pushout_assoc_symm_is_pushout g₁ g₂ g₃ g₄⟩⟩⟩ variables [has_pushout (g₃ ≫ f₂) g₄] [has_pushout g₁ (g₂ ≫ f₃)] /-- The canonical isomorphism `(X₁ ⨿[Z₁] X₂) ⨿[Z₂] X₃ ≅ X₁ ⨿[Z₁] (X₂ ⨿[Z₂] X₃)`. -/ noncomputable def pushout_assoc : pushout (g₃ ≫ pushout.inr : _ ⟶ pushout g₁ g₂) g₄ ≅ pushout g₁ (g₂ ≫ pushout.inl : _ ⟶ pushout g₃ g₄) := (pushout_pushout_left_is_pushout g₁ g₂ g₃ g₄).cocone_point_unique_up_to_iso (pushout_pushout_right_is_pushout g₁ g₂ g₃ g₄) @[simp, reassoc] lemma inl_inl_pushout_assoc_hom : pushout.inl ≫ pushout.inl ≫ (pushout_assoc g₁ g₂ g₃ g₄).hom = pushout.inl := begin transitivity f₁ ≫ l₁, { congr' 1, exact (pushout_pushout_left_is_pushout g₁ g₂ g₃ g₄) .comp_cocone_point_unique_up_to_iso_hom _ walking_cospan.left }, { exact pushout.inl_desc _ _ _ } end @[simp, reassoc] lemma inr_inl_pushout_assoc_hom : pushout.inr ≫ pushout.inl ≫ (pushout_assoc g₁ g₂ g₃ g₄).hom = pushout.inl ≫ pushout.inr := begin transitivity f₂ ≫ l₁, { congr' 1, exact (pushout_pushout_left_is_pushout g₁ g₂ g₃ g₄) .comp_cocone_point_unique_up_to_iso_hom _ walking_cospan.left }, { exact pushout.inr_desc _ _ _ } end @[simp, reassoc] lemma inr_inr_pushout_assoc_inv : pushout.inr ≫ pushout.inr ≫ (pushout_assoc g₁ g₂ g₃ g₄).inv = pushout.inr := begin transitivity f₄ ≫ l₂', { congr' 1, exact (pushout_pushout_left_is_pushout g₁ g₂ g₃ g₄).comp_cocone_point_unique_up_to_iso_inv (pushout_pushout_right_is_pushout g₁ g₂ g₃ g₄) walking_cospan.right }, { exact pushout.inr_desc _ _ _ } end @[simp, reassoc] lemma inl_pushout_assoc_inv : pushout.inl ≫ (pushout_assoc g₁ g₂ g₃ g₄).inv = pushout.inl ≫ pushout.inl := by rw [iso.comp_inv_eq, category.assoc, inl_inl_pushout_assoc_hom] @[simp, reassoc] lemma inl_inr_pushout_assoc_inv : pushout.inl ≫ pushout.inr ≫ (pushout_assoc g₁ g₂ g₃ g₄).inv = pushout.inr ≫ pushout.inl := by rw [← category.assoc, iso.comp_inv_eq, category.assoc, inr_inl_pushout_assoc_hom] @[simp, reassoc] lemma inr_pushout_assoc_hom : pushout.inr ≫ (pushout_assoc g₁ g₂ g₃ g₄).hom = pushout.inr ≫ pushout.inr := by rw [← iso.eq_comp_inv, category.assoc, inr_inr_pushout_assoc_inv] end pushout_assoc variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms See <https://stacks.math.columbia.edu/tag/001W> -/ abbreviation has_pullbacks := has_limits_of_shape walking_cospan.{v} C /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ abbreviation has_pushouts := has_colimits_of_shape walking_span.{v} C /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ lemma has_pullbacks_of_has_limit_cospan [Π {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}, has_limit (cospan f g)] : has_pullbacks C := { has_limit := λ F, has_limit_of_iso (diagram_iso_cospan F).symm } /-- If `C` has all colimits of diagrams `span f g`, then it has all pushouts -/ lemma has_pushouts_of_has_colimit_span [Π {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z}, has_colimit (span f g)] : has_pushouts C := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } /-- The duality equivalence `walking_spanᵒᵖ ≌ walking_cospan` -/ def walking_span_op_equiv : walking_spanᵒᵖ ≌ walking_cospan := wide_pushout_shape_op_equiv _ /-- The duality equivalence `walking_cospanᵒᵖ ≌ walking_span` -/ def walking_cospan_op_equiv : walking_cospanᵒᵖ ≌ walking_span := wide_pullback_shape_op_equiv _ end category_theory.limits
d192a88ffc409ec683fd14ac9c3aa97f64b4ea7d
92b50235facfbc08dfe7f334827d47281471333b
/hott/hit/torus.hlean
889ef24dafb5e77f77a39cde6e9f8d6f799c16e7
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
3,539
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of the torus -/ import .two_quotient open two_quotient eq bool unit relation namespace torus definition torus_R (x y : unit) := bool local infix `⬝r`:75 := @e_closure.trans unit torus_R star star star local postfix `⁻¹ʳ`:(max+10) := @e_closure.symm unit torus_R star star local notation `[`:max a `]`:0 := @e_closure.of_rel unit torus_R star star a inductive torus_Q : Π⦃x y : unit⦄, e_closure torus_R x y → e_closure torus_R x y → Type := | Qmk : torus_Q ([ff] ⬝r [tt]) ([tt] ⬝r [ff]) definition torus := two_quotient torus_R torus_Q definition base : torus := incl0 _ _ star definition loop1 : base = base := incl1 _ _ ff definition loop2 : base = base := incl1 _ _ tt definition surf : loop1 ⬝ loop2 = loop2 ⬝ loop1 := incl2 _ _ torus_Q.Qmk -- protected definition rec {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- (x : torus) : P x := -- sorry -- example {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) (Pl2 : Pb =[loop2] Pb) -- (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) : torus.rec Pb Pl1 Pl2 Pf base = Pb := idp -- definition rec_loop1 {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : apdo (torus.rec Pb Pl1 Pl2 Pf) loop1 = Pl1 := -- sorry -- definition rec_loop2 {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : apdo (torus.rec Pb Pl1 Pl2 Pf) loop2 = Pl2 := -- sorry -- definition rec_surf {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : cubeover P rfl1 (apds (torus.rec Pb Pl1 Pl2 Pf) fill) Pf -- (vdeg_squareover !rec_loop2) (vdeg_squareover !rec_loop2) -- (vdeg_squareover !rec_loop1) (vdeg_squareover !rec_loop1) := -- sorry protected definition elim {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) (x : torus) : P := begin induction x, { exact Pb}, { induction s, { exact Pl1}, { exact Pl2}}, { induction q, exact Ps}, end protected definition elim_on [reducible] {P : Type} (x : torus) (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : P := torus.elim Pb Pl1 Pl2 Ps x definition elim_loop1 {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : ap (torus.elim Pb Pl1 Pl2 Ps) loop1 = Pl1 := !elim_incl1 definition elim_loop2 {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : ap (torus.elim Pb Pl1 Pl2 Ps) loop2 = Pl2 := !elim_incl1 definition elim_surf {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : square (ap02 (torus.elim Pb Pl1 Pl2 Ps) surf) Ps (!ap_con ⬝ (!elim_loop1 ◾ !elim_loop2)) (!ap_con ⬝ (!elim_loop2 ◾ !elim_loop1)) := !elim_incl2 end torus attribute torus.base [constructor] attribute /-torus.rec-/ torus.elim [unfold 6] [recursor 6] --attribute torus.elim_type [unfold 9] attribute /-torus.rec_on-/ torus.elim_on [unfold 2] --attribute torus.elim_type_on [unfold 6]
7c8176074d3ba52a970ce0085b3b20b75fca4c77
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/list/pairwise.lean
ed96558f726767a567ec5d25e3211f5dd1e30c1d
[ "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
17,657
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.count import data.list.lex import data.list.sublists import data.set.pairwise /-! # Pairwise relations on a list This file provides basic results about `list.pairwise` and `list.pw_filter` (definitions are in `data.list.defs`). `pairwise r [a 0, ..., a (n - 1)]` means `∀ i j, i < j → r (a i) (a j)`. For example, `pairwise (≠) l` means that all elements of `l` are distinct, and `pairwise (<) l` means that `l` is strictly increasing. `pw_filter r l` is the list obtained by iteratively adding each element of `l` that doesn't break the pairwiseness of the list we have so far. It thus yields `l'` a maximal sublist of `l` such that `pairwise r l'`. ## Tags sorted, nodup -/ open nat function namespace list variables {α β : Type*} {R : α → α → Prop} mk_iff_of_inductive_prop list.pairwise list.pairwise_iff /-! ### Pairwise -/ theorem rel_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a :: l)) : ∀ {a'}, a' ∈ l → R a a' := (pairwise_cons.1 p).1 theorem pairwise_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a :: l)) : pairwise R l := (pairwise_cons.1 p).2 theorem pairwise.tail : ∀ {l : list α} (p : pairwise R l), pairwise R l.tail | [] h := h | (a :: l) h := pairwise_of_pairwise_cons h theorem pairwise.drop : ∀ {l : list α} {n : ℕ}, list.pairwise R l → list.pairwise R (l.drop n) | _ 0 h := h | [] (n + 1) h := list.pairwise.nil | (a :: l) (n + 1) h := pairwise.drop (pairwise_cons.mp h).right theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l := begin induction p with a l r p IH generalizing H; constructor, { exact ball.imp_right (λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r }, { exact IH (λ a b m m', H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) } end theorem pairwise.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l := pairwise.imp_of_mem (λ a b _ _, H a b) theorem pairwise.and {S : α → α → Prop} {l : list α} : pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l := ⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩, λ ⟨hR, hS⟩, begin clear_, induction hR with a l R1 R2 IH; simp only [pairwise.nil, pairwise_cons] at *, exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩ end⟩ theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop} (H : ∀ a b, R a b → S a b → T a b) {l : list α} (hR : pairwise R l) (hS : pairwise S l) : pairwise T l := (pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b) theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l := ⟨pairwise.imp_of_mem (λ a b m m', (H m m').1), pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩ theorem pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l := pairwise.iff_of_mem (λ a b _ _, H a b) theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l := by induction l; [exact pairwise.nil, simp only [*, pairwise_cons, forall_2_true_iff, and_true]] theorem pairwise.and_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l := pairwise.iff_of_mem (by simp only [true_and, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise.imp_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l := pairwise.iff_of_mem (by simp only [forall_prop_of_true, iff_self, forall_2_true_iff] {contextual := tt}) theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁ | ._ ._ sublist.slnil h := h | ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n | ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) := (pairwise_of_sublist s n).cons (ball.imp_left s.subset i) theorem forall_of_forall_of_pairwise (H : symmetric R) {l : list α} (H₁ : ∀ x ∈ l, R x x) (H₂ : pairwise R l) : ∀ (x ∈ l) (y ∈ l), R x y := begin induction l with a l IH, { exact forall_mem_nil _ }, cases forall_mem_cons.1 H₁ with H₁₁ H₁₂, cases pairwise_cons.1 H₂ with H₂₁ H₂₂, rintro x (rfl | hx) y (rfl | hy), exacts [H₁₁, H₂₁ _ hy, H (H₂₁ _ hx), IH H₁₂ H₂₂ _ hx _ hy] end lemma forall_of_pairwise (H : symmetric R) {l : list α} (hl : pairwise R l) : (∀a∈l, ∀b∈l, a ≠ b → R a b) := forall_of_forall_of_pairwise (λ a b h hne, H (h hne.symm)) (λ _ _ h, (h rfl).elim) (pairwise.imp (λ _ _ h _, h) hl) theorem pairwise_singleton (R) (a : α) : pairwise R [a] := by simp only [pairwise_cons, mem_singleton, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp only [pairwise_cons, mem_singleton, forall_eq, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, and_true] theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y := by induction l₁ with x l₁ IH; [simp only [list.pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_true_iff, and_true, true_and, nil_append], simp only [cons_append, pairwise_cons, forall_mem_append, IH, forall_mem_cons, forall_and_distrib, and_assoc, and.left_comm]] theorem pairwise_append_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp only [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a :: l₂) ↔ pairwise R (a :: (l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_append_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp only [map, pairwise.nil] | (b :: l) := have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp only [forall_eq'], by simp only [map, pairwise_cons, mem_map, exists_imp_distrib, and_imp, this, pairwise_map] theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : pairwise S (map f l)) : pairwise R l := ((pairwise_map f).1 p).imp H theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : pairwise R l) : pairwise S (map f l) := (pairwise_map f).2 $ p.imp H theorem pairwise_filter_map (f : β → option α) {l : list β} : pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l := let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in begin simp only [option.mem_def], induction l with a l IH, { simp only [filter_map, pairwise.nil] }, cases e : f a with b, { rw [filter_map_cons_none _ _ e, IH, pairwise_cons], simp only [e, forall_prop_of_false not_false, forall_3_true_iff, true_and] }, rw [filter_map_cons_some _ _ _ e], simp only [pairwise_cons, mem_filter_map, exists_imp_distrib, and_imp, IH, e, forall_eq'], show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔ (∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l, from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl end theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β) (H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α} (p : pairwise R l) : pairwise S (filter_map f l) := (pairwise_filter_map _).2 $ p.imp H theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l := begin rw [← filter_map_eq_filter, pairwise_filter_map], apply pairwise.iff, intros, simp only [option.mem_def, option.guard_eq_some, and_imp, forall_eq'], end theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R l → pairwise R (filter p l) := pairwise_of_sublist (filter_sublist _) theorem pairwise_pmap {p : β → Prop} {f : Π b, p b → α} {l : list β} (h : ∀ x ∈ l, p x) : pairwise R (l.pmap f h) ↔ pairwise (λ b₁ b₂, ∀ (h₁ : p b₁) (h₂ : p b₂), R (f b₁ h₁) (f b₂ h₂)) l := begin induction l with a l ihl, { simp }, obtain ⟨ha, hl⟩ : p a ∧ ∀ b, b ∈ l → p b, by simpa using h, simp only [ihl hl, pairwise_cons, bex_imp_distrib, pmap, and.congr_left_iff, mem_pmap], refine λ _, ⟨λ H b hb hpa hpb, H _ _ hb rfl, _⟩, rintro H _ b hb rfl, exact H b hb _ _ end theorem pairwise.pmap {l : list α} (hl : pairwise R l) {p : α → Prop} {f : Π a, p a → β} (h : ∀ x ∈ l, p x) {S : β → β → Prop} (hS : ∀ ⦃x⦄ (hx : p x) ⦃y⦄ (hy : p y), R x y → S (f x hx) (f y hy)) : pairwise S (l.pmap f h) := begin refine (pairwise_pmap h).2 (pairwise.imp_of_mem _ hl), intros, apply hS, assumption end theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔ (∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L := begin induction L with l L IH, {simp only [join, pairwise.nil, forall_prop_of_false (not_mem_nil _), forall_const, and_self]}, have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔ ∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y := ⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩, simp only [join, pairwise_append, IH, mem_join, exists_imp_distrib, and_imp, this, forall_mem_cons, pairwise_cons], simp only [and_assoc, and_comm, and.left_comm], end @[simp] theorem pairwise_reverse : ∀ {R} {l : list α}, pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l := suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l), from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩, λ R l p, by induction p with a l h p IH; [apply pairwise.nil, simpa only [reverse_cons, pairwise_append, IH, pairwise_cons, forall_prop_of_false (not_mem_nil _), forall_true_iff, pairwise.nil, mem_reverse, mem_singleton, forall_eq, true_and] using h] lemma pairwise.set_pairwise {l : list α} (h : pairwise R l) (hr : symmetric R) : set.pairwise {x | x ∈ l} R := begin induction h with hd tl imp h IH, { simp }, { intros x hx y hy hxy, simp only [mem_cons_iff, set.mem_set_of_eq] at hx hy, rcases hx with rfl|hx; rcases hy with rfl|hy, { contradiction }, { exact imp y hy }, { exact hr (imp x hx) }, { exact IH x hx y hy hxy } } end lemma pairwise_of_reflexive_on_dupl_of_forall_ne [decidable_eq α] {l : list α} {r : α → α → Prop} (hr : ∀ a, 1 < count a l → r a a) (h : ∀ (a ∈ l) (b ∈ l), a ≠ b → r a b) : l.pairwise r := begin induction l with hd tl IH, { simp }, { rw list.pairwise_cons, split, { intros x hx, by_cases H : hd = x, { rw H, refine hr _ _, simpa [count_cons, H, nat.succ_lt_succ_iff, count_pos] using hx }, { exact h hd (mem_cons_self _ _) x (mem_cons_of_mem _ hx) H } }, { refine IH _ _, { intros x hx, refine hr _ _, rw count_cons, split_ifs, { exact hx.trans (nat.lt_succ_self _) }, { exact hx } }, { intros x hx y hy, exact h x (mem_cons_of_mem _ hx) y (mem_cons_of_mem _ hy) } } } end lemma pairwise_of_reflexive_of_forall_ne {l : list α} {r : α → α → Prop} (hr : reflexive r) (h : ∀ (a ∈ l) (b ∈ l), a ≠ b → r a b) : l.pairwise r := begin classical, refine pairwise_of_reflexive_on_dupl_of_forall_ne _ h, exact λ _ _, hr _ end theorem pairwise_iff_nth_le {R} : ∀ {l : list α}, pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁) | [] := by simp only [pairwise.nil, true_iff]; exact λ i j h, (nat.not_lt_zero j).elim h | (a :: l) := begin rw [pairwise_cons, pairwise_iff_nth_le], refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _, λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩, { cases j with j, {exact (nat.not_lt_zero _).elim h₂}, cases i with i, { exact H.1 _ (nth_le_mem l _ _) }, { exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } }, { rcases nth_le_of_mem m with ⟨n, h, rfl⟩, exact H _ _ (succ_lt_succ h) (succ_pos _) } end theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l → pairwise (lex (swap R)) (sublists' l) | _ pairwise.nil := pairwise_singleton _ _ | _ (@pairwise.cons _ _ a l H₁ H₂) := begin simp only [sublists'_cons, pairwise_append, pairwise_map, mem_sublists', mem_map, exists_imp_distrib, and_imp], have IH := pairwise_sublists' H₂, refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩, intros l₁ sl₁ x l₂ sl₂ e, subst e, cases l₁ with b l₁, {constructor}, exact lex.rel (H₁ _ $ sl₁.subset $ mem_cons_self _ _) end theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) : pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) := by have := pairwise_sublists' (pairwise_reverse.2 H); rwa [sublists'_reverse, pairwise_map] at this /-! ### Pairwise filtering -/ variable [decidable_rel R] @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a :: l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a :: l) = pw_filter R l := if_neg h theorem pw_filter_map (f : β → α) : Π (l : list β), pw_filter R (map f l) = map f (pw_filter (λ x y, R (f x) (f y)) l) | [] := rfl | (x :: xs) := if h : ∀ b ∈ pw_filter R (map f xs), R (f x) b then have h' : ∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ b hb, h _ (by rw [pw_filter_map]; apply mem_map_of_mem _ hb), by rw [map,pw_filter_cons_of_pos h,pw_filter_cons_of_pos h',pw_filter_map,map] else have h' : ¬∀ (b : β), b ∈ pw_filter (λ (x y : β), R (f x) (f y)) xs → R (f x) (f b), from λ hh, h $ λ a ha, by { rw [pw_filter_map,mem_map] at ha, rcases ha with ⟨b,hb₀,hb₁⟩, subst a, exact hh _ hb₀, }, by rw [map,pw_filter_cons_of_neg h,pw_filter_cons_of_neg h',pw_filter_map] theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x :: l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact (pw_filter_sublist l).cons_cons _ }, { rw [pw_filter_cons_of_neg h], exact sublist_cons_of_sublist _ (pw_filter_sublist l) }, end theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l := (pw_filter_sublist _).subset theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l) | [] := pairwise.nil | (x :: l) := begin by_cases (∀ y ∈ pw_filter R l, R x y), { rw [pw_filter_cons_of_pos h], exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ }, { rw [pw_filter_cons_of_neg h], exact pairwise_pw_filter l }, end theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l := ⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin induction l with x l IH, {refl}, cases pairwise_cons.1 p with al p, rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p], end⟩ @[simp] theorem pw_filter_idempotent {l : list α} : pw_filter R (pw_filter R l) = pw_filter R l := pw_filter_eq_self.mpr (pairwise_pw_filter l) theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) := ⟨begin induction l with x l IH, { exact λ _ _, false.elim }, simp only [forall_mem_cons], by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp only [pw_filter_cons_of_pos h, forall_mem_cons, and_imp], exact λ r H, ⟨r, IH H⟩ }, { rw [pw_filter_cons_of_neg h], refine λ H, ⟨_, IH H⟩, cases e : find (λ y, ¬ R x y) (pw_filter R l) with k, { refine h.elim (ball.imp_right _ (find_eq_none.1 e)), exact λ y _, not_not.1 }, { have := find_some e, exact (neg_trans (H k (find_mem e))).resolve_right this } } end, ball.imp_left (pw_filter_subset l)⟩ end list
ab1911dfc8d17f137922de1667558c45eb441d7b
4727251e0cd73359b15b664c3170e5d754078599
/src/data/tree.lean
6e3e388016a30d878d9f4a4fdec2040321ee2ccd
[ "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
2,938
lean
/- Copyright (c) 2019 mathlib community. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Wojciech Nawrocki -/ import data.rbtree.init import data.num.basic /-! # Binary tree Provides binary tree storage for values of any type, with O(lg n) retrieval. See also `data.rbtree` for red-black trees - this version allows more operations to be defined and is better suited for in-kernel computation. ## References <https://leanprover-community.github.io/archive/stream/113488-general/topic/tactic.20question.html> -/ /-- A binary tree with values stored in non-leaf nodes. -/ @[derive has_reflect, derive decidable_eq] inductive {u} tree (α : Type u) : Type u | nil : tree | node : α → tree → tree → tree namespace tree universe u variable {α : Type u} /-- Construct a string representation of a tree. Provides a `has_repr` instance. -/ def repr [has_repr α] : tree α → string | nil := "nil" | (node a t1 t2) := "tree.node " ++ has_repr.repr a ++ " (" ++ repr t1 ++ ") (" ++ repr t2 ++ ")" instance [has_repr α] : has_repr (tree α) := ⟨tree.repr⟩ instance : inhabited (tree α) := ⟨nil⟩ /-- Makes a `tree α` out of a red-black tree. -/ def of_rbnode : rbnode α → tree α | rbnode.leaf := nil | (rbnode.red_node l a r) := node a (of_rbnode l) (of_rbnode r) | (rbnode.black_node l a r) := node a (of_rbnode l) (of_rbnode r) /-- Finds the index of an element in the tree assuming the tree has been constructed according to the provided decidable order on its elements. If it hasn't, the result will be incorrect. If it has, but the element is not in the tree, returns none. -/ def index_of (lt : α → α → Prop) [decidable_rel lt] (x : α) : tree α → option pos_num | nil := none | (node a t₁ t₂) := match cmp_using lt x a with | ordering.lt := pos_num.bit0 <$> index_of t₁ | ordering.eq := some pos_num.one | ordering.gt := pos_num.bit1 <$> index_of t₂ end /-- Retrieves an element uniquely determined by a `pos_num` from the tree, taking the following path to get to the element: - `bit0` - go to left child - `bit1` - go to right child - `pos_num.one` - retrieve from here -/ def get : pos_num → tree α → option α | _ nil := none | pos_num.one (node a t₁ t₂) := some a | (pos_num.bit0 n) (node a t₁ t₂) := t₁.get n | (pos_num.bit1 n) (node a t₁ t₂) := t₂.get n /-- Retrieves an element from the tree, or the provided default value if the index is invalid. See `tree.get`. -/ def get_or_else (n : pos_num) (t : tree α) (v : α) : α := (t.get n).get_or_else v /-- Apply a function to each value in the tree. This is the `map` function for the `tree` functor. TODO: implement `traversable tree`. -/ def map {β} (f : α → β) : tree α → tree β | nil := nil | (node a l r) := node (f a) (map l) (map r) end tree
e29224ab78b8ad629db69e62520ea265136f89ee
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/combinatorics/hales_jewett.lean
908ce0e4d3b88cc5c86fb8ea86f6742470f3db38
[ "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
15,423
lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import data.fintype.basic import algebra.big_operators.basic /-! # The Hales-Jewett theorem We prove the Hales-Jewett theorem and deduce Van der Waerden's theorem as a corollary. The Hales-Jewett theorem is a result in Ramsey theory dealing with *combinatorial lines*. Given an 'alphabet' `α : Type*` and `a b : α`, an example of a combinatorial line in `α^5` is `{ (a, x, x, b, x) | x : α }`. See `combinatorics.line` for a precise general definition. The Hales-Jewett theorem states that for any fixed finite types `α` and `κ`, there exists a (potentially huge) finite type `ι` such that whenever `ι → α` is `κ`-colored (i.e. for any coloring `C : (ι → α) → κ`), there exists a monochromatic line. We prove the Hales-Jewett theorem using the idea of *color focusing* and a *product argument*. See the proof of `combinatorics.line.exists_mono_in_high_dimension'` for details. The version of Van der Waerden's theorem in this file states that whenever a commutative monoid `M` is finitely colored and `S` is a finite subset, there exists a monochromatic homothetic copy of `S`. This follows from the Hales-Jewett theorem by considering the map `(ι → S) → M` sending `v` to `∑ i : ι, v i`, which sends a combinatorial line to a homothetic copy of `S`. ## Main results - `combinatorics.line.exists_mono_in_high_dimension`: the Hales-Jewett theorem. - `combinatorics.exists_mono_homothetic_copy`: a generalization of Van der Waerden's theorem. ## Implementation details For convenience, we work directly with finite types instead of natural numbers. That is, we write `α, ι, κ` for (finite) types where one might traditionally use natural numbers `n, H, c`. This allows us to work directly with `α`, `option α`, `(ι → α) → κ`, and `ι ⊕ ι'` instead of `fin n`, `fin (n+1)`, `fin (c^(n^H))`, and `fin (H + H')`. ## Todo - Prove a finitary version of Van der Waerden's theorem (either by compactness or by modifying the current proof). - One could reformulate the proof of Hales-Jewett to give explicit upper bounds on the number of coordinates needed. ## Tags combinatorial line, Ramsey theory, arithmetic progession ### References * https://en.wikipedia.org/wiki/Hales%E2%80%93Jewett_theorem -/ open_locale classical open_locale big_operators universes u v namespace combinatorics /-- The type of combinatorial lines. A line `l : line α ι` in the hypercube `ι → α` defines a function `α → ι → α` from `α` to the hypercube, such that for each coordinate `i : ι`, the function `λ x, l x i` is either `id` or constant. We require lines to be nontrivial in the sense that `λ x, l x i` is `id` for at least one `i`. Formally, a line is represented by the function `l.idx_fun : ι → option α` which says whether `λ x, l x i` is `id` (corresponding to `l.idx_fun i = none`) or constantly `y` (corresponding to `l.idx_fun i = some y`). When `α` has size `1` there can be many elements of `line α ι` defining the same function. -/ structure line (α ι : Type*) := (idx_fun : ι → option α) (proper : ∃ i, idx_fun i = none) namespace line /- This lets us treat a line `l : line α ι` as a function `α → ι → α`. -/ instance (α ι) : has_coe_to_fun (line α ι) (λ _, α → ι → α) := ⟨λ l x i, (l.idx_fun i).get_or_else x⟩ /-- A line is monochromatic if all its points are the same color. -/ def is_mono {α ι κ} (C : (ι → α) → κ) (l : line α ι) : Prop := ∃ c, ∀ x, C (l x) = c /-- The diagonal line. It is the identity at every coordinate. -/ def diagonal (α ι) [nonempty ι] : line α ι := { idx_fun := λ _, none, proper := ⟨classical.arbitrary ι, rfl⟩ } instance (α ι) [nonempty ι] : inhabited (line α ι) := ⟨diagonal α ι⟩ /-- The type of lines that are only one color except possibly at their endpoints. -/ structure almost_mono {α ι κ : Type*} (C : (ι → option α) → κ) := (line : line (option α) ι) (color : κ) (has_color : ∀ x : α, C (line (some x)) = color) instance {α ι κ : Type*} [nonempty ι] [inhabited κ] : inhabited (almost_mono (λ v : ι → option α, (default : κ))) := ⟨{ line := default, color := default, has_color := λ _, rfl }⟩ /-- The type of collections of lines such that - each line is only one color except possibly at its endpoint - the lines all have the same endpoint - the colors of the lines are distinct. Used in the proof `exists_mono_in_high_dimension`. -/ structure color_focused {α ι κ : Type*} (C : (ι → option α) → κ) := (lines : multiset (almost_mono C)) (focus : ι → option α) (is_focused : ∀ p ∈ lines, almost_mono.line p none = focus) (distinct_colors : (lines.map almost_mono.color).nodup) instance {α ι κ} (C : (ι → option α) → κ) : inhabited (color_focused C) := ⟨⟨0, λ _, none, λ _, false.elim, multiset.nodup_zero⟩⟩ /-- A function `f : α → α'` determines a function `line α ι → line α' ι`. For a coordinate `i`, `l.map f` is the identity at `i` if `l` is, and constantly `f y` if `l` is constantly `y` at `i`. -/ def map {α α' ι} (f : α → α') (l : line α ι) : line α' ι := { idx_fun := λ i, (l.idx_fun i).map f, proper := ⟨l.proper.some, by rw [l.proper.some_spec, option.map_none'] ⟩ } /-- A point in `ι → α` and a line in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def vertical {α ι ι'} (v : ι → α) (l : line α ι') : line α (ι ⊕ ι') := { idx_fun := sum.elim (some ∘ v) l.idx_fun, proper := ⟨sum.inr l.proper.some, l.proper.some_spec⟩ } /-- A line in `ι → α` and a point in `ι' → α` determine a line in `ι ⊕ ι' → α`. -/ def horizontal {α ι ι'} (l : line α ι) (v : ι' → α) : line α (ι ⊕ ι') := { idx_fun := sum.elim l.idx_fun (some ∘ v), proper := ⟨sum.inl l.proper.some, l.proper.some_spec⟩ } /-- One line in `ι → α` and one in `ι' → α` together determine a line in `ι ⊕ ι' → α`. -/ def prod {α ι ι'} (l : line α ι) (l' : line α ι') : line α (ι ⊕ ι') := { idx_fun := sum.elim l.idx_fun l'.idx_fun, proper := ⟨sum.inl l.proper.some, l.proper.some_spec⟩ } lemma apply {α ι} (l : line α ι) (x : α) : l x = λ i, (l.idx_fun i).get_or_else x := rfl lemma apply_none {α ι} (l : line α ι) (x : α) (i : ι) (h : l.idx_fun i = none) : l x i = x := by simp only [option.get_or_else_none, h, l.apply] lemma apply_of_ne_none {α ι} (l : line α ι) (x : α) (i : ι) (h : l.idx_fun i ≠ none) : some (l x i) = l.idx_fun i := by rw [l.apply, option.get_or_else_of_ne_none h] @[simp] lemma map_apply {α α' ι} (f : α → α') (l : line α ι) (x : α) : l.map f (f x) = f ∘ l x := by simp only [line.apply, line.map, option.get_or_else_map] @[simp] lemma vertical_apply {α ι ι'} (v : ι → α) (l : line α ι') (x : α) : l.vertical v x = sum.elim v (l x) := by { funext i, cases i; refl } @[simp] lemma horizontal_apply {α ι ι'} (l : line α ι) (v : ι' → α) (x : α) : l.horizontal v x = sum.elim (l x) v := by { funext i, cases i; refl } @[simp] lemma prod_apply {α ι ι'} (l : line α ι) (l' : line α ι') (x : α) : l.prod l' x = sum.elim (l x) (l' x) := by { funext i, cases i; refl } @[simp] lemma diagonal_apply {α ι} [nonempty ι] (x : α) : line.diagonal α ι x = λ i, x := by simp_rw [line.apply, line.diagonal, option.get_or_else_none] /-- The Hales-Jewett theorem. This version has a restriction on universe levels which is necessary for the proof. See `exists_mono_in_high_dimension` for a fully universe-polymorphic version. -/ private theorem exists_mono_in_high_dimension' : ∀ (α : Type u) [fintype α] (κ : Type (max v u)) [fintype κ], ∃ (ι : Type) (_ : fintype ι), ∀ C : (ι → α) → κ, ∃ l : line α ι, l.is_mono C := -- The proof proceeds by induction on `α`. fintype.induction_empty_option -- We have to show that the theorem is invariant under `α ≃ α'` for the induction to work. (λ α α' e, forall_imp $ λ κ, forall_imp $ λ _, Exists.imp $ λ ι, Exists.imp $ λ _ h C, let ⟨l, c, lc⟩ := h (λ v, C (e ∘ v)) in ⟨l.map e, c, e.forall_congr_left.mp $ λ x, by rw [←lc x, line.map_apply]⟩) begin -- This deals with the degenerate case where `α` is empty. introsI κ _, by_cases h : nonempty κ, { resetI, exact ⟨unit, infer_instance, λ C, ⟨default, classical.arbitrary _, pempty.rec _⟩⟩, }, { exact ⟨empty, infer_instance, λ C, (h ⟨C (empty.rec _)⟩).elim⟩, } end begin -- Now we have to show that the theorem holds for `option α` if it holds for `α`. introsI α _ ihα κ _, -- Later we'll need `α` to be nonempty. So we first deal with the trivial case where `α` is empty. -- Then `option α` has only one element, so any line is monochromatic. by_cases h : nonempty α, work_on_goal 1 { refine ⟨unit, infer_instance, λ C, ⟨diagonal _ _, C (λ _, none), _⟩⟩, rintros (_ | ⟨a⟩), refl, exact (h ⟨a⟩).elim, }, -- The key idea is to show that for every `r`, in high dimension we can either find -- `r` color focused lines or a monochromatic line. suffices key : ∀ r : ℕ, ∃ (ι : Type) (_ : fintype ι), ∀ C : (ι → (option α)) → κ, (∃ s : color_focused C, s.lines.card = r) ∨ (∃ l, is_mono C l), -- Given the key claim, we simply take `r = |κ| + 1`. We cannot have this many distinct colors so -- we must be in the second case, where there is a monochromatic line. { obtain ⟨ι, _inst, hι⟩ := key (fintype.card κ + 1), refine ⟨ι, _inst, λ C, (hι C).resolve_left _⟩, rintro ⟨s, sr⟩, apply nat.not_succ_le_self (fintype.card κ), rw [←nat.add_one, ←sr, ←multiset.card_map, ←finset.card_mk], exact finset.card_le_univ ⟨_, s.distinct_colors⟩ }, -- We now prove the key claim, by induction on `r`. intro r, induction r with r ihr, -- The base case `r = 0` is trivial as the empty collection is color-focused. { exact ⟨empty, infer_instance, λ C, or.inl ⟨default, multiset.card_zero⟩⟩, }, -- Supposing the key claim holds for `r`, we need to show it for `r+1`. First pick a high enough -- dimension `ι` for `r`. obtain ⟨ι, _inst, hι⟩ := ihr, resetI, -- Then since the theorem holds for `α` with any number of colors, pick a dimension `ι'` such that -- `ι' → α` always has a monochromatic line whenever it is `(ι → option α) → κ`-colored. specialize ihα ((ι → option α) → κ), obtain ⟨ι', _inst, hι'⟩ := ihα, resetI, -- We claim that `ι ⊕ ι'` works for `option α` and `κ`-coloring. refine ⟨ι ⊕ ι', infer_instance, _⟩, intro C, -- A `κ`-coloring of `ι ⊕ ι' → option α` induces an `(ι → option α) → κ`-coloring of `ι' → α`. specialize hι' (λ v' v, C (sum.elim v (some ∘ v'))), -- By choice of `ι'` this coloring has a monochromatic line `l'` with color class `C'`, where -- `C'` is a `κ`-coloring of `ι → α`. obtain ⟨l', C', hl'⟩ := hι', -- If `C'` has a monochromatic line, then so does `C`. We use this in two places below. have mono_of_mono : (∃ l, is_mono C' l) → (∃ l, is_mono C l), { rintro ⟨l, c, hl⟩, refine ⟨l.horizontal (some ∘ l' (classical.arbitrary α)), c, λ x, _⟩, rw [line.horizontal_apply, ←hl, ←hl'], }, -- By choice of `ι`, `C'` either has `r` color-focused lines or a monochromatic line. specialize hι C', rcases hι with ⟨s, sr⟩ | _, -- By above, we are done if `C'` has a monochromatic line. work_on_goal 1 { exact or.inr (mono_of_mono hι) }, -- Here we assume `C'` has `r` color focused lines. We split into cases depending on whether one of -- these `r` lines has the same color as the focus point. by_cases h : ∃ p ∈ s.lines, (p : almost_mono _).color = C' s.focus, -- If so then this is a `C'`-monochromatic line and we are done. { obtain ⟨p, p_mem, hp⟩ := h, refine or.inr (mono_of_mono ⟨p.line, p.color, _⟩), rintro (_ | _), rw [hp, s.is_focused p p_mem], apply p.has_color, }, -- If not, we get `r+1` color focused lines by taking the product of the `r` lines with `l'` and -- adding to this the vertical line obtained by the focus point and `l`. refine or.inl ⟨⟨(s.lines.map _).cons ⟨(l'.map some).vertical s.focus, C' s.focus, λ x, _⟩, sum.elim s.focus (l'.map some none), _, _⟩, _⟩, -- The vertical line is almost monochromatic. { rw [vertical_apply, ←congr_fun (hl' x), line.map_apply], }, { refine λ p, ⟨p.line.prod (l'.map some), p.color, λ x, _⟩, -- The product lines are almost monochromatic. rw [line.prod_apply, line.map_apply, ←p.has_color, ←congr_fun (hl' x)], }, -- Our `r+1` lines have the same endpoint. { simp_rw [multiset.mem_cons, multiset.mem_map], rintros _ (rfl | ⟨q, hq, rfl⟩), { rw line.vertical_apply, }, { rw [line.prod_apply, s.is_focused q hq], }, }, -- Our `r+1` lines have distinct colors (this is why we needed to split into cases above). { rw [multiset.map_cons, multiset.map_map, multiset.nodup_cons, multiset.mem_map], exact ⟨λ ⟨q, hq, he⟩, h ⟨q, hq, he⟩, s.distinct_colors⟩, }, -- Finally, we really do have `r+1` lines! { rw [multiset.card_cons, multiset.card_map, sr], }, end /-- The Hales-Jewett theorem: for any finite types `α` and `κ`, there exists a finite type `ι` such that whenever the hypercube `ι → α` is `κ`-colored, there is a monochromatic combinatorial line. -/ theorem exists_mono_in_high_dimension (α : Type u) [fintype α] (κ : Type v) [fintype κ] : ∃ (ι : Type) [fintype ι], ∀ C : (ι → α) → κ, ∃ l : line α ι, l.is_mono C := let ⟨ι, ιfin, hι⟩ := exists_mono_in_high_dimension' α (ulift κ) in ⟨ι, ιfin, λ C, let ⟨l, c, hc⟩ := hι (ulift.up ∘ C) in ⟨l, c.down, λ x, by rw ←hc⟩ ⟩ end line /-- A generalization of Van der Waerden's theorem: if `M` is a finitely colored commutative monoid, and `S` is a finite subset, then there exists a monochromatic homothetic copy of `S`. -/ theorem exists_mono_homothetic_copy {M κ} [add_comm_monoid M] (S : finset M) [fintype κ] (C : M → κ) : ∃ (a > 0) (b : M) (c : κ), ∀ s ∈ S, C (a • s + b) = c := begin obtain ⟨ι, _inst, hι⟩ := line.exists_mono_in_high_dimension S κ, resetI, specialize hι (λ v, C $ ∑ i, v i), obtain ⟨l, c, hl⟩ := hι, set s : finset ι := { i ∈ finset.univ | l.idx_fun i = none } with hs, refine ⟨s.card, finset.card_pos.mpr ⟨l.proper.some, _⟩, ∑ i in sᶜ, ((l.idx_fun i).map coe).get_or_else 0, c, _⟩, { rw [hs, finset.sep_def, finset.mem_filter], exact ⟨finset.mem_univ _, l.proper.some_spec⟩, }, intros x xs, rw ←hl ⟨x, xs⟩, clear hl, congr, rw ←finset.sum_add_sum_compl s, congr' 1, { rw ←finset.sum_const, apply finset.sum_congr rfl, intros i hi, rw [hs, finset.sep_def, finset.mem_filter] at hi, rw [l.apply_none _ _ hi.right, subtype.coe_mk], }, { apply finset.sum_congr rfl, intros i hi, rw [hs, finset.sep_def, finset.compl_filter, finset.mem_filter] at hi, obtain ⟨y, hy⟩ := option.ne_none_iff_exists.mp hi.right, simp_rw [line.apply, ←hy, option.map_some', option.get_or_else_some], }, end end combinatorics
61c614e9674ab964139b57a899225e6aea97de85
26bff4ed296b8373c92b6b025f5d60cdf02104b9
/tests/lean/hott/433.hlean
3d9d2f541220aeb26d5609dc986f3be683f1f954
[ "Apache-2.0" ]
permissive
guiquanz/lean
b8a878ea24f237b84b0e6f6be2f300e8bf028229
242f8ba0486860e53e257c443e965a82ee342db3
refs/heads/master
1,526,680,092,098
1,427,492,833,000
1,427,493,281,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,854
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Ported from Coq HoTT Theorems about pi-types (dependent function spaces) -/ import types.sigma open eq equiv is_equiv funext namespace pi universe variables l k variables {A A' : Type.{l}} {B : A → Type.{k}} {B' : A' → Type.{k}} {C : Πa, B a → Type} {D : Πa b, C a b → Type} {a a' a'' : A} {b b₁ b₂ : B a} {b' : B a'} {b'' : B a''} {f g : Πa, B a} /- Paths -/ /- Paths [p : f ≈ g] in a function type [Πx:X, P x] are equivalent to functions taking values in path types, [H : Πx:X, f x ≈ g x], or concisely, [H : f ∼ g]. This equivalence, however, is just the combination of [apD10] and function extensionality [funext], and as such, [path_forall], et seq. are given in axioms.funext and path: -/ /- Now we show how these things compute. -/ definition apD10_path_pi (H : funext) (h : f ∼ g) : apD10 (eq_of_homotopy h) ∼ h := apD10 (retr apD10 h) definition path_pi_eta (H : funext) (p : f = g) : eq_of_homotopy (apD10 p) = p := sect apD10 p print classes definition path_pi_idp (H : funext) : eq_of_homotopy (λx : A, refl (f x)) = refl f := path_pi_eta H _ /- The identification of the path space of a dependent function space, up to equivalence, is of course just funext. -/ definition path_equiv_homotopy (H : funext) (f g : Πx, B x) : (f = g) ≃ (f ∼ g) := equiv.mk _ !is_equiv_apD definition is_equiv_path_pi [instance] (H : funext) (f g : Πx, B x) : is_equiv (@eq_of_homotopy _ _ f g) := is_equiv_inv apD10 definition homotopy_equiv_path (H : funext) (f g : Πx, B x) : (f ∼ g) ≃ (f = g) := equiv.mk _ (is_equiv_path_pi H f g) /- Transport -/ protected definition transport (p : a = a') (f : Π(b : B a), C a b) : (transport (λa, Π(b : B a), C a b) p f) ∼ (λb, transport (C a') !tr_inv_tr (transportD _ _ p _ (f (p⁻¹ ▹ b)))) := eq.rec_on p (λx, idp) /- A special case of [transport_pi] where the type [B] does not depend on [A], and so it is just a fixed type [B]. -/ definition transport_constant {C : A → A' → Type} (p : a = a') (f : Π(b : A'), C a b) : (eq.transport (λa, Π(b : A'), C a b) p f) ∼ (λb, eq.transport (λa, C a b) p (f b)) := eq.rec_on p (λx, idp) /- Maps on paths -/ /- The action of maps given by lambda. -/ definition ap_lambdaD (H : funext) {C : A' → Type} (p : a = a') (f : Πa b, C b) : ap (λa b, f a b) p = eq_of_homotopy (λb, ap (λa, f a b) p) := begin apply (eq.rec_on p), apply inverse, apply (path_pi_idp H) end /- Dependent paths -/ /- with more implicit arguments the conclusion of the following theorem is (Π(b : B a), transportD B C p b (f b) = g (eq.transport B p b)) ≃ (eq.transport (λa, Π(b : B a), C a b) p f = g) -/ definition dpath_pi (H : funext) (p : a = a') (f : Π(b : B a), C a b) (g : Π(b' : B a'), C a' b') : (Π(b : B a), p ▹D (f b) = g (p ▹ b)) ≃ (p ▹ f = g) := eq.rec_on p (λg, homotopy_equiv_path H f g) g section open sigma sigma.ops /- more implicit arguments: (Π(b : B a), eq.transport C (sigma.path p idp) (f b) = g (p ▹ b)) ≃ (Π(b : B a), transportD B (λ(a : A) (b : B a), C ⟨a, b⟩) p b (f b) = g (eq.transport B p b)) -/ definition dpath_pi_sigma {C : (Σa, B a) → Type} (p : a = a') (f : Π(b : B a), C ⟨a, b⟩) (g : Π(b' : B a'), C ⟨a', b'⟩) : (Π(b : B a), (sigma.sigma_eq p idp) ▹ (f b) = g (p ▹ b)) ≃ (Π(b : B a), p ▹D (f b) = g (p ▹ b)) := eq.rec_on p (λg, !equiv.refl) g end variables (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') definition transport_V [reducible] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▹ u protected definition functor_pi : (Π(a:A), B a) → (Π(a':A'), B' a') := (λg a', f1 a' (g (f0 a'))) /- Equivalences -/ definition isequiv_functor_pi [instance] (f0 : A' → A) (f1 : Π(a':A'), B (f0 a') → B' a') [H0 : is_equiv f0] [H1 : Πa', @is_equiv (B (f0 a')) (B' a') (f1 a')] : is_equiv (functor_pi f0 f1) := begin apply (adjointify (functor_pi f0 f1) (functor_pi (f0⁻¹) (λ(a : A) (b' : B' (f0⁻¹ a)), transport B (retr f0 a) ((f1 (f0⁻¹ a))⁻¹ b')))), intro h, apply eq_of_homotopy, esimp {functor_pi, function.compose}, -- simplify (and unfold function_pi and function.compose) --first subgoal intro a', esimp, rewrite adj, rewrite -transport_compose, rewrite {f1 a' _}(fn_tr_eq_tr_fn _ f1 _), rewrite (retr (f1 _) _), apply apD, intro h, beta, apply eq_of_homotopy, intro a, esimp, apply (transport_V (λx, retr f0 a ▹ x = h a) (sect (f1 _) _)), esimp {function.id}, apply apD end end pi
c9a67951c68aefdd70a453f183de34c32859221c
592ee40978ac7604005a4e0d35bbc4b467389241
/Library/generated/mathscheme-lean/Group.lean
b259ae41ef152a7ade042347dc412ea26bc42049
[]
no_license
ysharoda/Deriving-Definitions
3e149e6641fae440badd35ac110a0bd705a49ad2
dfecb27572022de3d4aa702cae8db19957523a59
refs/heads/master
1,679,127,857,700
1,615,939,007,000
1,615,939,007,000
229,785,731
4
0
null
null
null
null
UTF-8
Lean
false
false
8,818
lean
import init.data.nat.basic import init.data.fin.basic import data.vector import .Prelude open Staged open nat open fin open vector section Group structure Group (A : Type) : Type := (e : A) (op : (A → (A → A))) (lunit_e : (∀ {x : A} , (op e x) = x)) (runit_e : (∀ {x : A} , (op x e) = x)) (associative_op : (∀ {x y z : A} , (op (op x y) z) = (op x (op y z)))) (inv : (A → A)) (leftInverse_inv_op_e : (∀ {x : A} , (op x (inv x)) = e)) (rightInverse_inv_op_e : (∀ {x : A} , (op (inv x) x) = e)) open Group structure Sig (AS : Type) : Type := (eS : AS) (opS : (AS → (AS → AS))) (invS : (AS → AS)) structure Product (A : Type) : Type := (eP : (Prod A A)) (opP : ((Prod A A) → ((Prod A A) → (Prod A A)))) (invP : ((Prod A A) → (Prod A A))) (lunit_eP : (∀ {xP : (Prod A A)} , (opP eP xP) = xP)) (runit_eP : (∀ {xP : (Prod A A)} , (opP xP eP) = xP)) (associative_opP : (∀ {xP yP zP : (Prod A A)} , (opP (opP xP yP) zP) = (opP xP (opP yP zP)))) (leftInverse_inv_op_eP : (∀ {xP : (Prod A A)} , (opP xP (invP xP)) = eP)) (rightInverse_inv_op_eP : (∀ {xP : (Prod A A)} , (opP (invP xP) xP) = eP)) structure Hom {A1 : Type} {A2 : Type} (Gr1 : (Group A1)) (Gr2 : (Group A2)) : Type := (hom : (A1 → A2)) (pres_e : (hom (e Gr1)) = (e Gr2)) (pres_op : (∀ {x1 x2 : A1} , (hom ((op Gr1) x1 x2)) = ((op Gr2) (hom x1) (hom x2)))) (pres_inv : (∀ {x1 : A1} , (hom ((inv Gr1) x1)) = ((inv Gr2) (hom x1)))) structure RelInterp {A1 : Type} {A2 : Type} (Gr1 : (Group A1)) (Gr2 : (Group A2)) : Type 1 := (interp : (A1 → (A2 → Type))) (interp_e : (interp (e Gr1) (e Gr2))) (interp_op : (∀ {x1 x2 : A1} {y1 y2 : A2} , ((interp x1 y1) → ((interp x2 y2) → (interp ((op Gr1) x1 x2) ((op Gr2) y1 y2)))))) (interp_inv : (∀ {x1 : A1} {y1 : A2} , ((interp x1 y1) → (interp ((inv Gr1) x1) ((inv Gr2) y1))))) inductive GroupTerm : Type | eL : GroupTerm | opL : (GroupTerm → (GroupTerm → GroupTerm)) | invL : (GroupTerm → GroupTerm) open GroupTerm inductive ClGroupTerm (A : Type) : Type | sing : (A → ClGroupTerm) | eCl : ClGroupTerm | opCl : (ClGroupTerm → (ClGroupTerm → ClGroupTerm)) | invCl : (ClGroupTerm → ClGroupTerm) open ClGroupTerm inductive OpGroupTerm (n : ℕ) : Type | v : ((fin n) → OpGroupTerm) | eOL : OpGroupTerm | opOL : (OpGroupTerm → (OpGroupTerm → OpGroupTerm)) | invOL : (OpGroupTerm → OpGroupTerm) open OpGroupTerm inductive OpGroupTerm2 (n : ℕ) (A : Type) : Type | v2 : ((fin n) → OpGroupTerm2) | sing2 : (A → OpGroupTerm2) | eOL2 : OpGroupTerm2 | opOL2 : (OpGroupTerm2 → (OpGroupTerm2 → OpGroupTerm2)) | invOL2 : (OpGroupTerm2 → OpGroupTerm2) open OpGroupTerm2 def simplifyCl {A : Type} : ((ClGroupTerm A) → (ClGroupTerm A)) | (opCl eCl x) := x | (opCl x eCl) := x | eCl := eCl | (opCl x1 x2) := (opCl (simplifyCl x1) (simplifyCl x2)) | (invCl x1) := (invCl (simplifyCl x1)) | (sing x1) := (sing x1) def simplifyOpB {n : ℕ} : ((OpGroupTerm n) → (OpGroupTerm n)) | (opOL eOL x) := x | (opOL x eOL) := x | eOL := eOL | (opOL x1 x2) := (opOL (simplifyOpB x1) (simplifyOpB x2)) | (invOL x1) := (invOL (simplifyOpB x1)) | (v x1) := (v x1) def simplifyOp {n : ℕ} {A : Type} : ((OpGroupTerm2 n A) → (OpGroupTerm2 n A)) | (opOL2 eOL2 x) := x | (opOL2 x eOL2) := x | eOL2 := eOL2 | (opOL2 x1 x2) := (opOL2 (simplifyOp x1) (simplifyOp x2)) | (invOL2 x1) := (invOL2 (simplifyOp x1)) | (v2 x1) := (v2 x1) | (sing2 x1) := (sing2 x1) def evalB {A : Type} : ((Group A) → (GroupTerm → A)) | Gr eL := (e Gr) | Gr (opL x1 x2) := ((op Gr) (evalB Gr x1) (evalB Gr x2)) | Gr (invL x1) := ((inv Gr) (evalB Gr x1)) def evalCl {A : Type} : ((Group A) → ((ClGroupTerm A) → A)) | Gr (sing x1) := x1 | Gr eCl := (e Gr) | Gr (opCl x1 x2) := ((op Gr) (evalCl Gr x1) (evalCl Gr x2)) | Gr (invCl x1) := ((inv Gr) (evalCl Gr x1)) def evalOpB {A : Type} {n : ℕ} : ((Group A) → ((vector A n) → ((OpGroupTerm n) → A))) | Gr vars (v x1) := (nth vars x1) | Gr vars eOL := (e Gr) | Gr vars (opOL x1 x2) := ((op Gr) (evalOpB Gr vars x1) (evalOpB Gr vars x2)) | Gr vars (invOL x1) := ((inv Gr) (evalOpB Gr vars x1)) def evalOp {A : Type} {n : ℕ} : ((Group A) → ((vector A n) → ((OpGroupTerm2 n A) → A))) | Gr vars (v2 x1) := (nth vars x1) | Gr vars (sing2 x1) := x1 | Gr vars eOL2 := (e Gr) | Gr vars (opOL2 x1 x2) := ((op Gr) (evalOp Gr vars x1) (evalOp Gr vars x2)) | Gr vars (invOL2 x1) := ((inv Gr) (evalOp Gr vars x1)) def inductionB {P : (GroupTerm → Type)} : ((P eL) → ((∀ (x1 x2 : GroupTerm) , ((P x1) → ((P x2) → (P (opL x1 x2))))) → ((∀ (x1 : GroupTerm) , ((P x1) → (P (invL x1)))) → (∀ (x : GroupTerm) , (P x))))) | pel popl pinvl eL := pel | pel popl pinvl (opL x1 x2) := (popl _ _ (inductionB pel popl pinvl x1) (inductionB pel popl pinvl x2)) | pel popl pinvl (invL x1) := (pinvl _ (inductionB pel popl pinvl x1)) def inductionCl {A : Type} {P : ((ClGroupTerm A) → Type)} : ((∀ (x1 : A) , (P (sing x1))) → ((P eCl) → ((∀ (x1 x2 : (ClGroupTerm A)) , ((P x1) → ((P x2) → (P (opCl x1 x2))))) → ((∀ (x1 : (ClGroupTerm A)) , ((P x1) → (P (invCl x1)))) → (∀ (x : (ClGroupTerm A)) , (P x)))))) | psing pecl popcl pinvcl (sing x1) := (psing x1) | psing pecl popcl pinvcl eCl := pecl | psing pecl popcl pinvcl (opCl x1 x2) := (popcl _ _ (inductionCl psing pecl popcl pinvcl x1) (inductionCl psing pecl popcl pinvcl x2)) | psing pecl popcl pinvcl (invCl x1) := (pinvcl _ (inductionCl psing pecl popcl pinvcl x1)) def inductionOpB {n : ℕ} {P : ((OpGroupTerm n) → Type)} : ((∀ (fin : (fin n)) , (P (v fin))) → ((P eOL) → ((∀ (x1 x2 : (OpGroupTerm n)) , ((P x1) → ((P x2) → (P (opOL x1 x2))))) → ((∀ (x1 : (OpGroupTerm n)) , ((P x1) → (P (invOL x1)))) → (∀ (x : (OpGroupTerm n)) , (P x)))))) | pv peol popol pinvol (v x1) := (pv x1) | pv peol popol pinvol eOL := peol | pv peol popol pinvol (opOL x1 x2) := (popol _ _ (inductionOpB pv peol popol pinvol x1) (inductionOpB pv peol popol pinvol x2)) | pv peol popol pinvol (invOL x1) := (pinvol _ (inductionOpB pv peol popol pinvol x1)) def inductionOp {n : ℕ} {A : Type} {P : ((OpGroupTerm2 n A) → Type)} : ((∀ (fin : (fin n)) , (P (v2 fin))) → ((∀ (x1 : A) , (P (sing2 x1))) → ((P eOL2) → ((∀ (x1 x2 : (OpGroupTerm2 n A)) , ((P x1) → ((P x2) → (P (opOL2 x1 x2))))) → ((∀ (x1 : (OpGroupTerm2 n A)) , ((P x1) → (P (invOL2 x1)))) → (∀ (x : (OpGroupTerm2 n A)) , (P x))))))) | pv2 psing2 peol2 popol2 pinvol2 (v2 x1) := (pv2 x1) | pv2 psing2 peol2 popol2 pinvol2 (sing2 x1) := (psing2 x1) | pv2 psing2 peol2 popol2 pinvol2 eOL2 := peol2 | pv2 psing2 peol2 popol2 pinvol2 (opOL2 x1 x2) := (popol2 _ _ (inductionOp pv2 psing2 peol2 popol2 pinvol2 x1) (inductionOp pv2 psing2 peol2 popol2 pinvol2 x2)) | pv2 psing2 peol2 popol2 pinvol2 (invOL2 x1) := (pinvol2 _ (inductionOp pv2 psing2 peol2 popol2 pinvol2 x1)) def stageB : (GroupTerm → (Staged GroupTerm)) | eL := (Now eL) | (opL x1 x2) := (stage2 opL (codeLift2 opL) (stageB x1) (stageB x2)) | (invL x1) := (stage1 invL (codeLift1 invL) (stageB x1)) def stageCl {A : Type} : ((ClGroupTerm A) → (Staged (ClGroupTerm A))) | (sing x1) := (Now (sing x1)) | eCl := (Now eCl) | (opCl x1 x2) := (stage2 opCl (codeLift2 opCl) (stageCl x1) (stageCl x2)) | (invCl x1) := (stage1 invCl (codeLift1 invCl) (stageCl x1)) def stageOpB {n : ℕ} : ((OpGroupTerm n) → (Staged (OpGroupTerm n))) | (v x1) := (const (code (v x1))) | eOL := (Now eOL) | (opOL x1 x2) := (stage2 opOL (codeLift2 opOL) (stageOpB x1) (stageOpB x2)) | (invOL x1) := (stage1 invOL (codeLift1 invOL) (stageOpB x1)) def stageOp {n : ℕ} {A : Type} : ((OpGroupTerm2 n A) → (Staged (OpGroupTerm2 n A))) | (sing2 x1) := (Now (sing2 x1)) | (v2 x1) := (const (code (v2 x1))) | eOL2 := (Now eOL2) | (opOL2 x1 x2) := (stage2 opOL2 (codeLift2 opOL2) (stageOp x1) (stageOp x2)) | (invOL2 x1) := (stage1 invOL2 (codeLift1 invOL2) (stageOp x1)) structure StagedRepr (A : Type) (Repr : (Type → Type)) : Type := (eT : (Repr A)) (opT : ((Repr A) → ((Repr A) → (Repr A)))) (invT : ((Repr A) → (Repr A))) end Group
78a9b57f0fe3bf0d8ba5d8cbf2e08305b3548cd4
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/interactive/goTo.lean
5882374e2ffd3924597a1703da65a020f649a72c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,095
lean
import Lean.Elab structure Bar where structure Foo where foo₁ : Nat foo₂ : Nat bar : Bar def mkFoo₁ : Foo := { --v textDocument/definition foo₁ := 1 --v textDocument/declaration foo₂ := 2 --v textDocument/typeDefinition bar := ⟨⟩ } structure HandWrittenStruct where n : Nat -- def HandWrittenStruct.n := fun | mk n => n --v textDocument/definition def hws : HandWrittenStruct := { --v textDocument/definition n := 3 } --v textDocument/declaration def mkFoo₂ := mkFoo₁ syntax (name := elabTest) "test" : term @[termElab elabTest] def elabElabTest : Lean.Elab.Term.TermElab := fun _ _ => do let stx ← `(2) Lean.Elab.Term.elabTerm stx none --v textDocument/declaration #check test --^ textDocument/definition def Baz (α : Type) := α #check fun (b : Baz Nat) => b --^ textDocument/typeDefinition example : Nat := let a := 1 --v textDocument/definition a + b --^ textDocument/definition where b := 2 macro_rules | `(test) => `(3) #check test --^ textDocument/definition
c83784234d45945f58caae9bf2e52656fec9b5eb
f20db13587f4dd28a4b1fbd31953afd491691fa0
/library/init/data/list/basic.lean
da272096038810c5de1ab1ca3a05719e89793655
[ "Apache-2.0" ]
permissive
AHartNtkn/lean
9a971edfc6857c63edcbf96bea6841b9a84cf916
0d83a74b26541421fc1aa33044c35b03759710ed
refs/heads/master
1,620,592,591,236
1,516,749,881,000
1,516,749,881,000
118,697,288
1
0
null
1,516,759,470,000
1,516,759,470,000
null
UTF-8
Lean
false
false
9,906
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic init.data.nat.basic init.data.bool.basic init.propext open decidable list universes u v w instance (α : Type u) : inhabited (list α) := ⟨list.nil⟩ variables {α : Type u} {β : Type v} {γ : Type w} namespace list protected def has_dec_eq [s : decidable_eq α] : decidable_eq (list α) | [] [] := is_true rfl | (a::as) [] := is_false (λ h, list.no_confusion h) | [] (b::bs) := is_false (λ h, list.no_confusion h) | (a::as) (b::bs) := match s a b with | is_true hab := match has_dec_eq as bs with | is_true habs := is_true (eq.subst hab (eq.subst habs rfl)) | is_false nabs := is_false (λ h, list.no_confusion h (λ _ habs, absurd habs nabs)) end | is_false nab := is_false (λ h, list.no_confusion h (λ hab _, absurd hab nab)) end instance [decidable_eq α] : decidable_eq (list α) := list.has_dec_eq @[simp] protected def append : list α → list α → list α | [] l := l | (h :: s) t := h :: (append s t) instance : has_append (list α) := ⟨list.append⟩ protected def mem : α → list α → Prop | a [] := false | a (b :: l) := a = b ∨ mem a l instance : has_mem α (list α) := ⟨list.mem⟩ instance decidable_mem [decidable_eq α] (a : α) : ∀ (l : list α), decidable (a ∈ l) | [] := is_false not_false | (b::l) := if h₁ : a = b then is_true (or.inl h₁) else match decidable_mem l with | is_true h₂ := is_true (or.inr h₂) | is_false h₂ := is_false (not_or h₁ h₂) end instance : has_emptyc (list α) := ⟨list.nil⟩ protected def erase {α} [decidable_eq α] : list α → α → list α | [] b := [] | (a::l) b := if a = b then l else a :: erase l b protected def bag_inter {α} [decidable_eq α] : list α → list α → list α | [] _ := [] | _ [] := [] | (a::l₁) l₂ := if a ∈ l₂ then a :: bag_inter l₁ (l₂.erase a) else bag_inter l₁ l₂ protected def diff {α} [decidable_eq α] : list α → list α → list α | l [] := l | l₁ (a::l₂) := if a ∈ l₁ then diff (l₁.erase a) l₂ else diff l₁ l₂ @[simp] def length : list α → nat | [] := 0 | (a :: l) := length l + 1 def empty : list α → bool | [] := tt | (_ :: _) := ff open option nat @[simp] def nth : list α → nat → option α | [] n := none | (a :: l) 0 := some a | (a :: l) (n+1) := nth l n @[simp] def nth_le : Π (l : list α) (n), n < l.length → α | [] n h := absurd h (not_lt_zero n) | (a :: l) 0 h := a | (a :: l) (n+1) h := nth_le l n (le_of_succ_le_succ h) @[simp] def head [inhabited α] : list α → α | [] := default α | (a :: l) := a @[simp] def tail : list α → list α | [] := [] | (a :: l) := l def reverse_core : list α → list α → list α | [] r := r | (a::l) r := reverse_core l (a::r) def reverse : list α → list α := λ l, reverse_core l [] @[simp] def map (f : α → β) : list α → list β | [] := [] | (a :: l) := f a :: map l @[simp] def map₂ (f : α → β → γ) : list α → list β → list γ | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys def join : list (list α) → list α | [] := [] | (l :: ls) := l ++ join ls def filter_map (f : α → option β) : list α → list β | [] := [] | (a::l) := match f a with | none := filter_map l | some b := b :: filter_map l end def filter (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: filter l else filter l def partition (p : α → Prop) [decidable_pred p] : list α → list α × list α | [] := ([], []) | (a::l) := let (l₁, l₂) := partition l in if p a then (a :: l₁, l₂) else (l₁, a :: l₂) def drop_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then drop_while l else a::l def span (p : α → Prop) [decidable_pred p] : list α → list α × list α | [] := ([], []) | (a::xs) := if p a then let (l, r) := span xs in (a :: l, r) else ([], a::xs) def find_index (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (a::l) := if p a then 0 else succ (find_index l) def index_of [decidable_eq α] (a : α) : list α → nat := find_index (eq a) def remove_all [decidable_eq α] (xs ys : list α) : list α := filter (∉ ys) xs def update_nth : list α → ℕ → α → list α | (x::xs) 0 a := a :: xs | (x::xs) (i+1) a := x :: update_nth xs i a | [] _ _ := [] def remove_nth : list α → ℕ → list α | [] _ := [] | (x::xs) 0 := xs | (x::xs) (i+1) := x :: remove_nth xs i @[simp] def drop : ℕ → list α → list α | 0 a := a | (succ n) [] := [] | (succ n) (x::r) := drop n r @[simp] def take : ℕ → list α → list α | 0 a := [] | (succ n) [] := [] | (succ n) (x :: r) := x :: take n r @[simp] def foldl (f : α → β → α) : α → list β → α | a [] := a | a (b :: l) := foldl (f a b) l @[simp] def foldr (f : α → β → β) (b : β) : list α → β | [] := b | (a :: l) := f a (foldr l) def any (l : list α) (p : α → bool) : bool := foldr (λ a r, p a || r) ff l def all (l : list α) (p : α → bool) : bool := foldr (λ a r, p a && r) tt l def bor (l : list bool) : bool := any l id def band (l : list bool) : bool := all l id def zip_with (f : α → β → γ) : list α → list β → list γ | (x::xs) (y::ys) := f x y :: zip_with xs ys | _ _ := [] def zip : list α → list β → list (prod α β) := zip_with prod.mk def unzip : list (α × β) → list α × list β | [] := ([], []) | ((a, b) :: t) := match unzip t with (al, bl) := (a::al, b::bl) end protected def insert [decidable_eq α] (a : α) (l : list α) : list α := if a ∈ l then l else a :: l instance [decidable_eq α] : has_insert α (list α) := ⟨list.insert⟩ protected def union [decidable_eq α] (l₁ l₂ : list α) : list α := foldr insert l₂ l₁ instance [decidable_eq α] : has_union (list α) := ⟨list.union⟩ protected def inter [decidable_eq α] (l₁ l₂ : list α) : list α := filter (∈ l₂) l₁ instance [decidable_eq α] : has_inter (list α) := ⟨list.inter⟩ @[simp] def repeat (a : α) : ℕ → list α | 0 := [] | (succ n) := a :: repeat n def range_core : ℕ → list ℕ → list ℕ | 0 l := l | (succ n) l := range_core n (n :: l) def range (n : ℕ) : list ℕ := range_core n [] def iota : ℕ → list ℕ | 0 := [] | (succ n) := succ n :: iota n def enum_from : ℕ → list α → list (ℕ × α) | n [] := nil | n (x :: xs) := (n, x) :: enum_from (n + 1) xs def enum : list α → list (ℕ × α) := enum_from 0 @[simp] def last : Π l : list α, l ≠ [] → α | [] h := absurd rfl h | [a] h := a | (a::b::l) h := last (b::l) (λ h, list.no_confusion h) def ilast [inhabited α] : list α → α | [] := arbitrary α | [a] := a | [a, b] := b | (a::b::l) := ilast l def init : list α → list α | [] := [] | [a] := [] | (a::l) := a::init l def intersperse (sep : α) : list α → list α | [] := [] | [x] := [x] | (x::xs) := x::sep::intersperse xs def intercalate (sep : list α) (xs : list (list α)) : list α := join (intersperse sep xs) @[inline] def bind {α : Type u} {β : Type v} (a : list α) (b : α → list β) : list β := join (map b a) @[inline] def ret {α : Type u} (a : α) : list α := [a] protected def lt [has_lt α] : list α → list α → Prop | [] [] := false | [] (b::bs) := true | (a::as) [] := false | (a::as) (b::bs) := a < b ∨ lt as bs instance [has_lt α] : has_lt (list α) := ⟨list.lt⟩ instance has_decidable_lt [has_lt α] [h : decidable_rel ((<) : α → α → Prop)] : Π l₁ l₂ : list α, decidable (l₁ < l₂) | [] [] := is_false not_false | [] (b::bs) := is_true trivial | (a::as) [] := is_false not_false | (a::as) (b::bs) := match h a b with | is_true h₁ := is_true (or.inl h₁) | is_false h₁ := match has_decidable_lt as bs with | is_true h₂ := is_true (or.inr h₂) | is_false h₂ := is_false (λ hd, or.elim hd (λ n₁, absurd n₁ h₁) (λ n₂, absurd n₂ h₂)) end end @[reducible] protected def le [has_lt α] (a b : list α) : Prop := ¬ b < a instance [has_lt α] : has_le (list α) := ⟨list.le⟩ instance has_decidable_le [has_lt α] [h : decidable_rel ((<) : α → α → Prop)] : Π l₁ l₂ : list α, decidable (l₁ ≤ l₂) := λ a b, not.decidable lemma le_eq_not_gt [has_lt α] : ∀ l₁ l₂ : list α, (l₁ ≤ l₂) = ¬ (l₂ < l₁) := λ l₁ l₂, rfl lemma lt_eq_not_ge [has_lt α] [decidable_rel ((<) : α → α → Prop)] : ∀ l₁ l₂ : list α, (l₁ < l₂) = ¬ (l₂ ≤ l₁) := λ l₁ l₂, show (l₁ < l₂) = ¬ ¬ (l₁ < l₂), from eq.subst (propext (not_not_iff (l₁ < l₂))).symm rfl /-- `is_prefix_of l₁ l₂` returns `tt` iff `l₁` is a prefix of `l₂`. -/ def is_prefix_of [decidable_eq α] : list α → list α → bool | [] _ := tt | _ [] := ff | (a::as) (b::bs) := to_bool (a = b) && is_prefix_of as bs /-- `is_suffix_of l₁ l₂` returns `tt` iff `l₁` is a suffix of `l₂`. -/ def is_suffix_of [decidable_eq α] (l₁ l₂ : list α) : bool := is_prefix_of l₁.reverse l₂.reverse end list namespace bin_tree private def to_list_aux : bin_tree α → list α → list α | empty as := as | (leaf a) as := a::as | (node l r) as := to_list_aux l (to_list_aux r as) def to_list (t : bin_tree α) : list α := to_list_aux t [] end bin_tree
0ce0548abc0cd3a891268e4dd9250e487e663fe5
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/unsigned/default.lean
76bee50c3ce5442329745d77c76937edb6ac480d
[ "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
227
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.unsigned.basic init.data.unsigned.ops
080a2d667e93bc6af24cb050b5e15ef36dd99982
7b4371534ac437ca8cfb325dd5c6638ff111d31a
/other_problems.lean
29b49b5de3d20ea3aa1c4fe3887334a973bf225f
[]
no_license
Shamrock-Frost/boolean_rings
6d78294568b6b9ad7b9c67b5de5e9545227826da
5da11beeaa37ec186c1deff946f2dbf7594fceb4
refs/heads/master
1,588,394,857,485
1,553,973,949,000
1,553,973,949,000
177,757,941
0
0
null
null
null
null
UTF-8
Lean
false
false
9,827
lean
import .algebra_util section definitions variables {R : Type _} [ring R] def is_nilpotent (x : R) := ∃ n : ℕ, x^n = 0 def is_unit (u : R) := ∃ v, u*v = 1 def sequence (A : Type _) := nat → A def convolve (a b : sequence R) := λ n, sum_over (λ j : fin (nat.succ n), a j.val * b (n - j.val)) infix ` ∗ `:70 := convolve lemma convolution_assoc : ∀ a b c : sequence R, (a ∗ b) ∗ c = a ∗ (b ∗ c) := begin intros, funext, dsimp [(∗), (∗)], transitivity sum_over (λ (j : fin (nat.succ n)), sum_over (λ (j_1 : fin (nat.succ (j.val))), a (j_1.val) * b (j.val - j_1.val) * c (n - j.val))), { congr, funext, rw mul_sum_over_right }, transitivity sum_over (λ (j : fin (nat.succ n)), sum_over (λ (j_1 : fin (nat.succ (n - j.val))), a (j.val) * (b (j_1.val) * c (n - j.val - j_1.val)))), { rw double_sum_triangle (λ (j j_1 : fin (nat.succ n)), a (j_1.val) * b (j.val - j_1.val) * c (n - j.val)), congr, funext, have : nat.succ n - k.val = nat.succ (n - k.val), rw nat.succ_sub (nat.le_of_succ_le_succ k.is_lt), congr, funext, exact this, apply fin.funext _ this, intro x, cases x, simp *, rw nat.add_sub_cancel, rw ← mul_assoc, apply congr_arg, apply congr_arg, rw nat.sub_sub, rw add_comm }, { congr, funext, rw mul_sum_over_left } end structure power_series (R' : Type _) := (coefficients : sequence R') lemma power_series.eq {R' : Type _} : ∀ p q : power_series R', (∀ n, p.coefficients n = q.coefficients n) → p = q | (power_series.mk a) (power_series.mk b) := λ h, congr_arg power_series.mk (funext h) postfix `[[x]]`:100 := power_series def power_series.zero_coeff : sequence R := λ _, 0 def power_series.one_coeff : sequence R | 0 := 1 | (nat.succ _) := 0 lemma power_series.one_coeff_of_pos : ∀ {n}, 0 < n → power_series.one_coeff n = (0 : R) := by { intros, cases n, exfalso, exact lt_irrefl 0 a, refl } meta def power_series_preamble := `[intros, apply power_series.eq, intro, dsimp [power_series.coefficients]] instance : ring (R[[x]]) := { ring . zero := power_series.mk power_series.zero_coeff, one := power_series.mk power_series.one_coeff, add := λ p q, power_series.mk (λ n, p.coefficients n + q.coefficients n), neg := λ p, power_series.mk (λ n, - p.coefficients n), mul := λ p q, power_series.mk (convolve p.coefficients q.coefficients), zero_add := by { power_series_preamble, apply zero_add }, add_zero := by { power_series_preamble, apply add_zero }, add_left_neg := by { power_series_preamble, apply add_left_neg }, add_assoc := by { power_series_preamble, apply add_assoc }, add_comm := by { power_series_preamble, apply add_comm }, mul_assoc := by { intros, cases a, cases b, cases c, dsimp [power_series.coefficients], rw convolution_assoc }, one_mul := by { power_series_preamble, dsimp [(∗)], rw sum_over.step_front, dsimp [power_series.one_coeff], rw one_mul, transitivity a.coefficients n + 0, congr, rw ← sum_over_eq_zero, congr, funext, transitivity 0 * a.coefficients (n - nat.succ (j.val)), congr, apply sum_over_eq_zero, apply zero_mul, apply add_zero }, mul_one := by { power_series_preamble, dsimp [(∗)], rw sum_over.step, rw nat.sub_self, dsimp [power_series.one_coeff], rw mul_one, transitivity 0 + a.coefficients n, congr, rw ← sum_over_eq_zero, congr, funext, dsimp [fin.restrict], transitivity a.coefficients k.val * 0, congr, rw power_series.one_coeff_of_pos (nat.sub_pos_of_lt k.is_lt), apply mul_zero, apply zero_add }, left_distrib := by { power_series_preamble, dsimp [(∗)], rw ← sum_over_sum, congr, funext, apply left_distrib }, right_distrib := by { power_series_preamble, dsimp [(∗)], rw ← sum_over_sum, congr, funext, apply right_distrib } } end definitions section lemmas variables {R : Type _} [ring R] lemma my_mul_zero : ∀ x : R, x * 0 = 0 := λ x, add_group.eq_zero_of_add_eq_self $ eq.symm $ calc x * 0 = x * (0 + 0) : by rw zero_add ... = x * 0 + x * 0 : left_distrib _ _ _ end lemmas namespace problem1 section parameters {R : Type _} [ring R] lemma a : 1 * 1 = (1 : R) := mul_one 1 lemma b : (- 1) * (- 1) = (1 : R) := have (-1)*(-1) = -(-1 : R), from add_group.inv_unique (-1 : R) (-1 * -1) $ calc -1 * (-1 : R) + -1 = -1 * -1 + -1 * 1 : by rw mul_one ... = (-1) * (-1 + 1) : by rw eq.symm (left_distrib (-1 : R) (-1) 1) ... = (-1) * 0 : by rw [neg_add_eq_sub, sub_self] ... = 0 : my_mul_zero (-1), show (-1 : R) * (-1) = 1, from eq.trans this $ neg_neg (1 : R) end end problem1 namespace problem2 section parameters {R : Type _} [comm_ring R] lemma a : ∀ x y : R, is_nilpotent x → is_nilpotent y → is_nilpotent (x + y) := begin intros x y hx hy, cases hx with n hx, cases hy with m hy, existsi n + m, rw binomial_theorem x y (mul_comm x y), rw ← @sum_over_eq_zero _ _ (n+m+1), dsimp [binomial_expansion], congr, funext, cases k with k hk, simp, by_cases k < n, { rw (_ : n + m - k = m + (n - k)), rw [monoid.pow_of_sum_eq_mul, hy], simp, rw [nat.add_comm, nat.add_sub_assoc], apply le_of_lt, assumption }, { rw (_ : x^k = x^(n + (k - n))), rw [monoid.pow_of_sum_eq_mul, hx], simp, congr, rw [nat.add_comm, nat.sub_add_cancel], apply le_of_not_gt, assumption } end lemma b.helper1 : ∀ (x : R) (n : nat), x^n = 0 → (- x)^n = 0 := by intros; rw neg_eq_neg_one_mul; rw [power_of_prod, a, mul_zero] lemma b.helper2 : ∀ (x y : R), x * y = 1 → ∀ (n : nat), x^n * y^n = 1 := by intros; rw [← power_of_prod]; rw a; rw power_of_one n lemma b : ∀ x y : R, is_nilpotent x → is_unit y → is_unit (x + y) := begin intros x y hx hy, cases hy with y_inv hy, cases hx with n hx, cases n with n; simp [(^), mul_n_times] at hx, { existsi (0 : R), rw hx, apply mul_zero }, cases n with n, { simp [ mul_n_times] at hx, subst hx, rw zero_add, existsi y_inv, assumption }, rw (_ : (x + y) = -((- 1) - x * y_inv) * y), { existsi y_inv * elephant (- 1) (x * y_inv) (nat.succ (nat.succ (n * 2))), rw mul_assoc, transitivity -(-1 - x * y_inv) * ((y * y_inv) * elephant (-1) (x * y_inv) (nat.succ (nat.succ (n * 2)))), rw mul_assoc, rw [hy, one_mul], { rw [neg_eq_neg_one_mul, mul_assoc], rw [← elephant_teacup], rw (_ : (x * y_inv) ^ nat.succ (nat.succ (nat.succ (n * 2))) = (x * y_inv) ^ ((n+2) + (n + 1))), { rw [monoid.pow_of_sum_eq_mul, power_of_prod], rw (_ : x ^ (n + 2) = mul_n_times x (nat.succ n) * x), rw [hx, zero_mul, zero_mul, sub_zero, mul_comm], transitivity (-1 : R)^((n+2)*2), { dsimp [(^)], congr, dsimp [(*)], rw [(_ : nat.add 1 0 = 1), (_ : nat.add n 0 = n), (_ : nat.mul (n+2) 1 = n + 2)], rw [(_ : nat.mul n 2 = n + n), (_ : n + 2 = n.succ.succ)], rw ← nat.succ_add, rw ← nat.succ_add, refl, any_goals {refl}, rw ← nat.mul_two, refl, transitivity (n+2)*1, refl, rw mul_one }, { rw mul_comm, rw exp_of_prod, rw (_ : (-1)^2 = (1 : R)), apply power_of_one, dsimp [(^), mul_n_times], rw [one_mul], rw problem1.b }, { refl } }, congr, rw nat.mul_two, rw [(_ : nat.add n 0 = n), (_ : n + 2 = n.succ.succ)], rw [← nat.succ_add, ← nat.succ_add], refl, refl, refl, rw mul_comm, } }, { rw [neg_sub, sub_neg_eq_add, right_distrib], rw [one_mul, mul_assoc, mul_comm _ y, hy, mul_one] } end end end problem2 -- for parts a and c, see boolean_rings namespace problem3 lemma b {R} [integral_domain R] : (∀ x : R, x*x = x) → (∀ x : R, x = 1 ∨ x = 0) := begin intros is_bool x, rw (_ : x = 1 ↔ 1 + -x = 0), apply eq_zero_or_eq_zero_of_mul_eq_zero, rw [right_distrib, neg_mul_eq_neg_mul_symm, is_bool], rw one_mul, apply add_neg_self, constructor; intro h, subst h, apply add_neg_self, rw eq_add_of_add_neg_eq h, simp, end end problem3 namespace problem4 section parameters {R : Type _} [ring R] def a.helper1 (aₙ : sequence R) (b₀ : R) : sequence R | 0 := b₀ | (nat.succ n) := b₀ * -sum_over (λ (j : fin (nat.succ n)), have this : n - j.val < nat.succ n := nat.lt_of_le_of_lt (nat.sub_le _ _) (nat.lt_succ_self _), aₙ j.val.succ * a.helper1 (n - j.val)) lemma a.helper1.of_zero (aₙ : sequence R) (b₀ : R) : a.helper1 aₙ b₀ 0 = b₀ := rfl lemma a.helper1.of_succ (aₙ : sequence R) (b₀ : R) : ∀ n, a.helper1 aₙ b₀ (nat.succ n) = b₀ * -sum_over (λ (j : fin (nat.succ n)), aₙ j.val.succ * a.helper1 aₙ b₀ (n - j.val)) := λ _, rfl lemma a : ∀ p : R[[x]], is_unit p ↔ is_unit (p.coefficients 0) := begin intro p, constructor, { intro h, cases h with q h, existsi q.coefficients 0, have : (p*q).coefficients 0 = power_series.coefficients 1 0, { rw h }, dsimp [power_series.coefficients, (∗)] at this, dsimp [sum_over] at this, rw zero_add at this, exact this }, { intro h, cases h with b₀ h, existsi (power_series.mk (a.helper1 p.coefficients b₀)), apply power_series.eq, intro, dsimp [power_series.coefficients], cases n with n, { dsimp [(∗), sum_over], rw (a.helper1.of_zero), rw [zero_add, h], refl }, { dsimp [(∗)], rw sum_over.step_front, simp, rw [a.helper1.of_succ, ← mul_assoc, h, one_mul], rw add_comm, rw add_neg_self, refl } } end end end problem4 section week2 end week2
f7f825e064263531da0447212a8500edcbea5afe
92b50235facfbc08dfe7f334827d47281471333b
/hott/init/path.hlean
81f31f54d8ac607fd666ddf6f95a6a2761f7a827
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
25,449
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .function .datatypes .relation .tactic open function eq /- Path equality -/ namespace eq variables {A B C : Type} {P : A → Type} {x y z t : A} --notation a = b := eq a b notation x = y `:>`:50 A:49 := @eq A x y definition idp [reducible] [constructor] {a : A} := refl a definition idpath [reducible] [constructor] (a : A) := refl a -- unbased path induction definition rec' [reducible] [unfold 6] {P : Π (a b : A), (a = b) → Type} (H : Π (a : A), P a a idp) {a b : A} (p : a = b) : P a b p := eq.rec (H a) p definition rec_on' [reducible] [unfold 5] {P : Π (a b : A), (a = b) → Type} {a b : A} (p : a = b) (H : Π (a : A), P a a idp) : P a b p := eq.rec (H a) p /- Concatenation and inverse -/ definition concat [trans] [unfold 6] (p : x = y) (q : y = z) : x = z := eq.rec (λp', p') q p definition inverse [symm] [unfold 4] (p : x = y) : y = x := eq.rec (refl x) p infix ⬝ := concat postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded postfix [parsing-only] `⁻¹ᵖ`:std.prec.max_plus := inverse /- The 1-dimensional groupoid structure -/ -- The identity path is a right unit. definition con_idp [unfold-full] (p : x = y) : p ⬝ idp = p := idp -- The identity path is a right unit. definition idp_con [unfold 4] (p : x = y) : idp ⬝ p = p := eq.rec_on p idp -- Concatenation is associative. definition con.assoc' (p : x = y) (q : y = z) (r : z = t) : p ⬝ (q ⬝ r) = (p ⬝ q) ⬝ r := eq.rec_on r (eq.rec_on q idp) definition con.assoc (p : x = y) (q : y = z) (r : z = t) : (p ⬝ q) ⬝ r = p ⬝ (q ⬝ r) := eq.rec_on r (eq.rec_on q idp) -- The left inverse law. definition con.right_inv [unfold 4] (p : x = y) : p ⬝ p⁻¹ = idp := eq.rec_on p idp -- The right inverse law. definition con.left_inv [unfold 4] (p : x = y) : p⁻¹ ⬝ p = idp := eq.rec_on p idp /- Several auxiliary theorems about canceling inverses across associativity. These are somewhat redundant, following from earlier theorems. -/ definition inv_con_cancel_left (p : x = y) (q : y = z) : p⁻¹ ⬝ (p ⬝ q) = q := eq.rec_on q (eq.rec_on p idp) definition con_inv_cancel_left (p : x = y) (q : x = z) : p ⬝ (p⁻¹ ⬝ q) = q := eq.rec_on q (eq.rec_on p idp) definition con_inv_cancel_right (p : x = y) (q : y = z) : (p ⬝ q) ⬝ q⁻¹ = p := eq.rec_on q (eq.rec_on p idp) definition inv_con_cancel_right (p : x = z) (q : y = z) : (p ⬝ q⁻¹) ⬝ q = p := eq.rec_on q (take p, eq.rec_on p idp) p -- Inverse distributes over concatenation definition con_inv (p : x = y) (q : y = z) : (p ⬝ q)⁻¹ = q⁻¹ ⬝ p⁻¹ := eq.rec_on q (eq.rec_on p idp) definition inv_con_inv_left (p : y = x) (q : y = z) : (p⁻¹ ⬝ q)⁻¹ = q⁻¹ ⬝ p := eq.rec_on q (eq.rec_on p idp) -- universe metavariables definition inv_con_inv_right (p : x = y) (q : z = y) : (p ⬝ q⁻¹)⁻¹ = q ⬝ p⁻¹ := eq.rec_on p (take q, eq.rec_on q idp) q definition inv_con_inv_inv (p : y = x) (q : z = y) : (p⁻¹ ⬝ q⁻¹)⁻¹ = q ⬝ p := eq.rec_on p (eq.rec_on q idp) -- Inverse is an involution. definition inv_inv (p : x = y) : p⁻¹⁻¹ = p := eq.rec_on p idp -- auxiliary definition used by 'cases' tactic definition elim_inv_inv {A : Type} {a b : A} {C : a = b → Type} (H₁ : a = b) (H₂ : C (H₁⁻¹⁻¹)) : C H₁ := eq.rec_on (inv_inv H₁) H₂ /- Theorems for moving things around in equations -/ definition con_eq_of_eq_inv_con {p : x = z} {q : y = z} {r : y = x} : p = r⁻¹ ⬝ q → r ⬝ p = q := eq.rec_on r (take p h, !idp_con ⬝ h ⬝ !idp_con) p definition con_eq_of_eq_con_inv [unfold 5] {p : x = z} {q : y = z} {r : y = x} : r = q ⬝ p⁻¹ → r ⬝ p = q := eq.rec_on p (take q h, h) q definition inv_con_eq_of_eq_con {p : x = z} {q : y = z} {r : x = y} : p = r ⬝ q → r⁻¹ ⬝ p = q := eq.rec_on r (take q h, !idp_con ⬝ h ⬝ !idp_con) q definition con_inv_eq_of_eq_con [unfold 5] {p : z = x} {q : y = z} {r : y = x} : r = q ⬝ p → r ⬝ p⁻¹ = q := eq.rec_on p (take r h, h) r definition eq_con_of_inv_con_eq {p : x = z} {q : y = z} {r : y = x} : r⁻¹ ⬝ q = p → q = r ⬝ p := eq.rec_on r (take p h, !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹) p definition eq_con_of_con_inv_eq [unfold 5] {p : x = z} {q : y = z} {r : y = x} : q ⬝ p⁻¹ = r → q = r ⬝ p := eq.rec_on p (take q h, h) q definition eq_inv_con_of_con_eq {p : x = z} {q : y = z} {r : x = y} : r ⬝ q = p → q = r⁻¹ ⬝ p := eq.rec_on r (take q h, !idp_con⁻¹ ⬝ h ⬝ !idp_con⁻¹) q definition eq_con_inv_of_con_eq [unfold 5] {p : z = x} {q : y = z} {r : y = x} : q ⬝ p = r → q = r ⬝ p⁻¹ := eq.rec_on p (take r h, h) r definition eq_of_con_inv_eq_idp [unfold 5] {p q : x = y} : p ⬝ q⁻¹ = idp → p = q := eq.rec_on q (take p h, h) p definition eq_of_inv_con_eq_idp {p q : x = y} : q⁻¹ ⬝ p = idp → p = q := eq.rec_on q (take p h, !idp_con⁻¹ ⬝ h) p definition eq_inv_of_con_eq_idp' [unfold 5] {p : x = y} {q : y = x} : p ⬝ q = idp → p = q⁻¹ := eq.rec_on q (take p h, h) p definition eq_inv_of_con_eq_idp {p : x = y} {q : y = x} : q ⬝ p = idp → p = q⁻¹ := eq.rec_on q (take p h, !idp_con⁻¹ ⬝ h) p definition eq_of_idp_eq_inv_con {p q : x = y} : idp = p⁻¹ ⬝ q → p = q := eq.rec_on p (take q h, h ⬝ !idp_con) q definition eq_of_idp_eq_con_inv [unfold 4] {p q : x = y} : idp = q ⬝ p⁻¹ → p = q := eq.rec_on p (take q h, h) q definition inv_eq_of_idp_eq_con [unfold 4] {p : x = y} {q : y = x} : idp = q ⬝ p → p⁻¹ = q := eq.rec_on p (take q h, h) q definition inv_eq_of_idp_eq_con' {p : x = y} {q : y = x} : idp = p ⬝ q → p⁻¹ = q := eq.rec_on p (take q h, h ⬝ !idp_con) q definition con_inv_eq_idp {p q : x = y} (r : p = q) : p ⬝ q⁻¹ = idp := by cases r;apply con.right_inv definition inv_con_eq_idp {p q : x = y} (r : p = q) : q⁻¹ ⬝ p = idp := by cases r;apply con.left_inv definition con_eq_idp {p : x = y} {q : y = x} (r : p = q⁻¹) : p ⬝ q = idp := by cases q;exact r definition idp_eq_inv_con {p q : x = y} (r : p = q) : idp = p⁻¹ ⬝ q := by cases r;exact !con.left_inv⁻¹ definition idp_eq_con_inv {p q : x = y} (r : p = q) : idp = q ⬝ p⁻¹ := by cases r;exact !con.right_inv⁻¹ definition idp_eq_con {p : x = y} {q : y = x} (r : p⁻¹ = q) : idp = q ⬝ p := by cases p;exact r /- Transport -/ definition transport [subst] [reducible] [unfold 5] (P : A → Type) {x y : A} (p : x = y) (u : P x) : P y := eq.rec_on p u -- This idiom makes the operation right associative. notation p `▸` x := transport _ p x definition cast [reducible] [unfold 3] {A B : Type} (p : A = B) (a : A) : B := p ▸ a definition tr_rev [reducible] [unfold 6] (P : A → Type) {x y : A} (p : x = y) (u : P y) : P x := p⁻¹ ▸ u definition ap [unfold 6] ⦃A B : Type⦄ (f : A → B) {x y:A} (p : x = y) : f x = f y := eq.rec_on p idp abbreviation ap01 [parsing-only] := ap definition homotopy [reducible] (f g : Πx, P x) : Type := Πx : A, f x = g x infix ~ := homotopy protected definition homotopy.refl [refl] [reducible] (f : Πx, P x) : f ~ f := λ x, idp protected definition homotopy.symm [symm] [reducible] {f g : Πx, P x} (H : f ~ g) : g ~ f := λ x, (H x)⁻¹ protected definition homotopy.trans [trans] [reducible] {f g h : Πx, P x} (H1 : f ~ g) (H2 : g ~ h) : f ~ h := λ x, H1 x ⬝ H2 x definition apd10 [unfold 5] {f g : Πx, P x} (H : f = g) : f ~ g := λx, eq.rec_on H idp --the next theorem is useful if you want to write "apply (apd10' a)" definition apd10' [unfold 6] {f g : Πx, P x} (a : A) (H : f = g) : f a = g a := eq.rec_on H idp definition ap10 [reducible] [unfold 5] {f g : A → B} (H : f = g) : f ~ g := apd10 H definition ap11 {f g : A → B} (H : f = g) {x y : A} (p : x = y) : f x = g y := eq.rec_on H (eq.rec_on p idp) definition apd [unfold 6] (f : Πa, P a) {x y : A} (p : x = y) : p ▸ f x = f y := eq.rec_on p idp /- More theorems for moving things around in equations -/ definition tr_eq_of_eq_inv_tr {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : u = p⁻¹ ▸ v → p ▸ u = v := eq.rec_on p (take v, id) v definition inv_tr_eq_of_eq_tr {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : u = p ▸ v → p⁻¹ ▸ u = v := eq.rec_on p (take u, id) u definition eq_inv_tr_of_tr_eq {P : A → Type} {x y : A} {p : x = y} {u : P x} {v : P y} : p ▸ u = v → u = p⁻¹ ▸ v := eq.rec_on p (take v, id) v definition eq_tr_of_inv_tr_eq {P : A → Type} {x y : A} {p : y = x} {u : P x} {v : P y} : p⁻¹ ▸ u = v → u = p ▸ v := eq.rec_on p (take u, id) u /- Functoriality of functions -/ -- Here we prove that functions behave like functors between groupoids, and that [ap] itself is -- functorial. -- Functions take identity paths to identity paths definition ap_idp (x : A) (f : A → B) : ap f idp = idp :> (f x = f x) := idp -- Functions commute with concatenation. definition ap_con (f : A → B) {x y z : A} (p : x = y) (q : y = z) : ap f (p ⬝ q) = ap f p ⬝ ap f q := eq.rec_on q (eq.rec_on p idp) definition con_ap_con_eq_con_ap_con_ap (f : A → B) {w x y z : A} (r : f w = f x) (p : x = y) (q : y = z) : r ⬝ ap f (p ⬝ q) = (r ⬝ ap f p) ⬝ ap f q := eq.rec_on q (take p, eq.rec_on p idp) p definition ap_con_con_eq_ap_con_ap_con (f : A → B) {w x y z : A} (p : x = y) (q : y = z) (r : f z = f w) : ap f (p ⬝ q) ⬝ r = ap f p ⬝ (ap f q ⬝ r) := eq.rec_on q (eq.rec_on p (take r, con.assoc _ _ _)) r -- Functions commute with path inverses. definition ap_inv' (f : A → B) {x y : A} (p : x = y) : (ap f p)⁻¹ = ap f p⁻¹ := eq.rec_on p idp definition ap_inv {A B : Type} (f : A → B) {x y : A} (p : x = y) : ap f p⁻¹ = (ap f p)⁻¹ := eq.rec_on p idp -- [ap] itself is functorial in the first argument. definition ap_id (p : x = y) : ap id p = p := eq.rec_on p idp definition ap_compose (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (g ∘ f) p = ap g (ap f p) := eq.rec_on p idp -- Sometimes we don't have the actual function [compose]. definition ap_compose' (g : B → C) (f : A → B) {x y : A} (p : x = y) : ap (λa, g (f a)) p = ap g (ap f p) := eq.rec_on p idp -- The action of constant maps. definition ap_constant [unfold 5] (p : x = y) (z : B) : ap (λu, z) p = idp := eq.rec_on p idp -- Naturality of [ap]. definition ap_con_eq_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ ap g q := eq.rec_on q !idp_con -- Naturality of [ap] at identity. definition ap_con_eq_con {f : A → A} (p : Πx, f x = x) {x y : A} (q : x = y) : ap f q ⬝ p y = p x ⬝ q := eq.rec_on q !idp_con definition con_ap_eq_con {f : A → A} (p : Πx, x = f x) {x y : A} (q : x = y) : p x ⬝ ap f q = q ⬝ p y := eq.rec_on q !idp_con⁻¹ -- Naturality of [ap] with constant function definition ap_con_eq {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : ap f q ⬝ p y = p x := eq.rec_on q !idp_con -- Naturality with other paths hanging around. definition con_ap_con_con_eq_con_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w z : B} (r : w = f x) (s : g y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (ap g q ⬝ s) := eq.rec_on s (eq.rec_on q idp) definition con_ap_con_eq_con_con_ap {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {w : B} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ ap g q := eq.rec_on q idp -- TODO: try this using the simplifier, and compare proofs definition ap_con_con_eq_con_ap_con {f g : A → B} (p : f ~ g) {x y : A} (q : x = y) {z : B} (s : g y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (ap g q ⬝ s) := eq.rec_on s (eq.rec_on q (calc (ap f idp) ⬝ (p x ⬝ idp) = idp ⬝ p x : idp ... = p x : !idp_con ... = (p x) ⬝ (ap g idp ⬝ idp) : idp)) -- This also works: -- eq.rec_on s (eq.rec_on q (!idp_con ▸ idp)) definition con_ap_con_con_eq_con_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w z : A} (r : w = f x) (s : y = z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) = (r ⬝ p x) ⬝ (q ⬝ s) := eq.rec_on s (eq.rec_on q idp) definition con_con_ap_con_eq_con_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w z : A} (r : w = x) (s : g y = z) : (r ⬝ p x) ⬝ (ap g q ⬝ s) = (r ⬝ q) ⬝ (p y ⬝ s) := eq.rec_on s (eq.rec_on q idp) definition con_ap_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {w : A} (r : w = f x) : (r ⬝ ap f q) ⬝ p y = (r ⬝ p x) ⬝ q := eq.rec_on q idp definition ap_con_con_eq_con_con {f : A → A} (p : f ~ id) {x y : A} (q : x = y) {z : A} (s : y = z) : ap f q ⬝ (p y ⬝ s) = p x ⬝ (q ⬝ s) := eq.rec_on s (eq.rec_on q (!idp_con ▸ idp)) definition con_con_ap_eq_con_con {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {w : A} (r : w = x) : (r ⬝ p x) ⬝ ap g q = (r ⬝ q) ⬝ p y := begin cases q, exact idp end definition con_ap_con_eq_con_con' {g : A → A} (p : id ~ g) {x y : A} (q : x = y) {z : A} (s : g y = z) : p x ⬝ (ap g q ⬝ s) = q ⬝ (p y ⬝ s) := begin apply (eq.rec_on s), apply (eq.rec_on q), apply (idp_con (p x) ▸ idp) end /- Action of [apd10] and [ap10] on paths -/ -- Application of paths between functions preserves the groupoid structure definition apd10_idp (f : Πx, P x) (x : A) : apd10 (refl f) x = idp := idp definition apd10_con {f f' f'' : Πx, P x} (h : f = f') (h' : f' = f'') (x : A) : apd10 (h ⬝ h') x = apd10 h x ⬝ apd10 h' x := eq.rec_on h (take h', eq.rec_on h' idp) h' definition apd10_inv {f g : Πx : A, P x} (h : f = g) (x : A) : apd10 h⁻¹ x = (apd10 h x)⁻¹ := eq.rec_on h idp definition ap10_idp {f : A → B} (x : A) : ap10 (refl f) x = idp := idp definition ap10_con {f f' f'' : A → B} (h : f = f') (h' : f' = f'') (x : A) : ap10 (h ⬝ h') x = ap10 h x ⬝ ap10 h' x := apd10_con h h' x definition ap10_inv {f g : A → B} (h : f = g) (x : A) : ap10 h⁻¹ x = (ap10 h x)⁻¹ := apd10_inv h x -- [ap10] also behaves nicely on paths produced by [ap] definition ap_ap10 (f g : A → B) (h : B → C) (p : f = g) (a : A) : ap h (ap10 p a) = ap10 (ap (λ f', h ∘ f') p) a:= eq.rec_on p idp /- Transport and the groupoid structure of paths -/ definition idp_tr {P : A → Type} {x : A} (u : P x) : idp ▸ u = u := idp definition con_tr {P : A → Type} {x y z : A} (p : x = y) (q : y = z) (u : P x) : p ⬝ q ▸ u = q ▸ p ▸ u := eq.rec_on q (eq.rec_on p idp) definition tr_inv_tr {P : A → Type} {x y : A} (p : x = y) (z : P y) : p ▸ p⁻¹ ▸ z = z := (con_tr p⁻¹ p z)⁻¹ ⬝ ap (λr, transport P r z) (con.left_inv p) definition inv_tr_tr {P : A → Type} {x y : A} (p : x = y) (z : P x) : p⁻¹ ▸ p ▸ z = z := (con_tr p p⁻¹ z)⁻¹ ⬝ ap (λr, transport P r z) (con.right_inv p) definition con_tr_lemma {P : A → Type} {x y z w : A} (p : x = y) (q : y = z) (r : z = w) (u : P x) : ap (λe, e ▸ u) (con.assoc' p q r) ⬝ (con_tr (p ⬝ q) r u) ⬝ ap (transport P r) (con_tr p q u) = (con_tr p (q ⬝ r) u) ⬝ (con_tr q r (p ▸ u)) :> ((p ⬝ (q ⬝ r)) ▸ u = r ▸ q ▸ p ▸ u) := eq.rec_on r (eq.rec_on q (eq.rec_on p idp)) -- Here is another coherence lemma for transport. definition tr_inv_tr_lemma {P : A → Type} {x y : A} (p : x = y) (z : P x) : tr_inv_tr p (transport P p z) = ap (transport P p) (inv_tr_tr p z) := eq.rec_on p idp /- some properties for apd -/ definition apd_idp (x : A) (f : Πx, P x) : apd f idp = idp :> (f x = f x) := idp definition apd_con (f : Πx, P x) {x y z : A} (p : x = y) (q : y = z) : apd f (p ⬝ q) = con_tr p q (f x) ⬝ ap (transport P q) (apd f p) ⬝ apd f q := by cases p;cases q;apply idp definition apd_inv (f : Πx, P x) {x y : A} (p : x = y) : apd f p⁻¹ = (eq_inv_tr_of_tr_eq (apd f p))⁻¹ := by cases p;apply idp -- Dependent transport in a doubly dependent type. definition transportD [unfold 6] {P : A → Type} (Q : Πa, P a → Type) {a a' : A} (p : a = a') (b : P a) (z : Q a b) : Q a' (p ▸ b) := eq.rec_on p z -- In Coq the variables P, Q and b are explicit, but in Lean we can probably have them implicit -- using the following notation notation p `▸D`:65 x:64 := transportD _ p _ x -- Transporting along higher-dimensional paths definition transport2 [unfold 7] (P : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : P x) : p ▸ z = q ▸ z := ap (λp', p' ▸ z) r notation p `▸2`:65 x:64 := transport2 _ p _ x -- An alternative definition. definition tr2_eq_ap10 (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r z = ap10 (ap (transport Q) r) z := eq.rec_on r idp definition tr2_con {P : A → Type} {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) (z : P x) : transport2 P (r1 ⬝ r2) z = transport2 P r1 z ⬝ transport2 P r2 z := eq.rec_on r1 (eq.rec_on r2 idp) definition tr2_inv (Q : A → Type) {x y : A} {p q : x = y} (r : p = q) (z : Q x) : transport2 Q r⁻¹ z = (transport2 Q r z)⁻¹ := eq.rec_on r idp definition transportD2 [unfold 7] (B C : A → Type) (D : Π(a:A), B a → C a → Type) {x1 x2 : A} (p : x1 = x2) (y : B x1) (z : C x1) (w : D x1 y z) : D x2 (p ▸ y) (p ▸ z) := eq.rec_on p w notation p `▸D2`:65 x:64 := transportD2 _ _ _ p _ _ x definition ap_tr_con_tr2 (P : A → Type) {x y : A} {p q : x = y} {z w : P x} (r : p = q) (s : z = w) : ap (transport P p) s ⬝ transport2 P r w = transport2 P r z ⬝ ap (transport P q) s := eq.rec_on r !idp_con⁻¹ definition fn_tr_eq_tr_fn {P Q : A → Type} {x y : A} (p : x = y) (f : Πx, P x → Q x) (z : P x) : f y (p ▸ z) = (p ▸ (f x z)) := eq.rec_on p idp /- Transporting in particular fibrations -/ /- From the Coq HoTT library: One frequently needs lemmas showing that transport in a certain dependent type is equal to some more explicitly defined operation, defined according to the structure of that dependent type. For most dependent types, we prove these lemmas in the appropriate file in the types/ subdirectory. Here we consider only the most basic cases. -/ -- Transporting in a constant fibration. definition tr_constant (p : x = y) (z : B) : transport (λx, B) p z = z := eq.rec_on p idp definition tr2_constant {p q : x = y} (r : p = q) (z : B) : tr_constant p z = transport2 (λu, B) r z ⬝ tr_constant q z := eq.rec_on r !idp_con⁻¹ -- Transporting in a pulled back fibration. -- rename: tr_compose definition transport_compose (P : B → Type) (f : A → B) (p : x = y) (z : P (f x)) : transport (P ∘ f) p z = transport P (ap f p) z := eq.rec_on p idp definition ap_precompose (f : A → B) (g g' : B → C) (p : g = g') : ap (λh, h ∘ f) p = transport (λh : B → C, g ∘ f = h ∘ f) p idp := eq.rec_on p idp definition apd10_ap_precompose (f : A → B) (g g' : B → C) (p : g = g') (a : A) : apd10 (ap (λh : B → C, h ∘ f) p) a = apd10 p (f a) := eq.rec_on p idp definition apd10_ap_postcompose (f : B → C) (g g' : A → B) (p : g = g') (a : A) : apd10 (ap (λh : A → B, f ∘ h) p) a = ap f (apd10 p a) := eq.rec_on p idp -- A special case of [transport_compose] which seems to come up a lot. definition tr_eq_cast_ap {P : A → Type} {x y} (p : x = y) (u : P x) : p ▸ u = cast (ap P p) u := eq.rec_on p idp definition tr_eq_cast_ap_fn {P : A → Type} {x y} (p : x = y) : transport P p = cast (ap P p) := eq.rec_on p idp /- The behavior of [ap] and [apd] -/ -- In a constant fibration, [apd] reduces to [ap], modulo [transport_const]. definition apd_eq_tr_constant_con_ap (f : A → B) (p : x = y) : apd f p = tr_constant p (f x) ⬝ ap f p := eq.rec_on p idp /- The 2-dimensional groupoid structure -/ -- Horizontal composition of 2-dimensional paths. definition concat2 {p p' : x = y} {q q' : y = z} (h : p = p') (h' : q = q') : p ⬝ q = p' ⬝ q' := eq.rec_on h (eq.rec_on h' idp) -- 2-dimensional path inversion definition inverse2 [unfold 6] {p q : x = y} (h : p = q) : p⁻¹ = q⁻¹ := eq.rec_on h idp infixl `◾`:75 := concat2 postfix [parsing-only] `⁻²`:(max+10) := inverse2 --this notation is abusive, should we use it? /- Whiskering -/ definition whisker_left (p : x = y) {q r : y = z} (h : q = r) : p ⬝ q = p ⬝ r := idp ◾ h definition whisker_right {p q : x = y} (h : p = q) (r : y = z) : p ⬝ r = q ⬝ r := h ◾ idp -- Unwhiskering, a.k.a. cancelling definition cancel_left {x y z : A} {p : x = y} {q r : y = z} : (p ⬝ q = p ⬝ r) → (q = r) := λs, !inv_con_cancel_left⁻¹ ⬝ whisker_left p⁻¹ s ⬝ !inv_con_cancel_left definition cancel_right {x y z : A} {p q : x = y} {r : y = z} : (p ⬝ r = q ⬝ r) → (p = q) := λs, !con_inv_cancel_right⁻¹ ⬝ whisker_right s r⁻¹ ⬝ !con_inv_cancel_right -- Whiskering and identity paths. definition whisker_right_idp_right {p q : x = y} (h : p = q) : whisker_right h idp = h := eq.rec_on h (eq.rec_on p idp) definition whisker_right_idp_left (p : x = y) (q : y = z) : whisker_right idp q = idp :> (p ⬝ q = p ⬝ q) := eq.rec_on q idp definition whisker_left_idp_right (p : x = y) (q : y = z) : whisker_left p idp = idp :> (p ⬝ q = p ⬝ q) := eq.rec_on q idp definition whisker_left_idp_left {p q : x = y} (h : p = q) : (idp_con p) ⁻¹ ⬝ whisker_left idp h ⬝ idp_con q = h := eq.rec_on h (eq.rec_on p idp) definition con2_idp {p q : x = y} (h : p = q) : h ◾ idp = whisker_right h idp :> (p ⬝ idp = q ⬝ idp) := idp definition idp_con2 {p q : x = y} (h : p = q) : idp ◾ h = whisker_left idp h :> (idp ⬝ p = idp ⬝ q) := idp -- The interchange law for concatenation. definition con2_con_con2 {p p' p'' : x = y} {q q' q'' : y = z} (a : p = p') (b : p' = p'') (c : q = q') (d : q' = q'') : (a ◾ c) ⬝ (b ◾ d) = (a ⬝ b) ◾ (c ⬝ d) := eq.rec_on d (eq.rec_on c (eq.rec_on b (eq.rec_on a idp))) definition whisker_right_con_whisker_left {x y z : A} {p p' : x = y} {q q' : y = z} (a : p = p') (b : q = q') : (whisker_right a q) ⬝ (whisker_left p' b) = (whisker_left p b) ⬝ (whisker_right a q') := eq.rec_on b (eq.rec_on a !idp_con⁻¹) -- Structure corresponding to the coherence equations of a bicategory. -- The "pentagonator": the 3-cell witnessing the associativity pentagon. definition pentagon {v w x y z : A} (p : v = w) (q : w = x) (r : x = y) (s : y = z) : whisker_left p (con.assoc' q r s) ⬝ con.assoc' p (q ⬝ r) s ⬝ whisker_right (con.assoc' p q r) s = con.assoc' p q (r ⬝ s) ⬝ con.assoc' (p ⬝ q) r s := by induction s;induction r;induction q;induction p;reflexivity -- The 3-cell witnessing the left unit triangle. definition triangulator (p : x = y) (q : y = z) : con.assoc' p idp q ⬝ whisker_right (con_idp p) q = whisker_left p (idp_con q) := eq.rec_on q (eq.rec_on p idp) definition eckmann_hilton {x:A} (p q : idp = idp :> x = x) : p ⬝ q = q ⬝ p := (!whisker_right_idp_right ◾ !whisker_left_idp_left)⁻¹ ⬝ whisker_left _ !idp_con ⬝ !whisker_right_con_whisker_left ⬝ whisker_right !idp_con⁻¹ _ ⬝ (!whisker_left_idp_left ◾ !whisker_right_idp_right) -- The action of functions on 2-dimensional paths definition ap02 [unfold 8] [reducible] (f : A → B) {x y : A} {p q : x = y} (r : p = q) : ap f p = ap f q := ap (ap f) r definition ap02_con (f : A → B) {x y : A} {p p' p'' : x = y} (r : p = p') (r' : p' = p'') : ap02 f (r ⬝ r') = ap02 f r ⬝ ap02 f r' := eq.rec_on r (eq.rec_on r' idp) definition ap02_con2 (f : A → B) {x y z : A} {p p' : x = y} {q q' :y = z} (r : p = p') (s : q = q') : ap02 f (r ◾ s) = ap_con f p q ⬝ (ap02 f r ◾ ap02 f s) ⬝ (ap_con f p' q')⁻¹ := eq.rec_on r (eq.rec_on s (eq.rec_on q (eq.rec_on p idp))) definition apd02 [unfold 8] {p q : x = y} (f : Π x, P x) (r : p = q) : apd f p = transport2 P r (f x) ⬝ apd f q := eq.rec_on r !idp_con⁻¹ -- And now for a lemma whose statement is much longer than its proof. definition apd02_con {P : A → Type} (f : Π x:A, P x) {x y : A} {p1 p2 p3 : x = y} (r1 : p1 = p2) (r2 : p2 = p3) : apd02 f (r1 ⬝ r2) = apd02 f r1 ⬝ whisker_left (transport2 P r1 (f x)) (apd02 f r2) ⬝ con.assoc' _ _ _ ⬝ (whisker_right (tr2_con r1 r2 (f x))⁻¹ (apd f p3)) := eq.rec_on r2 (eq.rec_on r1 (eq.rec_on p1 idp)) end eq
8bd5ce5ef09987005987645e096da45112788689
d0664585e88edfefe384f2b01de54487029040bb
/solutions/covers_from_pseudometric.lean
8fb9a9628f7909c2ce35c9f3a07bedcc2534fdd2
[]
no_license
ImperialCollegeLondon/uniform-structures
acf0a092d764925564595c59e7347e066d2a78ab
a41a170ef125b36bdac1e2201f54affa958d0349
refs/heads/master
1,668,088,958,039
1,592,495,127,000
1,592,495,127,000
269,964,470
2
0
null
null
null
null
UTF-8
Lean
false
false
2,473
lean
-- import the definitions of uniform space via covers import uniform_structure.covers -- import the definition of pseudometric space import pseudometric_space -- In this exercise we will show that a pseudometric on a set X -- gives rise to a distinguished family of covers for X -- which make X into a "uniform space in the sense of covers" -- This is a question about pseudometrics so let's put it -- in the pseudometric namespace namespace pseudometric -- Let X be a set (or a type), and let d be a pseudometric on X variables {X : Type} (d : X → X → ℝ) [is_pseudometric d] -- let's define a closed ball /-- Closed ball centre x radius ε -/ def closed_ball (x : X) (ε : ℝ) := {y : X | d x y ≤ ε} -- definition of closed ball lemma mem_closed_ball {x y : X} {ε : ℝ} : y ∈ closed_ball d x ε ↔ d x y ≤ ε := iff.rfl -- true by definition -- Here's an obvious lemma: if 0 ≤ ε then x is in the closed ball centre x -- and radius ε -- But do we need it? -- lemma self_mem_ball (x : X) (ε : ℝ) (hε : 0 ≤ ε) : x ∈ closed_ball d x ε := -- begin -- rw mem_closed_ball, -- rw d_self d, -- assumption -- end -- Define Θ to be the set of covers of X with the following property: -- there exists ε ≥ 0 such that each set in the cover contains a closed ball -- of radius ε (note that ε is independent of which set in the cover) def Θ : set (cover X) := {𝒞 | ∃ ε (hε : 0 < ε), ∀ x : X, ∃ U ∈ 𝒞.C, closed_ball d x ε ⊆ U} -- a cover is in Θ iff it's a closed ball cover, or the universal cover -- the proof is obvious lemma mem_Θ (𝒞 : cover X) : 𝒞 ∈ Θ d ↔ ∃ ε (hε : 0 < ε), ∀ x : X, ∃ U ∈ 𝒞.C, closed_ball d x ε ⊆ U := iff.rfl -- true by definition -- The exerise is to show that the 3 axioms for a distinguished family are -- satisfied by Θ -- Axiom 1: the universal cover is in lemma univ_mem : univ_cover X ∈ Θ d := begin sorry end -- Axiom 2 : anything star-bigger than a distinguished cover is distinguished lemma star_mem (P Q : cover X) (hP : P ∈ Θ d) (hPQ : P <* Q) : Q ∈ Θ d := begin sorry end -- Axiom 3: two covers have an upper bound in the <* ordering lemma ub_mem (P Q : cover X) (hP : P ∈ Θ d) (hQ : Q ∈ Θ d) : ∃ R : cover X, R ∈ Θ d ∧ R <* P ∧ R <* Q := begin sorry end definition to_cover : dist_covers X := { Θ := Θ d, univ_mem := univ_mem d, star_mem := star_mem d, ub_mem := ub_mem d} end pseudometric
8b996fdb41a2cc38d628244e0fa6ff8fd38a304d
947b78d97130d56365ae2ec264df196ce769371a
/stage0/src/Lean/Meta/ExprDefEq.lean
84833631842ae4627fe69be1e7bc8ba521fff180
[ "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
44,549
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ProjFns import Lean.Meta.WHNF import Lean.Meta.InferType import Lean.Meta.FunInfo import Lean.Meta.LevelDefEq import Lean.Meta.Check import Lean.Meta.Offset namespace Lean namespace Meta /-- Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`. Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean. Example: ``` (fun x : A => f ?m) =?= f ``` The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/ private def isDefEqEta (a b : Expr) : DefEqM Bool := if a.isLambda && !b.isLambda then do bType ← inferType b; bType ← whnfD bType; match bType with | Expr.forallE n d _ c => let b' := mkLambda n c.binderInfo d (mkApp b (mkBVar 0)); commitWhen $ Meta.isExprDefEqAux a b' | _ => pure false else pure false /-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/ def isDefEqNative (s t : Expr) : DefEqM LBool := do let isDefEq (s t) : DefEqM LBool := toLBoolM $ Meta.isExprDefEqAux s t; s? ← liftM $ reduceNative? s; t? ← liftM $ reduceNative? t; match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for reducing Nat basic operations. -/ def isDefEqNat (s t : Expr) : DefEqM LBool := do let isDefEq (s t) : DefEqM LBool := toLBoolM $ Meta.isExprDefEqAux s t; if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then pure LBool.undef else do s? ← liftM $ reduceNat? s; t? ← liftM $ reduceNat? t; match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for constraints of the form `("..." =?= String.mk cs)` -/ def isDefEqStringLit (s t : Expr) : DefEqM LBool := do let isDefEq (s t) : DefEqM LBool := toLBoolM $ Meta.isExprDefEqAux s t; if s.isStringLit && t.isAppOf `String.mk then isDefEq (toCtorIfLit s) t else if s.isAppOf `String.mk && t.isStringLit then isDefEq s (toCtorIfLit t) else pure LBool.undef /-- Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned. Remark: `n` may be 0. -/ def isEtaUnassignedMVar (e : Expr) : DefEqM Bool := match e.etaExpanded? with | some (Expr.mvar mvarId _) => condM (isReadOnlyOrSyntheticOpaqueExprMVar mvarId) (pure false) (condM (isExprMVarAssigned mvarId) (pure false) (pure true)) | _ => pure false /- First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases Here, we say a case is easy if it is of the form ?m =?= t or t =?= ?m where `?m` is unassigned. These easy cases are not just an optimization. When `?m` is a function, by assigning it to t, we make sure a unification constraint (in the explicit part) ``` ?m t =?= f s ``` is not higher-order. We also handle the eta-expanded cases: ``` fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ This is important because type inference often produces eta-expanded terms, and without this extra case, we could introduce counter intuitive behavior. Pre: `paramInfo.size <= args₁.size = args₂.size` -/ private partial def isDefEqArgsFirstPass (paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : Nat → Array Nat → DefEqM (Option (Array Nat)) | i, postponed => if h : i < paramInfo.size then let info := paramInfo.get ⟨i, h⟩; let a₁ := args₁.get! i; let a₂ := args₂.get! i; if info.implicit || info.instImplicit then condM (isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) (condM (Meta.isExprDefEqAux a₁ a₂) (isDefEqArgsFirstPass (i+1) postponed) (pure none)) (isDefEqArgsFirstPass (i+1) (postponed.push i)) else condM (Meta.isExprDefEqAux a₁ a₂) (isDefEqArgsFirstPass (i+1) postponed) (pure none) else pure (some postponed) private partial def isDefEqArgsAux (args₁ args₂ : Array Expr) (h : args₁.size = args₂.size) : Nat → DefEqM Bool | i => if h₁ : i < args₁.size then let a₁ := args₁.get ⟨i, h₁⟩; let a₂ := args₂.get ⟨i, h ▸ h₁⟩; condM (Meta.isExprDefEqAux a₁ a₂) (isDefEqArgsAux (i+1)) (pure false) else pure true @[specialize] private def trySynthPending (e : Expr) : DefEqM Bool := do mvarId? ← getStuckMVar? e; match mvarId? with | some mvarId => liftM $ Meta.synthPending mvarId | none => pure false private def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : DefEqM Bool := if h : args₁.size = args₂.size then do finfo ← liftM $ getFunInfoNArgs f args₁.size; (some postponed) ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ 0 #[] | pure false; (isDefEqArgsAux args₁ args₂ h finfo.paramInfo.size) <&&> (postponed.allM $ fun i => do /- Second pass: unify implicit arguments. In the second pass, we make sure we are unfolding at least non reducible definitions (default setting). -/ let a₁ := args₁.get! i; let a₂ := args₂.get! i; let info := finfo.paramInfo.get! i; when info.instImplicit $ do { _ ← trySynthPending a₁; _ ← trySynthPending a₂; pure () }; withAtLeastTransparency TransparencyMode.default $ Meta.isExprDefEqAux a₁ a₂) else pure false /-- Check whether the types of the free variables at `fvars` are definitionally equal to the types at `ds₂`. Pre: `fvars.size == ds₂.size` This method also updates the set of local instances, and invokes the continuation `k` with the updated set. We can't use `withNewLocalInstances` because the `isDeq fvarType d₂` may use local instances. -/ @[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) : Nat → DefEqM Bool → DefEqM Bool | i, k => if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩; fvarDecl ← getFVarLocalDecl fvar; let fvarType := fvarDecl.type; let d₂ := ds₂.get! i; condM (Meta.isExprDefEqAux fvarType d₂) (do c? ← isClass? fvarType; match c? with | some className => withNewLocalInstance className fvar $ isDefEqBindingDomain (i+1) k | none => isDefEqBindingDomain (i+1) k) (pure false) else k /- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`. It accumulates the new free variables in `fvars`, and declare them at `lctx`. We use the domain types of `e₁` to create the new free variables. We store the domain types of `e₂` at `ds₂`. -/ private partial def isDefEqBindingAux : LocalContext → Array Expr → Expr → Expr → Array Expr → DefEqM Bool | lctx, fvars, e₁, e₂, ds₂ => let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : DefEqM Bool := do { let d₁ := d₁.instantiateRev fvars; let d₂ := d₂.instantiateRev fvars; fvarId ← mkFreshId; let lctx := lctx.mkLocalDecl fvarId n d₁; let fvars := fvars.push (mkFVar fvarId); isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂) }; match e₁, e₂ with | Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | _, _ => adaptReader (fun (ctx : Context) => { ctx with lctx := lctx }) $ isDefEqBindingDomain fvars ds₂ 0 $ Meta.isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars) @[inline] private def isDefEqBinding (a b : Expr) : DefEqM Bool := do lctx ← getLCtx; isDefEqBindingAux lctx #[] a b #[] private def checkTypesAndAssign (mvar : Expr) (v : Expr) : DefEqM Bool := traceCtx `Meta.isDefEq.assign.checkTypes $ do -- must check whether types are definitionally equal or not, before assigning and returning true mvarType ← inferType mvar; vType ← inferType v; condM (withTransparency TransparencyMode.default $ Meta.isExprDefEqAux mvarType vType) (do trace! `Meta.isDefEq.assign.final (mvar ++ " := " ++ v); assignExprMVar mvar.mvarId! v; pure true) (do trace `Meta.isDefEq.assign.typeMismatch $ fun _ => mvar ++ " : " ++ mvarType ++ " := " ++ v ++ " : " ++ vType; pure false) /- Each metavariable is declared in a particular local context. We use the notation `C |- ?m : t` to denote a metavariable `?m` that was declared at the local context `C` with type `t` (see `MetavarDecl`). We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. The following method process the unification constraint ?m@C a₁ ... aₙ =?= t We say the unification constraint is a pattern IFF 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` Claim: we don't have to check free variable declarations. That is, if `t` contains a reference to `x : A := v`, we don't need to check `v`. Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3). If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`. So, condition 4 and 5 are satisfied. If the conditions above have been satisfied, then the solution for the unification constrain is ?m := fun a₁ ... aₙ => t Now, we consider some workarounds/approximations. A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3) (precise) solution: unfold `x` in `t`. A2) Suppose some `aᵢ` is in `C` (failed condition 2) (approximated) solution (when `config.ctxApprox` is set to true) : ignore condition and also use ?m := fun a₁ ... aₙ => t Here is an example where this approximation fails: Given `C` containing `a : nat`, consider the following two constraints ?m@C a =?= a ?m@C b =?= a If we use the approximation in the first constraint, we get ?m := fun x => x when we apply this solution to the second one we get a failure. IMPORTANT: When applying this approximation we need to make sure the abstracted term `fun a₁ ... aₙ => t` is type correct. The check can only be skipped in the pattern case described above. Consider the following example. Given the local context (α : Type) (a : α) we try to solve ?m α =?= @id α a If we use the approximation above we obtain: ?m := (fun α' => @id α' a) which is a type incorrect term. `a` has type `α` but it is expected to have type `α'`. The problem occurs because the right hand side contains a free variable `a` that depends on the free variable `α` being abstracted. Note that this dependency cannot occur in patterns. We can address this by type checking the term after abstraction. This is not a significant performance bottleneck because this case doesn't happen very often in practice (262 times when compiling stdlib on Jan 2018). The second example is trickier, but it also occurs less frequently (8 times when compiling stdlib on Jan 2018, and all occurrences were at Init/Control when we define monads and auxiliary combinators for them). We considered three options for the addressing the issue on the second example: A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1). In Lean3, we would try to approximate this case using an approach similar to A2. However, this approximation complicates the code, and is never used in the Lean3 stdlib and mathlib. A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`. If `?m'` is assigned, we substitute. If not, we create an auxiliary metavariable with a smaller scope. Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step. A5) If some `aᵢ` is not a free variable, then we use first-order unification (if `config.foApprox` is set to true) ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k reduces to ?M a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k A6) If (m =?= v) is of the form ?m a_1 ... a_n =?= ?m b_1 ... b_k then we use first-order unification (if `config.foApprox` is set to true) A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form ``` ?m s₁ ... sₙ =?= t ``` where `s₁ ... sₙ` are arbitrary terms. We solve them by assigning the constant function to `?m`. ``` ?m := fun _ ... _ => t ``` In general, this approximation may produce bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure "hello"; f () ``` with expected type `IO String`. In this example, the following unification contraint is generated. ``` ?m () String =?= IO String ``` It is not a higher-order pattern, first-order approximation reduces it to ``` ?m () =?= IO ``` which fails to be solved. However, constant approximation solves it by assigning ``` ?m := fun _ => IO ``` Note that `f`s type is `(x : ?α) -> ?m x String`. The metavariable `?m` may depend on `x`. If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide whether we should apply it or not. The heuristic is based on observing where the constraints above come from. In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f` does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected by any functional programmer used to non-dependently type languages (e.g., Haskell). We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks how many metavariable arguments are representing dependencies. -/ namespace CheckAssignment def registerCheckAssignmentId : IO InternalExceptionId := registerInternalExceptionId `checkAssignment @[init registerCheckAssignmentId, matchPattern] constant checkAssignmentExceptionId : InternalExceptionId := arbitrary _ def registerOutOfScopeId : IO InternalExceptionId := registerInternalExceptionId `outOfScope @[init registerOutOfScopeId, matchPattern] constant outOfScopeExceptionId : InternalExceptionId := arbitrary _ structure State := (cache : ExprStructMap Expr := {}) structure Context := (mvarId : MVarId) (mvarDecl : MetavarDecl) (fvars : Array Expr) (hasCtxLocals : Bool) (rhs : Expr) abbrev CheckAssignmentM := ReaderT Context $ StateRefT State $ DefEqM def throwCheckAssignmentFailure {α} : CheckAssignmentM α := throw $ Exception.internal checkAssignmentExceptionId def throwOutOfScopeFVar {α} : CheckAssignmentM α := throw $ Exception.internal outOfScopeExceptionId private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do s ← get; pure $ s.cache.find? e private def cache (e r : Expr) : CheckAssignmentM Unit := do modify fun s => { s with cache := s.cache.insert e r } instance : MonadCache Expr Expr CheckAssignmentM := { findCached? := findCached?, cache := cache } @[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr := if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e f private def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do ctx ← read; pure $ msg ++ " @ " ++ mkMVar ctx.mvarId ++ " " ++ ctx.fvars ++ " := " ++ ctx.rhs @[specialize] def checkFVar (check : Expr → CheckAssignmentM Expr) (fvar : Expr) : CheckAssignmentM Expr := do ctxMeta ← readThe Meta.Context; ctx ← read; if ctx.mvarDecl.lctx.containsFVar fvar then pure fvar else do let lctx := ctxMeta.lctx; match lctx.findFVar? fvar with | some (LocalDecl.ldecl _ _ _ _ v _) => visit check v | _ => if ctx.fvars.contains fvar then pure fvar else do traceM `Meta.isDefEq.assign.outOfScopeFVar $ addAssignmentInfo fvar; throwOutOfScopeFVar def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : CheckAssignmentM Expr := do mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs @[specialize] def checkMVar (check : Expr → CheckAssignmentM Expr) (mvar : Expr) : CheckAssignmentM Expr := do let mvarId := mvar.mvarId!; ctx ← read; mctx ← getMCtx; if mvarId == ctx.mvarId then do traceM `Meta.isDefEq.assign.occursCheck $ addAssignmentInfo "occurs check failed"; throwCheckAssignmentFailure else match mctx.getExprAssignment? mvarId with | some v => check v | none => match mctx.findDecl? mvarId with | none => liftM $ throwUnknownMVar mvarId | some mvarDecl => if ctx.hasCtxLocals then throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned. We "substract" variables being abstracted because we use `elimMVarDeps` -/ pure mvar else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then do traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx $ addAssignmentInfo (mkMVar mvarId); throwCheckAssignmentFailure else do ctxMeta ← readThe Meta.Context; if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then do mvarType ← check mvarDecl.type; /- Create an auxiliary metavariable with a smaller context and "checked" type. Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains a metavariable that we also need to reduce the context. -/ newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType mvarDecl.numScopeArgs; modifyThe Meta.State (fun s => { s with mctx := s.mctx.assignExpr mvarId newMVar }); pure newMVar else pure mvar /- Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables, and one of them is out-of-scope. See `Expr.app` case at `check`. If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope, an assigning `?m := fun _ ... _ => ?n` -/ def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : DefEqM Bool := do mvarType ← inferType mvar; forallBoundedTelescope mvarType numArgs $ fun xs _ => if xs.size != numArgs then pure false else do v ← mkLambdaFVars xs newMVar; checkTypesAndAssign mvar v partial def check : Expr → CheckAssignmentM Expr | e@(Expr.mdata _ b _) => do b ← visit check b; pure $ e.updateMData! b | e@(Expr.proj _ _ s _) => do s ← visit check s; pure $ e.updateProj! s | e@(Expr.lam _ d b _) => do d ← visit check d; b ← visit check b; pure $ e.updateLambdaE! d b | e@(Expr.forallE _ d b _) => do d ← visit check d; b ← visit check b; pure $ e.updateForallE! d b | e@(Expr.letE _ t v b _) => do t ← visit check t; v ← visit check v; b ← visit check b; pure $ e.updateLet! t v b | e@(Expr.bvar _ _) => pure e | e@(Expr.sort _ _) => pure e | e@(Expr.const _ _ _) => pure e | e@(Expr.lit _ _) => pure e | e@(Expr.fvar _ _) => visit (checkFVar check) e | e@(Expr.mvar _ _) => visit (checkMVar check) e | Expr.localE _ _ _ _ => unreachable! | e@(Expr.app _ _ _) => e.withApp $ fun f args => do ctxMeta ← readThe Meta.Context; if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then do f ← visit (checkMVar check) f; catchInternalId outOfScopeExceptionId (do args ← args.mapM (visit check); pure $ mkAppN f args) (fun ex => condM (isDelayedAssigned f.mvarId!) (throw ex) do eType ← inferType e; mvarType ← check eType; /- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar` Note that `mvarType` may be different from `eType`. -/ ctx ← read; newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType; condM (liftM $ assignToConstFun f args.size newMVar) (pure newMVar) (throw ex)) else do f ← visit check f; args ← args.mapM (visit check); pure $ mkAppN f args @[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : DefEqM (Option Expr) := do mvarDecl ← getMVarDecl mvarId; let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context }; let x : CheckAssignmentM (Option Expr) := catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId] (do e ← x; pure $ some e) (fun _ => pure none); (x.run ctx).run' {} end CheckAssignment namespace CheckAssignmentQuick @[inline] private def visit (f : Expr → Bool) (e : Expr) : Bool := if !e.hasExprMVar && !e.hasFVar then true else f e partial def check (hasCtxLocals ctxApprox : Bool) (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) : Expr → Bool | e@(Expr.mdata _ b _) => check b | e@(Expr.proj _ _ s _) => check s | e@(Expr.app f a _) => visit check f && visit check a | e@(Expr.lam _ d b _) => visit check d && visit check b | e@(Expr.forallE _ d b _) => visit check d && visit check b | e@(Expr.letE _ t v b _) => visit check t && visit check v && visit check b | e@(Expr.bvar _ _) => true | e@(Expr.sort _ _) => true | e@(Expr.const _ _ _) => true | e@(Expr.lit _ _) => true | e@(Expr.fvar fvarId _) => if mvarDecl.lctx.contains fvarId then true else match lctx.find? fvarId with | some (LocalDecl.ldecl _ _ _ _ v _) => false -- need expensive CheckAssignment.check | _ => if fvars.any $ fun x => x.fvarId! == fvarId then true else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it | e@(Expr.mvar mvarId' _) => do match mctx.getExprAssignment? mvarId' with | some _ => false -- use CheckAssignment.check to instantiate | none => if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception else match mctx.findDecl? mvarId' with | none => false | some mvarDecl' => if hasCtxLocals then false -- use CheckAssignment.check else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true else if mvarDecl'.depth != mctx.depth || mvarDecl'.kind.isSyntheticOpaque then false -- use CheckAssignment.check else if ctxApprox && mvarDecl.lctx.isSubPrefixOf mvarDecl'.lctx then false -- use CheckAssignment.check else true | Expr.localE _ _ _ _ => unreachable! end CheckAssignmentQuick -- See checkAssignment def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : DefEqM (Option Expr) := do CheckAssignment.run (CheckAssignment.check v) mvarId fvars hasCtxLocals v /-- Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`. It will check whether we can perform the assignment ``` ?m := fun fvars => t ``` The result is `none` if the assignment can't be performed. The result is `some newV` where `newV` is a possibly updated `v`. This method may need to unfold let-declarations. -/ def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : DefEqM (Option Expr) := do if !v.hasExprMVar && !v.hasFVar then pure (some v) else do mvarDecl ← getMVarDecl mvarId; let hasCtxLocals := fvars.any $ fun fvar => mvarDecl.lctx.containsFVar fvar; ctx ← read; mctx ← getMCtx; if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then pure (some v) else do v ← instantiateMVars v; checkAssignmentAux mvarId fvars hasCtxLocals v private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : DefEqM Bool := match v with | Expr.app f a _ => Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f | _ => pure false /- Auxiliary method for applying first-order unification. It is an approximation. Remark: this method is trying to solve the unification constraint: ?m a₁ ... aₙ =?= v It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`. We have added support for unfolding here because we want to be able to solve unification problems such as ?m Unit =?= ITactic where `ITactic` is defined as def ITactic := Tactic Unit -/ private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) : Expr → DefEqM Bool | v => do cfg ← getConfig; if !cfg.foApprox then pure false else do trace! `Meta.isDefEq.foApprox (mvar ++ " " ++ args ++ " := " ++ v); condM (commitWhen $ processAssignmentFOApproxAux mvar args v) (pure true) (do v? ← unfoldDefinition? v; match v? with | none => pure false | some v => processAssignmentFOApprox v) private partial def simpAssignmentArgAux : Expr → DefEqM Expr | Expr.mdata _ e _ => simpAssignmentArgAux e | e@(Expr.fvar fvarId _) => do decl ← getLocalDecl fvarId; match decl.value? with | some value => simpAssignmentArgAux value | _ => pure e | e => pure e /- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`. We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`, and then removes metadata, and zeta-expand let-decls. -/ private def simpAssignmentArg (arg : Expr) : DefEqM Expr := do arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg; simpAssignmentArgAux arg private def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : DefEqM Bool := do cfg ← getConfig; let mvarId := mvar.mvarId!; mvarDecl ← getMVarDecl mvarId; if mvarDecl.numScopeArgs == numArgs || cfg.constApprox then do v? ← checkAssignment mvarId #[] v; match v? with | none => pure false | some v => do forallBoundedTelescope mvarDecl.type numArgs $ fun xs _ => if xs.size != numArgs then pure false else do v ← mkLambdaFVars xs v; trace! `Meta.isDefEq.constApprox (mvar ++ " := " ++ v); checkTypesAndAssign mvar v else pure false private partial def processAssignmentAux (mvar : Expr) (mvarDecl : MetavarDecl) : Nat → Array Expr → Expr → DefEqM Bool | i, args, v => do cfg ← getConfig; let useFOApprox (args : Array Expr) : DefEqM Bool := processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v; if h : i < args.size then do let arg := args.get ⟨i, h⟩; arg ← simpAssignmentArg arg; let args := args.set ⟨i, h⟩ arg; match arg with | Expr.fvar fvarId _ => if args.anyRange 0 i (fun prevArg => prevArg == arg) then useFOApprox args else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then useFOApprox args else processAssignmentAux (i+1) args v | _ => useFOApprox args else do v ← instantiateMVars v; -- enforce A4 if v.getAppFn == mvar then -- using A6 useFOApprox args else do let mvarId := mvar.mvarId!; v? ← checkAssignment mvarId args v; match v? with | none => useFOApprox args | some v => do trace `Meta.isDefEq.assign.beforeMkLambda $ fun _ => mvar ++ " " ++ args ++ " := " ++ v; v ← mkLambdaFVars args v; if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ condM (liftM $ isTypeCorrect v) (checkTypesAndAssign mvar v) (do trace `Meta.isDefEq.assign.typeError $ fun _ => mvar ++ " := " ++ v; useFOApprox args) else checkTypesAndAssign mvar v /-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`. It assumes `?m` is unassigned. -/ private def processAssignment (mvarApp : Expr) (v : Expr) : DefEqM Bool := traceCtx `Meta.isDefEq.assign $ do trace! `Meta.isDefEq.assign (mvarApp ++ " := " ++ v); let mvar := mvarApp.getAppFn; mvarDecl ← getMVarDecl mvar.mvarId!; processAssignmentAux mvar mvarDecl 0 mvarApp.getAppArgs v private def isDeltaCandidate? (t : Expr) : DefEqM (Option ConstantInfo) := match t.getAppFn with | Expr.const c _ _ => liftM $ getConst? c | _ => pure none /-- Auxiliary method for isDefEqDelta -/ private def isListLevelDefEq (us vs : List Level) : DefEqM LBool := toLBoolM $ isListLevelDefEqAux us vs /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeft (fn : Name) (t s : Expr) : DefEqM LBool := do trace! `Meta.isDefEq.delta.unfoldLeft fn; toLBoolM $ Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqRight (fn : Name) (t s : Expr) : DefEqM LBool := do trace! `Meta.isDefEq.delta.unfoldRight fn; toLBoolM $ Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeftRight (fn : Name) (t s : Expr) : DefEqM LBool := do trace! `Meta.isDefEq.delta.unfoldLeftRight fn; toLBoolM $ Meta.isExprDefEqAux t s /-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`. Auxiliary method for isDefEqDelta -/ private def tryHeuristic (t s : Expr) : DefEqM Bool := let tFn := t.getAppFn; let sFn := s.getAppFn; traceCtx `Meta.isDefEq.delta $ commitWhen $ do b ← isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!; unless b $ trace! `Meta.isDefEq.delta ("heuristic failed " ++ t ++ " =?= " ++ s); pure b /-- Auxiliary method for isDefEqDelta -/ private abbrev unfold {α} (e : Expr) (failK : DefEqM α) (successK : Expr → DefEqM α) : DefEqM α := do e? ← unfoldDefinition? e; match e? with | some e => successK e | none => failK /-- Auxiliary method for isDefEqDelta -/ private def unfoldBothDefEq (fn : Name) (t s : Expr) : DefEqM LBool := match t, s with | Expr.const _ ls₁ _, Expr.const _ ls₂ _ => isListLevelDefEq ls₁ ls₂ | Expr.app _ _ _, Expr.app _ _ _ => condM (tryHeuristic t s) (pure LBool.true) (unfold t (unfold s (pure LBool.false) (fun s => isDefEqRight fn t s)) (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s))) | _, _ => pure LBool.false private def sameHeadSymbol (t s : Expr) : Bool := match t.getAppFn, s.getAppFn with | Expr.const c₁ _ _, Expr.const c₂ _ _ => true | _, _ => false /-- - If headSymbol (unfold t) == headSymbol s, then unfold t - If headSymbol (unfold s) == headSymbol t, then unfold s - Otherwise unfold t and s if possible. Auxiliary method for isDefEqDelta -/ private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : DefEqM LBool := unfold t (unfold s (pure LBool.undef) -- `t` and `s` failed to be unfolded (fun s => isDefEqRight sInfo.name t s)) (fun tNew => if sameHeadSymbol tNew s then isDefEqLeft tInfo.name tNew s else unfold s (isDefEqLeft tInfo.name tNew s) (fun sNew => if sameHeadSymbol t sNew then isDefEqRight sInfo.name t sNew else isDefEqLeftRight tInfo.name tNew sNew)) /-- If `t` and `s` do not contain metavariables, then use kernel definitional equality heuristics. Otherwise, use `unfoldComparingHeadsDefEq`. Auxiliary method for isDefEqDelta -/ private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : DefEqM LBool := if !t.hasExprMVar && !s.hasExprMVar then /- If `t` and `s` do not contain metavariables, we simulate strategy used in the kernel. -/ if tInfo.hints.lt sInfo.hints then unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else if sInfo.hints.lt tInfo.hints then unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else unfoldComparingHeadsDefEq tInfo sInfo t s else unfoldComparingHeadsDefEq tInfo sInfo t s /-- When `TransparencyMode` is set to `default` or `all`. If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s` If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)` Otherwise, use `unfoldDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : DefEqM LBool := condM shouldReduceReducibleOnly (unfoldDefEq tInfo sInfo t s) (do tReducible ← liftM $ Meta.isReducible tInfo.name; sReducible ← liftM $ Meta.isReducible sInfo.name; if tReducible && !sReducible then unfold t (unfoldDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else if !tReducible && sReducible then unfold s (unfoldDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else unfoldDefEq tInfo sInfo t s) /-- If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)` If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s` Otherwise, use `unfoldReducibeDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : DefEqM LBool := do env ← getEnv; let tProj? := env.isProjectionFn tInfo.name; let sProj? := env.isProjectionFn sInfo.name; if tProj? && !sProj? then unfold s (unfoldDefEq tInfo sInfo t s) $ fun s => isDefEqRight sInfo.name t s else if !tProj? && sProj? then unfold t (unfoldDefEq tInfo sInfo t s) $ fun t => isDefEqLeft tInfo.name t s else unfoldReducibeDefEq tInfo sInfo t s /-- isDefEq by lazy delta reduction. This method implements many different heuristics: 1- If only `t` can be unfolded => then unfold `t` and continue 2- If only `s` can be unfolded => then unfold `s` and continue 3- If `t` and `s` can be unfolded and they have the same head symbol, then a) First try to solve unification by unifying arguments. b) If it fails, unfold both and continue. Implemented by `unfoldBothDefEq` 4- If `t` is a projection function application and `s` is not => then unfold `s` and continue. 5- If `s` is a projection function application and `t` is not => then unfold `t` and continue. Remark: 4&5 are implemented by `unfoldNonProjFnDefEq` 6- If `t` is reducible and `s` is not => then unfold `t` and continue. 7- If `s` is reducible and `t` is not => then unfold `s` and continue Remark: 6&7 are implemented by `unfoldReducibeDefEq` 8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel. Implemented by `unfoldDefEq` 9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue. 10- If `headSymbol (unfold s) == headSymbol t`, then unfold s 11- Otherwise, unfold `t` and `s` and continue. Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/ private def isDefEqDelta (t s : Expr) : DefEqM LBool := do tInfo? ← isDeltaCandidate? t.getAppFn; sInfo? ← isDeltaCandidate? s.getAppFn; match tInfo?, sInfo? with | none, none => pure LBool.undef | some tInfo, none => unfold t (pure LBool.undef) $ fun t => isDefEqLeft tInfo.name t s | none, some sInfo => unfold s (pure LBool.undef) $ fun s => isDefEqRight sInfo.name t s | some tInfo, some sInfo => if tInfo.name == sInfo.name then unfoldBothDefEq tInfo.name t s else unfoldNonProjFnDefEq tInfo sInfo t s private def isAssigned : Expr → DefEqM Bool | Expr.mvar mvarId _ => isExprMVarAssigned mvarId | _ => pure false private def isDelayedAssignedHead (tFn : Expr) (t : Expr) : DefEqM Bool := match tFn with | Expr.mvar mvarId _ => do condM (isDelayedAssigned mvarId) (do tNew ← instantiateMVars t; pure $ tNew != t) (pure false) | _ => pure false private def isSynthetic : Expr → DefEqM Bool | Expr.mvar mvarId _ => do mvarDecl ← getMVarDecl mvarId; match mvarDecl.kind with | MetavarKind.synthetic => pure true | MetavarKind.syntheticOpaque => pure true | MetavarKind.natural => pure false | _ => pure false private def isAssignable : Expr → DefEqM Bool | Expr.mvar mvarId _ => do b ← isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b) | _ => pure false private def etaEq (t s : Expr) : Bool := match t.etaExpanded? with | some t => t == s | none => false private def isLetFVar (fvarId : FVarId) : DefEqM Bool := do decl ← getLocalDecl fvarId; pure decl.isLet private def isDefEqProofIrrel (t s : Expr) : DefEqM LBool := do status ← liftM $ isProofQuick t; match status with | LBool.false => pure LBool.undef | LBool.true => do tType ← inferType t; sType ← inferType s; toLBoolM $ Meta.isExprDefEqAux tType sType | LBool.undef => do tType ← inferType t; condM (isProp tType) (do sType ← inferType s; toLBoolM $ Meta.isExprDefEqAux tType sType) (pure LBool.undef) /- Remove unnecessary let-decls -/ private def consumeLet : Expr → Expr | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b | e => e private partial def isDefEqQuick : Expr → Expr → DefEqM LBool | t, s => do let t := consumeLet t; let s := consumeLet s; match t, s with | Expr.lit l₁ _, Expr.lit l₂ _ => pure (l₁ == l₂).toLBool | Expr.sort u _, Expr.sort v _ => toLBoolM $ isLevelDefEqAux u v | t@(Expr.lam _ _ _ _), s@(Expr.lam _ _ _ _) => if t == s then pure LBool.true else toLBoolM $ isDefEqBinding t s | t@(Expr.forallE _ _ _ _), s@(Expr.forallE _ _ _ _) => if t == s then pure LBool.true else toLBoolM $ isDefEqBinding t s | Expr.mdata _ t _, s => isDefEqQuick t s | t, Expr.mdata _ s _ => isDefEqQuick t s | t@(Expr.fvar fvarId₁ _), s@(Expr.fvar fvarId₂ _) => condM (isLetFVar fvarId₁ <||> isLetFVar fvarId₂) (pure LBool.undef) (if fvarId₁ == fvarId₂ then pure LBool.true else isDefEqProofIrrel t s) | t, s => cond (t == s) (pure LBool.true) $ cond (etaEq t s || etaEq s t) (pure LBool.true) $ -- t =?= (fun xs => t xs) let tFn := t.getAppFn; let sFn := s.getAppFn; cond (!tFn.isMVar && !sFn.isMVar) (pure LBool.undef) $ condM (isAssigned tFn) (do t ← instantiateMVars t; isDefEqQuick t s) $ condM (isAssigned sFn) (do s ← instantiateMVars s; isDefEqQuick t s) $ condM (isDelayedAssignedHead tFn t) (do t ← instantiateMVars t; isDefEqQuick t s) $ condM (isDelayedAssignedHead sFn s) (do s ← instantiateMVars s; isDefEqQuick t s) $ condM (isSynthetic tFn <&&> trySynthPending tFn) (do t ← instantiateMVars t; isDefEqQuick t s) $ condM (isSynthetic sFn <&&> trySynthPending sFn) (do s ← instantiateMVars s; isDefEqQuick t s) $ do tAssign? ← isAssignable tFn; sAssign? ← isAssignable sFn; trace! `Meta.isDefEq (t ++ (if tAssign? then " [assignable]" else " [nonassignable]") ++ " =?= " ++ s ++ (if sAssign? then " [assignable]" else " [nonassignable]")); let assign (t s : Expr) : DefEqM LBool := toLBoolM $ processAssignment t s; cond (tAssign? && !sAssign?) (assign t s) $ cond (!tAssign? && sAssign?) (assign s t) $ cond (!tAssign? && !sAssign?) (if tFn.isMVar || sFn.isMVar then do ctx ← read; if ctx.config.isDefEqStuckEx then do trace! `Meta.isDefEq.stuck (t ++ " =?= " ++ s); Meta.throwIsDefEqStuck else pure LBool.false else pure LBool.undef) $ do -- Both `t` and `s` are terms of the form `?m ...` tMVarDecl ← getMVarDecl tFn.mvarId!; sMVarDecl ← getMVarDecl sFn.mvarId!; if s.isMVar && !t.isMVar then /- Solve `?m t =?= ?n` by trying first `?n := ?m t`. Reason: this assignment is precise. -/ condM (commitWhen (processAssignment s t)) (pure LBool.true) $ assign t s else condM (commitWhen (processAssignment t s)) (pure LBool.true) $ assign s t @[inline] def whenUndefDo (x : DefEqM LBool) (k : DefEqM Bool) : DefEqM Bool := do status ← x; match status with | LBool.true => pure true | LBool.false => pure false | LBool.undef => k @[specialize] private def unstuckMVar (e : Expr) (successK : Expr → DefEqM Bool) (failK : DefEqM Bool): DefEqM Bool := do mvarId? ← getStuckMVar? e; match mvarId? with | some mvarId => condM (liftM $ Meta.synthPending mvarId) (do e ← instantiateMVars e; successK e) failK | none => failK private def isDefEqOnFailure (t s : Expr) : DefEqM Bool := unstuckMVar t (fun t => Meta.isExprDefEqAux t s) $ unstuckMVar s (fun s => Meta.isExprDefEqAux t s) $ pure false private def isDefEqProj : Expr → Expr → DefEqM Bool | Expr.proj _ i t _, Expr.proj _ j s _ => pure (i == j) <&&> Meta.isExprDefEqAux t s | _, _ => pure false partial def isExprDefEqAuxImpl : Expr → Expr → DefEqM Bool | t, s => do trace `Meta.isDefEq.step $ fun _ => t ++ " =?= " ++ s; whenUndefDo (isDefEqQuick t s) $ whenUndefDo (isDefEqProofIrrel t s) do t' ← whnfCore t; s' ← whnfCore s; if t != t' || s != s' then isExprDefEqAuxImpl t' s' else do condM (isDefEqEta t s <||> isDefEqEta s t) (pure true) $ condM (isDefEqProj t s) (pure true) $ whenUndefDo (isDefEqNative t s) do whenUndefDo (isDefEqNat t s) do whenUndefDo (isDefEqOffset t s) do whenUndefDo (isDefEqDelta t s) $ match t, s with | Expr.const c us _, Expr.const d vs _ => if c == d then isListLevelDefEqAux us vs else pure false | Expr.app _ _ _, Expr.app _ _ _ => let tFn := t.getAppFn; condM (commitWhen (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) (pure true) (isDefEqOnFailure t s) | _, _ => whenUndefDo (isDefEqStringLit t s) $ isDefEqOnFailure t s @[init] def setIsExprDefEqAuxRef : IO Unit := isExprDefEqAuxRef.set isExprDefEqAuxImpl @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Meta.isDefEq; registerTraceClass `Meta.isDefEq.foApprox; registerTraceClass `Meta.isDefEq.constApprox; registerTraceClass `Meta.isDefEq.delta; registerTraceClass `Meta.isDefEq.step; registerTraceClass `Meta.isDefEq.assign end Meta end Lean
8174c4e62b2327f1374dce26bda6cb18edcf7f11
d751a70f46ed26dc0111a87f5bbe83e5c6648904
/Code/src/inst/primitives.lean
ff71d5a71276d82603352cc9c0daa09dc24dac34
[]
no_license
marcusrossel/bachelors-thesis
92cb12ae8436c10fbfab9bfe4929a0081e615b37
d1ec2c2b5c3c6700a506f2e3cc93f1160e44b422
refs/heads/main
1,682,873,547,703
1,619,795,735,000
1,619,795,735,000
306,041,494
2
0
null
null
null
null
UTF-8
Lean
false
false
11,282
lean
import data.finset import order.lexicographic import mathlib -- The type of opaque values that can be passed between reactors and processed by reactions. -- Their equality has to be decidable, but beyond that their values are of no interest. variables (υ : Type*) [decidable_eq υ] -- A list of state variables as used by reactors. -- The indices into the list can be viewed as the IDs for individual state variables. def reactor.state_vars := list υ -- A list of ports as used by reactors. -- The indices into the list are used as the IDs for individual state variables. -- Absent values are represented by `option.none`. -- We often call an instance of this type a "port assignment". @[derive has_append] def reactor.ports := list (option υ) namespace reactor namespace ports variable {υ} -- Ports can be input- our output-ports. -- Making this distinction explicit is useful for avoiding code duplication for some algorithms. inductive role | input : role | output : role -- Returns the opposite of the given role. @[reducible] def role.opposite : role → role | role.input := role.output | role.output := role.input -- Accessing in index that contains an absent value, and accessing an index -- that isn't part of the list should both return `none`. -- This helps avoid nested optional values. def nth (p : ports υ) (n : ℕ) : option υ := (p.nth n).join -- Exentionality of ports. @[ext] lemma ext {p p' : ports υ} (hₚ : p.nth = p'.nth) (hₗ : p.length = p'.length) : p = p' := begin ext1 x, by_cases hc : x < p.length, { have h' : ∀ n, p.nth n = p'.nth n, from congr_fun hₚ, unfold nth at h', replace h' := h' x, rw list.nth_le_nth hc at h' ⊢, have hj : ∀ n : option υ, (option.some n).join = n, by finish, rw hj at h', rw hₗ at hc, rw list.nth_le_nth hc at h' ⊢, rw hj at h', rw h' }, { have h, from not_lt.mp hc, rw hₗ at hc, have h', from not_lt.mp hc, rw [list.nth_len_le h, list.nth_len_le h'] } end -- The proposition that two port assignments have the same values at given indices. def eq_at (i : finset ℕ) (p p' : ports υ) : Prop := ∀ x ∈ i, p.nth x = p'.nth x notation p =i= q := (eq_at i p q) -- For fixed indices, `reactor.ports.eq_at` is reflexive. @[refl] lemma eq_at_refl (i : finset ℕ) (p : ports υ) : p =i= p := by tauto -- For fixed indices, `reactor.ports.eq_at` is symmetric. @[symm] lemma eq_at_symm {i : finset ℕ} {p p' : ports υ} (h : p =i= p') : p' =i= p := by tauto -- For fixed indices, `reactor.ports.eq_at` is transitive. @[trans] lemma eq_at_trans {i : finset ℕ} {p₁ p₂ p₃ : ports υ} (h₁₂ : p₁ =i= p₂) (h₂₃ : p₂ =i= p₃) : p₁ =i= p₃ := assume x hₓ, eq.trans (h₁₂ x hₓ) (h₂₃ x hₓ) variable υ -- A port assignment that only contains absent values. def empty (n : ℕ) : ports υ := list.repeat none n -- Empty ports can be constructed from absent values. @[simp] lemma empty_cons (n : ℕ) : empty υ (n + 1) = none :: empty υ n := by refl variable {υ} -- The proposition, that a given port assignment is empty. def is_empty (p : ports υ) : Prop := (p = empty υ p.length) -- The set of indices for which the given port assignments have different values. noncomputable def index_diff (before after : ports υ) : finset ℕ := @finset.filter _ (λ i, before.nth i ≠ after.nth i) (classical.dec_pred _) (finset.range (max before.length after.length)) -- Index-diffing is commutative. lemma index_diff_comm (before after : ports υ) : before.index_diff after = after.index_diff before := begin unfold index_diff, rw max_comm, congr, ext, tauto end -- The index-diff of equal port assignments is empty. @[simp] lemma index_diff_eq_ports_empty {p p' : ports υ} (h : p = p') : p.index_diff p' = ∅ := by simp [index_diff, h] -- An index-diff is always a subset of the index-range of the longer port assignment. @[simp] lemma index_diff_range (before after : ports υ) : before.index_diff after ⊆ finset.range (max before.length after.length) := begin unfold index_diff, simp only [(⊆)], intro x, rw finset.mem_filter, intro h, exact h.left end -- The indices in the given port assignment that have a non-absent value. def inhabited_indices (p : ports υ) : finset ℕ := (finset.range p.length).filter (λ i, p.nth i ≠ none) -- Indicies with an absent value are not part of a port assignments inhabited indices. lemma inhabited_indices_none {p : ports υ} {o : ℕ} (h : p.nth o = none) : o ∉ p.inhabited_indices := by simp [inhabited_indices, not_congr finset.mem_filter, h] -- Merges a given port assignment *onto* another one. -- The `src` ports override the `dst` ports, but the length remains that of `dst`. def merge (dst src : ports υ) : ports υ := (src.zip_with (<|>) dst) ++ (dst.drop src.length) -- The length of merged ports is that of the first instance. @[simp] lemma merge_length (dst src : ports υ) : (dst.merge src).length = dst.length := begin unfold merge, by_cases h : dst.length ≤ src.length, simp [h], { rw not_le at h, rw [list.length_append, list.length_zip_with, list.length_drop], rw [min_eq_left_of_lt h, ←nat.add_sub_assoc (le_of_lt h), nat.add_sub_cancel_left] } end -- If the source of a merge contains an absent value for some port, that port stays unaffected. -- The proof is a bit long, as there are many cases to be covered. @[simp] lemma merge_none_eq (dst : ports υ) {src : ports υ} {p : ℕ} (h : src.nth p = none) : (dst.merge src).nth p = dst.nth p := begin replace h := option.join_eq_none.mp h, unfold merge, simp only [ports.nth, list.nth_zip_with], by_cases hcₗ : dst.length ≤ src.length, { simp only [list.drop_eq_nil_iff_le.mpr hcₗ, list.append_nil, list.nth_zip_with, option.map_eq_map, option.bind_eq_bind, (<*>)], cases h, all_goals { simp [h] }, { rw list.nth_eq_none_iff at h, simp [list.nth_eq_none_iff.mpr (has_le.le.trans hcₗ h)] }, { rw list.nth_eq_some at h, by_cases hc : list.nth dst p = none, simp [hc], { simp at hc, simp [list.nth_le_nth hc] } } }, { rw not_le at hcₗ, by_cases hc : p < (list.zip_with has_orelse.orelse src dst).length, { simp only [list.nth_append hc, list.nth_zip_with, list.map_eq_map, option.bind_eq_bind, (<*>)], congr, rw [list.length_zip_with, min_eq_left_of_lt hcₗ] at hc, cases h, { exfalso, have, from not_lt_of_le (list.nth_eq_none_iff.mp h), contradiction }, simp [h, list.nth_le_nth (has_lt.lt.trans hc hcₗ)] }, { replace hc := le_of_not_lt hc, rw list.nth_append_right hc, rw [list.length_zip_with, min_eq_left_of_lt hcₗ] at hc ⊢, rw list.nth_drop, rw ←nat.add_sub_assoc hc, simp } } end example {n m x : ℕ} (h : n - x < m - x) : n < m := begin exact nat.lt_of_sub_lt_sub_right h, end -- Any index beyond the source ports will remain unchanged by a merge. @[simp] lemma merge_after_src_eq_dst (dst : ports υ) {src : ports υ} {p : ℕ} (h : src.length ≤ p) : (dst.merge src).nth p = dst.nth p := begin have hₙ, from list.nth_len_le h, have hj, from option.join_eq_none.mpr (or.inl hₙ), exact merge_none_eq _ hj end -- If we merge "too few" ports, then the diff above is always empty. lemma merge_index_diff_range_sub_src {dst src : ports υ} (hₗ : src.length ≤ dst.length) : dst.index_diff (dst.merge src) ⊆ finset.range src.length := begin simp only [(⊆)], intros x hₓ, simp [index_diff] at hₓ, by_cases hc : x ≥ src.length, { exfalso, have, from merge_after_src_eq_dst dst hc, replace hₓ := ne.symm hₓ.right, contradiction, }, exact finset.mem_range.mpr (not_le.mp hc) end -- The indices that change from a merge have to be less than the length of the destination ports. lemma merge_index_diff_range_sub_dst (dst src : ports υ) : dst.index_diff (dst.merge src) ⊆ finset.range dst.length := begin simp only [(⊆)], intros x hₓ, simp [merge, index_diff] at hₓ, replace hₓ := hₓ.left, cases hₓ, exact list.mem_range.mpr hₓ, { by_cases h : list.length dst ≤ list.length src, { rw [min_comm, min_eq_left h, nat.sub_eq_zero_of_le h] at hₓ, exact list.mem_range.mpr hₓ }, { rw not_le at h, rw [min_eq_left_of_lt h, ←nat.add_sub_assoc (le_of_lt h), nat.add_sub_cancel_left] at hₓ, exact list.mem_range.mpr hₓ } } end -- The indices that change from a merge have to be less than the length of the source ports. lemma merge_index_diff_range_sub_src' (dst src : ports υ) : dst.index_diff (dst.merge src) ⊆ finset.range src.length := begin by_cases h : src.length ≤ dst.length, exact merge_index_diff_range_sub_src h, { have h', from index_diff_range dst (dst.merge src), simp only [(⊆)] at h' ⊢, intro x, simp only [finset.mem_range] at h' ⊢, intro hᵢ, have h'', from h' hᵢ, norm_num at h'', rw not_le at h, transitivity, exact h'', exact h } end -- The index-diff of merging `src` onto `dst` is a subset of the inhabited indices of `src`. lemma merge_index_diff_sub_inhabited (dst src : ports υ) : dst.index_diff (dst.merge src) ⊆ src.inhabited_indices := begin simp only [(⊆)], by_contradiction, rw not_forall at h, obtain ⟨x, hₓ⟩ := h, rw not_imp at hₓ, obtain ⟨hd, hᵢ⟩ := hₓ, unfold inhabited_indices at hᵢ, rw not_congr finset.mem_filter at hᵢ, cases not_and_distrib.mp hᵢ, { have h', from merge_index_diff_range_sub_src' dst src, simp only [(⊆)] at h', have hc, from h' hd, contradiction }, { have h' : src.nth x = none, by finish, have hₑ, from merge_none_eq dst h', unfold index_diff at hd, rw [finset.mem_filter, hₑ] at hd, replace hd := hd.right, contradiction, } end end ports end reactor
928e921916d80dafedea0a776b8a8ea8201302c8
7c92a46ce39266c13607ecdef7f228688f237182
/src/for_mathlib/topology.lean
8359f9d6d0da0826b69787e07c8f0e0ae7cbeaf7
[ "Apache-2.0" ]
permissive
asym57/lean-perfectoid-spaces
3217d01f6ddc0d13e9fb68651749469750420767
359187b429f254a946218af4411d45f08705c83e
refs/heads/master
1,609,457,937,251
1,577,542,616,000
1,577,542,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,128
lean
import topology.opens import topology.algebra.continuous_functions import for_mathlib.filter import for_mathlib.data.set.basic open topological_space function local notation `𝓝` x:70 := nhds x local notation f `∘₂` g := function.bicompr f g -- We need to think whether we could directly use the class t2_space (which is not using opens though) definition is_hausdorff (α : Type*) [topological_space α] : Prop := ∀ x y, x ≠ y → ∃ u v : opens α, x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ open set filter instance regular_of_discrete {α : Type*} [topological_space α] [discrete_topology α] : regular_space α := { t1 := λ x, is_open_discrete _, regular := begin intros s a s_closed a_not, refine ⟨s, is_open_discrete s, subset.refl s, _⟩, erw [← empty_in_sets_eq_bot, mem_inf_sets], use {a}, rw nhds_discrete α, simp, refine ⟨s, subset.refl s, _ ⟩, rintro x ⟨xa, xs⟩, rw ← mem_singleton_iff.1 xa at a_not, exact a_not xs end } lemma continuous_of_const {α : Type*} {β : Type*} [topological_space α] [topological_space β] {f : α → β} (h : ∀a b, f a = f b) : continuous f := λ s _, by convert @is_open_const _ _ (∃ a, f a ∈ s); exact set.ext (λ a, ⟨λ fa, ⟨_, fa⟩, λ ⟨b, fb⟩, show f a ∈ s, from h b a ▸ fb⟩) section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] def continuous₂ (f : α → β → γ) := continuous (function.uncurry' f) lemma continuous₂_def (f : α → β → γ) : continuous₂ f ↔ continuous (function.uncurry' f) := iff.rfl lemma continuous₂_curry (f : α × β → γ) : continuous₂ (function.curry f) ↔ continuous f := by rw [←function.uncurry'_curry f] {occs := occurrences.pos [2]} ; refl lemma continuous₂.comp {f : α → β → γ} {g : γ → δ} (hf : continuous₂ f)(hg : continuous g) : continuous₂ (g ∘₂ f) := hg.comp hf section open set filter lattice function /- f α → β g ↓ ↓ h γ → δ i -/ variables {f : α → β} {g : α → γ} {i : γ → δ} {h : β → δ} lemma continuous_of_continuous_on_of_induced (H : h ∘ f = i ∘ g) (hi : continuous_on i $ range g) (hg : ‹topological_space α› = induced g ‹topological_space γ›) (hh : ‹topological_space β› = induced h ‹topological_space δ›) : continuous f := begin rw continuous_iff_continuous_at, intro x, dsimp [continuous_at, tendsto], rw [hg, hh, nhds_induced, nhds_induced, ← map_le_iff_le_comap, map_comm H], specialize hi (g x) ⟨x, rfl⟩, have := calc nhds_within (g x) (range g) = 𝓝 g x ⊓ principal (range g) : rfl ... = 𝓝 g x ⊓ map g (principal univ) : by rw [← image_univ, ← map_principal] ... = 𝓝 g x ⊓ map g ⊤ : by rw principal_univ, rw [continuous_within_at, this, ← comp_app i g, ← congr_fun H x] at hi, clear this, have := calc map g (comap g 𝓝 g x) = map g (comap g 𝓝 g x ⊓ ⊤) : by rw inf_top_eq ... ≤ map g (comap g 𝓝 g x) ⊓ map g ⊤ : map_inf_le ... ≤ 𝓝 g x ⊓ map g ⊤ : inf_le_inf map_comap_le (le_refl _), exact le_trans (map_mono this) hi, end variables (eg : embedding g) (eh : embedding h) include eg lemma embedding.nhds_eq_comap (a : α) : nhds a = comap g (nhds $ g a) := by rw [eg.induced, nhds_induced] include eh lemma embedding.tendsto_iff (H : h ∘ f = i ∘ g) (a : α) : continuous_at i (g a) → continuous_at f a:= begin let N := nhds a, let Nf := nhds (f a), let Nhf := nhds (h $ f a), let Ng := nhds (g a), have Neq1 : Nf = comap h Nhf, from eh.nhds_eq_comap (f a), have Neq2 : N = comap g Ng, from eg.nhds_eq_comap a, intro hyp, replace hyp : Ng ≤ comap i Nhf, { unfold continuous_at at hyp, rw ← show h (f a) = i (g a), from congr_fun H a at hyp, rwa tendsto_iff_comap at hyp }, rw calc continuous_at f a ↔ tendsto f N Nf : iff.rfl ... ↔ N ≤ comap f Nf : tendsto_iff_comap ... ↔ comap g Ng ≤ comap f (comap h Nhf) : by rw [Neq1, Neq2] ... ↔ comap g Ng ≤ comap g (comap i Nhf) : by rw comap_comm H, exact comap_mono hyp end end end namespace dense_inducing open set function filter variables {α : Type*} {β : Type*} {δ : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space δ] [topological_space γ] /- f α → β g ↓ ↓ h γ → δ i -/ variables {f : α → β} {g : α → γ} {i : γ → δ} {h : β → δ} lemma comp (dh : dense_inducing h) (df : dense_inducing f) : dense_inducing (h ∘ f) := { dense := dense_range.comp _ dh.dense df.dense dh.continuous, induced := (dh.to_inducing.comp df.to_inducing).induced } lemma of_comm_square (dg : dense_inducing g) (di : dense_inducing i) (dh : dense_inducing h) (H : h ∘ f = i ∘ g) : dense_inducing f := have dhf : dense_inducing (h ∘ f), by {rw H, exact di.comp dg }, { dense := begin intro x, have H := dhf.dense (h x), rw mem_closure_iff_nhds at H ⊢, intros t ht, rw [dh.nhds_eq_comap x, mem_comap_sets] at ht, rcases ht with ⟨u, hu, hinc⟩, replace H := H u hu, rw ne_empty_iff_exists_mem at H ⊢, rcases H with ⟨v, hv1, a, rfl⟩, use f a, split, swap, apply mem_range_self, apply mem_of_mem_of_subset _ hinc, rwa mem_preimage, end , -- inj := λ a b H, dhf.inj (by {show h (f a) = _, rw H}), induced := by rw [dg.induced, di.induced, induced_compose, ← H, ← induced_compose, dh.induced] } end dense_inducing namespace dense_embedding open set function filter variables {α : Type*} {β : Type*} {δ : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space δ] [topological_space γ] /- f α → β g ↓ ↓ h γ → δ i -/ variables {f : α → β} {g : α → γ} {i : γ → δ} {h : β → δ} -- TODO: fix implicit argument in dense_range.comp before PRing lemma comp (dh : dense_embedding h) (df : dense_embedding f) : dense_embedding (h ∘ f) := { dense := dense_range.comp _ dh.dense df.dense dh.to_dense_inducing.continuous, inj := function.injective_comp dh.inj df.inj, induced := (dh.to_inducing.comp df.to_inducing).induced } lemma of_homeo (h : α ≃ₜ β) : dense_embedding h := { dense := dense_range_iff_closure_range.mpr $ (range_iff_surjective.mpr h.to_equiv.surjective).symm ▸ closure_univ, inj := h.to_equiv.injective, induced := h.induced_eq.symm, } lemma of_comm_square (dg : dense_embedding g) (di : dense_embedding i) (dh : dense_embedding h) (H : h ∘ f = i ∘ g) : dense_embedding f := { inj := begin intros a b hab, have : (h ∘ f) a = (h ∘ f) b := by convert congr_arg h hab, rw H at this, exact dg.inj (di.inj this), end, ..dense_inducing.of_comm_square dg.to_dense_inducing di.to_dense_inducing dh.to_dense_inducing H } end dense_embedding section open filter variables {α : Type*} [topological_space α] {β : Type*} [topological_space β] [discrete_topology β] lemma continuous_into_discrete_iff (f : α → β) : continuous f ↔ ∀ b : β, is_open (f ⁻¹' {b}) := begin split, { intros hf b, exact hf _ (is_open_discrete _) }, { intro h, rw continuous_iff_continuous_at, intro x, have key : f ⁻¹' {f x} ∈ nhds x, from mem_nhds_sets (h $ f x) (set.mem_insert (f x) ∅), calc map f (nhds x) ≤ pure (f x) : (tendsto_pure f (nhds x) (f x)).2 key ... ≤ nhds (f x) : pure_le_nhds _ } end lemma discrete_iff_open_singletons : discrete_topology α ↔ ∀ x, is_open ({x} : set α) := ⟨by introsI ; exact is_open_discrete _, λ h, ⟨eq_bot_of_singletons_open h⟩⟩ lemma discrete_iff_nhds_eq_pure {X : Type*} [topological_space X] : discrete_topology X ↔ ∀ x : X, nhds x = pure x := begin split, { introsI h, exact congr_fun (nhds_discrete X) }, { intro h, constructor, apply eq_bot_of_singletons_open, intro x, change _root_.is_open {x}, rw is_open_iff_nhds, simp [h] }, end lemma discrete_of_embedding_discrete {X : Type*} {Y : Type*} [topological_space X] [topological_space Y] {f : X → Y} (hf : embedding f) [discrete_topology Y] : discrete_topology X := begin rw discrete_iff_nhds_eq_pure, intro x, rw [hf.to_inducing.nhds_eq_comap, nhds_discrete], suffices : f ⁻¹' {f x} = {x}, by simpa, ext, simp [hf.inj] end lemma is_open_singleton_iff {X : Type*} [topological_space X] {x : X} : is_open ({x} : set X) ↔ {x} ∈ nhds x := begin rw is_open_iff_nhds, split ; intro h, { apply h x (mem_singleton _), simp }, { intros y y_in, rw mem_singleton_iff at y_in, simp [*] }, end end -- tools for proving that a product of top rings is a top ring def continuous_pi₁ {I : Type*} {R : I → Type*} {S : I → Type*} [∀ i, topological_space (R i)] [∀ i, topological_space (S i)] {f : Π (i : I), (R i) → (S i)} (Hfi : ∀ i, continuous (f i)) : continuous (λ rs i, f i (rs i) : (Π (i : I), R i) → Π (i : I), S i) := continuous_pi (λ i, (Hfi i).comp (continuous_apply i)) def continuous_pi₂ {I : Type*} {R : I → Type*} {S : I → Type*} {T : I → Type*} [∀ i, topological_space (R i)] [∀ i, topological_space (S i)] [∀ i, topological_space (T i)] {f : Π (i : I), (R i) × (S i) → (T i)} (Hfi : ∀ i, continuous (f i)) : continuous (λ rs i, f i ⟨rs.1 i, rs.2 i⟩ : (Π (i : I), R i) × (Π (i : I), S i) → Π (i : I), T i) := continuous_pi (λ i, (Hfi i).comp (continuous.prod_mk ((continuous_apply i).comp continuous_fst) $ (continuous_apply i).comp continuous_snd)) /- The following class probably won't have global instances, but is meant to model proofs where we implictly fix a neighborhood filter basis. -/ class nhds_basis (α : Type*) [topological_space α] := (B : α → filter_basis α) (is_nhds : ∀ x, 𝓝 x = (B x).filter) namespace nhds_basis open filter set variables {α : Type*} {ι : Type*} [topological_space α] [nhds_basis α] variables {β : Type*} [topological_space β] {δ : Type*} lemma mem_nhds_iff (x : α) (U : set α) : U ∈ 𝓝 x ↔ ∃ V ∈ B x, V ⊆ U := by rw [is_nhds x, filter_basis.mem_filter] lemma mem_nhds_of_basis {x : α} {U : set α} (U_in : U ∈ B x) : U ∈ 𝓝 x := (is_nhds x).symm ▸ filter_basis.mem_filter_of_mem U_in lemma tendsto_from {f : α → δ} {x : α} {y : filter δ} : tendsto f (𝓝 x) y ↔ ∀ {V}, V ∈ y → ∃ U ∈ B x, U ⊆ f ⁻¹' V := by split ; intros h V V_in ; specialize h V_in ; rwa [← mem_nhds_iff x] at * lemma continuous_from {f : α → β} : continuous f ↔ ∀ x, ∀ {V}, V ∈ 𝓝 f x → ∃ U ∈ B x, U ⊆ f ⁻¹' V := by simp [continuous_iff_continuous_at, continuous_at, tendsto_from] lemma tendsto_into {f : δ → α} {x : filter δ} {y : α} : tendsto f x 𝓝 y ↔ ∀ U ∈ B y, f ⁻¹' U ∈ x := begin split ; intros h, { rintro U U_in, exact h (mem_nhds_of_basis U_in) }, { intros V V_in, rcases (mem_nhds_iff _ _).1 V_in with ⟨W, W_in, hW⟩, filter_upwards [h W W_in], exact preimage_mono hW } end lemma continuous_into {f : β → α} : continuous f ↔ ∀ x, ∀ U ∈ B (f x), f ⁻¹' U ∈ 𝓝 x := by simp [continuous_iff_continuous_at, continuous_at, tendsto_into] lemma tendsto_both [nhds_basis β] {f : α → β} {x : α} {y : β} : tendsto f (𝓝 x) 𝓝 y ↔ ∀ U ∈ B y, ∃ V ∈ B x, V ⊆ f ⁻¹' U := begin rw tendsto_into, split ; introv h U_in ; specialize h U U_in ; rwa mem_nhds_iff x at * end lemma continuous_both [nhds_basis β] {f : α → β} : continuous f ↔ ∀ x, ∀ U ∈ B (f x), ∃ V ∈ B x, V ⊆ f ⁻¹' U := by simp [continuous_iff_continuous_at, continuous_at, tendsto_both] end nhds_basis lemma dense_range.mem_nhds {α : Type*} [topological_space α] {β : Type*} [topological_space β] {f : α → β} (h : dense_range f) {b : β} {U : set β} (U_in : U ∈ nhds b) : ∃ a : α, f a ∈ U := begin rcases exists_mem_of_ne_empty (mem_closure_iff_nhds.mp ((dense_range_iff_closure_range.mp h).symm ▸ mem_univ b : b ∈ closure (range f)) U U_in) with ⟨_, h, a, rfl⟩, exact ⟨a, h⟩ end lemma mem_closure_union {α : Type*} [topological_space α] {s₁ s₂ : set α} {x : α} (h : x ∈ closure (s₁ ∪ s₂)) (h₁ : -s₁ ∈ 𝓝 x) : x ∈ closure s₂ := begin rw closure_eq_nhds at *, have := calc 𝓝 x ⊓ principal (s₁ ∪ s₂) = 𝓝 x ⊓ (principal s₁ ⊔ principal s₂) : by rw sup_principal ... = (𝓝 x ⊓ principal s₁) ⊔ (𝓝 x ⊓ principal s₂) : by rw lattice.inf_sup_left ... = ⊥ ⊔ 𝓝 x ⊓ principal s₂ : by rw inf_principal_eq_bot h₁ ... = 𝓝 x ⊓ principal s₂ : by rw lattice.bot_sup_eq, dsimp, rwa ← this end open lattice lemma mem_closure_image {α : Type*} {β : Type*} [topological_space α] [topological_space β] {f : α → β} {x : α} {s : set α} (hf : continuous_at f x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := begin rw [closure_eq_nhds, mem_set_of_eq] at *, rw ← bot_lt_iff_ne_bot, calc ⊥ < map f (𝓝 x ⊓ principal s) : bot_lt_iff_ne_bot.mpr (map_ne_bot hx) ... ≤ (map f 𝓝 x) ⊓ (map f $ principal s) : map_inf_le ... = (map f 𝓝 x) ⊓ (principal $ f '' s) : by rw map_principal ... ≤ 𝓝 (f x) ⊓ (principal $ f '' s) : inf_le_inf hf (le_refl _) end lemma continuous_at.prod_mk {α : Type*} {β : Type*} {γ : Type*} [topological_space α] [topological_space β] [topological_space γ] {f : γ → α} {g : γ → β} {x : γ} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λ x, prod.mk (f x) $ g x) x := calc map (λ (x : γ), (f x, g x)) (𝓝 x) ≤ (map f 𝓝 x).prod (map g 𝓝 x) : filter.map_prod_mk _ _ _ ... ≤ (𝓝 f x).prod (𝓝 g x) : filter.prod_mono hf hg ... = 𝓝 (f x, g x) : by rw nhds_prod_eq lemma continuous_at.congr_aux {α : Type*} {β : Type*} [topological_space α] [topological_space β] {f g : α → β} {a : α} (h : {x | f x = g x } ∈ 𝓝 a) (hf : continuous_at f a) : continuous_at g a := begin intros U U_in, rw show g a = f a, from (mem_of_nhds h).symm at U_in, let V := {x : α | g x ∈ U} ∩ {x | f x = g x}, suffices : V ∈ 𝓝 a, { rw mem_map, exact mem_sets_of_superset this (inter_subset_left _ _) }, have : V = {x : α | f x ∈ U} ∩ {x | f x = g x}, { ext x, split ; rintros ⟨hl, hr⟩ ; rw mem_set_of_eq at hr hl ; [ rw ← hr at hl, rw hr at hl ] ; exact ⟨hl, hr⟩ }, rw this, exact filter.inter_mem_sets (hf U_in) ‹_› end lemma continuous_at.congr {α : Type*} {β : Type*} [topological_space α] [topological_space β] {f g : α → β} {a : α} (h : {x | f x = g x } ∈ 𝓝 a) : continuous_at f a ↔ continuous_at g a := begin split ; intro h', { exact continuous_at.congr_aux h h' }, { apply continuous_at.congr_aux _ h', convert h, ext x, rw eq_comm } end
4959eaa6e35e83be6a5e6770cea08fce0205d9c9
4727251e0cd73359b15b664c3170e5d754078599
/src/algebraic_topology/simplex_category.lean
0445dbca20df55feb9d0522aee81d78f29373ecd
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
26,922
lean
/- Copyright (c) 2020 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 category_theory.skeletal import tactic.linarith import data.fintype.sort import order.category.NonemptyFinLinOrd import category_theory.functor.reflects_isomorphisms /-! # The simplex category We construct a skeletal model of the simplex category, with objects `ℕ` and the morphism `n ⟶ m` being the monotone maps from `fin (n+1)` to `fin (m+1)`. We show that this category is equivalent to `NonemptyFinLinOrd`. ## Remarks The definitions `simplex_category` and `simplex_category.hom` are marked as irreducible. We provide the following functions to work with these objects: 1. `simplex_category.mk` creates an object of `simplex_category` out of a natural number. Use the notation `[n]` in the `simplicial` locale. 2. `simplex_category.len` gives the "length" of an object of `simplex_category`, as a natural. 3. `simplex_category.hom.mk` makes a morphism out of a monotone map between `fin`'s. 4. `simplex_category.hom.to_order_hom` gives the underlying monotone map associated to a term of `simplex_category.hom`. -/ universe v open category_theory /-- The simplex category: * objects are natural numbers `n : ℕ` * morphisms from `n` to `m` are monotone functions `fin (n+1) → fin (m+1)` -/ @[derive inhabited, irreducible] def simplex_category := ℕ namespace simplex_category section local attribute [semireducible] simplex_category -- TODO: Make `mk` irreducible. /-- Interpet a natural number as an object of the simplex category. -/ def mk (n : ℕ) : simplex_category := n localized "notation `[`n`]` := simplex_category.mk n" in simplicial -- TODO: Make `len` irreducible. /-- The length of an object of `simplex_category`. -/ def len (n : simplex_category) : ℕ := n @[ext] lemma ext (a b : simplex_category) : a.len = b.len → a = b := id @[simp] lemma len_mk (n : ℕ) : [n].len = n := rfl @[simp] lemma mk_len (n : simplex_category) : [n.len] = n := rfl /-- Morphisms in the simplex_category. -/ @[irreducible, nolint has_inhabited_instance] protected def hom (a b : simplex_category) := fin (a.len + 1) →o fin (b.len + 1) namespace hom local attribute [semireducible] simplex_category.hom /-- Make a moprhism in `simplex_category` from a monotone map of fin's. -/ def mk {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) : simplex_category.hom a b := f /-- Recover the monotone map from a morphism in the simplex category. -/ def to_order_hom {a b : simplex_category} (f : simplex_category.hom a b) : fin (a.len + 1) →o fin (b.len + 1) := f @[ext] lemma ext {a b : simplex_category} (f g : simplex_category.hom a b) : f.to_order_hom = g.to_order_hom → f = g := id @[simp] lemma mk_to_order_hom {a b : simplex_category} (f : simplex_category.hom a b) : mk (f.to_order_hom) = f := rfl @[simp] lemma to_order_hom_mk {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) : (mk f).to_order_hom = f := rfl lemma mk_to_order_hom_apply {a b : simplex_category} (f : fin (a.len + 1) →o fin (b.len + 1)) (i : fin (a.len + 1)) : (mk f).to_order_hom i = f i := rfl /-- Identity morphisms of `simplex_category`. -/ @[simp] def id (a : simplex_category) : simplex_category.hom a a := mk order_hom.id /-- Composition of morphisms of `simplex_category`. -/ @[simp] def comp {a b c : simplex_category} (f : simplex_category.hom b c) (g : simplex_category.hom a b) : simplex_category.hom a c := mk $ f.to_order_hom.comp g.to_order_hom end hom @[simps] instance small_category : small_category.{0} simplex_category := { hom := λ n m, simplex_category.hom n m, id := λ m, simplex_category.hom.id _, comp := λ _ _ _ f g, simplex_category.hom.comp g f, } /-- The constant morphism from [0]. -/ def const (x : simplex_category) (i : fin (x.len+1)) : [0] ⟶ x := hom.mk $ ⟨λ _, i, by tauto⟩ @[simp] lemma const_comp (x y : simplex_category) (i : fin (x.len + 1)) (f : x ⟶ y) : const x i ≫ f = const y (f.to_order_hom i) := rfl /-- Make a morphism `[n] ⟶ [m]` from a monotone map between fin's. This is useful for constructing morphisms beetween `[n]` directly without identifying `n` with `[n].len`. -/ @[simp] def mk_hom {n m : ℕ} (f : (fin (n+1)) →o (fin (m+1))) : [n] ⟶ [m] := simplex_category.hom.mk f lemma hom_zero_zero (f : [0] ⟶ [0]) : f = 𝟙 _ := by { ext : 2, dsimp, apply subsingleton.elim } end open_locale simplicial section generators /-! ## Generating maps for the simplex category TODO: prove that the simplex category is equivalent to one given by the following generators and relations. -/ /-- The `i`-th face map from `[n]` to `[n+1]` -/ def δ {n} (i : fin (n+2)) : [n] ⟶ [n+1] := mk_hom (fin.succ_above i).to_order_hom /-- The `i`-th degeneracy map from `[n+1]` to `[n]` -/ def σ {n} (i : fin (n+1)) : [n+1] ⟶ [n] := mk_hom { to_fun := fin.pred_above i, monotone' := fin.pred_above_right_monotone i } /-- The generic case of the first simplicial identity -/ lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) : δ i ≫ δ j.succ = δ j ≫ δ i.cast_succ := begin ext k, dsimp [δ, fin.succ_above], simp only [order_embedding.to_order_hom_coe, order_embedding.coe_of_strict_mono, function.comp_app, simplex_category.hom.to_order_hom_mk, order_hom.comp_coe], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, split_ifs; { simp at *; linarith }, end /-- The special case of the first simplicial identity -/ lemma δ_comp_δ_self {n} {i : fin (n+2)} : δ i ≫ δ i.cast_succ = δ i ≫ δ i.succ := (δ_comp_δ (le_refl i)).symm /-- The second simplicial identity -/ lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) : δ i.cast_succ ≫ σ j.succ = σ j ≫ δ i := begin ext k, suffices : ite (j.succ.cast_succ < ite (k < i) k.cast_succ k.succ) (ite (k < i) (k:ℕ) (k + 1) - 1) (ite (k < i) k (k + 1)) = ite ((if h : (j:ℕ) < k then k.pred (by { rintro rfl, exact nat.not_lt_zero _ h }) else k.cast_lt (by { cases j, cases k, simp only [len_mk], linarith })).cast_succ < i) (ite (j.cast_succ < k) (k - 1) k) (ite (j.cast_succ < k) (k - 1) k + 1), { dsimp [δ, σ, fin.succ_above, fin.pred_above], simp [fin.pred_above] with push_cast, convert rfl }, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [subtype.mk_le_mk, fin.cast_succ_mk] at H, dsimp, simp only [if_congr, subtype.mk_lt_mk, dif_ctx_congr], split_ifs, -- Most of the goals can now be handled by `linarith`, -- but we have to deal with two of them by hand. swap 8, { exact (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) ‹_›)).symm, }, swap 7, { have : k ≤ i := nat.le_of_pred_lt ‹_›, linarith, }, -- Hope for the best from `linarith`: all_goals { try { refl <|> simp at * }; linarith, }, end /-- The first part of the third simplicial identity -/ lemma δ_comp_σ_self {n} {i : fin (n+1)} : δ i.cast_succ ≫ σ i = 𝟙 [n] := begin ext j, suffices : ite (fin.cast_succ i < ite (j < i) (fin.cast_succ j) j.succ) (ite (j < i) (j:ℕ) (j + 1) - 1) (ite (j < i) j (j + 1)) = j, { dsimp [δ, σ, fin.succ_above, fin.pred_above], simpa [fin.pred_above] with push_cast }, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, dsimp, simp only [if_congr, subtype.mk_lt_mk], split_ifs; { simp at *; linarith, }, end /-- The second part of the third simplicial identity -/ lemma δ_comp_σ_succ {n} {i : fin (n+1)} : δ i.succ ≫ σ i = 𝟙 [n] := begin ext j, rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, dsimp [δ, σ, fin.succ_above, fin.pred_above], simp [fin.pred_above] with push_cast, split_ifs; { simp at *; linarith, }, end /-- The fourth simplicial identity -/ lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) : δ i.succ ≫ σ j.cast_succ = σ j ≫ δ i := begin ext k, dsimp [δ, σ, fin.succ_above, fin.pred_above], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [subtype.mk_lt_mk, fin.cast_succ_mk] at H, suffices : ite (_ < ite (k < i + 1) _ _) _ _ = ite _ (ite (j < k) (k - 1) k) (ite (j < k) (k - 1) k + 1), { simpa [apply_dite fin.cast_succ, fin.pred_above] with push_cast, }, split_ifs, -- Most of the goals can now be handled by `linarith`, -- but we have to deal with three of them by hand. swap 2, { simp only [subtype.mk_lt_mk] at h_1, simp only [not_lt] at h_2, simp only [self_eq_add_right, one_ne_zero], exact lt_irrefl (k - 1) (lt_of_lt_of_le (nat.pred_lt (ne_of_lt (lt_of_le_of_lt (zero_le _) h_1)).symm) (le_trans (nat.le_of_lt_succ h) h_2)) }, swap 4, { simp only [subtype.mk_lt_mk] at h_1, simp only [not_lt] at h, simp only [nat.add_succ_sub_one, add_zero], exfalso, exact lt_irrefl _ (lt_of_le_of_lt (nat.le_pred_of_lt (nat.lt_of_succ_le h)) h_3), }, swap 4, { simp only [subtype.mk_lt_mk] at h_1, simp only [not_lt] at h_3, simp only [nat.add_succ_sub_one, add_zero], exact (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) h_2)).symm, }, -- Hope for the best from `linarith`: all_goals { simp at h_1 h_2 ⊢; linarith, }, end local attribute [simp] fin.pred_mk /-- The fifth simplicial identity -/ lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) : σ i.cast_succ ≫ σ j = σ j.succ ≫ σ i := begin ext k, dsimp [σ, fin.pred_above], rcases i with ⟨i, _⟩, rcases j with ⟨j, _⟩, rcases k with ⟨k, _⟩, simp only [subtype.mk_le_mk] at H, -- At this point `simp with push_cast` makes good progress, but neither `simp?` nor `squeeze_simp` -- return usable sets of lemmas. -- To avoid using a non-terminal simp, we make a `suffices` statement indicating the shape -- of the goal we're looking for, and then use `simpa with push_cast`. -- I'm not sure this is actually much more robust that a non-terminal simp. suffices : ite (_ < dite (i < k) _ _) _ _ = ite (_ < dite (j + 1 < k) _ _) _ _, { simpa [fin.pred_above] with push_cast, }, split_ifs, -- `split_ifs` created 12 goals. -- Most of them are dealt with `by simp at *; linarith`, -- but we pull out two harder ones to do by hand. swap 3, { simp only [not_lt] at h_2, exact false.elim (lt_irrefl (k - 1) (lt_of_lt_of_le (nat.pred_lt (id (ne_of_lt (lt_of_le_of_lt (zero_le i) h)).symm)) (le_trans h_2 (nat.succ_le_of_lt h_1)))) }, swap 3, { simp only [subtype.mk_lt_mk, not_lt] at h_1, exact false.elim (lt_irrefl j (lt_of_lt_of_le (nat.pred_lt_pred (nat.succ_ne_zero j) h_2) h_1)) }, -- Deal with the rest automatically. all_goals { simp at *; linarith, }, end end generators section skeleton /-- The functor that exhibits `simplex_category` as skeleton of `NonemptyFinLinOrd` -/ @[simps obj map] def skeletal_functor : simplex_category ⥤ NonemptyFinLinOrd.{v} := { obj := λ a, NonemptyFinLinOrd.of $ ulift (fin (a.len + 1)), map := λ a b f, ⟨λ i, ulift.up (f.to_order_hom i.down), λ i j h, f.to_order_hom.monotone h⟩, map_id' := λ a, by { ext, simp, }, map_comp' := λ a b c f g, by { ext, simp, }, } lemma skeletal : skeletal simplex_category := λ X Y ⟨I⟩, begin suffices : fintype.card (fin (X.len+1)) = fintype.card (fin (Y.len+1)), { ext, simpa }, { apply fintype.card_congr, refine equiv.ulift.symm.trans (((skeletal_functor ⋙ forget _).map_iso I).to_equiv.trans _), apply equiv.ulift } end namespace skeletal_functor instance : full skeletal_functor.{v} := { preimage := λ a b f, simplex_category.hom.mk ⟨λ i, (f (ulift.up i)).down, λ i j h, f.monotone h⟩, witness' := by { intros m n f, dsimp at *, ext1 ⟨i⟩, ext1, ext1, cases x, simp, } } instance : faithful skeletal_functor.{v} := { map_injective' := λ m n f g h, begin ext1, ext1, ext1 i, apply ulift.up.inj, change (skeletal_functor.map f) ⟨i⟩ = (skeletal_functor.map g) ⟨i⟩, rw h, end } instance : ess_surj skeletal_functor.{v} := { mem_ess_image := λ X, ⟨mk (fintype.card X - 1 : ℕ), ⟨begin have aux : fintype.card X = fintype.card X - 1 + 1, { exact (nat.succ_pred_eq_of_pos $ fintype.card_pos_iff.mpr ⟨⊥⟩).symm, }, let f := mono_equiv_of_fin X aux, have hf := (finset.univ.order_emb_of_fin aux).strict_mono, refine { hom := ⟨λ i, f i.down, _⟩, inv := ⟨λ i, ⟨f.symm i⟩, _⟩, hom_inv_id' := _, inv_hom_id' := _ }, { rintro ⟨i⟩ ⟨j⟩ h, show f i ≤ f j, exact hf.monotone h, }, { intros i j h, show f.symm i ≤ f.symm j, rw ← hf.le_iff_le, show f (f.symm i) ≤ f (f.symm j), simpa only [order_iso.apply_symm_apply], }, { ext1, ext1 ⟨i⟩, ext1, exact f.symm_apply_apply i }, { ext1, ext1 i, exact f.apply_symm_apply i }, end⟩⟩, } noncomputable instance is_equivalence : is_equivalence (skeletal_functor.{v}) := equivalence.of_fully_faithfully_ess_surj skeletal_functor end skeletal_functor /-- The equivalence that exhibits `simplex_category` as skeleton of `NonemptyFinLinOrd` -/ noncomputable def skeletal_equivalence : simplex_category ≌ NonemptyFinLinOrd.{v} := functor.as_equivalence skeletal_functor end skeleton /-- `simplex_category` is a skeleton of `NonemptyFinLinOrd`. -/ noncomputable def is_skeleton_of : is_skeleton_of NonemptyFinLinOrd simplex_category skeletal_functor.{v} := { skel := skeletal, eqv := skeletal_functor.is_equivalence } /-- The truncated simplex category. -/ @[derive small_category] def truncated (n : ℕ) := {a : simplex_category // a.len ≤ n} namespace truncated instance {n} : inhabited (truncated n) := ⟨⟨[0],by simp⟩⟩ /-- The fully faithful inclusion of the truncated simplex category into the usual simplex category. -/ @[derive [full, faithful]] def inclusion {n : ℕ} : simplex_category.truncated n ⥤ simplex_category := full_subcategory_inclusion _ end truncated section concrete instance : concrete_category.{0} simplex_category := { forget := { obj := λ i, fin (i.len + 1), map := λ i j f, f.to_order_hom }, forget_faithful := {} } end concrete section epi_mono /-- A morphism in `simplex_category` is a monomorphism precisely when it is an injective function -/ theorem mono_iff_injective {n m : simplex_category} {f : n ⟶ m} : mono f ↔ function.injective f.to_order_hom := begin split, { introsI m x y h, have H : const n x ≫ f = const n y ≫ f, { dsimp, rw h }, change (n.const x).to_order_hom 0 = (n.const y).to_order_hom 0, rw cancel_mono f at H, rw H }, { exact concrete_category.mono_of_injective f } end /-- A morphism in `simplex_category` is an epimorphism if and only if it is a surjective function -/ lemma epi_iff_surjective {n m : simplex_category} {f: n ⟶ m} : epi f ↔ function.surjective f.to_order_hom := begin split, { introsI hyp_f_epi x, by_contra' h_ab, -- The proof is by contradiction: assume f is not surjective, -- then introduce two non-equal auxiliary functions equalizing f, and get a contradiction. -- First we define the two auxiliary functions. set chi_1 : m ⟶ [1] := hom.mk ⟨λ u, if u ≤ x then 0 else 1, begin intros a b h, dsimp only [], split_ifs with h1 h2 h3, any_goals { exact le_rfl }, { exact bot_le }, { exact false.elim (h1 (le_trans h h3)) } end ⟩, set chi_2 : m ⟶ [1] := hom.mk ⟨λ u, if u < x then 0 else 1, begin intros a b h, dsimp only [], split_ifs with h1 h2 h3, any_goals { exact le_rfl }, { exact bot_le }, { exact false.elim (h1 (lt_of_le_of_lt h h3)) } end ⟩, -- The two auxiliary functions equalize f have f_comp_chi_i : f ≫ chi_1 = f ≫ chi_2, { dsimp, ext, simp [le_iff_lt_or_eq, h_ab x_1] }, -- We now just have to show the two auxiliary functions are not equal. rw category_theory.cancel_epi f at f_comp_chi_i, rename f_comp_chi_i eq_chi_i, apply_fun (λ e, e.to_order_hom x) at eq_chi_i, suffices : (0 : fin 2) = 1, by exact bot_ne_top this, simpa using eq_chi_i }, { exact concrete_category.epi_of_surjective f } end /-- A monomorphism in `simplex_category` must increase lengths-/ lemma len_le_of_mono {x y : simplex_category} {f : x ⟶ y} : mono f → (x.len ≤ y.len) := begin intro hyp_f_mono, have f_inj : function.injective f.to_order_hom.to_fun, { exact mono_iff_injective.elim_left (hyp_f_mono) }, simpa using fintype.card_le_of_injective f.to_order_hom.to_fun f_inj, end lemma le_of_mono {n m : ℕ} {f : [n] ⟶ [m]} : (category_theory.mono f) → (n ≤ m) := len_le_of_mono /-- An epimorphism in `simplex_category` must decrease lengths-/ lemma len_le_of_epi {x y : simplex_category} {f : x ⟶ y} : epi f → y.len ≤ x.len := begin intro hyp_f_epi, have f_surj : function.surjective f.to_order_hom.to_fun, { exact epi_iff_surjective.elim_left (hyp_f_epi) }, simpa using fintype.card_le_of_surjective f.to_order_hom.to_fun f_surj, end lemma le_of_epi {n m : ℕ} {f : [n] ⟶ [m]} : epi f → (m ≤ n) := len_le_of_epi instance {n : ℕ} {i : fin (n+2)} : mono (δ i) := begin rw mono_iff_injective, exact fin.succ_above_right_injective, end instance {n : ℕ} {i : fin (n+1)} : epi (σ i) := begin rw epi_iff_surjective, intro b, simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk], by_cases b ≤ i, { use b, rw fin.pred_above_below i b (by simpa only [fin.coe_eq_cast_succ] using h), simp only [fin.coe_eq_cast_succ, fin.cast_pred_cast_succ], }, { use b.succ, rw [fin.pred_above_above i b.succ _, fin.pred_succ], rw not_le at h, rw fin.lt_iff_coe_lt_coe at h ⊢, simpa only [fin.coe_succ, fin.coe_cast_succ] using nat.lt.step h, } end instance : reflects_isomorphisms (forget simplex_category) := ⟨begin intros x y f, introI, exact is_iso.of_iso { hom := f, inv := hom.mk { to_fun := inv ((forget simplex_category).map f), monotone' :=λ y₁ y₂ h, begin by_cases h' : y₁ < y₂, { by_contradiction h'', have eq := λ i, congr_hom (iso.inv_hom_id (as_iso ((forget _).map f))) i, have ineq := f.to_order_hom.monotone' (le_of_not_ge h''), dsimp at ineq, erw [eq, eq] at ineq, exact not_le.mpr h' ineq, }, { rw eq_of_le_of_not_lt h h', } end, }, hom_inv_id' := by { ext1, ext1, exact iso.hom_inv_id (as_iso ((forget _).map f)), }, inv_hom_id' := by { ext1, ext1, exact iso.inv_hom_id (as_iso ((forget _).map f)), }, }, end⟩ lemma is_iso_of_bijective {x y : simplex_category} {f : x ⟶ y} (hf : function.bijective (f.to_order_hom.to_fun)) : is_iso f := begin haveI : is_iso ((forget simplex_category).map f) := (is_iso_iff_bijective _).mpr hf, exact is_iso_of_reflects_iso f (forget simplex_category), end /-- An isomorphism in `simplex_category` induces an `order_iso`. -/ @[simp] def order_iso_of_iso {x y : simplex_category} (e : x ≅ y) : fin (x.len+1) ≃o fin (y.len+1) := equiv.to_order_iso { to_fun := e.hom.to_order_hom, inv_fun := e.inv.to_order_hom, left_inv := λ i, by simpa only using congr_arg (λ φ, (hom.to_order_hom φ) i) e.hom_inv_id', right_inv := λ i, by simpa only using congr_arg (λ φ, (hom.to_order_hom φ) i) e.inv_hom_id', } e.hom.to_order_hom.monotone e.inv.to_order_hom.monotone lemma iso_eq_iso_refl {x : simplex_category} (e : x ≅ x) : e = iso.refl x := begin have h : (finset.univ : finset (fin (x.len+1))).card = x.len+1 := finset.card_fin (x.len+1), have eq₁ := finset.order_emb_of_fin_unique' h (λ i, finset.mem_univ ((order_iso_of_iso e) i)), have eq₂ := finset.order_emb_of_fin_unique' h (λ i, finset.mem_univ ((order_iso_of_iso (iso.refl x)) i)), ext1, ext1, convert congr_arg (λ φ, (order_embedding.to_order_hom φ)) (eq₁.trans eq₂.symm), ext1, ext1 i, refl, end lemma eq_id_of_is_iso {x : simplex_category} {f : x ⟶ x} (hf : is_iso f) : f = 𝟙 _ := congr_arg (λ (φ : _ ≅ _), φ.hom) (iso_eq_iso_refl (as_iso f)) lemma eq_σ_comp_of_not_injective' {n : ℕ} {Δ' : simplex_category} (θ : mk (n+1) ⟶ Δ') (i : fin (n+1)) (hi : θ.to_order_hom i.cast_succ = θ.to_order_hom i.succ): ∃ (θ' : mk n ⟶ Δ'), θ = σ i ≫ θ' := begin use δ i.succ ≫ θ, ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp, σ, mk_hom, order_hom.coe_fun_mk], by_cases h' : x ≤ i.cast_succ, { rw fin.pred_above_below i x h', have eq := fin.cast_succ_cast_pred (gt_of_gt_of_ge (fin.cast_succ_lt_last i) h'), erw fin.succ_above_below i.succ x.cast_pred _, swap, { rwa [eq, ← fin.le_cast_succ_iff], }, rw eq, }, { simp only [not_le] at h', let y := x.pred begin intro h, rw h at h', simpa only [fin.lt_iff_coe_lt_coe, nat.not_lt_zero, fin.coe_zero] using h', end, simp only [show x = y.succ, by rw fin.succ_pred] at h' ⊢, rw [fin.pred_above_above i y.succ h', fin.pred_succ], by_cases h'' : y = i, { rw h'', convert hi.symm, erw fin.succ_above_below i.succ _, exact fin.lt_succ, }, { erw fin.succ_above_above i.succ _, simp only [fin.lt_iff_coe_lt_coe, fin.le_iff_coe_le_coe, fin.coe_succ, fin.coe_cast_succ, nat.lt_succ_iff, fin.ext_iff] at h' h'' ⊢, cases nat.le.dest h' with c hc, cases c, { exfalso, rw [add_zero] at hc, rw [hc] at h'', exact h'' rfl, }, { rw ← hc, simp only [add_le_add_iff_left, nat.succ_eq_add_one, le_add_iff_nonneg_left, zero_le], }, }, } end lemma eq_σ_comp_of_not_injective {n : ℕ} {Δ' : simplex_category} (θ : mk (n+1) ⟶ Δ') (hθ : ¬function.injective θ.to_order_hom) : ∃ (i : fin (n+1)) (θ' : mk n ⟶ Δ'), θ = σ i ≫ θ' := begin simp only [function.injective, exists_prop, not_forall] at hθ, -- as θ is not injective, there exists `x<y` such that `θ x = θ y` -- and then, `θ x = θ (x+1)` have hθ₂ : ∃ (x y : fin (n+2)), (hom.to_order_hom θ) x = (hom.to_order_hom θ) y ∧ x<y, { rcases hθ with ⟨x, y, ⟨h₁, h₂⟩⟩, by_cases x<y, { exact ⟨x, y, ⟨h₁, h⟩⟩, }, { refine ⟨y, x, ⟨h₁.symm, _⟩⟩, cases lt_or_eq_of_le (not_lt.mp h) with h' h', { exact h', }, { exfalso, exact h₂ h'.symm, }, }, }, rcases hθ₂ with ⟨x, y, ⟨h₁, h₂⟩⟩, let z := x.cast_pred, use z, simp only [← (show z.cast_succ = x, by exact fin.cast_succ_cast_pred (lt_of_lt_of_le h₂ (fin.le_last y)))] at h₁ h₂, apply eq_σ_comp_of_not_injective', rw fin.cast_succ_lt_iff_succ_le at h₂, apply le_antisymm, { exact θ.to_order_hom.monotone (le_of_lt (fin.cast_succ_lt_succ z)), }, { rw h₁, exact θ.to_order_hom.monotone h₂, }, end lemma eq_comp_δ_of_not_surjective' {n : ℕ} {Δ : simplex_category} (θ : Δ ⟶ mk (n+1)) (i : fin (n+2)) (hi : ∀ x, θ.to_order_hom x ≠ i) : ∃ (θ' : Δ ⟶ (mk n)), θ = θ' ≫ δ i := begin by_cases i < fin.last (n+1), { use θ ≫ σ (fin.cast_pred i), ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp], by_cases h' : θ.to_order_hom x ≤ i, { simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk], erw fin.pred_above_below (fin.cast_pred i) (θ.to_order_hom x) (by simpa [fin.cast_succ_cast_pred h] using h'), erw fin.succ_above_below i, swap, { simp only [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ], exact lt_of_le_of_lt (fin.coe_cast_pred_le_self _) (fin.lt_iff_coe_lt_coe.mp ((ne.le_iff_lt (hi x)).mp h')), }, rw fin.cast_succ_cast_pred, apply lt_of_le_of_lt h' h, }, { simp only [not_le] at h', simp only [σ, mk_hom, hom.to_order_hom_mk, order_hom.coe_fun_mk, fin.pred_above_above (fin.cast_pred i) (θ.to_order_hom x) (by simpa only [fin.cast_succ_cast_pred h] using h')], erw [fin.succ_above_above i _, fin.succ_pred], simpa only [fin.le_iff_coe_le_coe, fin.coe_cast_succ, fin.coe_pred] using nat.le_pred_of_lt (fin.lt_iff_coe_lt_coe.mp h'), }, }, { obtain rfl := le_antisymm (fin.le_last i) (not_lt.mp h), use θ ≫ σ (fin.last _), ext1, ext1, ext1 x, simp only [hom.to_order_hom_mk, function.comp_app, order_hom.comp_coe, hom.comp, small_category_comp, σ, δ, mk_hom, order_hom.coe_fun_mk, order_embedding.to_order_hom_coe, fin.pred_above_last, fin.succ_above_last, fin.cast_succ_cast_pred ((ne.le_iff_lt (hi x)).mp (fin.le_last _))], }, end lemma eq_comp_δ_of_not_surjective {n : ℕ} {Δ : simplex_category} (θ : Δ ⟶ mk (n+1)) (hθ : ¬function.surjective θ.to_order_hom) : ∃ (i : fin (n+2)) (θ' : Δ ⟶ (mk n)), θ = θ' ≫ δ i := begin cases not_forall.mp hθ with i hi, use i, exact eq_comp_δ_of_not_surjective' θ i (not_exists.mp hi), end lemma eq_id_of_mono {x : simplex_category} (i : x ⟶ x) [mono i] : i = 𝟙 _ := begin apply eq_id_of_is_iso, apply is_iso_of_bijective, erw [fintype.bijective_iff_injective_and_card i.to_order_hom, ← mono_iff_injective, eq_self_iff_true, and_true], apply_instance, end lemma eq_id_of_epi {x : simplex_category} (i : x ⟶ x) [epi i] : i = 𝟙 _ := begin apply eq_id_of_is_iso, apply is_iso_of_bijective, erw [fintype.bijective_iff_surjective_and_card i.to_order_hom, ← epi_iff_surjective, eq_self_iff_true, and_true], apply_instance, end lemma eq_σ_of_epi {n : ℕ} (θ : mk (n+1) ⟶ mk n) [epi θ] : ∃ (i : fin (n+1)), θ = σ i := begin rcases eq_σ_comp_of_not_injective θ _ with ⟨i, θ', h⟩, swap, { by_contradiction, simpa only [nat.one_ne_zero, add_le_iff_nonpos_right, nonpos_iff_eq_zero] using le_of_mono (mono_iff_injective.mpr h), }, use i, haveI : epi (σ i ≫ θ') := by { rw ← h, apply_instance, }, haveI := category_theory.epi_of_epi (σ i) θ', erw [h, eq_id_of_epi θ', category.comp_id], end lemma eq_δ_of_mono {n : ℕ} (θ : mk n ⟶ mk (n+1)) [mono θ] : ∃ (i : fin (n+2)), θ = δ i := begin rcases eq_comp_δ_of_not_surjective θ _ with ⟨i, θ', h⟩, swap, { by_contradiction, simpa only [add_le_iff_nonpos_right, nonpos_iff_eq_zero] using le_of_epi (epi_iff_surjective.mpr h), }, use i, haveI : mono (θ' ≫ δ i) := by { rw ← h, apply_instance, }, haveI := category_theory.mono_of_mono θ' (δ i), erw [h, eq_id_of_mono θ', category.id_comp], end end epi_mono end simplex_category
fb3333d06b1888192cae3b81fd2996aeefe67feb
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/analysis/mean_inequalities.lean
2b3097964f715b7e84df50ff2da6b8fcd085a0d2
[ "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
22,746
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Sébastien Gouëzel -/ import analysis.convex.specific_functions import analysis.special_functions.pow import data.real.conjugate_exponents import tactic.nth_rewrite /-! # Mean value inequalities In this file we prove several inequalities, including AM-GM inequality, Young's inequality, Hölder inequality, and Minkowski inequality. ## Main theorems ### AM-GM inequality: The inequality says that the geometric mean of a tuple of non-negative numbers is less than or equal to their arithmetic mean. We prove the weighted version of this inequality: if $w$ and $z$ are two non-negative vectors and $\sum_{i\in s} w_i=1$, then $$ \prod_{i\in s} z_i^{w_i} ≤ \sum_{i\in s} w_iz_i. $$ The classical version is a special case of this inequality for $w_i=\frac{1}{n}$. We prove a few versions of this inequality. Each of the following lemmas comes in two versions: a version for real-valued non-negative functions is in the `real` namespace, and a version for `nnreal`-valued functions is in the `nnreal` namespace. - `geom_mean_le_arith_mean_weighted` : weighted version for functions on `finset`s; - `geom_mean_le_arith_mean2_weighted` : weighted version for two numbers; - `geom_mean_le_arith_mean3_weighted` : weighted version for three numbers. ### Generalized mean inequality The inequality says that for two non-negative vectors $w$ and $z$ with $\sum_{i\in s} w_i=1$ and $p ≤ q$ we have $$ \sqrt[p]{\sum_{i\in s} w_i z_i^p} ≤ \sqrt[q]{\sum_{i\in s} w_i z_i^q}. $$ Currently we only prove this inequality for $p=1$. As in the rest of `mathlib`, we provide different theorems for natural exponents (`pow_arith_mean_le_arith_mean_pow`), integer exponents (`fpow_arith_mean_le_arith_mean_fpow`), and real exponents (`rpow_arith_mean_le_arith_mean_rpow` and `arith_mean_le_rpow_mean`). In the first two cases we prove $$ \left(\sum_{i\in s} w_i z_i\right)^n ≤ \sum_{i\in s} w_i z_i^n $$ in order to avoid using real exponents. For real exponents we prove both this and standard versions. ### Young's inequality Young's inequality says that for non-negative numbers `a`, `b`, `p`, `q` such that $\frac{1}{p}+\frac{1}{q}=1$ we have $$ ab ≤ \frac{a^p}{p} + \frac{b^q}{q}. $$ This inequality is a special case of the AM-GM inequality. It can be used to prove Hölder's inequality (see below) but we use a different proof. ### Hölder's inequality The inequality says that for two conjugate exponents `p` and `q` (i.e., for two positive numbers such that $\frac{1}{p}+\frac{1}{q}=1$) and any two non-negative vectors their inner product is less than or equal to the product of the $L_p$ norm of the first vector and the $L_q$ norm of the second vector: $$ \sum_{i\in s} a_ib_i ≤ \sqrt[p]{\sum_{i\in s} a_i^p}\sqrt[q]{\sum_{i\in s} b_i^q}. $$ We give versions of this result in `real`, `nnreal` and `ennreal`. There are at least two short proofs of this inequality. In one proof we prenormalize both vectors, then apply Young's inequality to each $a_ib_i$. We use a different proof deducing this inequality from the generalized mean inequality for well-chosen vectors and weights. ### Minkowski's inequality The inequality says that for `p ≥ 1` the function $$ \|a\|_p=\sqrt[p]{\sum_{i\in s} a_i^p} $$ satisfies the triangle inequality $\|a+b\|_p\le \|a\|_p+\|b\|_p$. We give versions of this result in `real`, `nnreal` and `ennreal`. We deduce this inequality from Hölder's inequality. Namely, Hölder inequality implies that $\|a\|_p$ is the maximum of the inner product $\sum_{i\in s}a_ib_i$ over `b` such that $\|b\|_q\le 1$. Now Minkowski's inequality follows from the fact that the maximum value of the sum of two functions is less than or equal to the sum of the maximum values of the summands. ## TODO - each inequality `A ≤ B` should come with a theorem `A = B ↔ _`; one of the ways to prove them is to define `strict_convex_on` functions. - generalized mean inequality with any `p ≤ q`, including negative numbers; - prove that the power mean tends to the geometric mean as the exponent tends to zero. - prove integral versions of these inequalities. -/ universes u v open finset open_locale classical nnreal big_operators noncomputable theory variables {ι : Type u} (s : finset ι) namespace real /-- AM-GM inequality: the geometric mean is less than or equal to the arithmetic mean, weighted version for real-valued nonnegative functions. -/ theorem geom_mean_le_arith_mean_weighted (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) : (∏ i in s, (z i) ^ (w i)) ≤ ∑ i in s, w i * z i := begin -- If some number `z i` equals zero and has non-zero weight, then LHS is 0 and RHS is nonnegative. by_cases A : ∃ i ∈ s, z i = 0 ∧ w i ≠ 0, { rcases A with ⟨i, his, hzi, hwi⟩, rw [prod_eq_zero his], { exact sum_nonneg (λ j hj, mul_nonneg (hw j hj) (hz j hj)) }, { rw hzi, exact zero_rpow hwi } }, -- If all numbers `z i` with non-zero weight are positive, then we apply Jensen's inequality -- for `exp` and numbers `log (z i)` with weights `w i`. { simp only [not_exists, not_and, ne.def, not_not] at A, have := convex_on_exp.map_sum_le hw hw' (λ i _, set.mem_univ $ log (z i)), simp only [exp_sum, (∘), smul_eq_mul, mul_comm (w _) (log _)] at this, convert this using 1; [apply prod_congr rfl, apply sum_congr rfl]; intros i hi, { cases eq_or_lt_of_le (hz i hi) with hz hz, { simp [A i hi hz.symm] }, { exact rpow_def_of_pos hz _ } }, { cases eq_or_lt_of_le (hz i hi) with hz hz, { simp [A i hi hz.symm] }, { rw [exp_log hz] } } } end theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) (n : ℕ) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := (convex_on_pow n).map_sum_le hw hw' hz theorem pow_arith_mean_le_arith_mean_pow_of_even (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) {n : ℕ} (hn : n.even) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := (convex_on_pow_of_even hn).map_sum_le hw hw' (λ _ _, trivial) theorem fpow_arith_mean_le_arith_mean_fpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 < z i) (m : ℤ) : (∑ i in s, w i * z i) ^ m ≤ ∑ i in s, (w i * z i ^ m) := (convex_on_fpow m).map_sum_le hw hw' hz theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := (convex_on_rpow hp).map_sum_le hw hw' hz theorem arith_mean_le_rpow_mean (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : ∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) := begin have : 0 < p := lt_of_lt_of_le zero_lt_one hp, rw [← rpow_le_rpow_iff _ _ this, ← rpow_mul, one_div_mul_cancel (ne_of_gt this), rpow_one], exact rpow_arith_mean_le_arith_mean_rpow s w z hw hw' hz hp, all_goals { apply_rules [sum_nonneg, rpow_nonneg_of_nonneg], intros i hi, apply_rules [mul_nonneg, rpow_nonneg_of_nonneg, hw i hi, hz i hi] }, end end real namespace nnreal /-- The geometric mean is less than or equal to the arithmetic mean, weighted version for `nnreal`-valued functions. -/ theorem geom_mean_le_arith_mean_weighted (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) : (∏ i in s, (z i) ^ (w i:ℝ)) ≤ ∑ i in s, w i * z i := by exact_mod_cast real.geom_mean_le_arith_mean_weighted _ _ _ (λ i _, (w i).coe_nonneg) (by assumption_mod_cast) (λ i _, (z i).coe_nonneg) /-- The geometric mean is less than or equal to the arithmetic mean, weighted version for two `nnreal` numbers. -/ theorem geom_mean_le_arith_mean2_weighted (w₁ w₂ p₁ p₂ : ℝ≥0) : w₁ + w₂ = 1 → p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) ≤ w₁ * p₁ + w₂ * p₂ := by simpa only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero, fin.cons_succ, fin.cons_zero, add_zero, mul_one] using geom_mean_le_arith_mean_weighted (univ : finset (fin 2)) (fin.cons w₁ $ fin.cons w₂ fin_zero_elim) (fin.cons p₁ $ fin.cons p₂ $ fin_zero_elim) theorem geom_mean_le_arith_mean3_weighted (w₁ w₂ w₃ p₁ p₂ p₃ : ℝ≥0) : w₁ + w₂ + w₃ = 1 → p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) * p₃ ^ (w₃:ℝ) ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃ := by simpa only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero, fin.cons_succ, fin.cons_zero, add_zero, mul_one, ← add_assoc, mul_assoc] using geom_mean_le_arith_mean_weighted (univ : finset (fin 3)) (fin.cons w₁ $ fin.cons w₂ $ fin.cons w₃ fin_zero_elim) (fin.cons p₁ $ fin.cons p₂ $ fin.cons p₃ fin_zero_elim) /-- Weighted generalized mean inequality, version sums over finite sets, with `ℝ≥0`-valued functions and natural exponent. -/ theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) (n : ℕ) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := by exact_mod_cast real.pow_arith_mean_le_arith_mean_pow s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) n /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := by exact_mod_cast real.rpow_arith_mean_le_arith_mean_rpow s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem arith_mean_le_rpow_mean (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : ∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) := by exact_mod_cast real.arith_mean_le_rpow_mean s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp end nnreal namespace real theorem geom_mean_le_arith_mean2_weighted {w₁ w₂ p₁ p₂ : ℝ} (hw₁ : 0 ≤ w₁) (hw₂ : 0 ≤ w₂) (hp₁ : 0 ≤ p₁) (hp₂ : 0 ≤ p₂) (hw : w₁ + w₂ = 1) : p₁ ^ w₁ * p₂ ^ w₂ ≤ w₁ * p₁ + w₂ * p₂ := nnreal.geom_mean_le_arith_mean2_weighted ⟨w₁, hw₁⟩ ⟨w₂, hw₂⟩ ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ $ nnreal.coe_eq.1 $ by assumption /-- Young's inequality, a version for nonnegative real numbers. -/ theorem young_inequality_of_nonneg {a b p q : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hpq : p.is_conjugate_exponent q) : a * b ≤ a^p / p + b^q / q := by simpa [← rpow_mul, ha, hb, hpq.ne_zero, hpq.symm.ne_zero, div_eq_inv_mul] using geom_mean_le_arith_mean2_weighted hpq.one_div_nonneg hpq.symm.one_div_nonneg (rpow_nonneg_of_nonneg ha p) (rpow_nonneg_of_nonneg hb q) hpq.inv_add_inv_conj /-- Young's inequality, a version for arbitrary real numbers. -/ theorem young_inequality (a b : ℝ) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : a * b ≤ (abs a)^p / p + (abs b)^q / q := calc a * b ≤ abs (a * b) : le_abs_self (a * b) ... = abs a * abs b : abs_mul a b ... ≤ (abs a)^p / p + (abs b)^q / q : real.young_inequality_of_nonneg (abs_nonneg a) (abs_nonneg b) hpq end real namespace nnreal /-- Young's inequality, `ℝ≥0` version. We use `{p q : ℝ≥0}` in order to avoid constructing witnesses of `0 ≤ p` and `0 ≤ q` for the denominators. -/ theorem young_inequality (a b : ℝ≥0) {p q : ℝ≥0} (hp : 1 < p) (hpq : 1 / p + 1 / q = 1) : a * b ≤ a^(p:ℝ) / p + b^(q:ℝ) / q := real.young_inequality_of_nonneg a.coe_nonneg b.coe_nonneg ⟨hp, nnreal.coe_eq.2 hpq⟩ /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with `ℝ≥0`-valued functions. -/ theorem inner_le_Lp_mul_Lq (f g : ι → ℝ≥0) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : ∑ i in s, f i * g i ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) * (∑ i in s, (g i) ^ q) ^ (1 / q) := begin -- Let `G=∥g∥_q` be the `L_q`-norm of `g`. set G := (∑ i in s, (g i) ^ q) ^ (1 / q), have hGq : G ^ q = ∑ i in s, (g i) ^ q, { rw [← rpow_mul, one_div_mul_cancel hpq.symm.ne_zero, rpow_one], }, -- First consider the trivial case `∥g∥_q=0` by_cases hG : G = 0, { rw [hG, sum_eq_zero, mul_zero], intros i hi, simp only [rpow_eq_zero_iff, sum_eq_zero_iff] at hG, simp [(hG.1 i hi).1] }, { -- Move power from right to left rw [← div_le_iff hG, sum_div], -- Now the inequality follows from the weighted generalized mean inequality -- with weights `w_i` and numbers `z_i` given by the following formulas. set w : ι → ℝ≥0 := λ i, (g i) ^ q / G ^ q, set z : ι → ℝ≥0 := λ i, f i * (G / g i) ^ (q / p), -- Show that the sum of weights equals one have A : ∑ i in s, w i = 1, { rw [← sum_div, hGq, div_self], simpa [rpow_eq_zero_iff, hpq.symm.ne_zero] using hG }, -- LHS of the goal equals LHS of the weighted generalized mean inequality calc (∑ i in s, f i * g i / G) = (∑ i in s, w i * z i) : begin refine sum_congr rfl (λ i hi, _), have : q - q / p = 1, by field_simp [hpq.ne_zero, hpq.symm.mul_eq_add], dsimp only [w, z], rw [← div_rpow, mul_left_comm, mul_div_assoc, ← @inv_div _ _ _ G, inv_rpow, ← div_eq_mul_inv, ← rpow_sub']; simp [this] end -- Apply the generalized mean inequality ... ≤ (∑ i in s, w i * (z i) ^ p) ^ (1 / p) : nnreal.arith_mean_le_rpow_mean s w z A (le_of_lt hpq.one_lt) -- Simplify the right hand side. Terms with `g i ≠ 0` are equal to `(f i) ^ p`, -- the others are zeros. ... ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) : begin refine rpow_le_rpow (sum_le_sum (λ i hi, _)) hpq.one_div_nonneg, dsimp only [w, z], rw [mul_rpow, mul_left_comm, ← rpow_mul _ _ p, div_mul_cancel _ hpq.ne_zero, div_rpow, div_mul_div, mul_comm (G ^ q), mul_div_mul_right], { nth_rewrite 1 [← mul_one ((f i) ^ p)], exact canonically_ordered_semiring.mul_le_mul (le_refl _) (div_self_le _) }, { simpa [hpq.symm.ne_zero] using hG } end } end /-- The `L_p` seminorm of a vector `f` is the greatest value of the inner product `∑ i in s, f i * g i` over functions `g` of `L_q` seminorm less than or equal to one. -/ theorem is_greatest_Lp (f : ι → ℝ≥0) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : is_greatest ((λ g : ι → ℝ≥0, ∑ i in s, f i * g i) '' {g | ∑ i in s, (g i)^q ≤ 1}) ((∑ i in s, (f i)^p) ^ (1 / p)) := begin split, { use λ i, ((f i) ^ p / f i / (∑ i in s, (f i) ^ p) ^ (1 / q)), by_cases hf : ∑ i in s, (f i)^p = 0, { simp [hf, hpq.ne_zero, hpq.symm.ne_zero] }, { have A : p + q - q ≠ 0, by simp [hpq.ne_zero], have B : ∀ y : ℝ≥0, y * y^p / y = y^p, { refine λ y, mul_div_cancel_left_of_imp (λ h, _), simpa [h, hpq.ne_zero] }, simp only [set.mem_set_of_eq, div_rpow, ← sum_div, ← rpow_mul, div_mul_cancel _ hpq.symm.ne_zero, rpow_one, div_le_iff hf, one_mul, hpq.mul_eq_add, ← rpow_sub' _ A, _root_.add_sub_cancel, le_refl, true_and, ← mul_div_assoc, B], rw [div_eq_iff, ← rpow_add hf, hpq.inv_add_inv_conj, rpow_one], simpa [hpq.symm.ne_zero] using hf } }, { rintros _ ⟨g, hg, rfl⟩, apply le_trans (inner_le_Lp_mul_Lq s f g hpq), simpa only [mul_one] using canonically_ordered_semiring.mul_le_mul (le_refl _) (nnreal.rpow_le_one hg (le_of_lt hpq.symm.one_div_pos)) } end /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `nnreal`-valued functions. -/ theorem Lp_add_le (f g : ι → ℝ≥0) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, (f i + g i) ^ p) ^ (1 / p) ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) + (∑ i in s, (g i) ^ p) ^ (1 / p) := begin -- The result is trivial when `p = 1`, so we can assume `1 < p`. rcases eq_or_lt_of_le hp with rfl|hp, { simp [finset.sum_add_distrib] }, have hpq := real.is_conjugate_exponent_conjugate_exponent hp, have := is_greatest_Lp s (f + g) hpq, simp only [pi.add_apply, add_mul, sum_add_distrib] at this, rcases this.1 with ⟨φ, hφ, H⟩, rw ← H, exact add_le_add ((is_greatest_Lp s f hpq).2 ⟨φ, hφ, rfl⟩) ((is_greatest_Lp s g hpq).2 ⟨φ, hφ, rfl⟩) end end nnreal namespace real variables (f g : ι → ℝ) {p q : ℝ} /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with real-valued functions. -/ theorem inner_le_Lp_mul_Lq (hpq : is_conjugate_exponent p q) : ∑ i in s, f i * g i ≤ (∑ i in s, (abs $ f i)^p) ^ (1 / p) * (∑ i in s, (abs $ g i)^q) ^ (1 / q) := begin have := nnreal.coe_le_coe.2 (nnreal.inner_le_Lp_mul_Lq s (λ i, ⟨_, abs_nonneg (f i)⟩) (λ i, ⟨_, abs_nonneg (g i)⟩) hpq), push_cast at this, refine le_trans (sum_le_sum $ λ i hi, _) this, simp only [← abs_mul, le_abs_self] end /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `real`-valued functions. -/ theorem Lp_add_le (hp : 1 ≤ p) : (∑ i in s, (abs $ f i + g i) ^ p) ^ (1 / p) ≤ (∑ i in s, (abs $ f i) ^ p) ^ (1 / p) + (∑ i in s, (abs $ g i) ^ p) ^ (1 / p) := begin have := nnreal.coe_le_coe.2 (nnreal.Lp_add_le s (λ i, ⟨_, abs_nonneg (f i)⟩) (λ i, ⟨_, abs_nonneg (g i)⟩) hp), push_cast at this, refine le_trans (rpow_le_rpow _ (sum_le_sum $ λ i hi, _) _) this; simp [sum_nonneg, rpow_nonneg_of_nonneg, abs_nonneg, le_trans zero_le_one hp, abs_add, rpow_le_rpow] end variables {f g} /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with real-valued nonnegative functions. -/ theorem inner_le_Lp_mul_Lq_of_nonneg (hpq : is_conjugate_exponent p q) (hf : ∀ i ∈ s, 0 ≤ f i) (hg : ∀ i ∈ s, 0 ≤ g i) : ∑ i in s, f i * g i ≤ (∑ i in s, (f i)^p) ^ (1 / p) * (∑ i in s, (g i)^q) ^ (1 / q) := by convert inner_le_Lp_mul_Lq s f g hpq using 3; apply sum_congr rfl; intros i hi; simp only [abs_of_nonneg, hf i hi, hg i hi] /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `real`-valued nonnegative functions. -/ theorem Lp_add_le_of_nonneg (hp : 1 ≤ p) (hf : ∀ i ∈ s, 0 ≤ f i) (hg : ∀ i ∈ s, 0 ≤ g i) : (∑ i in s, (f i + g i) ^ p) ^ (1 / p) ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) + (∑ i in s, (g i) ^ p) ^ (1 / p) := by convert Lp_add_le s f g hp using 2 ; [skip, congr' 1, congr' 1]; apply sum_congr rfl; intros i hi; simp only [abs_of_nonneg, hf i hi, hg i hi, add_nonneg] end real namespace ennreal variables (f g : ι → ennreal) {p q : ℝ} /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with `ennreal`-valued functions. -/ theorem inner_le_Lp_mul_Lq (hpq : p.is_conjugate_exponent q) : (∑ i in s, f i * g i) ≤ (∑ i in s, (f i)^p) ^ (1/p) * (∑ i in s, (g i)^q) ^ (1/q) := begin by_cases H : (∑ i in s, (f i)^p) ^ (1/p) = 0 ∨ (∑ i in s, (g i)^q) ^ (1/q) = 0, { replace H : (∀ i ∈ s, f i = 0) ∨ (∀ i ∈ s, g i = 0), by simpa [ennreal.rpow_eq_zero_iff, hpq.pos, hpq.symm.pos, asymm hpq.pos, asymm hpq.symm.pos, sum_eq_zero_iff_of_nonneg] using H, have : ∀ i ∈ s, f i * g i = 0 := λ i hi, by cases H; simp [H i hi], have : (∑ i in s, f i * g i) = (∑ i in s, 0) := sum_congr rfl this, simp [this] }, push_neg at H, by_cases H' : (∑ i in s, (f i)^p) ^ (1/p) = ⊤ ∨ (∑ i in s, (g i)^q) ^ (1/q) = ⊤, { cases H'; simp [H', -one_div, H] }, replace H' : (∀ i ∈ s, f i ≠ ⊤) ∧ (∀ i ∈ s, g i ≠ ⊤), by simpa [ennreal.rpow_eq_top_iff, asymm hpq.pos, asymm hpq.symm.pos, hpq.pos, hpq.symm.pos, ennreal.sum_eq_top_iff, not_or_distrib] using H', have := ennreal.coe_le_coe.2 (@nnreal.inner_le_Lp_mul_Lq _ s (λ i, ennreal.to_nnreal (f i)) (λ i, ennreal.to_nnreal (g i)) _ _ hpq), simp [← ennreal.coe_rpow_of_nonneg, le_of_lt (hpq.pos), le_of_lt (hpq.one_div_pos), le_of_lt (hpq.symm.pos), le_of_lt (hpq.symm.one_div_pos)] at this, convert this using 1; [skip, congr' 2]; [skip, skip, simp, skip, simp]; { apply finset.sum_congr rfl (λ i hi, _), simp [H'.1 i hi, H'.2 i hi, -with_zero.coe_mul, with_top.coe_mul.symm] }, end /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `ennreal` valued nonnegative functions. -/ theorem Lp_add_le (hp : 1 ≤ p) : (∑ i in s, (f i + g i) ^ p)^(1/p) ≤ (∑ i in s, (f i)^p) ^ (1/p) + (∑ i in s, (g i)^p) ^ (1/p) := begin by_cases H' : (∑ i in s, (f i)^p) ^ (1/p) = ⊤ ∨ (∑ i in s, (g i)^p) ^ (1/p) = ⊤, { cases H'; simp [H', -one_div] }, have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, replace H' : (∀ i ∈ s, f i ≠ ⊤) ∧ (∀ i ∈ s, g i ≠ ⊤), by simpa [ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, not_or_distrib] using H', have := ennreal.coe_le_coe.2 (@nnreal.Lp_add_le _ s (λ i, ennreal.to_nnreal (f i)) (λ i, ennreal.to_nnreal (g i)) _ hp), push_cast [← ennreal.coe_rpow_of_nonneg, le_of_lt (pos), le_of_lt (one_div_pos.2 pos)] at this, convert this using 2; [skip, congr' 1, congr' 1]; { apply finset.sum_congr rfl (λ i hi, _), simp [H'.1 i hi, H'.2 i hi] } end end ennreal
7f9f833c0e1bbadf494e07a0a38650356f9df3ba
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/limits/preserves/shapes/pullbacks.lean
e791e9be8db90bc6002e84aff8ac93cf617add7f
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
10,599
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Andrew Yang -/ import category_theory.limits.shapes.pullbacks import category_theory.limits.preserves.basic /-! # Preserving pullbacks Constructions to relate the notions of preserving pullbacks and reflecting pullbacks to concrete pullback cones. In particular, we show that `pullback_comparison G f g` is an isomorphism iff `G` preserves the pullback of `f` and `g`. The dual is also given. ## TODO * Generalise to wide pullbacks -/ noncomputable theory universes v₁ v₂ u₁ u₂ open category_theory category_theory.category category_theory.limits namespace category_theory.limits section pullback variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] variables (G : C ⥤ D) variables {W X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} {h : W ⟶ X} {k : W ⟶ Y} (comm : h ≫ f = k ≫ g) /-- The map of a pullback cone is a limit iff the fork consisting of the mapped morphisms is a limit. This essentially lets us commute `pullback_cone.mk` with `functor.map_cone`. -/ def is_limit_map_cone_pullback_cone_equiv : is_limit (G.map_cone (pullback_cone.mk h k comm)) ≃ is_limit (pullback_cone.mk (G.map h) (G.map k) (by simp only [← G.map_comp, comm]) : pullback_cone (G.map f) (G.map g)) := (is_limit.postcompose_hom_equiv (diagram_iso_cospan.{v₂} _) _).symm.trans $ is_limit.equiv_iso_limit $ cones.ext (iso.refl _) $ (by rintro (_|_|_); dsimp; simp only [comp_id, id_comp, G.map_comp]) /-- The property of preserving pullbacks expressed in terms of binary fans. -/ def is_limit_pullback_cone_map_of_is_limit [preserves_limit (cospan f g) G] (l : is_limit (pullback_cone.mk h k comm)) : is_limit (pullback_cone.mk (G.map h) (G.map k) _) := is_limit_map_cone_pullback_cone_equiv G comm (preserves_limit.preserves l) /-- The property of reflecting pullbacks expressed in terms of binary fans. -/ def is_limit_of_is_limit_pullback_cone_map [reflects_limit (cospan f g) G] (l : is_limit (pullback_cone.mk (G.map h) (G.map k) _)) : is_limit (pullback_cone.mk h k comm) := reflects_limit.reflects ((is_limit_map_cone_pullback_cone_equiv G comm).symm l) variables (f g) [preserves_limit (cospan f g) G] /-- If `G` preserves pullbacks and `C` has them, then the pullback cone constructed of the mapped morphisms of the pullback cone is a limit. -/ def is_limit_of_has_pullback_of_preserves_limit [has_pullback f g] : is_limit (pullback_cone.mk (G.map pullback.fst) (G.map pullback.snd) _) := is_limit_pullback_cone_map_of_is_limit G _ (pullback_is_pullback f g) /-- If `F` preserves the pullback of `f, g`, it also preserves the pullback of `g, f`. -/ def preserves_pullback_symmetry : preserves_limit (cospan g f) G := { preserves := λ c hc, begin apply (is_limit.postcompose_hom_equiv (diagram_iso_cospan.{v₂} _) _).to_fun, apply is_limit.of_iso_limit _ (pullback_cone.iso_mk _).symm, apply pullback_cone.flip_is_limit, apply (is_limit_map_cone_pullback_cone_equiv _ _).to_fun, { apply_with preserves_limit.preserves { instances := ff }, { dsimp, apply_instance }, apply pullback_cone.flip_is_limit, apply is_limit.of_iso_limit _ (pullback_cone.iso_mk _), exact (is_limit.postcompose_hom_equiv (diagram_iso_cospan.{v₁} _) _).inv_fun hc }, { exact (c.π.naturality walking_cospan.hom.inr).symm.trans (c.π.naturality walking_cospan.hom.inl : _) } end } variables [has_pullback f g] [has_pullback (G.map f) (G.map g)] /-- If `G` preserves the pullback of `(f,g)`, then the pullback comparison map for `G` at `(f,g)` is an isomorphism. -/ def preserves_pullback.iso : G.obj (pullback f g) ≅ pullback (G.map f) (G.map g) := is_limit.cone_point_unique_up_to_iso (is_limit_of_has_pullback_of_preserves_limit G f g) (limit.is_limit _) @[reassoc] lemma preserves_pullback.iso_hom_fst : (preserves_pullback.iso G f g).hom ≫ pullback.fst = G.map pullback.fst := by simp [preserves_pullback.iso] @[reassoc] lemma preserves_pullback.iso_hom_snd : (preserves_pullback.iso G f g).hom ≫ pullback.snd = G.map pullback.snd := by simp [preserves_pullback.iso] @[simp, reassoc] lemma preserves_pullback.iso_inv_fst : (preserves_pullback.iso G f g).inv ≫ G.map pullback.fst = pullback.fst := by simp [preserves_pullback.iso, iso.inv_comp_eq] @[simp, reassoc] lemma preserves_pullback.iso_inv_snd : (preserves_pullback.iso G f g).inv ≫ G.map pullback.snd = pullback.snd := by simp [preserves_pullback.iso, iso.inv_comp_eq] end pullback section pushout variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] variables (G : C ⥤ D) variables {W X Y Z : C} {h : X ⟶ Z} {k : Y ⟶ Z} {f : W ⟶ X} {g : W ⟶ Y} (comm : f ≫ h = g ≫ k) /-- The map of a pushout cocone is a colimit iff the cofork consisting of the mapped morphisms is a colimit. This essentially lets us commute `pushout_cocone.mk` with `functor.map_cocone`. -/ def is_colimit_map_cocone_pushout_cocone_equiv : is_colimit (G.map_cocone (pushout_cocone.mk h k comm)) ≃ is_colimit (pushout_cocone.mk (G.map h) (G.map k) (by simp only [← G.map_comp, comm]) : pushout_cocone (G.map f) (G.map g)) := (is_colimit.precompose_hom_equiv (diagram_iso_span.{v₂} _).symm _).symm.trans $ is_colimit.equiv_iso_colimit $ cocones.ext (iso.refl _) $ (by rintro (_|_|_); dsimp; simp only [category.comp_id, category.id_comp, ← G.map_comp]) /-- The property of preserving pushouts expressed in terms of binary cofans. -/ def is_colimit_pushout_cocone_map_of_is_colimit [preserves_colimit (span f g) G] (l : is_colimit (pushout_cocone.mk h k comm)) : is_colimit (pushout_cocone.mk (G.map h) (G.map k) _) := is_colimit_map_cocone_pushout_cocone_equiv G comm (preserves_colimit.preserves l) /-- The property of reflecting pushouts expressed in terms of binary cofans. -/ def is_colimit_of_is_colimit_pushout_cocone_map [reflects_colimit (span f g) G] (l : is_colimit (pushout_cocone.mk (G.map h) (G.map k) _)) : is_colimit (pushout_cocone.mk h k comm) := reflects_colimit.reflects ((is_colimit_map_cocone_pushout_cocone_equiv G comm).symm l) variables (f g) [preserves_colimit (span f g) G] /-- If `G` preserves pushouts and `C` has them, then the pushout cocone constructed of the mapped morphisms of the pushout cocone is a colimit. -/ def is_colimit_of_has_pushout_of_preserves_colimit [has_pushout f g] : is_colimit (pushout_cocone.mk (G.map pushout.inl) (G.map pushout.inr) _) := is_colimit_pushout_cocone_map_of_is_colimit G _ (pushout_is_pushout f g) /-- If `F` preserves the pushout of `f, g`, it also preserves the pushout of `g, f`. -/ def preserves_pushout_symmetry : preserves_colimit (span g f) G := { preserves := λ c hc, begin apply (is_colimit.precompose_hom_equiv (diagram_iso_span.{v₂} _).symm _).to_fun, apply is_colimit.of_iso_colimit _ (pushout_cocone.iso_mk _).symm, apply pushout_cocone.flip_is_colimit, apply (is_colimit_map_cocone_pushout_cocone_equiv _ _).to_fun, { apply_with preserves_colimit.preserves { instances := ff }, { dsimp, apply_instance }, apply pushout_cocone.flip_is_colimit, apply is_colimit.of_iso_colimit _ (pushout_cocone.iso_mk _), exact (is_colimit.precompose_hom_equiv (diagram_iso_span.{v₁} _) _).inv_fun hc }, { exact (c.ι.naturality walking_span.hom.snd).trans (c.ι.naturality walking_span.hom.fst).symm } end } variables [has_pushout f g] [has_pushout (G.map f) (G.map g)] /-- If `G` preserves the pushout of `(f,g)`, then the pushout comparison map for `G` at `(f,g)` is an isomorphism. -/ def preserves_pushout.iso : pushout (G.map f) (G.map g) ≅ G.obj (pushout f g) := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (is_colimit_of_has_pushout_of_preserves_colimit G f g) @[reassoc] lemma preserves_pushout.inl_iso_hom : pushout.inl ≫ (preserves_pushout.iso G f g).hom = G.map pushout.inl := by { delta preserves_pushout.iso, simp } @[reassoc] lemma preserves_pushout.inr_iso_hom : pushout.inr ≫ (preserves_pushout.iso G f g).hom = G.map pushout.inr := by { delta preserves_pushout.iso, simp } @[simp, reassoc] lemma preserves_pushout.inl_iso_inv : G.map pushout.inl ≫ (preserves_pushout.iso G f g).inv = pushout.inl := by simp [preserves_pushout.iso, iso.comp_inv_eq] @[simp, reassoc] lemma preserves_pushout.inr_iso_inv : G.map pushout.inr ≫ (preserves_pushout.iso G f g).inv = pushout.inr := by simp [preserves_pushout.iso, iso.comp_inv_eq] end pushout section variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₁} D] variables (G : C ⥤ D) section pullback variables {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} variables [has_pullback f g] [has_pullback (G.map f) (G.map g)] /-- If the pullback comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the pullback of `(f,g)`. -/ def preserves_pullback.of_iso_comparison [i : is_iso (pullback_comparison G f g)] : preserves_limit (cospan f g) G := begin apply preserves_limit_of_preserves_limit_cone (pullback_is_pullback f g), apply (is_limit_map_cone_pullback_cone_equiv _ _).symm _, apply is_limit.of_point_iso (limit.is_limit (cospan (G.map f) (G.map g))), apply i, end variable [preserves_limit (cospan f g) G] @[simp] lemma preserves_pullback.iso_hom : (preserves_pullback.iso G f g).hom = pullback_comparison G f g := rfl instance : is_iso (pullback_comparison G f g) := begin rw ← preserves_pullback.iso_hom, apply_instance end end pullback section pushout variables {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} variables [has_pushout f g] [has_pushout (G.map f) (G.map g)] /-- If the pushout comparison map for `G` at `(f,g)` is an isomorphism, then `G` preserves the pushout of `(f,g)`. -/ def preserves_pushout.of_iso_comparison [i : is_iso (pushout_comparison G f g)] : preserves_colimit (span f g) G := begin apply preserves_colimit_of_preserves_colimit_cocone (pushout_is_pushout f g), apply (is_colimit_map_cocone_pushout_cocone_equiv _ _).symm _, apply is_colimit.of_point_iso (colimit.is_colimit (span (G.map f) (G.map g))), apply i, end variable [preserves_colimit (span f g) G] @[simp] lemma preserves_pushout.iso_hom : (preserves_pushout.iso G f g).hom = pushout_comparison G f g := rfl instance : is_iso (pushout_comparison G f g) := begin rw ← preserves_pushout.iso_hom, apply_instance end end pushout end end category_theory.limits
f47b4b8ccfe2b082516b414d273cad081653450c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/simple_graph/regularity/lemma.lean
88ae521886eaa8a5b9f4024bb3822bb5d048d7bf
[ "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,433
lean
/- Copyright (c) 2021 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 combinatorics.simple_graph.regularity.increment /-! # Szemerédi's Regularity Lemma > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we prove Szemerédi's Regularity Lemma (aka SRL). This is a landmark result in combinatorics roughly stating that any sufficiently big graph behaves like a random graph. This is useful because random graphs are well-behaved in many aspects. More precisely, SRL states that for any `ε > 0` and integer `l` there exists a bound `M` such that any graph on at least `l` vertices can be partitioned into at least `l` parts and at most `M` parts such that the resulting partitioned graph is `ε`-uniform. This statement is very robust to tweaking and many different versions exist. Here, we prove the version where the resulting partition is equitable (aka an *equipartition*), namely all parts have the same size up to a difference of `1`. The proof we formalise goes as follows: 1. Define an auxiliary measure of edge density, the *energy* of a partition. 2. Start with an arbitrary equipartition of size `l`. 3. Repeatedly break up the parts of the current equipartition in a big but controlled number of parts. The key point is to break along the witnesses of non-uniformity, so that a lesser portion of the pairs of parts are non-`ε`-uniform. 4. Check that this results in an equipartition with an energy greater than the energy of the current partition, plus some constant. 5. Since the energy is between zero and one, we can't run this process forever. Check that when the process stops we have an `ε`-uniform equipartition. This file only contains the final result. The supporting material is spread across the `combinatorics.simple_graph.regularity` folder: * `combinatorics.simple_graph.regularity.bound`: Definition of the bound on the number of parts. Numerical inequalities involving the lemma constants. * `combinatorics.simple_graph.regularity.energy`: Definition of the energy of a simple graph along a partition. * `combinatorics.simple_graph.regularity.uniform`: Definition of uniformity of a simple graph along a pair of parts and along a partition. * `combinatorics.simple_graph.regularity.equitabilise`: Construction of an equipartition with a prescribed number of parts of each size and almost refining a given partition. * `combinatorics.simple_graph.regularity.chunk`: Break up one part of the current equipartition. Check that density between non-uniform parts increases, and that density between uniform parts doesn't decrease too much. * `combinatorics.simple_graph.regularity.increment`: Gather all those broken up parts into the new equipartition (aka *increment partition*). Check that energy increases by at least a fixed amount. * `combinatorics.simple_graph.regularity.lemma`: Wrap everything up into an induction on the energy. ## TODO We currently only prove the equipartition version of SRL. * Prove the diagonal version. * Prove the degree version. * Define the regularity of a partition and prove the corresponding version. ## References [Yaël Dillies, Bhavik Mehta, *Formalising Szemerédi’s Regularity Lemma in Lean*][srl_itp] -/ open finpartition finset fintype function szemeredi_regularity open_locale classical variables {α : Type*} [fintype α] (G : simple_graph α) {ε : ℝ} {l : ℕ} /-- Effective **Szemerédi Regularity Lemma**: For any sufficiently large graph, there is an `ε`-uniform equipartition of bounded size (where the bound does not depend on the graph). -/ theorem szemeredi_regularity (hε : 0 < ε) (hl : l ≤ card α) : ∃ P : finpartition univ, P.is_equipartition ∧ l ≤ P.parts.card ∧ P.parts.card ≤ bound ε l ∧ P.is_uniform G ε := begin obtain hα | hα := le_total (card α) (bound ε l), -- If `card α ≤ bound ε l`, then the partition into singletons is acceptable. { refine ⟨⊥, bot_is_equipartition _, _⟩, rw [card_bot, card_univ], exact ⟨hl, hα, bot_is_uniform _ hε⟩ }, -- Else, let's start from a dummy equipartition of size `initial_bound ε l`. let t := initial_bound ε l, have htα : t ≤ (univ : finset α).card := (initial_bound_le_bound _ _).trans (by rwa finset.card_univ), obtain ⟨dum, hdum₁, hdum₂⟩ := exists_equipartition_card_eq (univ : finset α) (initial_bound_pos _ _).ne' htα, obtain hε₁ | hε₁ := le_total 1 ε, ---If `ε ≥ 1`, then this dummy equipartition is `ε`-uniform, so we're done. { exact ⟨dum, hdum₁, (le_initial_bound ε l).trans hdum₂.ge, hdum₂.le.trans (initial_bound_le_bound ε l), (dum.is_uniform_one G).mono hε₁⟩ }, -- Else, set up the induction on energy. We phrase it through the existence for each `i` of an -- equipartition of size bounded by `step_bound^[i]) (initial_bound ε l)` and which is either -- `ε`-uniform or has energy at least `ε ^ 5 / 4 * i`. haveI : nonempty α, { rw ←fintype.card_pos_iff, exact (bound_pos _ _).trans_le hα }, suffices h : ∀ i, ∃ P : finpartition (univ : finset α), P.is_equipartition ∧ t ≤ P.parts.card ∧ P.parts.card ≤ (step_bound^[i]) t ∧ (P.is_uniform G ε ∨ ε ^ 5 / 4 * i ≤ P.energy G), -- For `i > 4 / ε ^ 5` we know that the partition we get can't have energy `≥ ε ^ 5 / 4 * i > 1`, -- so it must instead be `ε`-uniform and we won. { obtain ⟨P, hP₁, hP₂, hP₃, hP₄⟩ := h (⌊4 / ε ^ 5⌋₊ + 1), refine ⟨P, hP₁, (le_initial_bound _ _).trans hP₂, hP₃.trans _, hP₄.resolve_right $ λ hPenergy, lt_irrefl (1 : ℝ) _⟩, { rw iterate_succ_apply', exact mul_le_mul_left' (pow_le_pow_of_le_left (by norm_num) (by norm_num) _) _ }, calc 1 = ε ^ 5 / 4 * (4 / ε ^ 5) : by { rw [mul_comm, div_mul_div_cancel 4 (pow_pos hε 5).ne'], norm_num } ... < ε ^ 5 / 4 * (⌊4 / ε ^ 5⌋₊ + 1) : (mul_lt_mul_left $ by positivity).2 (nat.lt_floor_add_one _) ... ≤ (P.energy G : ℝ) : by rwa ←nat.cast_add_one ... ≤ 1 : by exact_mod_cast P.energy_le_one G }, -- Let's do the actual induction. intro i, induction i with i ih, -- For `i = 0`, the dummy equipartition is enough. { refine ⟨dum, hdum₁, hdum₂.ge, hdum₂.le, or.inr _⟩, rw [nat.cast_zero, mul_zero], exact_mod_cast dum.energy_nonneg G }, -- For the induction step at `i + 1`, find `P` the equipartition at `i`. obtain ⟨P, hP₁, hP₂, hP₃, hP₄⟩ := ih, by_cases huniform : P.is_uniform G ε, -- If `P` is already uniform, then no need to break it up further. We can just return `P` again. { refine ⟨P, hP₁, hP₂, _, or.inl huniform⟩, rw iterate_succ_apply', exact hP₃.trans (le_step_bound _) }, -- Else, `P` must instead have energy at least `ε ^ 5 / 4 * i`. replace hP₄ := hP₄.resolve_left huniform, -- We gather a few numerical facts. have hεl' : 100 < 4 ^ P.parts.card * ε ^ 5, { exact (hundred_lt_pow_initial_bound_mul hε l).trans_le (mul_le_mul_of_nonneg_right (pow_le_pow (by norm_num) hP₂) $ by positivity) }, have hi : (i : ℝ) ≤ 4 / ε ^ 5, { have hi : ε ^ 5 / 4 * ↑i ≤ 1 := hP₄.trans (by exact_mod_cast P.energy_le_one G), rw [div_mul_eq_mul_div, div_le_iff (show (0:ℝ) < 4, by norm_num)] at hi, norm_num at hi, rwa le_div_iff' (pow_pos hε _) }, have hsize : P.parts.card ≤ (step_bound^[⌊4 / ε ^ 5⌋₊] t) := hP₃.trans (monotone_iterate_of_id_le le_step_bound (nat.le_floor hi) _), have hPα : P.parts.card * 16 ^ P.parts.card ≤ card α := (nat.mul_le_mul hsize (nat.pow_le_pow_of_le_right (by norm_num) hsize)).trans hα, -- We return the increment equipartition of `P`, which has energy `≥ ε ^ 5 / 4 * (i + 1)`. refine ⟨increment hP₁ G ε, increment_is_equipartition hP₁ G ε, _, _, or.inr $ le_trans _ $ energy_increment hP₁ ((seven_le_initial_bound ε l).trans hP₂) hεl' hPα huniform hε₁⟩, { rw card_increment hPα huniform, exact hP₂.trans (le_step_bound _) }, { rw [card_increment hPα huniform, iterate_succ_apply'], exact step_bound_mono hP₃ }, { rw [nat.cast_succ, mul_add, mul_one], exact add_le_add_right hP₄ _ } end
ab629b712648da6b909314a6e07cd30ce01789e0
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/order/filter/ultrafilter.lean
bd3ff140164bf85c9509b9bb57d34b7c613f2ebc
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
12,568
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad -/ import order.filter.cofinite /-! # Ultrafilters An ultrafilter is a minimal (maximal in the set order) proper filter. In this file we define * `is_ultrafilter`: a predicate stating that a given filter is an ultrafiler; * `ultrafilter_of`: an ultrafilter that is less than or equal to a given filter; * `ultrafilter`: subtype of ultrafilters; * `ultrafilter.pure`: `pure x` as an `ultrafiler`; * `ultrafilter.map`, `ultrafilter.bind` : operations on ultrafilters; * `hyperfilter`: the ultra-filter extending the cofinite filter. -/ universes u v variables {α : Type u} {β : Type v} namespace filter open set zorn open_locale classical filter variables {f g : filter α} /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ def is_ultrafilter (f : filter α) := ne_bot f ∧ ∀g, ne_bot g → g ≤ f → f ≤ g lemma is_ultrafilter.unique (hg : is_ultrafilter g) (hf : ne_bot f) (h : f ≤ g) : f = g := le_antisymm h (hg.right _ hf h) lemma le_of_ultrafilter {g : filter α} (hf : is_ultrafilter f) (h : ne_bot (g ⊓ f)) : f ≤ g := by { rw inf_comm at h, exact le_of_inf_eq (hf.unique h inf_le_left) } /-- Equivalent characterization of ultrafilters: A filter f is an ultrafilter if and only if for each set s, -s belongs to f if and only if s does not belong to f. -/ lemma ultrafilter_iff_compl_mem_iff_not_mem : is_ultrafilter f ↔ (∀ s, sᶜ ∈ f ↔ s ∉ f) := ⟨assume hf s, ⟨assume hns hs, hf.1 $ empty_in_sets_eq_bot.mp $ by convert f.inter_sets hs hns; rw [inter_compl_self], assume hs, have f ≤ 𝓟 sᶜ, from le_of_ultrafilter hf $ assume h, hs $ mem_sets_of_eq_bot $ by rwa inf_comm, by simp only [le_principal_iff] at this; assumption⟩, assume hf, ⟨mt empty_in_sets_eq_bot.mpr ((hf ∅).mp (by convert f.univ_sets; rw [compl_empty])), assume g hg g_le s hs, classical.by_contradiction $ mt (hf s).mpr $ assume : sᶜ ∈ f, have s ∩ sᶜ ∈ g, from inter_mem_sets hs (g_le this), by simp only [empty_in_sets_eq_bot, hg, inter_compl_self] at this; contradiction⟩⟩ lemma mem_or_compl_mem_of_ultrafilter (hf : is_ultrafilter f) (s : set α) : s ∈ f ∨ sᶜ ∈ f := classical.or_iff_not_imp_left.2 (ultrafilter_iff_compl_mem_iff_not_mem.mp hf s).mpr lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : is_ultrafilter f) (h : s ∪ t ∈ f) : s ∈ f ∨ t ∈ f := (mem_or_compl_mem_of_ultrafilter hf s).imp_right (assume : sᶜ ∈ f, by filter_upwards [this, h] assume x hnx hx, hx.resolve_left hnx) lemma is_ultrafilter.em (hf : is_ultrafilter f) (p : α → Prop) : (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, ¬p x := mem_or_compl_mem_of_ultrafilter hf {x | p x} lemma is_ultrafilter.eventually_or (hf : is_ultrafilter f) {p q : α → Prop} : (∀ᶠ x in f, p x ∨ q x) ↔ (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, q x := ⟨mem_or_mem_of_ultrafilter hf, λ H, H.elim (λ hp, hp.mono $ λ x, or.inl) (λ hp, hp.mono $ λ x, or.inr)⟩ lemma is_ultrafilter.eventually_not (hf : is_ultrafilter f) {p : α → Prop} : (∀ᶠ x in f, ¬p x) ↔ ¬∀ᶠ x in f, p x := ultrafilter_iff_compl_mem_iff_not_mem.1 hf {x | p x} lemma is_ultrafilter.eventually_imp (hf : is_ultrafilter f) {p q : α → Prop} : (∀ᶠ x in f, p x → q x) ↔ (∀ᶠ x in f, p x) → ∀ᶠ x in f, q x := by simp only [imp_iff_not_or, hf.eventually_or, hf.eventually_not] lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : is_ultrafilter f) (hs : finite s) : ⋃₀ s ∈ f → ∃t∈s, t ∈ f := finite.induction_on hs (by simp only [sUnion_empty, empty_in_sets_eq_bot, hf.left.ne, forall_prop_of_false, not_false_iff]) $ λ t s' ht' hs' ih, by simp only [exists_prop, mem_insert_iff, set.sUnion_insert]; exact assume h, (mem_or_mem_of_ultrafilter hf h).elim (assume : t ∈ f, ⟨t, or.inl rfl, this⟩) (assume h, let ⟨t, hts', ht⟩ := ih h in ⟨t, or.inr hts', ht⟩) lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α} (hf : is_ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f) : ∃i∈is, s i ∈ f := have his : finite (image s is), from his.image s, have h : (⋃₀ image s is) ∈ f, from by simp only [sUnion_image, set.sUnion_image]; assumption, let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in ⟨i, hi, h_eq.symm ▸ ht⟩ lemma ultrafilter_map {f : filter α} {m : α → β} (h : is_ultrafilter f) : is_ultrafilter (map m f) := by rw ultrafilter_iff_compl_mem_iff_not_mem at ⊢ h; exact assume s, h (m ⁻¹' s) lemma ultrafilter_pure {a : α} : is_ultrafilter (pure a) := begin rw ultrafilter_iff_compl_mem_iff_not_mem, intro s, rw [mem_pure_sets, mem_pure_sets], exact iff.rfl end lemma ultrafilter_bind {f : filter α} (hf : is_ultrafilter f) {m : α → filter β} (hm : ∀ a, is_ultrafilter (m a)) : is_ultrafilter (f.bind m) := begin simp only [ultrafilter_iff_compl_mem_iff_not_mem] at ⊢ hf hm, intro s, dsimp [bind, join, map, preimage], simp only [hm], apply hf end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_ultrafilter (f : filter α) [h : ne_bot f] : ∃u, u ≤ f ∧ is_ultrafilter u := begin let τ := {f' // ne_bot f' ∧ f' ≤ f}, let r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, haveI := nonempty_of_ne_bot f, let top : τ := ⟨f, h, le_refl f⟩, let sup : Π(c:set τ), chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.1, infi_ne_bot_of_directed (directed_of_chain $ chain_insert hc $ λ ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩, have : ∀c (hc: chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _), have : (∃ (u : τ), ∀ (a : τ), r u a → r a u), from exists_maximal_of_chains_bounded (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), cases this with uτ hmin, exact ⟨uτ.val, uτ.property.right, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩ end /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def ultrafilter_of (f : filter α) : filter α := if f = ⊥ then ⊥ else classical.epsilon (λu, u ≤ f ∧ is_ultrafilter u) lemma ultrafilter_of_spec [h : ne_bot f] : ultrafilter_of f ≤ f ∧ is_ultrafilter (ultrafilter_of f) := by simpa only [ultrafilter_of, if_neg h] using classical.epsilon_spec (exists_ultrafilter f) lemma ultrafilter_of_le : ultrafilter_of f ≤ f := if h : f = ⊥ then by simp only [ultrafilter_of, if_pos h, bot_le] else (@ultrafilter_of_spec _ _ h).left lemma ultrafilter_ultrafilter_of [ne_bot f] : is_ultrafilter (ultrafilter_of f) := ultrafilter_of_spec.right lemma ultrafilter_ultrafilter_of' (hf : ne_bot f) : is_ultrafilter (ultrafilter_of f) := ultrafilter_ultrafilter_of instance ultrafilter_of_ne_bot [h : ne_bot f] : ne_bot (ultrafilter_of f) := ultrafilter_ultrafilter_of.left lemma ultrafilter_of_ultrafilter (h : is_ultrafilter f) : ultrafilter_of f = f := h.unique (ultrafilter_ultrafilter_of' h.left).left ultrafilter_of_le /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma sup_of_ultrafilters (f : filter α) : f = ⨆ (g) (u : is_ultrafilter g) (H : g ≤ f), g := begin refine le_antisymm _ (supr_le $ λ g, supr_le $ λ u, supr_le $ λ H, H), intros s hs, -- If `s ∉ f`, we'll apply the ultrafilter lemma to the restriction of f to -s. by_contradiction hs', let j : sᶜ → α := coe, have j_inv_s : j ⁻¹' s = ∅, by erw [←preimage_inter_range, subtype.range_coe, inter_compl_self, preimage_empty], let f' := comap (coe : sᶜ → α) f, have : ne_bot f', { refine comap_ne_bot (λ t ht, _), have : ¬(t ⊆ s) := λ h, hs' (mem_sets_of_superset ht h), simpa [subset_def, and_comm] using this }, resetI, rcases exists_ultrafilter f' with ⟨g', g'f', u'⟩, simp only [supr_sets_eq, mem_Inter] at hs, have := hs (g'.map coe) (ultrafilter_map u') (map_le_iff_le_comap.mpr g'f'), rw [←le_principal_iff, map_le_iff_le_comap, comap_principal, j_inv_s, principal_empty, le_bot_iff] at this, exact absurd this u'.1 end /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g, is_ultrafilter g → g ≤ l₁ → g.map f ≤ l₂ := ⟨assume h g u gx, le_trans (map_mono gx) h, assume h, by rw [sup_of_ultrafilters l₁]; simpa only [tendsto, map_supr, supr_le_iff]⟩ /-- The ultrafilter monad. The monad structure on ultrafilters is the restriction of the one on filters. -/ def ultrafilter (α : Type u) : Type u := {f : filter α // is_ultrafilter f} /-- Push-forward for ultra-filters. -/ def ultrafilter.map (m : α → β) (u : ultrafilter α) : ultrafilter β := ⟨u.val.map m, ultrafilter_map u.property⟩ /-- The principal ultra-filter associated to a point `x`. -/ def ultrafilter.pure (x : α) : ultrafilter α := ⟨pure x, ultrafilter_pure⟩ /-- Monadic bind for ultra-filters, coming from the one on filters defined in terms of map and join.-/ def ultrafilter.bind (u : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := ⟨u.val.bind (λ a, (m a).val), ultrafilter_bind u.property (λ a, (m a).property)⟩ instance ultrafilter.has_pure : has_pure ultrafilter := ⟨@ultrafilter.pure⟩ instance ultrafilter.has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance ultrafilter.functor : functor ultrafilter := { map := @ultrafilter.map } instance ultrafilter.monad : monad ultrafilter := { map := @ultrafilter.map } instance ultrafilter.inhabited [inhabited α] : inhabited (ultrafilter α) := ⟨pure (default _)⟩ /-- The ultra-filter extending the cofinite filter. -/ noncomputable def hyperfilter : filter α := ultrafilter_of cofinite lemma hyperfilter_le_cofinite : @hyperfilter α ≤ cofinite := ultrafilter_of_le lemma is_ultrafilter_hyperfilter [infinite α] : is_ultrafilter (@hyperfilter α) := ultrafilter_of_spec.2 @[instance] lemma hyperfilter_ne_bot [infinite α] : ne_bot (@hyperfilter α) := is_ultrafilter_hyperfilter.1 @[simp] lemma bot_ne_hyperfilter [infinite α] : ⊥ ≠ @hyperfilter α := is_ultrafilter_hyperfilter.1.symm theorem nmem_hyperfilter_of_finite [infinite α] {s : set α} (hf : s.finite) : s ∉ @hyperfilter α := λ hy, have hx : sᶜ ∉ hyperfilter := λ hs, (ultrafilter_iff_compl_mem_iff_not_mem.mp is_ultrafilter_hyperfilter s).mp hs hy, have ht : sᶜ ∈ cofinite.sets := by show sᶜ ∈ {s | _}; rwa [set.mem_set_of_eq, compl_compl], hx $ hyperfilter_le_cofinite ht theorem compl_mem_hyperfilter_of_finite [infinite α] {s : set α} (hf : set.finite s) : sᶜ ∈ @hyperfilter α := (ultrafilter_iff_compl_mem_iff_not_mem.mp is_ultrafilter_hyperfilter s).mpr $ nmem_hyperfilter_of_finite hf theorem mem_hyperfilter_of_finite_compl [infinite α] {s : set α} (hf : set.finite sᶜ) : s ∈ @hyperfilter α := s.compl_compl ▸ compl_mem_hyperfilter_of_finite hf section local attribute [instance] filter.monad filter.is_lawful_monad instance ultrafilter.is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, subtype.eq (id_map f.val), pure_bind := assume α β a f, subtype.eq (pure_bind a (subtype.val ∘ f)), bind_assoc := assume α β γ f m₁ m₂, subtype.eq (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, subtype.eq (bind_pure_comp_eq_map f x.val) } end lemma ultrafilter.eq_iff_val_le_val {u v : ultrafilter α} : u = v ↔ u.val ≤ v.val := ⟨assume h, by rw h; exact le_refl _, assume h, by rw subtype.ext_iff_val; apply v.property.unique u.property.1 h⟩ lemma exists_ultrafilter_iff (f : filter α) : (∃ (u : ultrafilter α), u.val ≤ f) ↔ ne_bot f := ⟨assume ⟨u, uf⟩, ne_bot_of_le_ne_bot u.property.1 uf, assume h, let ⟨u, uf, hu⟩ := @exists_ultrafilter _ _ h in ⟨⟨u, hu⟩, uf⟩⟩ end filter
5240b8284ef512e0dd6fe7b0af8e64eef30d65ae
274261f7150b4ed5f1962f172c9357591be8a2b5
/src/downset.lean
02b4bfad026e3ed2570b42373dbd928362863ab1
[]
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
1,820
lean
import data.set import data.set.lattice import order.lattice import .subsets open classical @[simp] def downset (α : Type) [partial_order α] := {S : set α | ∀ (a : S) (b : α), b ≤ a → b ∈ S} variables {α : Type} [partial_order α] @[simp] lemma empty_is_downset : ∅ ∈ downset α := by simp @[simp] lemma full_set_is_downset : (⊤ : set α) ∈ downset α := (by simp; intros; trivial) @[simp] def down_closure : α → set α := λ a, {b | b ≤ a} lemma lower_downset (a : downset α) (x : a) (y : α) : y ≤ x → y ∈ (a : set α) := begin intro h₁, exact a.property x y h₁ end lemma down_closure_is_downset (a : α) : down_closure a ∈ downset α := begin simp, intros, rw set.mem_set_of_eq, transitivity; assumption end @[simp] lemma intersections_of_downsets_are_downsets (a b : downset α) : (a : set α) ∩ b ∈ downset α := begin intros, dunfold downset, simp, intros, simp, have h_1 : b_1 ∈ (a : set α) := lower_downset a ⟨ x, set.mem_of_mem_inter_left h ⟩ b_1 a_1, have h_2 : b_1 ∈ (b : set α) := lower_downset b ⟨ x, set.mem_of_mem_inter_right h ⟩ b_1 a_1, exact ⟨ h_1 , h_2 ⟩ end @[simp] lemma union_of_downsets_are_downsets (a b : downset α) : (a : set α) ∪ b ∈ downset α := begin intros, dunfold downset, intros x y h₁, simp, have h₂ : x.val ∈ (a : set α) ∨ x.val ∈ (b : set α) := @set.mem_or_mem_of_mem_union α x a b x.property, cases h₂, exact or.inl (lower_downset a ⟨x, h₂ ⟩ y h₁), exact or.inr (lower_downset b ⟨x, h₂ ⟩ y h₁) end instance bounded_lattice_of_downset : lattice.bounded_lattice (downset α) := s_bounded_lattice (downset α) (intersections_of_downsets_are_downsets) (union_of_downsets_are_downsets) (empty_is_downset) (full_set_is_downset)
1ca4e924a83ea0b0945ea951d5ea0e0cc2e279d9
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/ODE/gronwall.lean
06a3849e4cc4b0d88922b032299683bb57055aa2
[ "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
13,181
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.special_functions.exp_deriv /-! # Grönwall's inequality The main technical result of this file is the Grönwall-like inequality `norm_le_gronwall_bound_of_norm_deriv_right_le`. It states that if `f : ℝ → E` satisfies `∥f a∥ ≤ δ` and `∀ x ∈ [a, b), ∥f' x∥ ≤ K * ∥f x∥ + ε`, then for all `x ∈ [a, b]` we have `∥f x∥ ≤ δ * exp (K * x) + (ε / K) * (exp (K * x) - 1)`. Then we use this inequality to prove some estimates on the possible rate of growth of the distance between two approximate or exact solutions of an ordinary differential equation. The proofs are based on [Hubbard and West, *Differential Equations: A Dynamical Systems Approach*, Sec. 4.5][HubbardWest-ode], where `norm_le_gronwall_bound_of_norm_deriv_right_le` is called “Fundamental Inequality”. ## TODO - Once we have FTC, prove an inequality for a function satisfying `∥f' x∥ ≤ K x * ∥f x∥ + ε`, or more generally `liminf_{y→x+0} (f y - f x)/(y - x) ≤ K x * f x + ε` with any sign of `K x` and `f x`. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open metric set asymptotics filter real open_locale classical topological_space nnreal /-! ### Technical lemmas about `gronwall_bound` -/ /-- Upper bound used in several Grönwall-like inequalities. -/ noncomputable def gronwall_bound (δ K ε x : ℝ) : ℝ := if K = 0 then δ + ε * x else δ * exp (K * x) + (ε / K) * (exp (K * x) - 1) lemma gronwall_bound_K0 (δ ε : ℝ) : gronwall_bound δ 0 ε = λ x, δ + ε * x := funext $ λ x, if_pos rfl lemma gronwall_bound_of_K_ne_0 {δ K ε : ℝ} (hK : K ≠ 0) : gronwall_bound δ K ε = λ x, δ * exp (K * x) + (ε / K) * (exp (K * x) - 1) := funext $ λ x, if_neg hK lemma has_deriv_at_gronwall_bound (δ K ε x : ℝ) : has_deriv_at (gronwall_bound δ K ε) (K * (gronwall_bound δ K ε x) + ε) x := begin by_cases hK : K = 0, { subst K, simp only [gronwall_bound_K0, zero_mul, zero_add], convert ((has_deriv_at_id x).const_mul ε).const_add δ, rw [mul_one] }, { simp only [gronwall_bound_of_K_ne_0 hK], convert (((has_deriv_at_id x).const_mul K).exp.const_mul δ).add ((((has_deriv_at_id x).const_mul K).exp.sub_const 1).const_mul (ε / K)) using 1, simp only [id, mul_add, (mul_assoc _ _ _).symm, mul_comm _ K, mul_div_cancel' _ hK], ring } end lemma has_deriv_at_gronwall_bound_shift (δ K ε x a : ℝ) : has_deriv_at (λ y, gronwall_bound δ K ε (y - a)) (K * (gronwall_bound δ K ε (x - a)) + ε) x := begin convert (has_deriv_at_gronwall_bound δ K ε _).comp x ((has_deriv_at_id x).sub_const a), rw [id, mul_one] end lemma gronwall_bound_x0 (δ K ε : ℝ) : gronwall_bound δ K ε 0 = δ := begin by_cases hK : K = 0, { simp only [gronwall_bound, if_pos hK, mul_zero, add_zero] }, { simp only [gronwall_bound, if_neg hK, mul_zero, exp_zero, sub_self, mul_one, add_zero] } end lemma gronwall_bound_ε0 (δ K x : ℝ) : gronwall_bound δ K 0 x = δ * exp (K * x) := begin by_cases hK : K = 0, { simp only [gronwall_bound_K0, hK, zero_mul, exp_zero, add_zero, mul_one] }, { simp only [gronwall_bound_of_K_ne_0 hK, zero_div, zero_mul, add_zero] } end lemma gronwall_bound_ε0_δ0 (K x : ℝ) : gronwall_bound 0 K 0 x = 0 := by simp only [gronwall_bound_ε0, zero_mul] lemma gronwall_bound_continuous_ε (δ K x : ℝ) : continuous (λ ε, gronwall_bound δ K ε x) := begin by_cases hK : K = 0, { simp only [gronwall_bound_K0, hK], exact continuous_const.add (continuous_id.mul continuous_const) }, { simp only [gronwall_bound_of_K_ne_0 hK], exact continuous_const.add ((continuous_id.mul continuous_const).mul continuous_const) } end /-! ### Inequality and corollaries -/ /-- A Grönwall-like inequality: if `f : ℝ → ℝ` is continuous on `[a, b]` and satisfies the inequalities `f a ≤ δ` and `∀ x ∈ [a, b), liminf_{z→x+0} (f z - f x)/(z - x) ≤ K * (f x) + ε`, then `f x` is bounded by `gronwall_bound δ K ε (x - a)` on `[a, b]`. See also `norm_le_gronwall_bound_of_norm_deriv_right_le` for a version bounding `∥f x∥`, `f : ℝ → E`. -/ theorem le_gronwall_bound_of_liminf_deriv_right_le {f f' : ℝ → ℝ} {δ K ε : ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[>] x, (z - x)⁻¹ * (f z - f x) < r) (ha : f a ≤ δ) (bound : ∀ x ∈ Ico a b, f' x ≤ K * f x + ε) : ∀ x ∈ Icc a b, f x ≤ gronwall_bound δ K ε (x - a) := begin have H : ∀ x ∈ Icc a b, ∀ ε' ∈ Ioi ε, f x ≤ gronwall_bound δ K ε' (x - a), { assume x hx ε' hε', apply image_le_of_liminf_slope_right_lt_deriv_boundary hf hf', { rwa [sub_self, gronwall_bound_x0] }, { exact λ x, has_deriv_at_gronwall_bound_shift δ K ε' x a }, { assume x hx hfB, rw [← hfB], apply lt_of_le_of_lt (bound x hx), exact add_lt_add_left hε' _ }, { exact hx } }, assume x hx, change f x ≤ (λ ε', gronwall_bound δ K ε' (x - a)) ε, convert continuous_within_at_const.closure_le _ _ (H x hx), { simp only [closure_Ioi, left_mem_Ici] }, exact (gronwall_bound_continuous_ε δ K (x - a)).continuous_within_at end /-- A Grönwall-like inequality: if `f : ℝ → E` is continuous on `[a, b]`, has right derivative `f' x` at every point `x ∈ [a, b)`, and satisfies the inequalities `∥f a∥ ≤ δ`, `∀ x ∈ [a, b), ∥f' x∥ ≤ K * ∥f x∥ + ε`, then `∥f x∥` is bounded by `gronwall_bound δ K ε (x - a)` on `[a, b]`. -/ theorem norm_le_gronwall_bound_of_norm_deriv_right_le {f f' : ℝ → E} {δ K ε : ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (ha : ∥f a∥ ≤ δ) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ K * ∥f x∥ + ε) : ∀ x ∈ Icc a b, ∥f x∥ ≤ gronwall_bound δ K ε (x - a) := le_gronwall_bound_of_liminf_deriv_right_le (continuous_norm.comp_continuous_on hf) (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha bound /-- If `f` and `g` are two approximate solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in some time-dependent set `s t`, and assumes that the solutions never leave this set. -/ theorem dist_le_of_approx_trajectories_ODE_of_mem_set {v : ℝ → E → E} {s : ℝ → set E} {K : ℝ} (hv : ∀ t, ∀ x y ∈ s t, dist (v t x) (v t y) ≤ K * dist x y) {f g f' g' : ℝ → E} {a b : ℝ} {εf εg δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (f' t) (Ici t) t) (f_bound : ∀ t ∈ Ico a b, dist (f' t) (v t (f t)) ≤ εf) (hfs : ∀ t ∈ Ico a b, f t ∈ s t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (g' t) (Ici t) t) (g_bound : ∀ t ∈ Ico a b, dist (g' t) (v t (g t)) ≤ εg) (hgs : ∀ t ∈ Ico a b, g t ∈ s t) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ gronwall_bound δ K (εf + εg) (t - a) := begin simp only [dist_eq_norm] at ha ⊢, have h_deriv : ∀ t ∈ Ico a b, has_deriv_within_at (λ t, f t - g t) (f' t - g' t) (Ici t) t, from λ t ht, (hf' t ht).sub (hg' t ht), apply norm_le_gronwall_bound_of_norm_deriv_right_le (hf.sub hg) h_deriv ha, assume t ht, have := dist_triangle4_right (f' t) (g' t) (v t (f t)) (v t (g t)), rw [dist_eq_norm] at this, refine this.trans ((add_le_add (add_le_add (f_bound t ht) (g_bound t ht)) (hv t (f t) (hfs t ht) (g t) (hgs t ht))).trans _), rw [dist_eq_norm, add_comm] end /-- If `f` and `g` are two approximate solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in the whole space. -/ theorem dist_le_of_approx_trajectories_ODE {v : ℝ → E → E} {K : ℝ≥0} (hv : ∀ t, lipschitz_with K (v t)) {f g f' g' : ℝ → E} {a b : ℝ} {εf εg δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (f' t) (Ici t) t) (f_bound : ∀ t ∈ Ico a b, dist (f' t) (v t (f t)) ≤ εf) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (g' t) (Ici t) t) (g_bound : ∀ t ∈ Ico a b, dist (g' t) (v t (g t)) ≤ εg) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ gronwall_bound δ K (εf + εg) (t - a) := have hfs : ∀ t ∈ Ico a b, f t ∈ (@univ E), from λ t ht, trivial, dist_le_of_approx_trajectories_ODE_of_mem_set (λ t x hx y hy, (hv t).dist_le_mul x y) hf hf' f_bound hfs hg hg' g_bound (λ t ht, trivial) ha /-- If `f` and `g` are two exact solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in some time-dependent set `s t`, and assumes that the solutions never leave this set. -/ theorem dist_le_of_trajectories_ODE_of_mem_set {v : ℝ → E → E} {s : ℝ → set E} {K : ℝ} (hv : ∀ t, ∀ x y ∈ s t, dist (v t x) (v t y) ≤ K * dist x y) {f g : ℝ → E} {a b : ℝ} {δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hfs : ∀ t ∈ Ico a b, f t ∈ s t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (hgs : ∀ t ∈ Ico a b, g t ∈ s t) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ δ * exp (K * (t - a)) := begin have f_bound : ∀ t ∈ Ico a b, dist (v t (f t)) (v t (f t)) ≤ 0, by { intros, rw [dist_self] }, have g_bound : ∀ t ∈ Ico a b, dist (v t (g t)) (v t (g t)) ≤ 0, by { intros, rw [dist_self] }, assume t ht, have := dist_le_of_approx_trajectories_ODE_of_mem_set hv hf hf' f_bound hfs hg hg' g_bound hgs ha t ht, rwa [zero_add, gronwall_bound_ε0] at this, end /-- If `f` and `g` are two exact solutions of the same ODE, then the distance between them can't grow faster than exponentially. This is a simple corollary of Grönwall's inequality, and some people call this Grönwall's inequality too. This version assumes all inequalities to be true in the whole space. -/ theorem dist_le_of_trajectories_ODE {v : ℝ → E → E} {K : ℝ≥0} (hv : ∀ t, lipschitz_with K (v t)) {f g : ℝ → E} {a b : ℝ} {δ : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (ha : dist (f a) (g a) ≤ δ) : ∀ t ∈ Icc a b, dist (f t) (g t) ≤ δ * exp (K * (t - a)) := have hfs : ∀ t ∈ Ico a b, f t ∈ (@univ E), from λ t ht, trivial, dist_le_of_trajectories_ODE_of_mem_set (λ t x hx y hy, (hv t).dist_le_mul x y) hf hf' hfs hg hg' (λ t ht, trivial) ha /-- There exists only one solution of an ODE \(\dot x=v(t, x)\) in a set `s ⊆ ℝ × E` with a given initial value provided that RHS is Lipschitz continuous in `x` within `s`, and we consider only solutions included in `s`. -/ theorem ODE_solution_unique_of_mem_set {v : ℝ → E → E} {s : ℝ → set E} {K : ℝ} (hv : ∀ t, ∀ x y ∈ s t, dist (v t x) (v t y) ≤ K * dist x y) {f g : ℝ → E} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hfs : ∀ t ∈ Ico a b, f t ∈ s t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (hgs : ∀ t ∈ Ico a b, g t ∈ s t) (ha : f a = g a) : ∀ t ∈ Icc a b, f t = g t := begin assume t ht, have := dist_le_of_trajectories_ODE_of_mem_set hv hf hf' hfs hg hg' hgs (dist_le_zero.2 ha) t ht, rwa [zero_mul, dist_le_zero] at this end /-- There exists only one solution of an ODE \(\dot x=v(t, x)\) with a given initial value provided that RHS is Lipschitz continuous in `x`. -/ theorem ODE_solution_unique {v : ℝ → E → E} {K : ℝ≥0} (hv : ∀ t, lipschitz_with K (v t)) {f g : ℝ → E} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ t ∈ Ico a b, has_deriv_within_at f (v t (f t)) (Ici t) t) (hg : continuous_on g (Icc a b)) (hg' : ∀ t ∈ Ico a b, has_deriv_within_at g (v t (g t)) (Ici t) t) (ha : f a = g a) : ∀ t ∈ Icc a b, f t = g t := have hfs : ∀ t ∈ Ico a b, f t ∈ (@univ E), from λ t ht, trivial, ODE_solution_unique_of_mem_set (λ t x hx y hy, (hv t).dist_le_mul x y) hf hf' hfs hg hg' (λ t ht, trivial) ha
510e79d8fb141c7f442d09361b50ccd56be885b0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/control/bitraversable/instances.lean
1b6bb4da9175d2f2106c8ba9c80c9c454552336b
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,924
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.bitraversable.lemmas import control.traversable.lemmas /-! # Bitraversable instances > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides `bitraversable` instances for concrete bifunctors: * `prod` * `sum` * `functor.const` * `flip` * `function.bicompl` * `function.bicompr` ## References * Hackage: <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> ## Tags traversable bitraversable functor bifunctor applicative -/ universes u v w variables {t : Type u → Type u → Type u} [bitraversable t] section variables {F : Type u → Type u} [applicative F] /-- The bitraverse function for `α × β`. -/ def prod.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α × β → F (α' × β') | (x, y) := prod.mk <$> f x <*> f' y instance : bitraversable prod := { bitraverse := @prod.bitraverse } instance : is_lawful_bitraversable prod := by constructor; introsI; cases x; simp [bitraverse,prod.bitraverse] with functor_norm; refl open functor /-- The bitraverse function for `α ⊕ β`. -/ def sum.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α ⊕ β → F (α' ⊕ β') | (sum.inl x) := sum.inl <$> f x | (sum.inr x) := sum.inr <$> f' x instance : bitraversable sum := { bitraverse := @sum.bitraverse } instance : is_lawful_bitraversable sum := by constructor; introsI; cases x; simp [bitraverse, sum.bitraverse] with functor_norm; refl /-- The bitraverse function for `const`. It throws away the second map. -/ @[nolint unused_arguments] def const.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : const α β → F (const α' β') := f instance bitraversable.const : bitraversable const := { bitraverse := @const.bitraverse } instance is_lawful_bitraversable.const : is_lawful_bitraversable const := by constructor; introsI; simp [bitraverse,const.bitraverse] with functor_norm; refl /-- The bitraverse function for `flip`. -/ def flip.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : flip t α β → F (flip t α' β') := (bitraverse f' f : t β α → F (t β' α')) instance bitraversable.flip : bitraversable (flip t) := { bitraverse := @flip.bitraverse t _ } open is_lawful_bitraversable instance is_lawful_bitraversable.flip [is_lawful_bitraversable t] : is_lawful_bitraversable (flip t) := by constructor; intros; unfreezingI { casesm is_lawful_bitraversable t }; tactic.apply_assumption open bitraversable functor @[priority 10] instance bitraversable.traversable {α} : traversable (t α) := { traverse := @tsnd t _ _ } @[priority 10] instance bitraversable.is_lawful_traversable [is_lawful_bitraversable t] {α} : is_lawful_traversable (t α) := by { constructor; introsI; simp [traverse,comp_tsnd] with functor_norm, { refl }, { simp [tsnd_eq_snd_id], refl }, { simp [tsnd,binaturality,function.comp] with functor_norm } } end open bifunctor traversable is_lawful_traversable is_lawful_bitraversable open function (bicompl bicompr) section bicompl variables (F G : Type u → Type u) [traversable F] [traversable G] /-- The bitraverse function for `bicompl`. -/ def bicompl.bitraverse {m} [applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompl t F G α α' → m (bicompl t F G β β') := (bitraverse (traverse f) (traverse f') : t (F α) (G α') → m _) instance : bitraversable (bicompl t F G) := { bitraverse := @bicompl.bitraverse t _ F G _ _ } instance [is_lawful_traversable F] [is_lawful_traversable G] [is_lawful_bitraversable t] : is_lawful_bitraversable (bicompl t F G) := begin constructor; introsI; simp [bitraverse, bicompl.bitraverse, bimap, traverse_id, bitraverse_id_id, comp_bitraverse] with functor_norm, { simp [traverse_eq_map_id',bitraverse_eq_bimap_id], }, { revert x, dunfold bicompl, simp [binaturality,naturality_pf] } end end bicompl section bicompr variables (F : Type u → Type u) [traversable F] /-- The bitraverse function for `bicompr`. -/ def bicompr.bitraverse {m} [applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompr F t α α' → m (bicompr F t β β') := (traverse (bitraverse f f') : F (t α α') → m _) instance : bitraversable (bicompr F t) := { bitraverse := @bicompr.bitraverse t _ F _ } instance [is_lawful_traversable F] [is_lawful_bitraversable t] : is_lawful_bitraversable (bicompr F t) := begin constructor; introsI; simp [bitraverse,bicompr.bitraverse,bitraverse_id_id] with functor_norm, { simp [bitraverse_eq_bimap_id',traverse_eq_map_id'], refl }, { revert x, dunfold bicompr, intro, simp [naturality,binaturality'] } end end bicompr
3ebb0cd777f5456729d9cf4bad7da3d8dcec2561
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/spectrum_of_a_ring/structure_sheaf.lean
7c1b93d6e67db7e4b2862790a617074e83d10512
[]
no_license
alreadydone/lean-scheme
04c51ab08eca7ccf6c21344d45d202780fa667af
52d7624f57415eea27ed4dfa916cd94189221a1c
refs/heads/master
1,599,418,221,423
1,562,248,559,000
1,562,248,559,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,159
lean
/- The structure presheaf is a sheaf of rings. https://stacks.math.columbia.edu/tag/01HR -/ import topology.basic import to_mathlib.localization.localization_alt import sheaves.sheaf_on_standard_basis import spectrum_of_a_ring.induced_homeomorphism import spectrum_of_a_ring.quasi_compact import spectrum_of_a_ring.structure_presheaf import spectrum_of_a_ring.structure_sheaf_condition import spectrum_of_a_ring.structure_sheaf_locality import spectrum_of_a_ring.structure_sheaf_gluing universes u v local attribute [instance] classical.prop_decidable variables {R : Type u} [comm_ring R] open topological_space open localization_alt open localization open classical section structure_sheaf theorem structure_presheaf_on_basis_is_sheaf_on_standard_basis_cofinal_system : sheaf_on_standard_basis.is_sheaf_on_standard_basis_cofinal_system (D_fs_standard_basis R) (structure_presheaf_on_basis R).to_presheaf_on_basis := begin intros U BU OC Hγ, let f := some BU, let Rf := localization R (S U), have HRf : is_localization_data (powers f) (localization.of : R → Rf) := structure_presheaf.localization BU, let fi : OC.γ → R := λ i, classical.some (OC.BUis i), let Hfi : ∀ i, OC.Uis i = Spec.DO R (fi i) := λ i, classical.some_spec (OC.BUis i), let fi' : OC.γ → Rf := λ i, localization.of (fi i), let F : set Rf := set.range fi', -- Lemma: ⋃ D(gᵢ') = Spec Rf. have Hcov : ⋃₀ (Spec.D' '' F) = set.univ, { let φ : Spec Rf → Spec R := Zariski.induced localization.of, dsimp [F], apply set.eq_univ_of_univ_subset, rintros P HP, have H : φ P ∈ U, suffices : φ P ∈ Spec.DO R (f), rw some_spec BU, exact this, show φ P ∈ Spec.D'(f), rw ←phi_image_Df HRf, use P, split, { trivial, }, { refl, }, rw ←OC.Hcov at H, rcases H with ⟨UiS, ⟨⟨UiO, ⟨⟨i, Hi⟩, HUiO⟩⟩, HPUiS⟩⟩, use [φ ⁻¹' UiS], have Hin : φ ⁻¹' UiS ∈ Spec.D' '' set.range fi', rw [←HUiO, ←Hi, Hfi], dsimp only [Spec.DO], use [fi' i], split, { use [i], }, { rw [←Zariski.induced.preimage_D localization.of _], }, use [Hin], exact HPUiS, }, -- We deduce: 1 ∈ <fi> have Hone : (1 : Rf) ∈ ideal.span F, rw [←ideal.eq_top_iff_one, ←Spec.V.empty_iff_ideal_top, ←Spec.V.set_eq_span], rw [Spec.D'.union F, ←set.compl_compl set.univ, set.compl_univ] at Hcov, apply set.ext, intros x, rw set.ext_iff at Hcov, replace Hcov := Hcov x, iterate 2 { rw set.mem_compl_iff at Hcov, }, rw not_iff_not at Hcov, exact Hcov, -- α is injective. let αi := λ i, structure_presheaf_on_basis.res BU (OC.BUis i) (subset_covering i), let Rfi := λ i, localization R (S (OC.Uis i)), let α' := @α Rf _ _ Hγ Rfi _ αi _, have Hlocα : Π i, is_localization_data (powers (fi' i)) (αi i) := λ i, structure_presheaf.res.localization BU (OC.BUis i) (subset_covering i), have Hsc₁ := @standard_covering₁ Rf _ _ Hγ fi' Rfi _ αi _ Hlocα Hone, -- ker β = im α. let Rfij := λ i j, localization R (S ((OC.Uis i) ∩ (OC.Uis j))), let βij := λ i j, structure_presheaf_on_basis.res_to_inter BU (OC.BUis i) (OC.BUis j) (subset_covering i), have Hlocβ := λ i j, structure_presheaf.res_to_inter.localization BU (OC.BUis i) (OC.BUis j) (subset_covering i), let β' := @β Rf _ _ Hγ fi' Rfi _ αi _ Hlocα Rfij _ βij _ Hlocβ, have Hsc₂ := @standard_covering₂ Rf _ _ Hγ fi' Rfi _ αi _ Hlocα Rfij _ βij _ Hlocβ Hone, constructor, { -- Locality. intros s t Hst, dsimp [structure_presheaf_on_basis, coe_fn, has_coe_to_fun.coe] at s, dsimp [structure_presheaf_on_basis, coe_fn, has_coe_to_fun.coe] at t, apply Hsc₁, dsimp [α, αi], apply funext, intros i, rw ←structure_presheaf_on_basis.res_eq, exact (Hst i), }, { -- Gluing. intros s Hs, have Hβ : β' s = 0, simp [β', β, -sub_eq_add_neg, sub_eq_zero, β1, β2], apply funext, intro j, apply funext, intro k, have Hsjk := Hs j k, dsimp only [sheaf_on_standard_basis.res_to_inter_left] at Hsjk, dsimp only [sheaf_on_standard_basis.res_to_inter_right] at Hsjk, rw structure_presheaf_on_basis.res_eq at Hsjk, -- The restriction to the left is the unique localization map from R[1/fj] to R[1/fjfk]. let β1 := structure_presheaf_on_basis.res_to_inter_right (OC.BUis j) (OC.BUis k), let Hβ1 := @inverts_powers1 Rf _ _ Hγ fi' Rfij _ βij _ Hlocβ j k, have Hcompβ1 : βij j k = β1 ∘ (αi k), dsimp only [βij, β1, αi], dsimp only [structure_presheaf_on_basis.res_to_inter_right], dsimp only [structure_presheaf_on_basis.res_to_inter], erw ←structure_presheaf_on_basis.res_comp, refl, have Huniqueβ1 := is_localization_unique.of_eq (powers (fi' k)) (αi k) (Hlocα k) β1 (s k) (βij j k) Hβ1 Hcompβ1, rw Huniqueβ1, -- The restriction to the right is the unique localization map from R[1/fk] to R[1/fjfk]. let β2 := structure_presheaf_on_basis.res_to_inter_left (OC.BUis j) (OC.BUis k), let Hβ2 := @inverts_powers2 Rf _ _ Hγ fi' Rfij _ βij _ Hlocβ j k, have Hcompβ2 : βij j k = β2 ∘ (αi j), dsimp only [βij, β2, αi], dsimp only [structure_presheaf_on_basis.res_to_inter_left], dsimp only [structure_presheaf_on_basis.res_to_inter], erw ←structure_presheaf_on_basis.res_comp, refl, have Huniqueβ2 := is_localization_unique.of_eq (powers (fi' j)) (αi j) (Hlocα j) β2 (s j) (βij j k) Hβ2 Hcompβ2, rw Huniqueβ2, -- Now we have it in the desired form. exact Hsjk.symm, -- Use global section found. rcases ((Hsc₂ s).1 Hβ) with ⟨S, HS⟩, use S, intros i, replace HS := (congr_fun HS) i, dsimp [α, αi] at HS, rw structure_presheaf_on_basis.res_eq, exact HS, } end theorem structure_presheaf_on_basis_is_sheaf_on_basis : sheaf_on_standard_basis.is_sheaf_on_standard_basis (D_fs_standard_basis R) (structure_presheaf_on_basis R).to_presheaf_on_basis := begin apply sheaf_on_standard_basis.cofinal_systems_coverings_standard_case, { apply structure_presheaf_on_basis_is_compact, }, { apply structure_presheaf_on_basis_is_sheaf_on_standard_basis_cofinal_system, }, end -- Structure sheaf. def structure_sheaf.presheaf (R : Type u) [comm_ring R] := presheaf_of_rings_on_basis_to_presheaf_of_rings (D_fs_standard_basis R) (structure_presheaf_on_basis R) theorem strucutre_presheaf_is_sheaf_of_rings (R : Type u) [comm_ring R] : is_sheaf_of_rings (structure_sheaf.presheaf R) := begin apply extension_is_sheaf_of_rings, intros U BU OC, exact structure_presheaf_on_basis_is_sheaf_on_basis BU OC, end def structure_sheaf (R : Type u) [comm_ring R] : sheaf_of_rings (Spec R) := { F := structure_sheaf.presheaf R, locality := (strucutre_presheaf_is_sheaf_of_rings R).1, gluing := (strucutre_presheaf_is_sheaf_of_rings R).2, } end structure_sheaf
fa9f0c7e8ff143f28db4cb6a112f109266bd2d08
367134ba5a65885e863bdc4507601606690974c1
/src/data/real/cau_seq_completion.lean
e94562394011c6f97e4a1821dec4dd3d55ba8cfb
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
9,898
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Robert Y. Lewis Generalizes the Cauchy completion of (ℚ, abs) to the completion of a commutative ring with absolute value. -/ import data.real.cau_seq namespace cau_seq.completion open cau_seq section parameters {α : Type*} [linear_ordered_field α] parameters {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] def Cauchy := @quotient (cau_seq _ abv) cau_seq.equiv def mk : cau_seq _ abv → Cauchy := quotient.mk @[simp] theorem mk_eq_mk (f) : @eq Cauchy ⟦f⟧ (mk f) := rfl theorem mk_eq {f g} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat (x : β) : Cauchy := mk (const abv x) instance : has_zero Cauchy := ⟨of_rat 0⟩ instance : has_one Cauchy := ⟨of_rat 1⟩ instance : inhabited Cauchy := ⟨0⟩ theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl @[simp] theorem mk_eq_zero {f} : mk f = 0 ↔ lim_zero f := by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq; rwa sub_zero at this instance : has_add Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f + g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using add_lim_zero hf hg⟩ @[simp] theorem mk_add (f g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl instance : has_neg Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk (-f)) $ λ f₁ f₂ hf, quotient.sound $ by simpa [(≈), setoid.r] using neg_lim_zero hf⟩ @[simp] theorem mk_neg (f : cau_seq β abv) : -mk f = mk (-f) := rfl instance : has_mul Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f * g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, mul_add, mul_comm, add_assoc, sub_eq_add_neg] using add_lim_zero (mul_lim_zero_right g₁ hf) (mul_lim_zero_right f₂ hg)⟩ @[simp] theorem mk_mul (f g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl instance : has_sub Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f - g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ show ((f₁ - g₁) - (f₂ - g₂)).lim_zero, by simpa [sub_eq_add_neg, add_assoc, add_comm, add_left_comm] using sub_lim_zero hf hg⟩ @[simp] theorem mk_sub (f g : cau_seq β abv) : mk f - mk g = mk (f - g) := rfl theorem of_rat_add (x y : β) : of_rat (x + y) = of_rat x + of_rat y := congr_arg mk (const_add _ _) theorem of_rat_neg (x : β) : of_rat (-x) = -of_rat x := congr_arg mk (const_neg _) theorem of_rat_mul (x y : β) : of_rat (x * y) = of_rat x * of_rat y := congr_arg mk (const_mul _ _) private lemma zero_def : 0 = mk 0 := rfl private lemma one_def : 1 = mk 1 := rfl instance : comm_ring Cauchy := by refine { neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := _, add := (+), zero := 0, mul := (*), one := 1, .. }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [zero_def, one_def, mul_left_comm, mul_comm, mul_add, add_comm, add_left_comm, sub_eq_add_neg] } theorem of_rat_sub (x y : β) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) end open_locale classical section parameters {α : Type*} [linear_ordered_field α] parameters {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] local notation `Cauchy` := @Cauchy _ _ _ _ abv _ noncomputable instance : has_inv Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk $ if h : lim_zero f then 0 else inv f h) $ λ f g fg, begin have := lim_zero_congr fg, by_cases hf : lim_zero f, { simp [hf, this.1 hf, setoid.refl] }, { have hg := mt this.2 hf, simp [hf, hg], have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf), have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg), rw [mk_eq.2 fg, ← Ig] at If, rw mul_comm at Ig, rw [← mul_one (mk (inv f hf)), ← Ig, ← mul_assoc, If, mul_assoc, Ig, mul_one] } end⟩ @[simp] theorem inv_zero : (0 : Cauchy)⁻¹ = 0 := congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero] @[simp] theorem inv_mk {f} (hf) : (@mk α _ β _ abv _ f)⁻¹ = mk (inv f hf) := congr_arg mk $ by rw dif_neg lemma cau_seq_zero_ne_one : ¬ (0 : cau_seq _ abv) ≈ 1 := λ h, have lim_zero (1 - 0), from setoid.symm h, have lim_zero 1, by simpa, one_ne_zero $ const_lim_zero.1 this lemma zero_ne_one : (0 : Cauchy) ≠ 1 := λ h, cau_seq_zero_ne_one $ mk_eq.1 h protected theorem inv_mul_cancel {x : Cauchy} : x ≠ 0 → x⁻¹ * x = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.inv_mul_cancel hf) end noncomputable def field : field Cauchy := { inv := has_inv.inv, mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0], exists_pair_ne := ⟨0, 1, zero_ne_one⟩, inv_zero := inv_zero, .. Cauchy.comm_ring } local attribute [instance] field theorem of_rat_inv (x : β) : of_rat (x⁻¹) = ((of_rat x)⁻¹ : Cauchy) := congr_arg mk $ by split_ifs with h; try {simp [const_lim_zero.1 h]}; refl theorem of_rat_div (x y : β) : of_rat (x / y) = (of_rat x / of_rat y : Cauchy) := by simp only [div_eq_inv_mul, of_rat_inv, of_rat_mul] end end cau_seq.completion variables {α : Type*} [linear_ordered_field α] namespace cau_seq section variables (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv] class is_complete := (is_complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b) end section variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] variable [is_complete β abv] lemma complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b := is_complete.is_complete noncomputable def lim (s : cau_seq β abv) := classical.some (complete s) lemma equiv_lim (s : cau_seq β abv) : s ≈ const abv (lim s) := classical.some_spec (complete s) lemma eq_lim_of_const_equiv {f : cau_seq β abv} {x : β} (h : cau_seq.const abv x ≈ f) : x = lim f := const_equiv.mp $ setoid.trans h $ equiv_lim f lemma lim_eq_of_equiv_const {f : cau_seq β abv} {x : β} (h : f ≈ cau_seq.const abv x) : lim f = x := (eq_lim_of_const_equiv $ setoid.symm h).symm lemma lim_eq_lim_of_equiv {f g : cau_seq β abv} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g @[simp] lemma lim_const (x : β) : lim (const abv x) = x := lim_eq_of_equiv_const $ setoid.refl _ lemma lim_add (f g : cau_seq β abv) : lim f + lim g = lim (f + g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f + lim g) - (f + g)), by rw [const_add, add_sub_comm]; exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g)) lemma lim_mul_lim (f g : cau_seq β abv) : lim f * lim g = lim (f * g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f * lim g) - f * g), from have h : const abv (lim f * lim g) - f * g = (const abv (lim f) - f) * g + const abv (lim f) * (const abv (lim g) - g) := by simp [const_mul (lim f), mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm], by rw h; exact add_lim_zero (mul_lim_zero_left _ (setoid.symm (equiv_lim _))) (mul_lim_zero_right _ (setoid.symm (equiv_lim _))) lemma lim_mul (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) := by rw [← lim_mul_lim, lim_const] lemma lim_neg (f : cau_seq β abv) : lim (-f) = -lim f := lim_eq_of_equiv_const (show lim_zero (-f - const abv (-lim f)), by rw [const_neg, sub_neg_eq_add, add_comm, ← sub_eq_add_neg]; exact setoid.symm (equiv_lim f)) lemma lim_eq_zero_iff (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f := ⟨assume h, by have hf := equiv_lim f; rw h at hf; exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl), assume h, have h₁ : f = (f - const abv 0) := ext (λ n, by simp [sub_apply, const_apply]), by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩ end section variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] lemma lim_inv {f : cau_seq β abv} (hf : ¬ lim_zero f) : lim (inv f hf) = (lim f)⁻¹ := have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf, lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abv (lim f)⁻¹), from have h₁ : ∀ (g f : cau_seq β abv) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) := λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f]; exact mul_lim_zero_right _ (setoid.symm (cau_seq.inv_mul_cancel _)), have h₂ : lim_zero ((inv f hf - const abv (lim f)⁻¹) - (const abv (lim f) - f) * (inv f hf * const abv (lim f)⁻¹)) := by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add]; exact show lim_zero (inv f hf - const abv (lim f) * (inv f hf * const abv (lim f)⁻¹) - (const abv (lim f)⁻¹ - f * (inv f hf * const abv (lim f)⁻¹))), from sub_lim_zero (by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _) (by rw [← mul_assoc]; exact h₁ _ _ _), (lim_zero_congr h₂).mpr $ mul_lim_zero_left _ (setoid.symm (equiv_lim f)) end section variables [is_complete α abs] lemma lim_le {f : cau_seq α abs} {x : α} (h : f ≤ cau_seq.const abs x) : lim f ≤ x := cau_seq.const_le.1 $ cau_seq.le_of_eq_of_le (setoid.symm (equiv_lim f)) h lemma le_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x ≤ f) : x ≤ lim f := cau_seq.const_le.1 $ cau_seq.le_of_le_of_eq h (equiv_lim f) lemma lt_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x < f) : x < lim f := cau_seq.const_lt.1 $ cau_seq.lt_of_lt_of_eq h (equiv_lim f) lemma lim_lt {f : cau_seq α abs} {x : α} (h : f < cau_seq.const abs x) : lim f < x := cau_seq.const_lt.1 $ cau_seq.lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h end end cau_seq
03dc23f761d1057499db15d9c3197a9eddee90b3
26ac254ecb57ffcb886ff709cf018390161a9225
/src/topology/category/Top/basic.lean
4f9f87ebfa50aef91764cbb6f3f15c14f4770a38
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
1,408
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison, Mario Carneiro -/ import category_theory.concrete_category.unbundled_hom import topology.opens open category_theory open topological_space universe u /-- The category of topological spaces and continuous maps. -/ def Top : Type (u+1) := bundled topological_space namespace Top instance : unbundled_hom @continuous := ⟨@continuous_id, @continuous.comp⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] Top instance topological_space_unbundled (x : Top) : topological_space x := x.str instance hom_has_coe_to_fun (X Y : Top.{u}) : has_coe_to_fun (X ⟶ Y) := { F := _, coe := subtype.val } @[simp] lemma id_app (X : Top.{u}) (x : X) : @coe_fn (X ⟶ X) (Top.hom_has_coe_to_fun X X) (𝟙 X) x = x := rfl /-- Construct a bundled `Top` from the underlying type and the typeclass. -/ def of (X : Type u) [topological_space X] : Top := ⟨X⟩ instance : inhabited Top := ⟨Top.of empty⟩ /-- The discrete topology on any type. -/ def discrete : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊥⟩, map := λ X Y f, ⟨f, continuous_bot⟩ } /-- The trivial topology on any type. -/ def trivial : Type u ⥤ Top.{u} := { obj := λ X, ⟨X, ⊤⟩, map := λ X Y f, ⟨f, continuous_top⟩ } end Top
0f063f583b59b8bb52fb31de44868139040e69b5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/AbstractNestedProofs.lean
b76e65db624728710009bb18e5be9bc71523ccd3
[ "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
3,203
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Closure namespace Lean.Meta namespace AbstractNestedProofs def getLambdaBody (e : Expr) : Expr := match e with | .lam _ _ b _ => getLambdaBody b | _ => e def isNonTrivialProof (e : Expr) : MetaM Bool := do if !(← isProof e) then pure false else -- We consider proofs such as `fun x => f x a` as trivial. -- For example, we don't want to abstract the body of `def rfl` (getLambdaBody e).withApp fun f args => pure $ !f.isAtomic || args.any fun arg => !arg.isAtomic structure Context where baseName : Name structure State where nextIdx : Nat := 1 abbrev M := ReaderT Context $ MonadCacheT ExprStructEq Expr $ StateRefT State MetaM private def mkAuxLemma (e : Expr) : M Expr := do let ctx ← read let s ← get let lemmaName ← mkAuxName (ctx.baseName ++ `proof) s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1 } /- We turn on zeta-expansion to make sure we don't need to perform an expensive `check` step to identify which let-decls can be abstracted. If we design a more efficient test, we can avoid the eager zeta expasion step. It a benchmark created by @selsam, The extra `check` step was a bottleneck. -/ mkAuxTheoremFor lemmaName e (zeta := true) partial def visit (e : Expr) : M Expr := do if e.isAtomic then pure e else let visitBinders (xs : Array Expr) (k : M Expr) : M Expr := do let localInstances ← getLocalInstances let mut lctx ← getLCtx for x in xs do let xFVarId := x.fvarId! let localDecl ← xFVarId.getDecl let type ← visit localDecl.type let localDecl := localDecl.setType type let localDecl ← match localDecl.value? with | some value => let value ← visit value; pure <| localDecl.setValue value | none => pure localDecl lctx :=lctx.modifyLocalDecl xFVarId fun _ => localDecl withLCtx lctx localInstances k checkCache { val := e : ExprStructEq } fun _ => do if (← isNonTrivialProof e) then mkAuxLemma e else match e with | .lam .. => lambdaLetTelescope e fun xs b => visitBinders xs do mkLambdaFVars xs (← visit b) (usedLetOnly := false) | .letE .. => lambdaLetTelescope e fun xs b => visitBinders xs do mkLambdaFVars xs (← visit b) (usedLetOnly := false) | .forallE .. => forallTelescope e fun xs b => visitBinders xs do mkForallFVars xs (← visit b) | .mdata _ b => return e.updateMData! (← visit b) | .proj _ _ b => return e.updateProj! (← visit b) | .app .. => e.withApp fun f args => return mkAppN f (← args.mapM visit) | _ => pure e end AbstractNestedProofs /-- Replace proofs nested in `e` with new lemmas. The new lemmas have names of the form `mainDeclName.proof_<idx>` -/ def abstractNestedProofs (mainDeclName : Name) (e : Expr) : MetaM Expr := AbstractNestedProofs.visit e |>.run { baseName := mainDeclName } |>.run |>.run' { nextIdx := 1 } end Lean.Meta
e93e2b76d60d03902e4e4c364b8f171893b39569
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/monads/transformers.lean
3e6e907dfeb6af6d50b0f91c7b105e3973a9af92
[ "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
12,217
lean
/-! # Monad Transformers In the previous sections you learned about some handy monads [Option](monads.lean.md), [IO](monads.lean.md), [Reader](readers.lean.md), [State](states.lean.md) and [Except](except.lean.md), and you now know how to make your function use one of these, but what you do not yet know is how to make your function use multiple monads at once. For example, suppose you need a function that wants to access some Reader context and optionally throw an exception? This would require composition of two monads `ReaderM` and `Except` and this is what monad transformers are for. A monad transformer is fundamentally a wrapper type. It is generally parameterized by another monadic type. You can then run actions from the inner monad, while adding your own customized behavior for combining actions in this new monad. The common transformers add `T` to the end of an existing monad name. You will find `OptionT`, `ExceptT`, `ReaderT`, `StateT` but there is no transformer for `IO`. So generally if you need `IO` it becomes the innermost wrapped monad. In the following example we use `ReaderT` to provide some read only context to a function and this `ReaderT` transformer will wrap an `Except` monad. If all goes well the `requiredArgument` returns the value of a required argument and `optionalSwitch` returns true if the optional argument is present. -/ abbrev Arguments := List String def indexOf? [BEq α] (xs : List α) (s : α) (start := 0): Option Nat := match xs with | [] => none | a :: tail => if a == s then some start else indexOf? tail s (start+1) def requiredArgument (name : String) : ReaderT Arguments (Except String) String := do let args ← read let value := match indexOf? args name with | some i => if i + 1 < args.length then args[i+1]! else "" | none => "" if value == "" then throw s!"Command line argument {name} missing" return value def optionalSwitch (name : String) : ReaderT Arguments (Except String) Bool := do let args ← read return match (indexOf? args name) with | some _ => true | none => false #eval requiredArgument "--input" |>.run ["--input", "foo"] -- Except.ok "foo" #eval requiredArgument "--input" |>.run ["foo", "bar"] -- Except.error "Command line argument --input missing" #eval optionalSwitch "--help" |>.run ["--help"] -- Except.ok true #eval optionalSwitch "--help" |>.run [] -- Except.ok false /-! Notice that `throw` was available from the inner `Except` monad. The cool thing is you can switch this around and get the exact same result using `ExceptT` as the outer monad transformer and `ReaderM` as the wrapped monad. Try changing requiredArgument to `ExceptT String (ReaderM Arguments) Bool`. Note: the `|>.` notation is described in [Readers](readers.lean.md#the-reader-solution). ## Adding more layers Here's the best part about monad transformers. Since the result of a monad transformer is itself a monad, you can wrap it inside another transformer! Suppose you need to pass in some read only context like the command line arguments, update some read-write state (like program Config) and optionally throw an exception, then you could write this: -/ structure Config where help : Bool := false verbose : Bool := false input : String := "" deriving Repr abbrev CliConfigM := StateT Config (ReaderT Arguments (Except String)) def parseArguments : CliConfigM Bool := do let mut config ← get if (← optionalSwitch "--help") then throw "Usage: example [--help] [--verbose] [--input <input file>]" config := { config with verbose := (← optionalSwitch "--verbose"), input := (← requiredArgument "--input") } set config return true def main (args : List String) : IO Unit := do let config : Config := { input := "default"} match parseArguments |>.run config |>.run args with | Except.ok (_, c) => do IO.println s!"Processing input '{c.input}' with verbose={c.verbose}" | Except.error s => IO.println s #eval main ["--help"] -- Usage: example [--help] [--verbose] [--input <input file>] #eval main ["--input", "foo"] -- Processing input file 'foo' with verbose=false #eval main ["--verbose", "--input", "bar"] -- Processing input 'bar' with verbose=true /-! In this example `parseArguments` is actually three stacked monads, `StateM`, `ReaderM`, `Except`. Notice the convention of abbreviating long monadic types with an alias like `CliConfigM`. ## Monad Lifting Lean makes it easy to compose functions that use different monads using a concept of automatic monad lifting. You already used lifting in the above code, because you were able to compose `optionalSwitch` which has type `ReaderT Arguments (Except String) Bool` and call it from `parseArguments` which has a bigger type `StateT Config (ReaderT Arguments (Except String))`. This "just worked" because Lean did some magic with monad lifting. To give you a simpler example of this, suppose you have the following function: -/ def divide (x : Float ) (y : Float): ExceptT String Id Float := if y == 0 then throw "can't divide by zero" else pure (x / y) #eval divide 6 3 -- Except.ok 2.000000 #eval divide 1 0 -- Except.error "can't divide by zero" /-! Notice here we used the `ExceptT` transformer, but we composed it with the `Id` identity monad. This is then the same as writing `Except String Float` since the identity monad does nothing. Now suppose you want to count the number of times divide is called and store the result in some global state: -/ def divideCounter (x : Float) (y : Float) : StateT Nat (ExceptT String Id) Float := do modify fun s => s + 1 divide x y #eval divideCounter 6 3 |>.run 0 -- Except.ok (2.000000, 1) #eval divideCounter 1 0 |>.run 0 -- Except.error "can't divide by zero" /-! The `modify` function is a helper which makes it easier to use `modifyGet` from the `StateM` monad. But something interesting is happening here, `divideCounter` is returning the value of `divide`, but the types don't match, yet it works? This is monad lifting in action. You can see this more clearly with the following test: -/ def liftTest (x : Except String Float) : StateT Nat (Except String) Float := x #eval liftTest (divide 5 1) |>.run 3 -- Except.ok (5.000000, 3) /-! Notice that `liftTest` returned `x` without doing anything to it, yet that matched the return type `StateT Nat (Except String) Float`. Monad lifting is provided by monad transformers. if you `#print liftTest` you will see that Lean is implementing this using a call to a function named `monadLift` from the `MonadLift` type class: ```lean,ignore class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α ``` So `monadLift` is a function for lifting a computation from an inner `Monad m α ` to an outer `Monad n α`. You could replace `x` in `liftTest` with `monadLift x` if you want to be explicit about it. The StateT monad transformer defines an instance of `MonadLift` like this: ```lean @[inline] protected def lift {α : Type u} (t : m α) : StateT σ m α := fun s => do let a ← t; pure (a, s) instance : MonadLift m (StateT σ m) := ⟨StateT.lift⟩ ``` This means that any monad `m` can be wrapped in a `StateT` monad by using the function `fun s => do let a ← t; pure (a, s)` that takes state `s`, runs the inner monad action `t`, and returns the result and the new state in a pair `(a, s)` without making any changes to `s`. Because `MonadLift` is a type class, Lean can automatically find the required `monadLift` instances in order to make your code compile and in this way it was able to find the `StateT.lift` function and use it to wrap the result of `divide` so that the correct type is returned from `divideCounter`. If you have an instance `MonadLift m n` that means there is a way to turn a computation that happens inside of `m` into one that happens inside of `n` and (this is the key part) usually *without* the instance itself creating any additional data that feeds into the computation. This means you can in principle declare lifting instances from any monad to any other monad, it does not, however, mean that you should do this in all cases. You can get a very nice report on how all this was done by adding the line `set_option trace.Meta.synthInstance true in` before `divideCounter` and moving you cursor to the end of the first line after `do`. This was a lot of detail, but it is very important to understand how monad lifting works because it is used heavily in Lean programs. ## Transitive lifting There is also a transitive version of `MonadLift` called `MonadLiftT` which can lift multiple monad layers at once. In the following example we added another monad layer with `ReaderT String ...` and notice that `x` is also automatically lifted to match. -/ def liftTest2 (x : Except String Float) : ReaderT String (StateT Nat (Except String)) Float := x #eval liftTest2 (divide 5 1) |>.run "" |>.run 3 -- Except.ok (5.000000, 3) /-! The ReaderT monadLift is even simpler than the one for StateT: ```lean,ignore instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x ``` This lift operation creates a function that defines the required `ReaderT` input argument, but the inner monad doesn't know or care about `ReaderT` so the monadLift function throws it away with the `_` then calls the inner monad action `x`. This is a perfectly legal implementation of the `ReaderM` monad. ## Add your own Custom MonadLift This does not compile: -/ def main2 : IO Unit := do try let ret ← divideCounter 5 2 |>.run 0 IO.println (toString ret) catch e => IO.println e /-! saying: ``` typeclass instance problem is stuck, it is often due to metavariables ToString ?m.4786 ``` The reason is `divideCounter` returns the big `StateT Nat (ExceptT String Id) Float` and that type cannot be automatically lifted into the `main` return type of `IO Unit` unless you give it some help. The following custom `MonadLift` solves this problem: -/ def liftIO (t : ExceptT String Id α) : IO α := do match t with | .ok r => EStateM.Result.ok r | .error s => EStateM.Result.error s instance : MonadLift (ExceptT String Id) IO where monadLift := liftIO def main3 : IO Unit := do try let ret ← divideCounter 5 2 |>.run 0 IO.println (toString ret) catch e => IO.println e #eval main3 -- (2.500000, 1) /-! It turns out that the `IO` monad you see in your `main` function is based on the `EStateM.Result` type which is similar to the `Except` type but it has an additional return value. The `liftIO` function converts any `Except String α` into `IO α` by simply mapping the ok case of the `Except` to the `Result.ok` and the error case to the `Result.error`. ## Lifting ExceptT In the previous [Except](except.lean.md) section you saw functions that `throw` Except values. When you get all the way back up to your `main` function which has type `IO Unit` you have the same problem you had above, because `Except String Float` doesn't match even if you use a `try/catch`. -/ def main4 : IO Unit := do try let ret ← divide 5 0 IO.println (toString ret) -- lifting happens here. catch e => IO.println s!"Unhandled exception: {e}" #eval main4 -- Unhandled exception: can't divide by zero /-! Without the `liftIO` the `(toString ret)` expression would not compile with a similar error: ``` typeclass instance problem is stuck, it is often due to metavariables ToString ?m.6007 ``` So the general lesson is that if you see an error like this when using monads, check for a missing `MonadLift`. ## Summary Now that you know how to combine your monads together, you're almost done with understanding the key concepts of monads! You could probably go out now and start writing some pretty nice code! But to truly master monads, you should know how to make your own, and there's one final concept that you should understand for that. This is the idea of type "laws". Each of the structures you've learned so far has a series of laws associated with it. And for your instances of these classes to make sense, they should follow the laws! Check out [Monad Laws](laws.lean.md). -/
1c11aa0206882257b138d5aef3ab090422fb9de5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/witt_vector/teichmuller.lean
7553bdf899ddedb1e419ccc07637f3b87860ea7f
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
4,473
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import ring_theory.witt_vector.basic /-! # Teichmüller lifts This file defines `witt_vector.teichmuller`, a monoid hom `R →* 𝕎 R`, which embeds `r : R` as the `0`-th component of a Witt vector whose other coefficients are `0`. ## Main declarations - `witt_vector.teichmuller`: the Teichmuller map. - `witt_vector.map_teichmuller`: `witt_vector.teichmuller` is a natural transformation. - `witt_vector.ghost_component_teichmuller`: the `n`-th ghost component of `witt_vector.teichmuller p r` is `r ^ p ^ n`. ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ namespace witt_vector open mv_polynomial variables (p : ℕ) {R S : Type*} [hp : fact p.prime] [comm_ring R] [comm_ring S] local notation `𝕎` := witt_vector p -- type as `\bbW` /-- The underlying function of the monoid hom `witt_vector.teichmuller`. The `0`-th coefficient of `teichmuller_fun p r` is `r`, and all others are `0`. -/ def teichmuller_fun (r : R) : 𝕎 R := ⟨p, λ n, if n = 0 then r else 0⟩ /-! ## `teichmuller` is a monoid homomorphism On ghost components, it is clear that `teichmuller_fun` is a monoid homomorphism. But in general the ghost map is not injective. We follow the same strategy as for proving that the the ring operations on `𝕎 R` satisfy the ring axioms. 1. We first prove it for rings `R` where `p` is invertible, because then the ghost map is in fact an isomorphism. 2. After that, we derive the result for `mv_polynomial R ℤ`, 3. and from that we can prove the result for arbitrary `R`. -/ include hp private lemma ghost_component_teichmuller_fun (r : R) (n : ℕ) : ghost_component n (teichmuller_fun p r) = r ^ p ^ n := begin rw [ghost_component_apply, aeval_witt_polynomial, finset.sum_eq_single 0, pow_zero, one_mul, nat.sub_zero], { refl }, { intros i hi h0, convert mul_zero _, convert zero_pow _, { cases i, { contradiction }, { refl } }, { exact pow_pos hp.1.pos _ } }, { rw finset.mem_range, intro h, exact (h (nat.succ_pos n)).elim } end private lemma map_teichmuller_fun (f : R →+* S) (r : R) : map f (teichmuller_fun p r) = teichmuller_fun p (f r) := by { ext n, cases n, { refl }, { exact f.map_zero } } private lemma teichmuller_mul_aux₁ (x y : mv_polynomial R ℚ) : teichmuller_fun p (x * y) = teichmuller_fun p x * teichmuller_fun p y := begin apply (ghost_map.bijective_of_invertible p (mv_polynomial R ℚ)).1, rw ring_hom.map_mul, ext1 n, simp only [pi.mul_apply, ghost_map_apply, ghost_component_teichmuller_fun, mul_pow], end private lemma teichmuller_mul_aux₂ (x y : mv_polynomial R ℤ) : teichmuller_fun p (x * y) = teichmuller_fun p x * teichmuller_fun p y := begin refine map_injective (mv_polynomial.map (int.cast_ring_hom ℚ)) (mv_polynomial.map_injective _ int.cast_injective) _, simp only [teichmuller_mul_aux₁, map_teichmuller_fun, ring_hom.map_mul] end /-- The Teichmüller lift of an element of `R` to `𝕎 R`. The `0`-th coefficient of `teichmuller p r` is `r`, and all others are `0`. This is a monoid homomorphism. -/ noncomputable def teichmuller : R →* 𝕎 R := { to_fun := teichmuller_fun p, map_one' := begin ext ⟨⟩, { rw one_coeff_zero, refl }, { rw one_coeff_eq_of_pos _ _ _ (nat.succ_pos n), refl } end, map_mul' := begin intros x y, rcases counit_surjective R x with ⟨x, rfl⟩, rcases counit_surjective R y with ⟨y, rfl⟩, simp only [← map_teichmuller_fun, ← ring_hom.map_mul, teichmuller_mul_aux₂], end } @[simp] lemma teichmuller_coeff_zero (r : R) : (teichmuller p r).coeff 0 = r := rfl @[simp] lemma teichmuller_coeff_pos (r : R) : ∀ (n : ℕ) (hn : 0 < n), (teichmuller p r).coeff n = 0 | (n+1) _ := rfl. @[simp] lemma teichmuller_zero : teichmuller p (0:R) = 0 := by ext ⟨⟩; { rw zero_coeff, refl } /-- `teichmuller` is a natural transformation. -/ @[simp] lemma map_teichmuller (f : R →+* S) (r : R) : map f (teichmuller p r) = teichmuller p (f r) := map_teichmuller_fun _ _ _ /-- The `n`-th ghost component of `teichmuller p r` is `r ^ p ^ n`. -/ @[simp] lemma ghost_component_teichmuller (r : R) (n : ℕ) : ghost_component n (teichmuller p r) = r ^ p ^ n := ghost_component_teichmuller_fun _ _ _ end witt_vector