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
b23a643cdf40300cd7cb9df77186b37b59aa47be
af58757c0ea0692dc50b847d50227363bf9b45bc
/src/utils/finvec.lean
4a74b5433e3feb9b994e0361342d7532d66a2188
[]
no_license
alyata/fol_lean
b5ca6a8e0adbbe4362bb31ea2ad21d4b40f8fd0a
5f2846e3e88d26712556697dd87b323fe7e6289f
refs/heads/master
1,682,445,984,511
1,622,871,465,000
1,622,871,465,000
372,267,980
1
0
null
null
null
null
UTF-8
Lean
false
false
1,247
lean
import data.fin namespace fin def to_nat {n : ℕ} : fin n → ℕ := (fin.fin_to_nat n).coe def vec (n : ℕ) (U : Type) : Type := fin n → U def dvec (n : ℕ) (U : fin n → Type) : Type := ∀(k : fin n), U k def vec_to_dvec {n : ℕ} {U : Type} (v : vec n U) : dvec n (λ_, U) := v def map {U V: Type} {n : ℕ} (f : U → V) (v : vec n U) : vec n V := λi, f (v i) def max' {n : ℕ} (vec : vec (n + 1) ℕ) : fin (n + 1) → ℕ := λfn, subtype.rec_on fn (λm p, nat.rec_on m (vec 0) -- Base Case (λk ih, max (vec (k + 1)) ih) -- Inductive Case ) --The more readable version of max' but that causes timeouts when used for #reduce computation --| ⟨0, _⟩ := vec 0 --| ⟨k + 1, hk⟩ := max (vec (k + 1)) (max' ⟨k, k.lt_succ_self.trans hk⟩) def max {n : ℕ} : (vec n ℕ) → ℕ := match n with | 0 := λv, 0 | (k + 1) := λv, @max' k v (last k) end def unzip_left {n : ℕ} {U : Type} {V : U → Type} (v : vec n (Σx : U, V x)) : vec n U := λi, (v i).fst def unzip_right {n : ℕ} {U : Type} {V : U → Type} (v : vec n (Σx : U, V x)) : dvec n (V ∘ (unzip_left v)) := λi, (v i).snd def empty {U : Type} : vec 0 U := (λi, i.elim0) infixr `::` := cons end fin
9ad859a023d81d3167c93265cd82f94c322f4e90
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/data/basic_auto.lean
d5e3f1d3cf3c6ae4938844e50d9a44bff27ec707
[]
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,051
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.data.setoid import Mathlib.Lean3Lib.init.data.quot import Mathlib.Lean3Lib.init.data.bool.basic import Mathlib.Lean3Lib.init.data.punit import Mathlib.Lean3Lib.init.data.nat.basic import Mathlib.Lean3Lib.init.data.prod import Mathlib.Lean3Lib.init.data.sum.basic import Mathlib.Lean3Lib.init.data.sigma.basic import Mathlib.Lean3Lib.init.data.subtype.basic import Mathlib.Lean3Lib.init.data.fin.basic import Mathlib.Lean3Lib.init.data.list.basic import Mathlib.Lean3Lib.init.data.char.basic import Mathlib.Lean3Lib.init.data.string.basic import Mathlib.Lean3Lib.init.data.option.basic import Mathlib.Lean3Lib.init.data.set import Mathlib.Lean3Lib.init.data.unsigned.basic import Mathlib.Lean3Lib.init.data.ordering.basic import Mathlib.Lean3Lib.init.data.repr import Mathlib.Lean3Lib.init.data.to_string namespace Mathlib end Mathlib
4f6087ff60572782fc721bd8f103bca2627b4b16
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/apply3.lean
eb519fca6dc62c392153082dd4a9673f7e3024fb
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
612
lean
open tactic print "------- fapply version ----------" example (a : nat) : ∃ x : nat, x = a := by do c₁ ← return (expr.const `Exists.intro [level.of_nat 1]), fapply c₁, /- fapply adds all unassigned variables -/ trace_state, swap, /- swap witness and ?M = a -/ a ← get_local `a, mk_app `eq.refl [a] >>= exact print "------- apply version ----------" example (a : nat) : ∃ x : nat, x = a := by do c₁ ← return (expr.const `Exists.intro [level.of_nat 1]), /- apply does not add the goal |- nat -/ apply c₁, trace_state, a ← get_local `a, mk_app `eq.refl [a] >>= exact
75768ac4a88a39495fc5b18bcfaa27f2f1806bce
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/algebra/big_operators/basic.lean
968069b1da3dc70222619b3507b30c02d674c06d
[ "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
46,147
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.finset.fold import data.equiv.mul_add import tactic.abel /-! # Big operators In this file we define products and sums indexed by finite sets (specifically, `finset`). ## Notation We introduce the following notation, localized in `big_operators`. To enable the notation, use `open_locale big_operators`. Let `s` be a `finset α`, and `f : α → β` a function. * `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`) * `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`) * `∏ x, f x` is notation for `finset.prod finset.univ f` (assuming `α` is a `fintype` and `β` is a `comm_monoid`) * `∑ x, f x` is notation for `finset.sum finset.univ f` (assuming `α` is a `fintype` and `β` is an `add_comm_monoid`) -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace finset /-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive "`∑ x in s, f` is the sum of `f x` as `x` ranges over the elements of the finite set `s`."] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod end finset /- ## Operator precedence of `∏` and `∑` There is no established mathematical convention for the operator precedence of big operators like `∏` and `∑`. We will have to make a choice. Online discussions, such as https://math.stackexchange.com/q/185538/30839 seem to suggest that `∏` and `∑` should have the same precedence, and that this should be somewhere between `*` and `+`. The latter have precedence levels `70` and `65` respectively, and we therefore choose the level `67`. In practice, this means that parentheses should be placed as follows: ```lean ∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k → ∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k) ``` (Example taken from page 490 of Knuth's *Concrete Mathematics*.) -/ localized "notation `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators localized "notation `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators localized "notation `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators localized "notation `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators open_locale big_operators namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : (∏ x in s, f x) = s.fold (*) 1 f := rfl end finset @[to_additive] lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := by simp only [finset.prod_eq_multiset_prod, g.map_multiset_prod, multiset.map_map] @[to_additive] lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (g : β ≃* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.prod = (l.map f).prod := f.to_monoid_hom.map_list_prod l lemma ring_hom.map_list_sum [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.sum = (l.map f).sum := f.to_add_monoid_hom.map_list_sum l lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ) (s : multiset β) : f s.prod = (s.map f).prod := f.to_monoid_hom.map_multiset_prod s lemma ring_hom.map_multiset_sum [semiring β] [semiring γ] (f : β →+* γ) (s : multiset β) : f s.sum = (s.map f).sum := f.to_add_monoid_hom.map_multiset_sum s lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := g.to_monoid_hom.map_prod f s lemma ring_hom.map_sum [semiring β] [semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) := g.to_add_monoid_hom.map_sum f s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty {α : Type u} {f : α → β} : (∏ x in (∅:finset α), f x) = 1 := rfl @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `a` is in `s` or `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `a` is in `s` or `f a = 0`. "] lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := begin by_cases hm : a ∈ s, { simp_rw insert_eq_of_mem hm }, { rw [prod_insert hm, h hm, one_mul] }, end /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `f a = 0`."] lemma prod_insert_one [decidable_eq α] (h : f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := prod_insert_of_eq_one_if_not_mem (λ _, h) @[simp, to_additive] lemma prod_singleton : (∏ x in (singleton a), f x) = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : (∏ x in ({a, b} : finset α), f x) = f a * f b := by rw [prod_insert (not_mem_singleton.2 h), prod_singleton] @[simp, priority 1100] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, priority 1100] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : (∑ x in s, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive] prod_const_one @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (∏ x in (s.map e), f x) = ∏ x in s, f (e x) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_union_inter [decidable_eq α] : (∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : ∏ x in s.image sum.inl ∪ t.image sum.inr, sum.elim f g x = (∏ x in s, f x) * (∏ x in t, g x) := begin rw [prod_union, prod_image, prod_image], { simp only [sum.elim_inl, sum.elim_inr] }, { exact λ _ _ _ _, sum.inr.inj }, { exact λ _ _ _ _, sum.inl.inj }, { rintros i hi, erw [finset.mem_inter, finset.mem_image, finset.mem_image] at hi, rcases hi with ⟨⟨i, hi, rfl⟩, ⟨j, hj, H⟩⟩, cases H } end @[to_additive] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y)) → (∏ x in (s.bind t), f x) = ∏ x in s, ∏ i in t x, f i := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → disjoint (t x) (t y), from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have ∀y∈s, x ≠ y, from assume _ hy h, by rw [←h] at hy; contradiction, have ∀y∈s, disjoint (t x) (t y), from assume _ hy, hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hy) (this _ hy), have disjoint (t x) (finset.bind s t), from (disjoint_bind_right _ _ _).mpr this, by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (∏ x in s.product t, f x) = ∏ x in s, ∏ y in t, f (x, y) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [disjoint_iff_ne, mem_image], rintros _ _ _ _ h ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ ⟨_, _⟩ ⟨_, _, ⟨_, _⟩⟩ _, apply h, cc end /-- An uncurried version of `prod_product`. -/ @[to_additive] lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s.product t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y := by rw prod_product @[to_additive] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ := by classical; calc (∏ x in s.sigma t, f x) = ∏ x in s.bind (λa, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bind ... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x : prod_bind $ assume a₁ ha a₂ ha₂ h x hx, by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_to_fun] at hx, rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc } ... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ : prod_congr rfl $ λ _ _, prod_map _ _ _ @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = ∏ x in s.filter (λc', g c' = g c), h x) : (∏ x in s.image g, f x) = ∏ x in s, h x := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive] lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) := begin classical, apply finset.induction_on s, { simp only [prod_empty, prod_const_one] }, { intros _ _ H ih, simp only [prod_insert H, prod_mul_distrib, ih] } end @[to_additive] lemma prod_hom [comm_monoid γ] (s : finset α) {f : α → β} (g : β → γ) [is_monoid_hom g] : (∏ x in s, g (f x)) = g (∏ x in s, f x) := ((monoid_hom.of g).map_prod f s).symm @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x := by haveI := classical.dec_eq α; exact have ∏ x in s₂ \ s₁, f x = ∏ x in s₂ \ s₁, 1, from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive] lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) : (∏ x in (s.filter p), f x) = (∏ x in s, f x) := prod_subset (filter_subset _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ } -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (∏ x in (s.filter $ λx, f x ≠ 1), f x) = (∏ x in s, f x) := prod_filter_of_ne $ λ _ _, id @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) := calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = ∏ a in s, if p a then f a else 1 : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc (∏ x in s, f x) = ∏ x in {a}, f x : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ x in s, f x) := by haveI := classical.dec_eq α; exact calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] /-- A product over `s.subtype p` equals one over `s.filter p`. -/ @[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."] lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] : ∏ x in s.subtype p, f x = ∏ x in s.filter p, f x := begin conv_lhs { erw ←prod_map (s.subtype p) (function.embedding.subtype _) f }, exact prod_congr (subtype_map _) (λ x hx, rfl) end /-- If all elements of a `finset` satisfy the predicate `p`, a product over `s.subtype p` equals that product over `s`. -/ @[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum over `s.subtype p` equals that sum over `s`."] lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x := by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h] /-- A product of a function over a `finset` in a subtype equals a product in the main type of a function that agrees with the first function on that `finset`. -/ @[to_additive "A sum of a function over a `finset` in a subtype equals a sum in the main type of a function that agrees with the first function on that `finset`."] lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β} {g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) : ∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x := begin rw finset.prod_map, exact finset.prod_congr rfl h end @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : (∏ x in s, f x) = 1 := calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h ... = 1 : finset.prod_const_one @[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ) (h : γ → β) : (∏ x in s, h (if hx : p x then f x hx else g x hx)) = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) := by letI := classical.dec_eq α; exact calc ∏ x in s, h (if hx : p x then f x hx else g x hx) = ∏ x in s.filter p ∪ s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx) : by rw [filter_union_filter_neg_eq] ... = (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) * (∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) : prod_union (by simp [disjoint_right] {contextual := tt}) ... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) : congr_arg2 _ prod_attach.symm prod_attach.symm ... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) : congr_arg2 _ (prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2))) (prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2))) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : (∏ x in s, h (if p x then f x else g x)) = (∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) := trans (prod_apply_dite _ _ _) (congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g))) @[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = (∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) * (∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) := by simp [prod_apply_dite _ _ (λ x, x)] @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : (∏ x in s, if p x then f x else g x) = (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[to_additive] lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) : ∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i := prod_congr rfl $ λ i hi, if_pos hi @[simp, to_additive] lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) : (∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) : (∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq s a (λ x _, b x) /-- When a product is taken over a conditional whose condition is an equality test on the index and whose alternative is 1, then the product's value is either the term at that index or `1`. The difference with `prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq' s a (λ x _, b x) /-- Reorder a product. The difference with `prod_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. -/ @[to_additive] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂) (i_surj : ∀b∈t, ∃a ha, b = i a ha) : (∏ x in s, f x) = (∏ x in t, g x) := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) /-- Reorder a product. The difference with `prod_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. -/ @[to_additive] lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, γ) (hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha)) (j : Πa∈t, α) (hj : ∀a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a) (right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : (∏ x in s, f x) = (∏ x in t, g x) := begin refine prod_bij i hi h _ _, {intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,}, {intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,}, end @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : (∏ x in s, f x) = (∏ x in t, g x) := by classical; exact calc (∏ x in s, f x) = ∏ x in (s.filter $ λx, f x ≠ 1), f x : prod_filter_ne_one.symm ... = ∏ x in (t.filter $ λx, g x ≠ 1), g x : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = (∏ x in t, g x) : prod_filter_ne_one @[to_additive] lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃a∈s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1) (hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i := begin rw [← prod_sdiff h, prod_eq_one hg, one_mul], exact prod_congr rfl hfg end lemma sum_range_succ {β} [add_comm_monoid β] (f : ℕ → β) (n : ℕ) : (∑ x in range (n + 1), f x) = f n + (∑ x in range n, f x) := by rw [range_succ, sum_insert not_mem_range_self] @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (∏ x in range (n + 1), f x) = f n * (∏ x in range n, f x) := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ @[to_additive] lemma prod_range_zero (f : ℕ → β) : (∏ k in range 0, f k) = 1 := by rw [range_zero, prod_empty] lemma prod_range_one (f : ℕ → β) : (∏ k in range 1, f k) = f 0 := by { rw [range_one], apply @prod_singleton ℕ β 0 f } lemma sum_range_one {δ : Type*} [add_comm_monoid δ] (f : ℕ → δ) : (∑ k in range 1, f k) = f 0 := @prod_range_one (multiplicative δ) _ f attribute [to_additive finset.sum_range_one] prod_range_one open multiset lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) : s.prod = ∏ m in s.to_finset, m ^ (s.count m) := begin apply s.induction_on, { rw [prod_zero, to_finset_zero, finset.prod_empty] }, intros a s ih, by_cases has : a ∈ s.to_finset, { rw [prod_cons, to_finset_cons, finset.insert_eq_of_mem has, ih, ← finset.insert_erase has, finset.prod_insert (finset.not_mem_erase _ _), finset.prod_insert (finset.not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ], congr' 1, refine finset.prod_congr rfl (λ x hx, _), rw [count_cons_of_ne (finset.ne_of_mem_erase hx)] }, rw [prod_cons, to_finset_cons, finset.prod_insert has, count_cons_self], rw mem_to_finset at has, rw [count_eq_zero_of_not_mem has, pow_one], congr' 1, rw ih, refine finset.prod_congr rfl (λ x hx, _), rw mem_to_finset at hx, rw count_cons_of_ne, rintro rfl, exact has hx end /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := begin classical, induction s using finset.induction with x hx s hs, simpa, rw finset.prod_insert, swap, assumption, apply p_mul, apply p_s, simp, apply hs, intros a ha, apply p_s, simp [ha], end /-- For any product along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking ratios of adjacent terms. This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/ lemma prod_range_induction {M : Type*} [comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) : ∏ k in finset.range n, f k = s n := begin induction n with k hk, { simp only [h0, finset.prod_range_zero] }, { simp only [hk, finset.prod_range_succ, h, mul_comm] } end /-- For any sum along `{0, ..., n-1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking differences of adjacent terms. This is a discrete analogue of the fundamental theorem of calculus. -/ lemma sum_range_induction {M : Type*} [add_comm_monoid M] (f s : ℕ → M) (h0 : s 0 = 0) (h : ∀ n, s (n + 1) = s n + f n) (n : ℕ) : ∑ k in finset.range n, f k = s n := @prod_range_induction (multiplicative M) _ f s h0 h n /-- A telescoping sum along `{0, ..., n-1}` of an additive commutative group valued function reduces to the difference of the last and first terms.-/ lemma sum_range_sub {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := by { apply sum_range_induction; abel, simp } lemma sum_range_sub' {G : Type*} [add_comm_group G] (f : ℕ → G) (n : ℕ) : ∑ i in range n, (f i - f (i+1)) = f 0 - f n := by { apply sum_range_induction; abel, simp } /-- A telescoping product along `{0, ..., n-1}` of a commutative group valued function reduces to the ratio of the last and first factors.-/ @[to_additive] lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f (i+1) * (f i)⁻¹) = f n * (f 0)⁻¹ := by apply @sum_range_sub (additive M) @[to_additive] lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f i * (f (i+1))⁻¹) = (f 0) * (f n)⁻¹ := by apply @sum_range_sub' (additive M) /-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of the last and first terms when the function we are summing is monotone. -/ lemma sum_range_sub_of_monotone {f : ℕ → ℕ} (h : monotone f) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := begin refine sum_range_induction _ _ (nat.sub_self _) (λ n, _) _, have h₁ : f n ≤ f (n+1) := h (nat.le_succ _), have h₂ : f 0 ≤ f n := h (nat.zero_le _), rw [←nat.sub_add_comm h₂, nat.add_sub_cancel' h₁], end @[simp] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : (∏ x in s, f x ^ n) = (∏ x in s, f x) ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [mul_pow] {contextual := tt}) -- `to_additive` fails on this lemma, so we prove it manually below lemma prod_flip {n : ℕ} (f : ℕ → β) : (∏ r in range (n + 1), f (n - r)) = (∏ k in range (n + 1), f k) := begin induction n with n ih, { rw [prod_range_one, prod_range_one] }, { rw [prod_range_succ', prod_range_succ _ (nat.succ n), mul_comm], simp [← ih] } end @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), (∏ x in s, f x) = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx])) /-- The product of the composition of functions `f` and `g`, is the product over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b` -/ lemma prod_comp [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card := calc ∏ a in s, f (g a) = ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) : prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) (by finish) ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b : prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt})) ... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card : prod_congr rfl (λ _ _, prod_const _) @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : (∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } @[to_additive] lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) : (∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) := by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] } @[to_additive] lemma mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : f i * (∏ x in s \ {i}, f x) = ∏ x in s, f x := by { convert s.prod_inter_mul_prod_diff {i} f, simp [h] } /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (∏ a in s.filter (λy, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 := begin suffices : ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y = (∏ x in s, f x), { rw [←this, ←finset.prod_eq_one], intros xbar xbar_in_s, rcases (mem_image).mp xbar_in_s with ⟨x, x_in_s, xbar_eq_x⟩, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s }, apply finset.prod_image' f, intros, refl end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) := begin apply prod_congr rfl (λj hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } /-- If a product of a `finset` of size at most 1 has a given value, so do the terms in that product. -/ lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β} (h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw prod_singleton at h, exact h } end /-- If a sum of a `finset` of size at most 1 has a given value, so do the terms in that sum. -/ lemma eq_of_card_le_one_of_sum_eq [add_comm_monoid γ] {s : finset α} (hc : s.card ≤ 1) {f : α → γ} {b : γ} (h : ∑ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw sum_singleton at h, exact h } end attribute [to_additive eq_of_card_le_one_of_sum_eq] eq_of_card_le_one_of_prod_eq /-- If a function applied at a point is 1, a product is unchanged by removing that point, if present, from a `finset`. -/ @[to_additive "If a function applied at a point is 0, a sum is unchanged by removing that point, if present, from a `finset`."] lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) : ∏ x in s.erase a, f x = ∏ x in s, f x := begin rw ←sdiff_singleton_eq_erase, apply prod_subset sdiff_subset_self, intros x hx hnx, rw sdiff_singleton_eq_erase at hnx, rwa eq_of_mem_of_not_mem_erase hx hnx end /-- If a product is 1 and the function is 1 except possibly at one point, it is 1 everywhere on the `finset`. -/ @[to_additive "If a sum is 0 and the function is 0 except possibly at one point, it is 0 everywhere on the `finset`."] lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1) (h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 := begin intros x hx, classical, by_cases h : x = a, { rw h, rw h at hx, rw [←prod_subset (singleton_subset_iff.2 hx) (λ t ht ha, h1 t ht (not_mem_singleton.1 ha)), prod_singleton] at hp, exact hp }, { exact h1 x hx h } end lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp end comm_monoid /-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s` is the sum of the products of `g` and `h`. -/ lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j) (h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i := by { classical, simp_rw [← mul_prod_diff_singleton hi, ← h1, right_distrib], congr' 2; apply prod_congr rfl; simpa } lemma sum_update_of_mem [add_comm_monoid β] [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∑ x in s, function.update f i b x) = b + (∑ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, sum_piecewise], simp [h] } attribute [to_additive] prod_update_of_mem lemma sum_nsmul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : (∑ x in s, n •ℕ (f x)) = n •ℕ ((∑ x in s, f x)) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive sum_nsmul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : (∑ x in s, b) = s.card •ℕ b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive] prod_const lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 := by simp lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀x ∈ s, f x = m) : (∑ x in s, f x) = card s * m := begin rw [← nat.nsmul_eq_mul, ← sum_const], apply sum_congr rfl h₁ end @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [semiring β] {hp : decidable_pred p} : (∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] @[norm_cast] lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) := (nat.cast_add_monoid_hom β).map_sum f s lemma sum_comp [add_comm_monoid β] [decidable_eq γ] {s : finset α} (f : γ → β) (g : α → γ) : ∑ a in s, f (g a) = ∑ b in s.image g, (s.filter (λ a, g a = b)).card •ℕ (f b) := @prod_comp _ (multiplicative β) _ _ _ _ _ _ attribute [to_additive "The sum of the composition of functions `f` and `g`, is the sum over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`"] prod_comp lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (∑ i in range (n + 1), f i) = (∑ i in range n, f (i + 1)) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive] prod_range_succ' lemma sum_flip [add_comm_monoid β] {n : ℕ} (f : ℕ → β) : (∑ i in range (n + 1), f (n - i)) = (∑ i in range (n + 1), f i) := @prod_flip (multiplicative β) _ _ _ attribute [to_additive] prod_flip section comm_group variables [comm_group β] @[simp, to_additive] lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := s.prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = ∑ a in s, card (t a) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bind t).card = ∑ u in s, card (t u) := calc (s.bind t).card = ∑ i in s.bind t, 1 : by simp ... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bind h ... = ∑ u in s, card (t u) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ ∑ a in s, (t a).card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ ∑ a in insert a s, card (t a) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card := by letI := classical.dec_eq α; exact calc s.card = ((s.image f).bind (λ a, s.filter (λ x, f x = a))).card : congr_arg _ (finset.ext $ λ x, ⟨λ hs, mem_bind.2 ⟨f x, mem_image_of_mem _ hs, mem_filter.2 ⟨hs, rfl⟩⟩, λ h, let ⟨a, ha₁, ha₂⟩ := mem_bind.1 h in by convert filter_subset s ha₂⟩) ... = ∑ a in s.image f, (s.filter (λ x, f x = a)).card : card_bind (by simp [disjoint_left, finset.ext_iff] {contextual := tt}) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (∑ a in s, f a) = ∑ a in s, gsmul z (f a) := (s.sum_hom (gsmul z)).symm @[simp] lemma sum_sub_distrib [add_comm_group β] : ∑ x in s, (f x - g x) = (∑ x in s, f x) - (∑ x in s, g x) := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section prod_eq_zero variables [comm_monoid_with_zero β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 := by haveI := classical.dec_eq α; calc (∏ x in s, f x) = ∏ x in insert a (erase s a), f x : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] : ∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 := begin split_ifs, { apply prod_eq_one, intros i hi, rw if_pos (h i hi) }, { push_neg at h, rcases h with ⟨i, hi, hq⟩, apply prod_eq_zero hi, rw [if_neg hq] }, end variables [nontrivial β] [no_zero_divisors β] lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃a∈s, f a = 0) := begin classical, apply finset.induction_on s, exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩, assume a s ha ih, rw [prod_insert ha, mul_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) := by { rw [ne, prod_eq_zero_iff], push_neg } end prod_eq_zero end finset namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : (∑ a in s.to_finset, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (∑ x in to_finset (a :: s), count x (a :: s)) = ∑ x in to_finset (a :: s), ((if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0, { rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} : count a (∑ x in s, f x) = ∑ x in s, count a (f x) := by { dunfold finset.sum, rw count_sum } lemma to_finset_sum_count_smul_eq (s : multiset α) : (∑ a in s.to_finset, s.count a •ℕ (a :: 0)) = s := begin apply ext', intro b, rw count_sum', have h : count b s = count b (count b s •ℕ (b :: 0)), { rw [singleton_coe, count_smul, ← singleton_coe, count_singleton, mul_one] }, rw h, clear h, apply finset.sum_eq_single b, { intros c h hcb, rw count_smul, convert mul_zero (count c s), apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) }, { intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_smul, zero_mul]} end theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ} (h : ∀ (a : α), k ∣ multiset.count a s) : ∃ (u : multiset α), s = k •ℕ u := begin use ∑ a in s.to_finset, (s.count a / k) •ℕ (a :: 0), have h₂ : ∑ (x : α) in s.to_finset, k •ℕ (count x s / k •ℕ (x :: 0)) = ∑ (x : α) in s.to_finset, count x s •ℕ (x :: 0), { refine congr_arg s.to_finset.sum _, apply funext, intro x, rw [← mul_nsmul, nat.mul_div_cancel' (h x)] }, rw [← finset.sum_nsmul, h₂, to_finset_sum_count_smul_eq] end end multiset
0cf3eb7a5191c7215020d090ab39546cdb06a5df
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/algebra/order_bigops.lean
9e3c54ab903fe9967b35af0f5075df6486f99941
[ "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
18,997
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Min and max over finite sets. To support constructive theories, we start with the class decidable_linear_ordered_cancel_comm_monoid, because: (1) We need a decidable linear order to have min and max (2) We need a default element for min and max over the empty set, and max empty = 0 is the right choice for nat. (3) All our number classes are instances. We can define variants of Min and Max if needed. -/ import .group_bigops .ordered_ring variables {A B : Type} section variable [decidable_linear_order A] definition max_comm_semigroup : comm_semigroup A := ⦃ comm_semigroup, mul := max, mul_assoc := max.assoc, mul_comm := max.comm ⦄ definition min_comm_semigroup : comm_semigroup A := ⦃ comm_semigroup, mul := min, mul_assoc := min.assoc, mul_comm := min.comm ⦄ end /- finset versions -/ namespace finset section deceq_A variable [decidable_eq A] section decidable_linear_ordered_cancel_comm_monoid_B variable [decidable_linear_ordered_cancel_comm_monoid B] section max_comm_semigroup local attribute max_comm_semigroup [instance] open Prod_semigroup definition Max (s : finset A) (f : A → B) : B := Prod_semigroup 0 s f notation `Max` binders `∈` s `, ` r:(scoped f, Max s f) := r proposition Max_empty (f : A → B) : (Max x ∈ ∅, f x) = 0 := !Prod_semigroup_empty proposition Max_singleton (f : A → B) (a : A) : (Max x ∈ '{a}, f x) = f a := !Prod_semigroup_singleton proposition Max_insert_insert (f : A → B) {a₁ a₂ : A} {s : finset A} : a₂ ∉ s → a₁ ∉ insert a₂ s → (Max x ∈ insert a₁ (insert a₂ s), f x) = max (f a₁) (Max x ∈ insert a₂ s, f x) := !Prod_semigroup_insert_insert proposition Max_insert (f : A → B) {a : A} {s : finset A} (anins : a ∉ s) (sne : s ≠ ∅) : (Max x ∈ insert a s, f x) = max (f a) (Max x ∈ s, f x) := !Prod_semigroup_insert anins sne end max_comm_semigroup proposition Max_pair (f : A → B) (a₁ a₂ : A) : (Max x ∈ '{a₁, a₂}, f x) = max (f a₁) (f a₂) := decidable.by_cases (suppose a₁ = a₂, by rewrite [this, pair_eq_singleton, max_self] ) (suppose a₁ ≠ a₂, have a₁ ∉ '{a₂}, by rewrite [mem_singleton_iff]; apply this, using this, by rewrite [Max_insert f this !singleton_ne_empty]) proposition le_Max (f : A → B) {a : A} {s : finset A} (H : a ∈ s) : f a ≤ Max x ∈ s, f x := begin induction s with a' s' a'nins' ih, {exact false.elim (not_mem_empty a H)}, cases (decidable.em (s' = ∅)) with s'empty s'nempty, {rewrite [s'empty at *, Max_singleton, eq_of_mem_singleton H]}, rewrite [Max_insert f a'nins' s'nempty], cases (eq_or_mem_of_mem_insert H) with aeqa' ains', {rewrite aeqa', apply le_max_left}, apply le.trans (ih ains') !le_max_right end proposition Max_le (f : A → B) {s : finset A} {b : B} (sne : s ≠ ∅) (H : ∀ a, a ∈ s → f a ≤ b) : (Max x ∈ s, f x) ≤ b := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'nempty, {rewrite [s'empty, Max_singleton], exact H a' !mem_insert}, rewrite [Max_insert f a'nins' s'nempty], apply max_le (H a' !mem_insert), apply ih s'nempty, intro a H', exact H a (mem_insert_of_mem a' H') end proposition Max_add_right (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) : (Max x ∈ s, f x + b) = (Max x ∈ s, f x) + b := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'ne, {rewrite [s'empty, Max_singleton]}, rewrite [*Max_insert _ a'nins' s'ne, ih s'ne, max_add_add_right] end proposition Max_add_left (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) : (Max x ∈ s, b + f x) = b + (Max x ∈ s, f x) := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'ne, {rewrite [s'empty, Max_singleton]}, rewrite [*Max_insert _ a'nins' s'ne, ih s'ne, max_add_add_left] end section min_comm_semigroup local attribute min_comm_semigroup [instance] open Prod_semigroup definition Min (s : finset A) (f : A → B) : B := Prod_semigroup 0 s f notation `Min` binders `∈` s `, ` r:(scoped f, Min s f) := r proposition Min_empty (f : A → B) : (Min x ∈ ∅, f x) = 0 := !Prod_semigroup_empty proposition Min_singleton (f : A → B) (a : A) : (Min x ∈ '{a}, f x) = f a := !Prod_semigroup_singleton proposition Min_insert_insert (f : A → B) {a₁ a₂ : A} {s : finset A} : a₂ ∉ s → a₁ ∉ insert a₂ s → (Min x ∈ insert a₁ (insert a₂ s), f x) = min (f a₁) (Min x ∈ insert a₂ s, f x) := !Prod_semigroup_insert_insert proposition Min_insert (f : A → B) {a : A} {s : finset A} (anins : a ∉ s) (sne : s ≠ ∅) : (Min x ∈ insert a s, f x) = min (f a) (Min x ∈ s, f x) := !Prod_semigroup_insert anins sne end min_comm_semigroup proposition Min_pair (f : A → B) (a₁ a₂ : A) : (Min x ∈ '{a₁, a₂}, f x) = min (f a₁) (f a₂) := decidable.by_cases (suppose a₁ = a₂, by rewrite [this, pair_eq_singleton, min_self] ) (suppose a₁ ≠ a₂, have a₁ ∉ '{a₂}, by rewrite [mem_singleton_iff]; apply this, using this, by rewrite [Min_insert f this !singleton_ne_empty]) proposition Min_le (f : A → B) {a : A} {s : finset A} (H : a ∈ s) : (Min x ∈ s, f x) ≤ f a := begin induction s with a' s' a'nins' ih, {exact false.elim (not_mem_empty a H)}, cases (decidable.em (s' = ∅)) with s'empty s'nempty, {rewrite [s'empty at *, Min_singleton, eq_of_mem_singleton H]}, rewrite [Min_insert f a'nins' s'nempty], cases (eq_or_mem_of_mem_insert H) with aeqa' ains', {rewrite aeqa', apply min_le_left}, apply le.trans !min_le_right (ih ains') end proposition le_Min (f : A → B) {s : finset A} {b : B} (sne : s ≠ ∅) (H : ∀ a, a ∈ s → b ≤ f a) : b ≤ Min x ∈ s, f x := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'nempty, {rewrite [s'empty, Min_singleton], exact H a' !mem_insert}, rewrite [Min_insert f a'nins' s'nempty], apply le_min (H a' !mem_insert), apply ih s'nempty, intro a H', exact H a (mem_insert_of_mem a' H') end proposition Min_add_right (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) : (Min x ∈ s, f x + b) = (Min x ∈ s, f x) + b := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'ne, {rewrite [s'empty, Min_singleton]}, rewrite [*Min_insert _ a'nins' s'ne, ih s'ne, min_add_add_right] end proposition Min_add_left (f : A → B) {s : finset A} (b : B) (sne : s ≠ ∅) : (Min x ∈ s, b + f x) = b + (Min x ∈ s, f x) := begin induction s with a' s' a'nins' ih, {exact absurd rfl sne}, cases (decidable.em (s' = ∅)) with s'empty s'ne, {rewrite [s'empty, Min_singleton]}, rewrite [*Min_insert _ a'nins' s'ne, ih s'ne, min_add_add_left] end end decidable_linear_ordered_cancel_comm_monoid_B section decidable_linear_ordered_comm_group_B variable [decidable_linear_ordered_comm_group B] proposition Max_neg (f : A → B) (s : finset A) : (Max x ∈ s, - f x) = - Min x ∈ s, f x := begin cases (decidable.em (s = ∅)) with se sne, {rewrite [se, Max_empty, Min_empty, neg_zero]}, apply eq_of_le_of_ge, {apply !Max_le sne, intro a ains, apply neg_le_neg, apply !Min_le ains}, apply neg_le_of_neg_le, apply !le_Min sne, intro a ains, apply neg_le_of_neg_le, apply !le_Max ains end proposition Min_neg (f : A → B) (s : finset A) : (Min x ∈ s, - f x) = - Max x ∈ s, f x := begin cases (decidable.em (s = ∅)) with se sne, {rewrite [se, Max_empty, Min_empty, neg_zero]}, apply eq_of_le_of_ge, {apply le_neg_of_le_neg, apply !Max_le sne, intro a ains, apply le_neg_of_le_neg, apply !Min_le ains}, apply !le_Min sne, intro a ains, apply neg_le_neg, apply !le_Max ains end proposition Max_eq_neg_Min_neg (f : A → B) (s : finset A) : (Max x ∈ s, f x) = - Min x ∈ s, - f x := by rewrite [Min_neg, neg_neg] proposition Min_eq_neg_Max_neg (f : A → B) (s : finset A) : (Min x ∈ s, f x) = - Max x ∈ s, - f x := by rewrite [Max_neg, neg_neg] end decidable_linear_ordered_comm_group_B end deceq_A /- Min and Max *of* a finset -/ section decidable_linear_ordered_semiring_A variable [decidable_linear_ordered_semiring A] definition Max₀ (s : finset A) : A := Max x ∈ s, x definition Min₀ (s : finset A) : A := Min x ∈ s, x proposition Max₀_empty : Max₀ ∅ = (0 : A) := !Max_empty proposition Max₀_singleton (a : A) : Max₀ '{a} = a := !Max_singleton proposition Max₀_insert_insert {a₁ a₂ : A} {s : finset A} (H₁ : a₂ ∉ s) (H₂ : a₁ ∉ insert a₂ s) : Max₀ (insert a₁ (insert a₂ s)) = max a₁ (Max₀ (insert a₂ s)) := !Max_insert_insert H₁ H₂ proposition Max₀_insert {s : finset A} {a : A} (anins : a ∉ s) (sne : s ≠ ∅) : Max₀ (insert a s) = max a (Max₀ s) := !Max_insert anins sne proposition Max₀_pair (a₁ a₂ : A) : Max₀ '{a₁, a₂} = max a₁ a₂ := !Max_pair proposition le_Max₀ {a : A} {s : finset A} (H : a ∈ s) : a ≤ Max₀ s := !le_Max H proposition Max₀_le {s : finset A} {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → x ≤ a) : Max₀ s ≤ a := !Max_le sne H proposition Min₀_empty : Min₀ ∅ = (0 : A) := !Min_empty proposition Min₀_singleton (a : A) : Min₀ '{a} = a := !Min_singleton proposition Min₀_insert_insert {a₁ a₂ : A} {s : finset A} (H₁ : a₂ ∉ s) (H₂ : a₁ ∉ insert a₂ s) : Min₀ (insert a₁ (insert a₂ s)) = min a₁ (Min₀ (insert a₂ s)) := !Min_insert_insert H₁ H₂ proposition Min₀_insert {s : finset A} {a : A} (anins : a ∉ s) (sne : s ≠ ∅) : Min₀ (insert a s) = min a (Min₀ s) := !Min_insert anins sne proposition Min₀_pair (a₁ a₂ : A) : Min₀ '{a₁, a₂} = min a₁ a₂ := !Min_pair proposition Min₀_le {a : A} {s : finset A} (H : a ∈ s) : Min₀ s ≤ a := !Min_le H proposition le_Min₀ {s : finset A} {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → a ≤ x) : a ≤ Min₀ s := !le_Min sne H end decidable_linear_ordered_semiring_A end finset /- finite set versions -/ namespace set open classical section decidable_linear_ordered_cancel_comm_monoid_B variable [decidable_linear_ordered_cancel_comm_monoid B] noncomputable definition Max (s : set A) (f : A → B) : B := finset.Max (to_finset s) f notation `Max` binders `∈` s `, ` r:(scoped f, Max s f) := r noncomputable definition Min (s : set A) (f : A → B) : B := finset.Min (to_finset s) f notation `Min` binders `∈` s `, ` r:(scoped f, Min s f) := r proposition Max_empty (f : A → B) : (Max x ∈ ∅, f x) = 0 := by rewrite [↑set.Max, to_finset_empty, finset.Max_empty] proposition Max_singleton (f : A → B) (a : A) : (Max x ∈ '{a}, f x) = f a := by rewrite [↑set.Max, to_finset_insert, to_finset_empty, finset.Max_singleton] proposition Max_insert_insert (f : A → B) {a₁ a₂ : A} {s : set A} [h : finite s] : a₂ ∉ s → a₁ ∉ insert a₂ s → (Max x ∈ insert a₁ (insert a₂ s), f x) = max (f a₁) (Max x ∈ insert a₂ s, f x) := begin rewrite [↑set.Max, -+mem_to_finset_eq, +to_finset_insert], apply finset.Max_insert_insert end proposition Max_insert (f : A → B) {a : A} {s : set A} [h : finite s] (anins : a ∉ s) (sne : s ≠ ∅) : (Max x ∈ insert a s, f x) = max (f a) (Max x ∈ s, f x) := begin revert anins sne, rewrite [↑set.Max, -+mem_to_finset_eq, +to_finset_insert], intro h1 h2, apply finset.Max_insert f h1 (λ h', h2 (eq_empty_of_to_finset_eq_empty h')), end proposition Max_pair (f : A → B) (a₁ a₂ : A) : (Max x ∈ '{a₁, a₂}, f x) = max (f a₁) (f a₂) := by rewrite [↑set.Max, +to_finset_insert, +to_finset_empty, finset.Max_pair] proposition le_Max (f : A → B) {a : A} {s : set A} [fins : finite s] (H : a ∈ s) : f a ≤ Max x ∈ s, f x := by rewrite [-+mem_to_finset_eq at H, ↑set.Max]; exact finset.le_Max f H proposition Max_le (f : A → B) {s : set A} [fins : finite s] {b : B} (sne : s ≠ ∅) (H : ∀ a, a ∈ s → f a ≤ b) : (Max x ∈ s, f x) ≤ b := begin rewrite [↑set.Max], apply finset.Max_le f (λ H', sne (eq_empty_of_to_finset_eq_empty H')), intro a H', apply H a, rewrite mem_to_finset_eq at H', exact H' end proposition Max_add_right (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) : (Max x ∈ s, f x + b) = (Max x ∈ s, f x) + b := begin rewrite [↑set.Max], apply finset.Max_add_right f b (λ h, sne (eq_empty_of_to_finset_eq_empty h)) end proposition Max_add_left (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) : (Max x ∈ s, b + f x) = b + (Max x ∈ s, f x) := begin rewrite [↑set.Max], apply finset.Max_add_left f b (λ h, sne (eq_empty_of_to_finset_eq_empty h)) end proposition Min_empty (f : A → B) : (Min x ∈ ∅, f x) = 0 := by rewrite [↑set.Min, to_finset_empty, finset.Min_empty] proposition Min_singleton (f : A → B) (a : A) : (Min x ∈ '{a}, f x) = f a := by rewrite [↑set.Min, to_finset_insert, to_finset_empty, finset.Min_singleton] proposition Min_insert_insert (f : A → B) {a₁ a₂ : A} {s : set A} [h : finite s] : a₂ ∉ s → a₁ ∉ insert a₂ s → (Min x ∈ insert a₁ (insert a₂ s), f x) = min (f a₁) (Min x ∈ insert a₂ s, f x) := begin rewrite [↑set.Min, -+mem_to_finset_eq, +to_finset_insert], apply finset.Min_insert_insert end proposition Min_insert (f : A → B) {a : A} {s : set A} [h : finite s] (anins : a ∉ s) (sne : s ≠ ∅) : (Min x ∈ insert a s, f x) = min (f a) (Min x ∈ s, f x) := begin revert anins sne, rewrite [↑set.Min, -+mem_to_finset_eq, +to_finset_insert], intro h1 h2, apply finset.Min_insert f h1 (λ h', h2 (eq_empty_of_to_finset_eq_empty h')), end proposition Min_pair (f : A → B) (a₁ a₂ : A) : (Min x ∈ '{a₁, a₂}, f x) = min (f a₁) (f a₂) := by rewrite [↑set.Min, +to_finset_insert, +to_finset_empty, finset.Min_pair] proposition Min_le (f : A → B) {a : A} {s : set A} [fins : finite s] (H : a ∈ s) : (Min x ∈ s, f x) ≤ f a := by rewrite [-+mem_to_finset_eq at H, ↑set.Min]; exact finset.Min_le f H proposition le_Min (f : A → B) {s : set A} [fins : finite s] {b : B} (sne : s ≠ ∅) (H : ∀ a, a ∈ s → b ≤ f a) : b ≤ Min x ∈ s, f x := begin rewrite [↑set.Min], apply finset.le_Min f (λ H', sne (eq_empty_of_to_finset_eq_empty H')), intro a H', apply H a, rewrite mem_to_finset_eq at H', exact H' end proposition Min_add_right (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) : (Min x ∈ s, f x + b) = (Min x ∈ s, f x) + b := begin rewrite [↑set.Min], apply finset.Min_add_right f b (λ h, sne (eq_empty_of_to_finset_eq_empty h)) end proposition Min_add_left (f : A → B) {s : set A} [fins : finite s] (b : B) (sne : s ≠ ∅) : (Min x ∈ s, b + f x) = b + (Min x ∈ s, f x) := begin rewrite [↑set.Min], apply finset.Min_add_left f b (λ h, sne (eq_empty_of_to_finset_eq_empty h)) end end decidable_linear_ordered_cancel_comm_monoid_B section decidable_linear_ordered_comm_group_B variable [decidable_linear_ordered_comm_group B] proposition Max_neg (f : A → B) (s : set A) : (Max x ∈ s, - f x) = - Min x ∈ s, f x := by rewrite [↑set.Max, finset.Max_neg] proposition Min_neg (f : A → B) (s : set A) : (Min x ∈ s, - f x) = - Max x ∈ s, f x := by rewrite [↑set.Min, finset.Min_neg] proposition Max_eq_neg_Min_neg (f : A → B) (s : set A) : (Max x ∈ s, f x) = - Min x ∈ s, - f x := by rewrite [↑set.Max, ↑set.Min, finset.Max_eq_neg_Min_neg] proposition Min_eq_neg_Max_neg (f : A → B) (s : set A) : (Min x ∈ s, f x) = - Max x ∈ s, - f x := by rewrite [↑set.Max, ↑set.Min, finset.Min_eq_neg_Max_neg] end decidable_linear_ordered_comm_group_B section decidable_linear_ordered_semiring_A variable [decidable_linear_ordered_semiring A] noncomputable definition Max₀ (s : set A) : A := Max x ∈ s, x noncomputable definition Min₀ (s : set A) : A := Min x ∈ s, x proposition Max₀_empty : Max₀ ∅ = (0 : A) := !Max_empty proposition Max₀_singleton (a : A) : Max₀ '{a} = a := !Max_singleton proposition Max₀_insert_insert {a₁ a₂ : A} {s : set A} [fins : finite s] (H₁ : a₂ ∉ s) (H₂ : a₁ ∉ insert a₂ s) : Max₀ (insert a₁ (insert a₂ s)) = max a₁ (Max₀ (insert a₂ s)) := !Max_insert_insert H₁ H₂ proposition Max₀_insert {s : set A} [fins : finite s] {a : A} (anins : a ∉ s) (sne : s ≠ ∅) : Max₀ (insert a s) = max a (Max₀ s) := !Max_insert anins sne proposition Max₀_pair (a₁ a₂ : A) : Max₀ '{a₁, a₂} = max a₁ a₂ := !Max_pair proposition le_Max₀ {a : A} {s : set A} [fins : finite s] (H : a ∈ s) : a ≤ Max₀ s := !le_Max H proposition Max₀_le {s : set A} [fins : finite s] {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → x ≤ a) : Max₀ s ≤ a := !Max_le sne H proposition Min₀_empty : Min₀ ∅ = (0 : A) := !Min_empty proposition Min₀_singleton (a : A) : Min₀ '{a} = a := !Min_singleton proposition Min₀_insert_insert {a₁ a₂ : A} {s : set A} [fins : finite s] (H₁ : a₂ ∉ s) (H₂ : a₁ ∉ insert a₂ s) : Min₀ (insert a₁ (insert a₂ s)) = min a₁ (Min₀ (insert a₂ s)) := !Min_insert_insert H₁ H₂ proposition Min₀_insert {s : set A} [fins : finite s] {a : A} (anins : a ∉ s) (sne : s ≠ ∅) : Min₀ (insert a s) = min a (Min₀ s) := !Min_insert anins sne proposition Min₀_pair (a₁ a₂ : A) : Min₀ '{a₁, a₂} = min a₁ a₂ := !Min_pair proposition Min₀_le {a : A} {s : set A} [fins : finite s] (H : a ∈ s) : Min₀ s ≤ a := !Min_le H proposition le_Min₀ {s : set A} [fins : finite s] {a : A} (sne : s ≠ ∅) (H : ∀ x, x ∈ s → a ≤ x) : a ≤ Min₀ s := !le_Min sne H end decidable_linear_ordered_semiring_A end set
8ba25bdbe49871945a22ed61a9a0b4171f244fe2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/choose/dvd_auto.lean
ad00bdd8246539c4a4eabe4da2803c3863ca3fef
[]
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
718
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Patrick Stevens -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.choose.basic import Mathlib.data.nat.prime import Mathlib.PostPort namespace Mathlib /-! # Divisibility properties of binomial coefficients -/ namespace nat namespace prime theorem dvd_choose_add {p : ℕ} {a : ℕ} {b : ℕ} (hap : a < p) (hbp : b < p) (h : p ≤ a + b) (hp : prime p) : p ∣ choose (a + b) a := sorry theorem dvd_choose_self {p : ℕ} {k : ℕ} (hk : 0 < k) (hkp : k < p) (hp : prime p) : p ∣ choose p k := sorry end Mathlib
00b135d6b48df42872bed72d1f15dcf3becef996
8c02fed42525b65813b55c064afe2484758d6d09
/src/spec/irstate.lean
4c829c14f22acf94b409f2121698a2f164a6d26b
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
microsoft/AliveInLean
3eac351a34154efedd3ffc4fe2fa4ec01b219e0d
4b739dd6e4266b26a045613849df221374119871
refs/heads/master
1,691,419,737,939
1,689,365,567,000
1,689,365,568,000
131,156,103
23
18
NOASSERTION
1,660,342,040,000
1,524,747,538,000
Lean
UTF-8
Lean
false
false
12,249
lean
-- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the MIT license. import .spec import .lemmas import ..irsem namespace spec open irsem /- - Lemmas about regfile. -/ -- Induction principle of regfile. lemma regfile.induction: ∀ {sem} {P: regfile sem → Prop} {HP0: P (@regfile.empty sem)} {HPU: ∀ rf, P rf → ∀ n v, P (regfile.update sem rf n v)}, ∀ rf, P rf := begin intros, induction rf, { apply HP0 }, { cases rf_hd, unfold regfile.update at HPU, apply HPU, assumption } end -- regfile.get returns none on regfile.empty lemma regfile.empty_get_none: ∀ {sem} rname, regfile.get sem (regfile.empty sem) rname = none := begin intros, unfold regfile.empty, unfold regfile.get, simp, unfold regfile.get._match_1 end lemma regfile.empty_apply_empty: ∀ {sem} f, regfile.apply_to_values sem (regfile.empty sem) f = regfile.empty sem := begin intros, unfold regfile.empty, refl end -- regfile.get returns the value which is updated just before -- if rname = rname2 lemma regfile.update_get_match: ∀ {sem} (rname rname2:string) vp rf (Hnameeq: rname2 = rname), regfile.get sem (regfile.update sem rf rname vp) rname2 = some vp := begin intros, unfold regfile.get, unfold regfile.update, rw list.filter_cons_of_pos, { unfold regfile.get._match_1 }, { simp, assumption } end -- Updating a register file does not affect the result -- of regfile.get if rname ≠ rname2 lemma regfile.update_get_nomatch: ∀ {sem} (rname rname2:string) vp rf (Hnameeq: rname2 ≠ rname), regfile.get sem (regfile.update sem rf rname vp) rname2 = regfile.get sem rf rname2 := begin intros, unfold regfile.get, unfold regfile.update, rw list.filter_cons_of_neg, { simp, assumption }, end lemma regfile.regnames_empty: ∀ {sem} n, n ∉ regfile.regnames sem (regfile.empty sem) := begin intros, unfold regfile.regnames, unfold regfile.empty, simp end lemma regfile.reg_in_regnames_update: ∀ {sem} rf n n' v (H: n ∈ regfile.regnames sem rf), n ∈ regfile.regnames sem (regfile.update sem rf n' v) := begin intros, unfold regfile.update, unfold regfile.regnames at *, simp, right, apply H end lemma regfile.reg_in_regnames_update2: ∀ {sem} rf n v, n ∈ regfile.regnames sem (regfile.update sem rf n v) := begin intros, unfold regfile.update, unfold regfile.regnames at *, simp end lemma regfile.reg_in_regnames_update3: ∀ {sem} rf n n' v (H: n ∈ regfile.regnames sem (regfile.update sem rf n' v)) (HNEQ: n ≠ n'), n ∈ regfile.regnames sem rf := begin intros, unfold regfile.update at H, unfold regfile.regnames at *, simp at *, cases H, { exfalso, apply HNEQ, assumption }, assumption end lemma regfile.reg_notin_regnames_get_none: ∀ {sem} (rname:string) (f:regfile sem), regfile.get sem f rname = none ↔ rname ∉ regfile.regnames sem f := begin intros, split, { intros H, induction f, { unfold regfile.regnames, simp }, { unfold regfile.get at H, unfold regfile.regnames, cases f_hd with n1 v1, unfold list.filter at H, simp, have H0: decidable (n1 = rname), apply_instance, cases H0, { rw if_neg at H, { intros H1, cases H1, { rw H1 at H0, apply H0, refl }, { apply f_ih, apply H, apply H1 } }, { simp, apply neq_symm, apply H0 } }, { rw if_pos at H, unfold regfile.get._match_1 at H, cases H, simp, rw H0 } } }, { intros H, induction f, { unfold regfile.get, simp, unfold regfile.get._match_1 }, { unfold regfile.regnames at H, simp at H, rw ← list.mem_cons_iff at H, rw list.notmem_and at H, unfold regfile.get, have H: decidable (f_hd.fst = rname), apply_instance, cases H, { -- first element is not rname unfold list.filter, rw if_neg, apply f_ih, cases H, apply H_right, intros H', rw H' at H_1, apply H_1, refl }, { cases H, rw H_1 at H_left, exfalso, apply H_left, refl } } } end lemma regfile.reg_in_regnames_get_some: ∀ {sem} (rname:string) (f:regfile sem), (∃ v, regfile.get sem f rname = some v) ↔ rname ∈ regfile.regnames sem f := begin intros, split, { apply regfile.induction f, { intros H, cases H, rw regfile.empty_get_none at H_h, cases H_h }, { intros s Hind n v H, have HN:decidable (n = rname), apply_instance, cases HN, { rw regfile.update_get_nomatch at H, have H := Hind H, apply regfile.reg_in_regnames_update, assumption, apply neq_symm, assumption }, { rw HN, apply regfile.reg_in_regnames_update2 } } }, { apply regfile.induction f, { intros H, cases H }, { intros rf Hind n v H, have HN:decidable (n = rname), apply_instance, cases HN, { rw regfile.update_get_nomatch, apply Hind, apply regfile.reg_in_regnames_update3, { apply H }, any_goals { apply neq_symm, assumption }, }, { rw HN, apply exists.intro v, apply regfile.update_get_match, refl } } } end lemma regfile.apply_update_comm: ∀ {sem} f n v rf, regfile.apply_to_values sem (regfile.update sem rf n v) f = regfile.update sem (regfile.apply_to_values sem rf f) n (f v) := begin intros, unfold regfile.apply_to_values, unfold regfile.update, refl end -- Note: reverse direction does not hold! lemma regfile.reg_apply_some: ∀ {sem} (rf:regfile sem) (f:valty sem → valty sem) v n (H:regfile.get sem rf n = some v), regfile.get sem (regfile.apply_to_values sem rf f) n = some (f v) := begin intros, revert H, apply regfile.induction rf, { intros H, rw regfile.empty_get_none at H, cases H }, { intros rf Hind n1 v1 H, have HNAME: decidable(n1 = n), apply_instance, cases HNAME, { rw regfile.update_get_nomatch at H, have H' := Hind H, rw regfile.apply_update_comm, rw regfile.update_get_nomatch, assumption, any_goals { apply neq_symm, assumption } }, { rw regfile.update_get_match at H, injection H, subst h_1, rw regfile.apply_update_comm, rw regfile.update_get_match, any_goals { rw HNAME } } } end lemma regfile.reg_apply_none: ∀ {sem} (rf:regfile sem) (f:valty sem → valty sem) n, regfile.get sem rf n = none ↔ regfile.get sem (regfile.apply_to_values sem rf f) n = none := begin intros, split, { apply regfile.induction rf, { intros H, rw regfile.empty_apply_empty, assumption }, { intros rf Hind n1 v1 H, have HNAME: decidable(n1 = n), apply_instance, cases HNAME, { rw regfile.update_get_nomatch at H, have H' := Hind H, rw regfile.apply_update_comm, rw regfile.update_get_nomatch, assumption, any_goals { apply neq_symm, assumption } }, { rw regfile.update_get_match at H, injection H, rw HNAME } } }, { apply regfile.induction rf, { intros H, rw regfile.empty_apply_empty at H, assumption }, { intros rf Hind n1 v1 H, have HNAME: decidable(n1 = n), apply_instance, cases HNAME, { rw regfile.apply_update_comm at H, rw regfile.update_get_nomatch at H, have H' := Hind H, rw regfile.update_get_nomatch, assumption, any_goals { apply neq_symm, assumption } }, { rw regfile.apply_update_comm at H, rw regfile.update_get_match at H, injection H, rw HNAME } } } end lemma irstate.updatereg_getreg_match_smt: ∀ (rname rname2:string) v st (Hnameeq: rname2 = rname), irstate.getreg irsem_smt (irstate.updatereg irsem_smt st rname v) rname2 = some v := begin intros, unfold irstate.getreg, unfold irstate.updatereg, simp, apply regfile.update_get_match, assumption end lemma irstate.notin_regnames_getreg_smt: ∀ (rname:string) (s:irstate irsem_smt) (H:rname ∉ irstate.regnames irsem_smt s), irstate.getreg irsem_smt s rname = none := begin intros, unfold irstate.getreg, unfold irstate.regnames at *, cases s, simp, rw regfile.reg_notin_regnames_get_none, apply H end lemma irstate.getreg_diff_smt: ∀ ss (n1 n2:string) v (H1: irstate.getreg irsem_smt ss n1 = none) (H2: irstate.getreg irsem_smt ss n2 = some v), n1 ≠ n2 := begin intros, intros HEQ, rw HEQ at H1, rw H1 at H2, cases H2 end lemma irstate.updatereg_getreg_nomatch_smt: ∀ ss ss' (n1 n2:string) v v' (H1: irstate.getreg irsem_smt ss n1 = v) (H2: ss' = irstate.updatereg irsem_smt ss n2 v') (HDIFF:n1 ≠ n2), irstate.getreg irsem_smt ss' n1 = v := begin intros, rw H2, unfold irstate.getreg at *, unfold irstate.updatereg at *, simp, rw regfile.update_get_nomatch, assumption, assumption end lemma irstate.updatereg_getreg_nomatch_inv_smt: ∀ ss ss' (n1 n2:string) v v' (H1: irstate.getreg irsem_smt ss' n1 = v) (H2: ss' = irstate.updatereg irsem_smt ss n2 v') (HDIFF:n1 ≠ n2), irstate.getreg irsem_smt ss n1 = v := begin intros, rw H2 at H1, unfold irstate.getreg at *, unfold irstate.updatereg at *, simp at H1, rw regfile.update_get_nomatch at H1, assumption, assumption end lemma irstate.getreg_empty_none_smt: ∀ s n (H:irstate.regnames irsem_smt s = []), irstate.getreg irsem_smt s n = none := begin intros, cases s with ub rf, unfold irstate.regnames at H, unfold regfile.regnames at H, simp at H, have H' : rf = [], { apply list.map_nil, apply H }, rw H', unfold irstate.getreg, unfold regfile.get, simp, delta regfile.get._match_1, simp end lemma irstate.getub_equiv: ∀ {ss:irstate_smt} {se:irstate_exec} {sret} {eret} (HSTEQ:irstate_equiv ss se) (HSSRET: sret = ss.getub irsem_smt) (HSERET: eret = se.getub irsem_exec), b_equiv sret eret := begin intros, cases HSTEQ, any_goals { -- irstate_equiv.noub unfold irstate.getub at HSSRET, unfold irstate.getub at HSERET, simp at HSSRET, simp at HSERET, subst HSSRET, subst HSERET, assumption } end lemma irstate.getub_updatereg_smt: ∀ (s:irstate irsem_smt) n v, irstate.getub irsem_smt (irstate.updatereg irsem_smt s n v) = irstate.getub irsem_smt s := begin intros, unfold irstate.updatereg, refl end lemma irstate.getreg_apply_some_smt: ∀ (s:irstate irsem_smt) (f:valty_smt → valty_smt) v n (H: irstate.getreg irsem_smt s n = some v), irstate.getreg irsem_smt (irstate.apply_to_values irsem_smt s f) n = some (f v) := begin intros, cases s, unfold irstate.apply_to_values, unfold irstate.getreg, apply regfile.reg_apply_some, apply H end lemma irstate.getreg_apply_none_smt: ∀ (s:irstate irsem_smt) (f:valty_smt → valty_smt) n, irstate.getreg irsem_smt s n = none ↔ irstate.getreg irsem_smt (irstate.apply_to_values irsem_smt s f) n = none := begin intros, split, { intros H, cases s, unfold irstate.apply_to_values, unfold irstate.getreg, rw ← regfile.reg_apply_none, apply H }, { intros H, cases s, unfold irstate.apply_to_values at H, unfold irstate.getreg, rw regfile.reg_apply_none, apply H } end lemma irstate.empty_apply_empty_smt: ∀ f, irstate.apply_to_values irsem_smt (irstate.empty irsem_smt) f = irstate.empty irsem_smt := begin intros, unfold irstate.empty, refl end lemma irstate.getub_apply_to_values: ∀ (s:irstate irsem_smt) f, irstate.getub irsem_smt (irstate.apply_to_values irsem_smt s f) = irstate.getub irsem_smt s := begin intros, unfold irstate.getub, unfold irstate.apply_to_values end lemma irstate.setub_apply_to_values: ∀ (s:irstate irsem_smt) f b, irstate.setub irsem_smt (irstate.apply_to_values irsem_smt s f) b = irstate.apply_to_values irsem_smt (irstate.setub irsem_smt s b) f := begin intros, unfold irstate.setub, unfold irstate.apply_to_values end end spec
4ab7d26fc8189f9b26f6319ab0c9415197186dc6
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/algebra/category/functor.lean
f8164838fee5533ff747e79ec38050dfca8524e4
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
4,271
lean
/- 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 -/ import .basic import logic.cast open function open category eq eq.ops heq structure functor (C D : Category) : Type := (object : C → D) (morphism : Π⦃a b : C⦄, hom a b → hom (object a) (object b)) (respect_id : Π (a : C), morphism (ID a) = ID (object a)) (respect_comp : Π ⦃a b c : C⦄ (g : hom b c) (f : hom a b), morphism (g ∘ f) = morphism g ∘ morphism f) infixl `⇒`:25 := functor namespace functor -- attribute object [coercion] -- attribute morphism [coercion] attribute respect_id [irreducible] attribute respect_comp [irreducible] variables {A B C D : Category} attribute [reducible] protected definition compose (G : functor B C) (F : functor A B) : functor A C := functor.mk (λx, G (F x)) (λ a b f, G (F f)) (λ a, proof calc G (F (ID a)) = G id : {respect_id F a} --not giving the braces explicitly makes the elaborator compute a couple more seconds ... = id : respect_id G (F a) qed) (λ a b c g f, proof calc G (F (g ∘ f)) = G (F g ∘ F f) : respect_comp F g f ... = G (F g) ∘ G (F f) : respect_comp G (F g) (F f) qed) infixr `∘f`:60 := functor.compose protected theorem assoc (H : functor C D) (G : functor B C) (F : functor A B) : H ∘f (G ∘f F) = (H ∘f G) ∘f F := rfl attribute [reducible] protected definition id {C : Category} : functor C C := mk (λa, a) (λ a b f, f) (λ a, rfl) (λ a b c f g, rfl) attribute [reducible] protected definition ID (C : Category) : functor C C := @functor.id C protected theorem id_left (F : functor C D) : (@functor.id D) ∘f F = F := functor.rec (λ obF homF idF compF, dcongr_arg4 mk rfl rfl !proof_irrel !proof_irrel) F protected theorem id_right (F : functor C D) : F ∘f (@functor.id C) = F := functor.rec (λ obF homF idF compF, dcongr_arg4 mk rfl rfl !proof_irrel !proof_irrel) F end functor namespace category open functor attribute [reducible] definition category_of_categories : category Category := mk (λ a b, functor a b) (λ a b c g f, functor.compose g f) (λ a, functor.id) (λ a b c d h g f, !functor.assoc) (λ a b f, !functor.id_left) (λ a b f, !functor.id_right) attribute [reducible] definition Category_of_categories := Mk category_of_categories namespace ops notation `Cat`:max := Category_of_categories attribute category_of_categories [instance] end ops end category namespace functor variables {C D : Category} theorem mk_heq {obF obG : C → D} {homF homG idF idG compF compG} (Hob : ∀x, obF x = obG x) (Hmor : ∀(a b : C) (f : a ⟶ b), homF a b f == homG a b f) : mk obF homF idF compF = mk obG homG idG compG := hddcongr_arg4 mk (funext Hob) (hfunext (λ a, hfunext (λ b, hfunext (λ f, !Hmor)))) !proof_irrel !proof_irrel protected theorem hequal {F G : C ⇒ D} : Π (Hob : ∀x, F x = G x) (Hmor : ∀a b (f : a ⟶ b), F f == G f), F = G := functor.rec (λ obF homF idF compF, functor.rec (λ obG homG idG compG Hob Hmor, mk_heq Hob Hmor) G) F -- theorem mk_eq {obF obG : C → D} {homF homG idF idG compF compG} (Hob : ∀x, obF x = obG x) -- (Hmor : ∀(a b : C) (f : a ⟶ b), cast (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (homF a b f) -- = homG a b f) -- : mk obF homF idF compF = mk obG homG idG compG := -- dcongr_arg4 mk -- (funext Hob) -- (funext (λ a, funext (λ b, funext (λ f, sorry ⬝ Hmor a b f)))) -- -- to fill this sorry use (a generalization of) cast_pull -- !proof_irrel -- !proof_irrel -- protected theorem equal {F G : C ⇒ D} : Π (Hob : ∀x, F x = G x) -- (Hmor : ∀a b (f : a ⟶ b), cast (congr_arg (λ x, x a ⟶ x b) (funext Hob)) (F f) = G f), F = G := -- functor.rec -- (λ obF homF idF compF, -- functor.rec -- (λ obG homG idG compG Hob Hmor, mk_eq Hob Hmor) -- G) -- F end functor
26811a06f66ad9665dcf1117e17fcbed60c1ae09
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Compiler/LCNF/DependsOn.lean
baf134a959bc4a9062cae9dfbc8b136f53204ef9
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
1,542
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.LCNF.Basic namespace Lean.Compiler.LCNF private abbrev M := ReaderT FVarIdSet Id private def fvarDepOn (fvarId : FVarId) : M Bool := return (← read).contains fvarId private def exprDepOn (e : Expr) : M Bool := do let s ← read return e.hasAnyFVar fun fvarId => s.contains fvarId private def LetDecl.depOn (decl : LetDecl) : M Bool := exprDepOn decl.type <||> exprDepOn decl.value private partial def depOn (c : Code) : M Bool := match c with | .let decl k => decl.depOn <||> depOn k | .jp decl k | .fun decl k => exprDepOn decl.type <||> depOn decl.value <||> depOn k | .cases c => exprDepOn c.resultType <||> fvarDepOn c.discr <||> c.alts.anyM fun alt => depOn alt.getCode | .jmp fvarId args => fvarDepOn fvarId <||> args.anyM exprDepOn | .return fvarId => fvarDepOn fvarId | .unreach _ => return false abbrev LetDecl.dependsOn (decl : LetDecl) (s : FVarIdSet) : Bool := decl.depOn s abbrev FunDecl.dependsOn (decl : FunDecl) (s : FVarIdSet) : Bool := exprDepOn decl.type s || depOn decl.value s def CodeDecl.dependsOn (decl : CodeDecl) (s : FVarIdSet) : Bool := match decl with | .let decl => decl.dependsOn s | .jp decl | .fun decl => decl.dependsOn s /-- Return `true` is `c` depends on a free variable in `s`. -/ def Code.dependsOn (c : Code) (s : FVarIdSet) : Bool := depOn c s end Lean.Compiler.LCNF
3e49725a6ef70cd62e590e194cae81323a85a523
750acab0c635b67751bcfec43c5411aa3941c441
/sipser.lean
5b93baaf983c2e169400b42b988fdf5b18301432
[]
no_license
nthomas103/lean_work
912f8e662cdd73ba97f5d3655ddb8a5d2cd204c9
7e9785cae2b60a77b41922fd5d5b159a1fae415c
refs/heads/master
1,586,739,169,355
1,455,759,226,000
1,455,759,226,000
50,978,095
0
0
null
null
null
null
UTF-8
Lean
false
false
5,218
lean
import standard algebra.order_bigops open algebra fin finset num nat fintype stream prod prod.ops list set open sigma sigma.ops decidable structure turing_machine (Q Γ : Type) := [fintypeQ : fintype Q] [fintypeΓ : fintype Γ] [dec_eqQ : decidable_eq Q] (b : Γ) --TODO maybe should require that b in not in the input (q₀ : Q) (qa : Q) (qr : Q) (qa_ne_qr : qa ≠ qr) (δ : Q → Γ → Q × Γ × bool) definition stream_sub {A : Type} (s : stream A) (n : ℕ) (a : A) : stream A := λ m : ℕ, if m = n then a else s m definition TM_move (b : bool) (n : ℕ) : ℕ := if b = bool.tt then n - 1 else n + 1 definition TM_compute_aux {Q Γ : Type} (TM : turing_machine Q Γ) : Q → stream Γ → ℕ → ℕ → (Q × stream Γ × ℕ) | q s n 0 := (q, s, n) | q s n (t+1) := let out := (turing_machine.δ TM q (s n)) in TM_compute_aux out.1.1 (stream_sub s n out.1.2) (TM_move out.2 n) t definition TM_compute {Q Γ : Type} (TM : turing_machine Q Γ) (input : list Γ) (t : ℕ) : Q × stream Γ × ℕ := TM_compute_aux TM (turing_machine.q₀ TM) (input ++ (const (turing_machine.b TM))) 0 t definition TM_accepts {Q Γ : Type} (TM : turing_machine Q Γ) (input : list Γ) := ∃ t, (TM_compute TM input t).1.1 = turing_machine.qa TM ∧ ¬ ∃ t', t' < t → (TM_compute TM input t).1.1 = turing_machine.qr TM definition TM_rejects {Q Γ : Type} (TM : turing_machine Q Γ) (input : list Γ) := ∃ t, (TM_compute TM input t).1.1 = turing_machine.qr TM ∧ ¬ ∃ t', t' < t → (TM_compute TM input t).1.1 = turing_machine.qa TM definition TM_halts {Q Γ : Type} (TM : turing_machine Q Γ) (input : list Γ) := TM_accepts TM input ∨ TM_rejects TM input definition TM_halts_time {Q Γ : Type} (TM : turing_machine Q Γ) (input : list Γ) := Σ t, (TM_compute TM input t).1.1 ∈ '{turing_machine.qa TM, turing_machine.qr TM} ∧ ¬ ∃ t', t' < t → (TM_compute TM input t').1.1 ∈ '{turing_machine.qa TM, turing_machine.qr TM} definition turing_recognizable {Γ : Type} (L : set (list Γ)) := ∃ (Q : Type) (TM : turing_machine Q Γ), ∀ s, s ∈ L → TM_accepts TM s definition TM_decides {Q Γ : Type} (TM : turing_machine Q Γ) (L : set (list Γ)) : Prop := (∀ s, s ∈ L → TM_accepts TM s) ∧ (∀ s, s ∉ L → TM_rejects TM s) definition turing_decidable {Γ : Type} (L : set (list Γ)) := ∃ (Q : Type) (TM : turing_machine Q Γ), TM_decides TM L /- --not totally sure about this definition turing_dec_to_dec {Γ : Type} (L : set (list Γ)) : turing_decidable L → ∀ s, decidable (s ∈ L) := sorry --example (A B C : Prop) (h₁ : A → B) (h₂ : ¬A → C) : -/ /- constant encode {Q Γ : Type} (TM : turing_machine Q Γ) : list Γ constant UQ : Type constant UTM {Γ : Type} : turing_machine UQ Γ constant UTM_spec {Q Γ : Type} (TM : turing_machine Q Γ) (input : list Γ) : TM_accepts UTM ((encode TM) ++ input) = TM_accepts TM input ∧ TM_rejects UTM ((encode TM) ++ input) = TM_rejects TM input -/ --theorem TM_undecidable {Γ : Type} : ¬ turing_decidable definition list_append {A : Type} (F : list A) : list (list A) → list (list A) | [] := [] | (l :: L) := (map (λ a : A, a :: l) F) ++ (list_append L) definition Γ [reducible] : Type₁ := bool /- alternatively: constant {Γ : Type₁} constant [finΓ : fintype Γ] constant [Γ_dec_eq : decidable_eq Γ] attribute [instance] finΓ Γ_dec_eq -/ definition len_list : ℕ → list (list Γ) | 0 := [[]] | (n+1) := list_append (fintype.elems Γ) (len_list n) definition len_finset (n : ℕ) : finset (list Γ) := to_finset (len_list n) definition time_complexity {Q : Type} (TM : turing_machine Q Γ) (halts : Π input, TM_halts_time TM input) (n : ℕ) : ℕ := Max input ∈ (len_finset n), (halts input).1 section o_notation open real definition big_O (f g : ℕ → ℕ) := ∃ c n0, ∀ n, n ≥ n0 → f n ≤ c * g n infixl `=O`:50 := big_O definition little_o (f g : ℕ → ℕ) := ∀ (c : ℝ), ∃ n0, ∀n, n ≥ n0 → f n < c * g n infixl `=o`:50 := little_o end o_notation definition TIME (t : ℕ → ℕ) : set (set (list Γ)) := {L : set (list Γ) | ∃ (Q : Type) (TM : turing_machine Q Γ) (halts : Π i, TM_halts_time TM i), TM_decides TM L ∧ (@time_complexity Q TM halts =O t)} definition P : set (set (list Γ)) := {L : set (list Γ) | ∃ k : ℕ, L ∈ TIME (λ n, n ^ k)} definition is_poly_time_verifiable (L : set (list Γ)) := ∃ (Q : Type) (TM : turing_machine Q Γ) (halts : Π i, TM_halts_time TM i) (c : list Γ → list Γ), L = {w | TM_accepts TM (w ++ (c w))} ∧ ∃ k : ℕ, (λ n, Max i ∈ (len_finset n), (halts (i++(c i))).1) =O (λ n, n ^ k) definition NP : set (set (list Γ)) := { L | is_poly_time_verifiable L } theorem P_ne_NP : P ≠ NP := sorry
3015d96944935717019f5fc6be58d128ca964aa5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/nestedWF.lean
d0afa3933958e2a3c39000333d6b516090b785ae
[ "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
946
lean
namespace Ex1 mutual def h (c : Nat) (x : Nat) := match g c x c c with | 0 => 1 | r => r + 2 def g (c : Nat) (t : Nat) (a b : Nat) : Nat := match t with | (n+1) => match g c n a b with | 0 => 0 | m => match g c (n - m) a b with | 0 => 0 | m + 1 => g c m a b | 0 => f c 0 def f (c : Nat) (x : Nat) := match h c x with | 0 => 1 | r => f c r end termination_by g x a b => 0 f c x => 0 h c x => 0 decreasing_by sorry attribute [simp] g attribute [simp] h attribute [simp] f #check g._eq_1 #check g._eq_2 #check h._eq_1 #check f._eq_1 end Ex1 namespace Ex2 def g (t : Nat) : Nat := match t with | (n+1) => match g n with | 0 => 0 | m + 1 => match g (n - m) with | 0 => 0 | m + 1 => g n | 0 => 0 termination_by' sorry decreasing_by sorry theorem ex1 : g 0 = 0 := by rw [g] #check g._eq_1 #check g._eq_2 theorem ex2 : g 0 = 0 := by unfold g simp #check g._unfold end Ex2
fe075c15b107831a2046bebfd759aad4bf0945f0
70f8755415fa7a17f87402cde4651e9f4db1b5bb
/src/mvpfunctor/M.lean
6ba1a7fbcd6da3dc496af8acc3d6ecc28226515b
[ "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
7,164
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 The M construction as a multivariate polynomial functor. -/ import mvpfunctor.basic pfunctor universe u namespace mvpfunctor open typevec variables {n : ℕ} (P : mvpfunctor.{u} (n+1)) inductive M_path : P.last.M → fin' n → Type u | root (x : P.last.M) (a : P.A) (f : P.last.B a → P.last.M) (h : pfunctor.M_dest x = ⟨a, f⟩) (i : fin' n) (c : P.drop.B a i) : M_path x i | child (x : P.last.M) (a : P.A) (f : P.last.B a → P.last.M) (h : pfunctor.M_dest x = ⟨a, f⟩) (j : P.last.B a) (i : fin' n) (c : M_path (f j) i) : M_path x i def Mp : mvpfunctor n := { A := P.last.M, B := P.M_path } def M (α : typevec n) : Type* := P.Mp.apply α instance mvfunctor_M : mvfunctor P.M := by delta M; apply_instance def M_corec_shape {β : Type u} (g₀ : β → P.A) (g₂ : Π b : β, P.last.B (g₀ b) → β) : β → P.last.M := pfunctor.M_corec (λ b, ⟨g₀ b, g₂ b⟩) def cast_dropB {a a' : P.A} (h : a = a') : P.drop.B a ⟹ P.drop.B a' := λ i b, eq.rec_on h b def cast_lastB {a a' : P.A} (h : a = a') : P.last.B a → P.last.B a' := λ b, eq.rec_on h b def M_corec_contents {α : typevec.{u} n} {β : Type u} (g₀ : β → P.A) (g₁ : Π b : β, P.drop.B (g₀ b) ⟹ α) (g₂ : Π b : β, P.last.B (g₀ b) → β) : Π x b, x = P.M_corec_shape g₀ g₂ b → P.M_path x ⟹ α | ._ b h ._ (M_path.root x a f h' i c) := have a = g₀ b, by { rw [h, M_corec_shape, pfunctor.M_dest_corec] at h', cases h', refl }, g₁ b i (P.cast_dropB this i c) | ._ b h ._ (M_path.child x a f h' j i c) := have h₀ : a = g₀ b, by { rw [h, M_corec_shape, pfunctor.M_dest_corec] at h', cases h', refl }, have h₁ : f j = M_corec_shape P g₀ g₂ (g₂ b (cast_lastB P h₀ j)), by { rw [h, M_corec_shape, pfunctor.M_dest_corec] at h', cases h', refl }, M_corec_contents (f j) (g₂ b (P.cast_lastB h₀ j)) h₁ i c def M_corec' {α : typevec n} {β : Type u} (g₀ : β → P.A) (g₁ : Π b : β, P.drop.B (g₀ b) ⟹ α) (g₂ : Π b : β, P.last.B (g₀ b) → β) : β → P.M α := λ b, ⟨M_corec_shape P g₀ g₂ b, M_corec_contents P g₀ g₁ g₂ _ _ rfl⟩ def M_corec {α : typevec n} {β : Type u} (g : β → P.apply (α.append1 β)) : β → P.M α := M_corec' P (λ b, (g b).fst) (λ b, drop_fun (g b).snd) (λ b, last_fun (g b).snd) def M_path_dest_left {α : typevec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : pfunctor.M_dest x = ⟨a, f⟩) (f' : P.M_path x ⟹ α) : P.drop.B a ⟹ α := λ i c, f' i (M_path.root x a f h i c) def M_path_dest_right {α : typevec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : pfunctor.M_dest x = ⟨a, f⟩) (f' : P.M_path x ⟹ α) : Π j : P.last.B a, P.M_path (f j) ⟹ α := λ j i c, f' i (M_path.child x a f h j i c) def M_dest' {α : typevec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : pfunctor.M_dest x = ⟨a, f⟩) (f' : P.M_path x ⟹ α) : P.apply (α.append1 (P.M α)) := ⟨a, split_fun (P.M_path_dest_left h f') (λ x, ⟨f x, P.M_path_dest_right h f' x⟩)⟩ def M_dest {α : typevec n} (x : P.M α) : P.apply (α.append1 (P.M α)) := P.M_dest' (sigma.eta $ pfunctor.M_dest x.fst).symm x.snd def M_mk {α : typevec n} : P.apply (α.append1 (P.M α)) → P.M α := M_corec _ (λ i, append_fun id (M_dest P) <$$> i) theorem M_dest'_eq_dest' {α : typevec n} {x : P.last.M} {a₁ : P.A} {f₁ : P.last.B a₁ → P.last.M} (h₁ : pfunctor.M_dest x = ⟨a₁, f₁⟩) {a₂ : P.A} {f₂ : P.last.B a₂ → P.last.M} (h₂ : pfunctor.M_dest x = ⟨a₂, f₂⟩) (f' : P.M_path x ⟹ α) : M_dest' P h₁ f' = M_dest' P h₂ f' := by cases h₁.symm.trans h₂; refl theorem M_dest_eq_dest' {α : typevec n} {x : P.last.M} {a : P.A} {f : P.last.B a → P.last.M} (h : pfunctor.M_dest x = ⟨a, f⟩) (f' : P.M_path x ⟹ α) : M_dest P ⟨x, f'⟩ = M_dest' P h f' := M_dest'_eq_dest' _ _ _ _ theorem M_dest_corec' {α : typevec.{u} n} {β : Type u} (g₀ : β → P.A) (g₁ : Π b : β, P.drop.B (g₀ b) ⟹ α) (g₂ : Π b : β, P.last.B (g₀ b) → β) (x : β) : P.M_dest (P.M_corec' g₀ g₁ g₂ x) = ⟨g₀ x, split_fun (g₁ x) (P.M_corec' g₀ g₁ g₂ ∘ (g₂ x))⟩ := rfl theorem M_dest_corec {α : typevec n} {β : Type u} (g : β → P.apply (α.append1 β)) (x : β) : P.M_dest (P.M_corec g x) = append_fun id (P.M_corec g) <$$> g x := begin transitivity, apply M_dest_corec', cases g x with a f, dsimp, rw mvpfunctor.map_eq, congr, conv { to_rhs, rw [←split_drop_fun_last_fun f, append_fun_comp_split_fun] }, refl end lemma M_bisim_lemma {α : typevec n} {a₁ : (Mp P).A} {f₁ : (Mp P).B a₁ ⟹ α} {a' : P.A} {f' : (P.B a').drop ⟹ α} {f₁' : (P.B a').last → M P α} (e₁ : M_dest P ⟨a₁, f₁⟩ = ⟨a', split_fun f' f₁'⟩) : ∃ g₁' (e₁' : pfunctor.M_dest a₁ = ⟨a', g₁'⟩), f' = M_path_dest_left P e₁' f₁ ∧ f₁' = λ (x : (last P).B a'), ⟨g₁' x, M_path_dest_right P e₁' f₁ x⟩ := begin generalize_hyp ef : @split_fun n _ (append1 α (M P α)) f' f₁' = ff at e₁, cases e₁' : pfunctor.M_dest a₁ with a₁' g₁', rw M_dest_eq_dest' _ e₁' at e₁, cases e₁, exact ⟨_, e₁', split_fun_inj ef⟩, end theorem M_bisim {α : typevec n} (R : P.M α → P.M α → Prop) (h : ∀ x y, R x y → ∃ a f f₁ f₂, P.M_dest x = ⟨a, split_fun f f₁⟩ ∧ P.M_dest y = ⟨a, split_fun f f₂⟩ ∧ ∀ i, R (f₁ i) (f₂ i)) (x y) (r : R x y) : x = y := begin cases x with a₁ f₁, cases y with a₂ f₂, dsimp [Mp] at *, have : a₁ = a₂, { refine pfunctor.M_bisim (λ a₁ a₂, ∃ x y, R x y ∧ x.1 = a₁ ∧ y.1 = a₂) _ _ _ ⟨⟨a₁, f₁⟩, ⟨a₂, f₂⟩, r, rfl, rfl⟩, rintro _ _ ⟨⟨a₁, f₁⟩, ⟨a₂, f₂⟩, r, rfl, rfl⟩, rcases h _ _ r with ⟨a', f', f₁', f₂', e₁, e₂, h'⟩, rcases M_bisim_lemma P e₁ with ⟨g₁', e₁', rfl, rfl⟩, rcases M_bisim_lemma P e₂ with ⟨g₂', e₂', _, rfl⟩, rw [e₁', e₂'], exact ⟨_, _, _, rfl, rfl, λ b, ⟨_, _, h' b, rfl, rfl⟩⟩ }, subst this, congr, ext i p, induction p with x a f h' i c x a f h' i c p IH generalizing f₁ f₂; try { rcases h _ _ r with ⟨a', f', f₁', f₂', e₁, e₂, h''⟩, rcases M_bisim_lemma P e₁ with ⟨g₁', e₁', rfl, rfl⟩, rcases M_bisim_lemma P e₂ with ⟨g₂', e₂', e₃, rfl⟩, cases h'.symm.trans e₁', cases h'.symm.trans e₂' }, { exact (congr_fun (congr_fun e₃ i) c : _) }, { exact IH _ _ (h'' _) } end theorem M_dest_map {α β : typevec n} (g : α ⟹ β) (x : P.M α) : P.M_dest (g <$$> x) = append_fun g (λ x, g <$$> x) <$$> P.M_dest x := begin cases x with a f, rw map_eq, conv { to_rhs, rw [M_dest, M_dest', map_eq, append_fun_comp_split_fun] }, reflexivity end end mvpfunctor
1881f2f9bffac164dd2e79a99b4878ce77c23c0c
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/compiler/externattr.lean
3e17b239fedb6ab04613f96c0d5c90889c4d74a8
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
6,612
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.option.basic import init.lean.expr import init.lean.environment import init.lean.attributes import init.lean.projfns namespace Lean inductive ExternEntry | adhoc (backend : Name) | inline (backend : Name) (pattern : String) | standard (backend : Name) (fn : String) | foreign (backend : Name) (fn : String) /- - `@[extern]` encoding: ```.entries = [adhoc `all]``` - `@[extern "level_hash"]` encoding: ```.entries = [standard `all "levelHash"]``` - `@[extern cpp "lean::string_size" llvm "lean_str_size"]` encoding: ```.entries = [standard `cpp "lean::string_size", standard `llvm "leanStrSize"]``` - `@[extern cpp inline "#1 + #2"]` encoding: ```.entries = [inline `cpp "#1 + #2"]``` - `@[extern cpp "foo" llvm adhoc]` encoding: ```.entries = [standard `cpp "foo", adhoc `llvm]``` - `@[extern 2 cpp "io_prim_println"]` encoding: ```.arity = 2, .entries = [standard `cpp "ioPrimPrintln"]``` -/ structure ExternAttrData := (arity : Option Nat := none) (entries : List ExternEntry) instance ExternAttrData.inhabited : Inhabited ExternAttrData := ⟨{ entries := [] }⟩ private partial def syntaxToExternEntries (a : Array Syntax) : Nat → List ExternEntry → Except String (List ExternEntry) | i entries := if i == a.size then Except.ok entries else match a.get i with | Syntax.ident _ _ backend _ _ => let i := i + 1; if i == a.size then Except.error "string or identifier expected" else match (a.get i).isIdOrAtom with | some "adhoc" => syntaxToExternEntries (i+1) (ExternEntry.adhoc backend :: entries) | some "inline" => let i := i + 1; match (a.get i).isStrLit with | some pattern => syntaxToExternEntries (i+1) (ExternEntry.inline backend pattern :: entries) | none => Except.error "string literal expected" | _ => match (a.get i).isStrLit with | some fn => syntaxToExternEntries (i+1) (ExternEntry.standard backend fn :: entries) | none => Except.error "string literal expected" | _ => Except.error "identifier expected" private def syntaxToExternAttrData (s : Syntax) : ExceptT String Id ExternAttrData := match s with | Syntax.missing => Except.ok { entries := [ ExternEntry.adhoc `all ] } | Syntax.node _ args _ => if args.size == 0 then Except.error "unexpected kind of argument" else let (arity, i) : Option Nat × Nat := match (args.get 0).isNatLit with | some arity => (some arity, 1) | none => (none, 0); match (args.get i).isStrLit with | some str => if args.size == i+1 then Except.ok { arity := arity, entries := [ ExternEntry.standard `all str ] } else Except.error "invalid extern attribute" | none => match syntaxToExternEntries args i [] with | Except.ok entries => Except.ok { arity := arity, entries := entries } | Except.error msg => Except.error msg | _ => Except.error "unexpected kind of argument" @[extern "lean_add_extern"] constant addExtern (env : Environment) (n : Name) : ExceptT String Id Environment := default _ def mkExternAttr : IO (ParametricAttribute ExternAttrData) := registerParametricAttribute `extern "builtin and foreign functions" (fun _ _ => syntaxToExternAttrData) (fun env declName _ => if env.isProjectionFn declName || env.isConstructor declName then addExtern env declName else pure env) @[init mkExternAttr] constant externAttr : ParametricAttribute ExternAttrData := default _ @[export lean.get_extern_attr_data_core] def getExternAttrData (env : Environment) (n : Name) : Option ExternAttrData := externAttr.getParam env n private def parseOptNum : Nat → String.Iterator → Nat → String.Iterator × Nat | 0 it r := (it, r) | (n+1) it r := if !it.hasNext then (it, r) else let c := it.curr; if '0' <= c && c <= '9' then parseOptNum n it.next (r*10 + (c.toNat - '0'.toNat)) else (it, r) def expandExternPatternAux (args : List String) : Nat → String.Iterator → String → String | 0 it r := r | (i+1) it r := if ¬ it.hasNext then r else let c := it.curr; if c ≠ '#' then expandExternPatternAux i it.next (r.push c) else let it := it.next; let (it, j) := parseOptNum it.remainingBytes it 0; let j := j-1; expandExternPatternAux i it (r ++ (args.getOpt j).getOrElse "") def expandExternPattern (pattern : String) (args : List String) : String := expandExternPatternAux args pattern.length pattern.mkIterator "" def mkSimpleFnCall (fn : String) (args : List String) : String := fn ++ "(" ++ ((args.intersperse ", ").foldl HasAppend.append "") ++ ")" def expandExternEntry : ExternEntry → List String → Option String | (ExternEntry.adhoc _) args := none -- backend must expand it | (ExternEntry.standard _ fn) args := some (mkSimpleFnCall fn args) | (ExternEntry.inline _ pat) args := some (expandExternPattern pat args) | (ExternEntry.foreign _ fn) args := some (mkSimpleFnCall fn args) def ExternEntry.backend : ExternEntry → Name | (ExternEntry.adhoc n) := n | (ExternEntry.inline n _) := n | (ExternEntry.standard n _) := n | (ExternEntry.foreign n _) := n def getExternEntryForAux (backend : Name) : List ExternEntry → Option ExternEntry | [] := none | (e::es) := if e.backend = `all then some e else if e.backend = backend then some e else getExternEntryForAux es def getExternEntryFor (d : ExternAttrData) (backend : Name) : Option ExternEntry := getExternEntryForAux backend d.entries def mkExternCall (d : ExternAttrData) (backend : Name) (args : List String) : Option String := do e ← getExternEntryFor d backend; expandExternEntry e args def isExtern (env : Environment) (fn : Name) : Bool := (getExternAttrData env fn).isSome /- We say a Lean function marked as `[extern "<c_fn_nane>"]` is for all backends, and it is implemented using `extern "C"`. Thus, there is no name mangling. -/ def isExternC (env : Environment) (fn : Name) : Bool := match getExternAttrData env fn with | some { entries := [ ExternEntry.standard `all _ ], .. } => true | _ => false def getExternNameFor (env : Environment) (backend : Name) (fn : Name) : Option String := do data ← getExternAttrData env fn; entry ← getExternEntryFor data backend; match entry with | ExternEntry.standard _ n => pure n | ExternEntry.foreign _ n => pure n | _ => failure end Lean
bfbc8a8e9425d946efe9ea6bf47f68116c194d3c
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/data/option/instances.lean
7397a497afa5431e518eff0304d25e949dc2cba9
[ "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
1,382
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.option.basic import init.meta.tactic universes u v @[inline] def option_bind {α : Type u} {β : Type v} : option α → (α → option β) → option β | none b := none | (some a) b := b a instance : monad option := {pure := @some, bind := @option_bind, id_map := λ α x, option.rec rfl (λ x, rfl) x, pure_bind := λ α β x f, rfl, bind_assoc := λ α β γ x f g, option.rec rfl (λ x, rfl) x} def option_orelse {α : Type u} : option α → option α → option α | (some a) o := some a | none (some a) := some a | none none := none instance : alternative option := { option.monad with failure := @none, orelse := @option_orelse } lemma option.eq_of_eq_some {α : Type u} : Π {x y : option α}, (∀z, x = some z ↔ y = some z) → x = y | none none h := rfl | none (some z) h := option.no_confusion ((h z).2 rfl) | (some z) none h := option.no_confusion ((h z).1 rfl) | (some z) (some w) h := option.no_confusion ((h w).2 rfl) (congr_arg some) lemma option.eq_some_of_is_some {α : Type u} : Π {o : option α} (h : option.is_some o), o = some (option.get h) | (some x) h := rfl | none h := false.rec _ $ bool.ff_ne_tt h
8c0cc26b603019a3c2c414940e9c61f1af7aad16
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/unzip_bug.lean
914789109ed078c238c39a4a6eeeeb5b7dc2d3b1
[ "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
406
lean
import data.examples.vector open nat vector prod variables {A B : Type} definition unzip : Π {n : nat}, vector (A × B) n → vector A n × vector B n | @unzip ⌞zero⌟ nil := (nil, nil) | @unzip ⌞succ n⌟ ((a, b) :: v) := match unzip v with (va, vb) := (a :: va, b :: vb) end example : unzip ((1, 20) :: ((2, 30) : nat × nat) :: nil) = (1 :: 2 :: nil, 20 :: 30 :: nil) := rfl
10972c8ac8d051b024ea7a9fd78f2323586f596b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/pfunctor/multivariate/basic.lean
1e0dacfdec7d7a2c0e34fd82ef1a813201dbc7cd
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,513
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import control.functor.multivariate import data.pfunctor.univariate.basic /-! # Multivariate polynomial functors. Multivariate polynomial functors are used for defining M-types and W-types. They map a type vector `α` to the type `Σ a : A, B a ⟹ α`, with `A : Type` and `B : A → typevec n`. They interact well with Lean's inductive definitions because they guarantee that occurrences of `α` are positive. -/ universes u v open_locale mvfunctor /-- multivariate polynomial functors -/ structure mvpfunctor (n : ℕ) := (A : Type.{u}) (B : A → typevec.{u} n) namespace mvpfunctor open mvfunctor (liftp liftr) variables {n m : ℕ} (P : mvpfunctor.{u} n) /-- Applying `P` to an object of `Type` -/ def obj (α : typevec.{u} n) : Type u := Σ a : P.A, P.B a ⟹ α /-- Applying `P` to a morphism of `Type` -/ def map {α β : typevec n} (f : α ⟹ β) : P.obj α → P.obj β := λ ⟨a, g⟩, ⟨a, typevec.comp f g⟩ instance : inhabited (mvpfunctor n) := ⟨⟨default, default⟩⟩ instance obj.inhabited {α : typevec n} [inhabited P.A] [Π i, inhabited (α i)] : inhabited (P.obj α) := ⟨ ⟨default, λ _ _, default⟩ ⟩ instance : mvfunctor P.obj := ⟨@mvpfunctor.map n P⟩ theorem map_eq {α β : typevec n} (g : α ⟹ β) (a : P.A) (f : P.B a ⟹ α) : @mvfunctor.map _ P.obj _ _ _ g ⟨a, f⟩ = ⟨a, g ⊚ f⟩ := rfl theorem id_map {α : typevec n} : ∀ x : P.obj α, typevec.id <$$> x = x | ⟨a, g⟩ := rfl theorem comp_map {α β γ : typevec n} (f : α ⟹ β) (g : β ⟹ γ) : ∀ x : P.obj α, (g ⊚ f) <$$> x = g <$$> (f <$$> x) | ⟨a, h⟩ := rfl instance : is_lawful_mvfunctor P.obj := { id_map := @id_map _ P, comp_map := @comp_map _ P } /-- Constant functor where the input object does not affect the output -/ def const (n : ℕ) (A : Type u) : mvpfunctor n := { A := A, B := λ a i, pempty } section const variables (n) {A : Type u} {α β : typevec.{u} n} /-- Constructor for the constant functor -/ def const.mk (x : A) {α} : (const n A).obj α := ⟨ x, λ i a, pempty.elim a ⟩ variables {n A} /-- Destructor for the constant functor -/ def const.get (x : (const n A).obj α) : A := x.1 @[simp] lemma const.get_map (f : α ⟹ β) (x : (const n A).obj α) : const.get (f <$$> x) = const.get x := by { cases x, refl } @[simp] lemma const.get_mk (x : A) : const.get (const.mk n x : (const n A).obj α) = x := by refl @[simp] lemma const.mk_get (x : (const n A).obj α) : const.mk n (const.get x) = x := by { cases x, dsimp [const.get,const.mk], congr' with _ ⟨ ⟩ } end const /-- Functor composition on polynomial functors -/ def comp (P : mvpfunctor.{u} n) (Q : fin2 n → mvpfunctor.{u} m) : mvpfunctor m := { A := Σ a₂ : P.1, Π i, P.2 a₂ i → (Q i).1, B := λ a, λ i, Σ j (b : P.2 a.1 j), (Q j).2 (a.snd j b) i } variables {P} {Q : fin2 n → mvpfunctor.{u} m} {α β : typevec.{u} m} /-- Constructor for functor composition -/ def comp.mk (x : P.obj (λ i, (Q i).obj α)) : (comp P Q).obj α := ⟨ ⟨ x.1, λ i a, (x.2 _ a).1 ⟩, λ i a, (x.snd a.fst (a.snd).fst).snd i (a.snd).snd ⟩ /-- Destructor for functor composition -/ def comp.get (x : (comp P Q).obj α) : P.obj (λ i, (Q i).obj α) := ⟨ x.1.1, λ i a, ⟨x.fst.snd i a, λ (j : fin2 m) (b : (Q i).B _ j), x.snd j ⟨i, ⟨a, b⟩⟩⟩ ⟩ lemma comp.get_map (f : α ⟹ β) (x : (comp P Q).obj α) : comp.get (f <$$> x) = (λ i (x : (Q i).obj α), f <$$> x) <$$> comp.get x := by { cases x, refl } @[simp] lemma comp.get_mk (x : P.obj (λ i, (Q i).obj α)) : comp.get (comp.mk x) = x := begin cases x, simp! [comp.get,comp.mk], end @[simp] lemma comp.mk_get (x : (comp P Q).obj α) : comp.mk (comp.get x) = x := begin cases x, dsimp [comp.get,comp.mk], ext : 2; intros, refl, refl, congr, ext1; intros; refl, ext : 2, congr, rcases x_1 with ⟨a,b,c⟩; refl end /- lifting predicates and relations -/ theorem liftp_iff {α : typevec n} (p : Π ⦃i⦄ , α i → Prop) (x : P.obj α) : liftp p x ↔ ∃ a f, x = ⟨a, f⟩ ∧ ∀ i j, p (f i j) := begin split, { rintros ⟨y, hy⟩, cases h : y with a f, refine ⟨a, λ i j, (f i j).val, _, λ i j, (f i j).property⟩, rw [←hy, h, map_eq], refl }, rintros ⟨a, f, xeq, pf⟩, use ⟨a, λ i j, ⟨f i j, pf i j⟩⟩, rw [xeq], reflexivity end theorem liftp_iff' {α : typevec n} (p : Π ⦃i⦄ , α i → Prop) (a : P.A) (f : P.B a ⟹ α) : @liftp.{u} _ P.obj _ α p ⟨a,f⟩ ↔ ∀ i x, p (f i x) := begin simp only [liftp_iff, sigma.mk.inj_iff]; split; intro, { casesm* [Exists _, _ ∧ _], subst_vars, assumption }, repeat { constructor <|> assumption } end theorem liftr_iff {α : typevec n} (r : Π ⦃i⦄, α i → α i → Prop) (x y : P.obj α) : liftr r x y ↔ ∃ a f₀ f₁, x = ⟨a, f₀⟩ ∧ y = ⟨a, f₁⟩ ∧ ∀ i j, r (f₀ i j) (f₁ i j) := begin split, { rintros ⟨u, xeq, yeq⟩, cases h : u with a f, use [a, λ i j, (f i j).val.fst, λ i j, (f i j).val.snd], split, { rw [←xeq, h], refl }, split, { rw [←yeq, h], refl }, intros i j, exact (f i j).property }, rintros ⟨a, f₀, f₁, xeq, yeq, h⟩, use ⟨a, λ i j, ⟨(f₀ i j, f₁ i j), h i j⟩⟩, dsimp, split, { rw [xeq], refl }, rw [yeq], refl end open set mvfunctor theorem supp_eq {α : typevec n} (a : P.A) (f : P.B a ⟹ α) (i) : @supp.{u} _ P.obj _ α (⟨a,f⟩ : P.obj α) i = f i '' univ := begin ext, simp only [supp, image_univ, mem_range, mem_set_of_eq], split; intro h, { apply @h (λ i x, ∃ (y : P.B a i), f i y = x), rw liftp_iff', intros, refine ⟨_,rfl⟩ }, { simp only [liftp_iff'], cases h, subst x, tauto } end end mvpfunctor /- Decomposing an n+1-ary pfunctor. -/ namespace mvpfunctor open typevec variables {n : ℕ} (P : mvpfunctor.{u} (n+1)) /-- Split polynomial functor, get a n-ary functor from a `n+1`-ary functor -/ def drop : mvpfunctor n := { A := P.A, B := λ a, (P.B a).drop } /-- Split polynomial functor, get a univariate functor from a `n+1`-ary functor -/ def last : pfunctor := { A := P.A, B := λ a, (P.B a).last } /-- append arrows of a polynomial functor application -/ @[reducible] def append_contents {α : typevec n} {β : Type*} {a : P.A} (f' : P.drop.B a ⟹ α) (f : P.last.B a → β) : P.B a ⟹ α ::: β := split_fun f' f end mvpfunctor
8bc7b067d819d565b7239cef4365dbba7e2d3492
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/tests/playground/flat_parser2.lean
790edd21da19c8c6f41a75ec8b2a0bb74ae8362e
[ "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
17,139
lean
import init.Lean.Message init.Lean.Parser.Syntax init.Lean.Parser.Trie init.Lean.Parser.basic import init.Lean.Parser.token namespace Lean namespace flatParser open String open Parser (Syntax Syntax.missing Syntax.atom Syntax.ident Syntax.rawNode number stringLit) open Parser (Trie TokenMap) def maxPrec : Nat := 1024 abbrev pos := String.utf8Pos /-- A precomputed cache for quickly mapping Char offsets to positions. -/ structure FileMap := (offsets : Array Nat) (lines : Array Nat) namespace FileMap private def fromStringAux (s : String) : Nat → Nat → Nat → pos → Array Nat → Array Nat → FileMap | 0 offset line i offsets lines := ⟨offsets.push offset, lines.push line⟩ | (k+1) offset line i offsets lines := if s.utf8AtEnd i then ⟨offsets.push offset, lines.push line⟩ else let c := s.utf8Get i in let i := s.utf8Next i in let offset := offset + 1 in if c = '\n' then fromStringAux k offset (line+1) i (offsets.push offset) (lines.push (line+1)) else fromStringAux k offset line i offsets lines def fromString (s : String) : FileMap := fromStringAux s s.length 0 1 0 (Array.nil.push 0) (Array.nil.push 1) /- Remark: `offset is in [(offsets.get b), (offsets.get e)]` and `b < e` -/ private def toPositionAux (offsets : Array Nat) (lines : Array Nat) (offset : Nat) : Nat → Nat → Nat → Position | 0 b e := ⟨offset, 1⟩ -- unreachable | (k+1) b e := let offsetB := offsets.read' b in if e = b + 1 then ⟨offset - offsetB, lines.read' b⟩ else let m := (b + e) / 2 in let offsetM := offsets.read' m in if offset = offsetM then ⟨0, lines.read' m⟩ else if offset > offsetM then toPositionAux k m e else toPositionAux k b m def toPosition : FileMap → Nat → Position | ⟨offsets, lines⟩ offset := toPositionAux offsets lines offset offsets.size 0 (offsets.size-1) end FileMap structure TokenConfig := («prefix» : String) (lbp : Nat := 0) structure FrontendConfig := (filename : String) (input : String) (FileMap : FileMap) /- Remark: if we have a Node in the Trie with `some TokenConfig`, the String induced by the path is equal to the `TokenConfig.prefix`. -/ structure ParserConfig extends FrontendConfig := (tokens : Trie TokenConfig) -- Backtrackable State structure ParserState := (messages : MessageLog) structure TokenCacheEntry := (startPos stopPos : pos) (tk : Syntax) -- Non-backtrackable State structure ParserCache := (tokenCache : Option TokenCacheEntry := none) inductive Result (α : Type) | ok (a : α) (i : pos) (cache : ParserCache) (State : ParserState) (eps : Bool) : Result | error {} (msg : String) (i : pos) (cache : ParserCache) (stx : Syntax) (eps : Bool) : Result inductive Result.IsOk {α : Type} : Result α → Prop | mk (a : α) (i : pos) (cache : ParserCache) (State : ParserState) (eps : Bool) : Result.IsOk (Result.ok a i cache State eps) theorem errorIsNotOk {α : Type} {msg : String} {i : pos} {cache : ParserCache} {stx : Syntax} {eps : Bool} (h : Result.IsOk (@Result.error α msg i cache stx eps)) : False := match h with end @[inline] def unreachableError {α β : Type} {msg : String} {i : pos} {cache : ParserCache} {stx : Syntax} {eps : Bool} (h : Result.IsOk (@Result.error α msg i cache stx eps)) : β := False.elim (errorIsNotOk h) def resultOk := {r : Result Unit // r.IsOk} @[inline] def mkResultOk (i : pos) (cache : ParserCache) (State : ParserState) (eps := tt) : resultOk := ⟨Result.ok () i cache State eps, Result.IsOk.mk _ _ _ _ _⟩ def mkError {α : Type} (r : resultOk) (msg : String) (stx : Syntax := Syntax.missing) (eps := tt) : Result α := match r with | ⟨Result.ok _ i c s _, _⟩ := Result.error msg i c stx eps | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h def parserCoreM (α : Type) := resultOk → Result α abbrev parserCore := parserCoreM Syntax @[inline] def parserCoreM.pure {α : Type} (a : α) : parserCoreM α := λ r, match r with | ⟨Result.ok _ it c s _, h⟩ := Result.ok a it c s tt | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inlineIfReduce] def strictOr (b₁ b₂ : Bool) := b₁ || b₂ @[inlineIfReduce] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂ @[inline] def parserCoreM.bind {α β : Type} (x : parserCoreM α) (f : α → parserCoreM β) : parserCoreM β := λ r, match x r with | Result.ok a i c s e₁ := (match f a (mkResultOk i c s) with | Result.ok b i c s e₂ := Result.ok b i c s (strictAnd e₁ e₂) | Result.error msg i c stx e₂ := Result.error msg i c stx (strictAnd e₁ e₂)) | Result.error msg i c stx e := Result.error msg i c stx e instance : Monad parserCoreM := {bind := @parserCoreM.bind, pure := @parserCoreM.pure} instance : Inhabited parserCore := ⟨λ r, mkError r "error"⟩ @[inline] def parserCoreM.error {α : Type} (msg : String) : parserCoreM α := λ r, mkError r msg @[inline] def error {α : Type} {m : Type → Type} [HasMonadLiftT parserCoreM m] (msg : String) : m α := monadLift $ parserCoreM.error msg abbrev BasicParserM : Type → Type := ReaderT ParserConfig parserCoreM abbrev basicParser : Type := BasicParserM Syntax abbrev CommandParserM (ρ : Type) : Type → Type := ReaderT ρ (ReaderT parserCore parserCoreM) abbrev TermParserM : Type → Type := ReaderT (Nat → parserCore) (CommandParserM ParserConfig) abbrev termParser : Type := TermParserM Syntax abbrev trailingTermParser : Type := Syntax → termParser structure CommandParserConfig extends ParserConfig := (leadingTermParsers : TokenMap termParser) (trailingTermParsers : TokenMap trailingTermParser) abbrev commandParser : Type := CommandParserM CommandParserConfig Syntax abbrev commandParserCore : Type := CommandParserM ParserConfig Syntax @[inline] def termParserOfBasicParser {α : Type} (p : BasicParserM α) : TermParserM α := λ _ cfg _, p cfg @[inline] def commandParserOfBasicParser {α : Type} (p : BasicParserM α) : CommandParserM CommandParserConfig α := λ cfg _, p cfg.toParserConfig instance basic2termP : HasMonadLift BasicParserM TermParserM := ⟨@termParserOfBasicParser⟩ instance basic2commandP : HasMonadLift BasicParserM (CommandParserM CommandParserConfig) := ⟨@commandParserOfBasicParser⟩ @[inline] def Term.Parser (rbp := 0) : termParser := λ p _ _, p rbp @[inline] def command.Parser : commandParser := λ _ p, p @[inline] def readCfg : TermParserM ParserConfig := λ _ cfg _, pure cfg def peekToken : BasicParserM Syntax := error "TODO" def currLbp : TermParserM Nat := do tk ← monadLift peekToken, match tk with | Syntax.atom ⟨_, sym⟩ := do cfg ← readCfg, (match cfg.tokens.matchPrefix sym.mkIterator with | some ⟨_, tkCfg⟩ := pure tkCfg.lbp | _ := error "currLbp: unreachable") | Syntax.rawNode {kind := @number, ..} := pure maxPrec | Syntax.rawNode {kind := @stringLit, ..} := pure maxPrec | Syntax.ident _ := pure maxPrec | _ := error "currLbp: unknown token kind" #exit match tk with | Syntax.atom ⟨_, sym⟩ := do cfg ← read, -- some ⟨_, tkCfg⟩ ← pure (cfg.tokens.matchPrefix sym.mkIterator) | error "currLbp: unreachable", pure 0 | Syntax.ident _ := pure maxPrec | Syntax.rawNode {kind := @number, ..} := pure maxPrec | Syntax.rawNode {kind := @stringLit, ..} := pure maxPrec | _ := error "currLbp: unknown token kind" private def trailing (cfg : CommandParserConfig) : trailingTermParser := λ _ p _ _ r, p 0 r -- TODO(Leo) private def leading (cfg : CommandParserConfig) : termParser := λ p _ _ r, p 0 r -- TODO(Leo) def dummy : Nat → parserCore := λ _ r, mkError r "dummy" def pratt (leadingP : termParser) (trailingP : trailingTermParser) (p : termParser) : commandParserCore := p dummy def commandParserOfTermParser (p : termParser) : commandParser := λ cfg rec r, let leadingP : termParser := leading cfg in let trailingP : trailingTermParser := trailing cfg in let cfg : ParserConfig := cfg.toParserConfig in let p : commandParserCore := pratt leadingP trailingP p in p cfg rec r #exit def prattParser (cfg : CommandParserConfig) : termParser := leading @[inline] def toParserCore (termP : Nat → Parser) (cmdP : parserCore) : Nat → parserCore := fix (λ recF rbp cfg r, termP rbp cmdP recF cfg r) @[inline] def Parser.run (x : Parser) (termP : Nat → Parser) (cmdP : parserCore) : parserCore := x cmdP (toParserCore termP cmdP) -- STOPPED HERE #exit def parserCore.run (cmdP : parserCore) (termP : parserCore) : parserCore := def aux (f : Nat → parserCore) : Nat → parserCore structure CommandParserConfig extends recParserConfig := (leadingTermParsers : TokenMap Parser) (trailingTermParsers : TokenMap trailingParser) abbrev CommandParserM (α : Type) : Type := parserCoreM CommandParserConfig α abbrev commandParser := CommandParserM Syntax #exit -- abbrev -- def parserM (α : Type) := recParsers → parserCoreM α abbreviation Parser := parserM Syntax abbreviation trailingParser := Syntax → Parser @[inline] def command.Parser : Parser := λ cfg, cfg.cmdParser cfg @[inline] def Term.Parser (rbp : Nat := 0) : Parser := λ ps, ps.termParser rbp instance : Monad parserM := {pure := @parserM.pure, bind := @parserM.bind} @[inline] protected def orelse {α : Type} (p q : parserM α) : parserM α := λ ps cfg r, match r with | ⟨Result.ok _ i₁ _ s₁ _, _⟩ := (match p ps cfg r with | Result.error msg₁ i₂ c₂ stx₁ tt := q ps cfg (mkResultOk i₁ c₂ s₁) | other := other) | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline] protected def failure {α : Type} : parserM α := λ _ _ r, match r with | ⟨Result.ok _ i c s _, h⟩ := Result.error "failure" i c Syntax.missing tt | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h instance : Alternative parserM := { orelse := @flatParser.orelse, failure := @flatParser.failure, ..flatParser.Monad } def setSilentError {α : Type} : Result α → Result α | (Result.error i c msg stx _) := Result.error i c msg stx tt | other := other /-- `try p` behaves like `p`, but it pretends `p` hasn't consumed any input when `p` fails. -/ @[inline] def try {α : Type} (p : parserM α) : parserM α := λ ps cfg r, setSilentError (p ps cfg r) @[inline] def atEnd (cfg : ParserConfig) (i : pos) : Bool := cfg.input.utf8AtEnd i @[inline] def curr (cfg : ParserConfig) (i : pos) : Char := cfg.input.utf8Get i @[inline] def next (cfg : ParserConfig) (i : pos) : pos := cfg.input.utf8Next i @[inline] def inputSize (cfg : ParserConfig) : Nat := cfg.input.length @[inline] def currPos : resultOk → pos | ⟨Result.ok _ i _ _ _, _⟩ := i | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline] def currState : resultOk → ParserState | ⟨Result.ok _ _ _ s _, _⟩ := s | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[inline] def satisfy (p : Char → Bool) : parserM Char := λ _ cfg r, match r with | ⟨Result.ok _ i ch st e, _⟩ := if atEnd cfg i then mkError r "end of input" else let c := curr cfg i in if p c then Result.ok c (next cfg i) ch st ff else mkError r "unexpected character" | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h def any : parserM Char := satisfy (λ _, tt) @[specialize] def takeUntilAux (p : Char → Bool) (cfg : ParserConfig) : Nat → resultOk → Result Unit | 0 r := r.val | (n+1) r := match r with | ⟨Result.ok _ i ch st e, _⟩ := if atEnd cfg i then r.val else let c := curr cfg i in if p c then r.val else takeUntilAux n (mkResultOk (next cfg i) ch st tt) | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h @[specialize] def takeUntil (p : Char → Bool) : parserM Unit := λ ps cfg r, takeUntilAux p cfg (inputSize cfg) r def takeUntilNewLine : parserM Unit := takeUntil (= '\n') def whitespace : parserM Unit := takeUntil (λ c, !c.isWhitespace) -- setOption Trace.Compiler.boxed True --- setOption pp.implicit True def strAux (cfg : ParserConfig) (str : String) (error : String) : Nat → resultOk → pos → Result Unit | 0 r j := mkError r error | (n+1) r j := if str.utf8AtEnd j then r.val else match r with | ⟨Result.ok _ i ch st e, _⟩ := if atEnd cfg i then Result.error error i ch Syntax.missing tt else if curr cfg i = str.utf8Get j then strAux n (mkResultOk (next cfg i) ch st tt) (str.utf8Next j) else Result.error error i ch Syntax.missing tt | ⟨Result.error _ _ _ _ _, h⟩ := unreachableError h -- #exit @[inline] def str (s : String) : parserM Unit := λ ps cfg r, strAux cfg s ("expected " ++ repr s) (inputSize cfg) r 0 @[specialize] def manyAux (p : parserM Unit) : Nat → Bool → parserM Unit | 0 fst := pure () | (k+1) fst := λ ps cfg r, let i₀ := currPos r in let s₀ := currState r in match p ps cfg r with | Result.ok a i c s _ := manyAux k ff ps cfg (mkResultOk i c s) | Result.error _ _ c _ _ := Result.ok () i₀ c s₀ fst @[inline] def many (p : parserM Unit) : parserM Unit := λ ps cfg r, manyAux p (inputSize cfg) tt ps cfg r @[inline] def many1 (p : parserM Unit) : parserM Unit := p *> many p def dummyParserCore : parserCore := λ cfg r, mkError r "dummy" def testParser {α : Type} (x : parserM α) (input : String) : String := let r := x { cmdParser := dummyParserCore, termParser := λ _, dummyParserCore } { filename := "test", input := input, FileMap := FileMap.fromString input, tokens := Lean.Parser.Trie.mk } (mkResultOk 0 {} {messages := MessageLog.Empty}) in match r with | Result.ok _ i _ _ _ := "Ok at " ++ toString i | Result.error msg i _ _ _ := "Error at " ++ toString i ++ ": " ++ msg /- mutual def recCmd, recTerm (parseCmd : Parser) (parseTerm : Nat → Parser) (parseLvl : Nat → parserCore) with recCmd : Nat → parserCore | 0 cfg r := mkError r "Parser: no progress" | (n+1) cfg r := parseCmd ⟨recCmd n, parseLvl, recTerm n⟩ cfg r with recTerm : Nat → Nat → parserCore | 0 rbp cfg r := mkError r "Parser: no progress" | (n+1) rbp cfg r := parseTerm rbp ⟨recCmd n, parseLvl, recTerm n⟩ cfg r -/ /- def runParser (x : Parser) (parseCmd : Parser) (parseLvl : Nat → Parser) (parseTerm : Nat → Parser) (input : Iterator) (cfg : ParserConfig) : Result Syntax := let it := input in let n := it.remaining in let r := mkResultOk it {} {messages := MessageLog.Empty} in let pl := recLvl (parseLvl) n in let ps : recParsers := { cmdParser := recCmd parseCmd parseTerm pl n, lvlParser := pl, termParser := recTerm parseCmd parseTerm pl n } in x ps cfg r -/ structure parsingTables := (leadingTermParsers : TokenMap Parser) (trailingTermParsers : TokenMap trailingParser) abbreviation CommandParserM (α : Type) := parsingTables → parserM α end flatParser end Lean def mkBigString : Nat → String → String | 0 s := s | (n+1) s := mkBigString n (s ++ "-- new comment\n") section open Lean.flatParser def flatP : parserM Unit := many1 (str "--" *> takeUntil (= '\n') *> any *> pure ()) end section open Lean.Parser open Lean.Parser.MonadParsec @[reducible] def Parser (α : Type) : Type := ReaderT Lean.flatParser.recParsers (ReaderT Lean.flatParser.ParserConfig (ParsecT Syntax (StateT ParserCache id))) α def testParsec (p : Parser Unit) (input : String) : String := let ps : Lean.flatParser.recParsers := { cmdParser := Lean.flatParser.dummyParserCore, termParser := λ _, Lean.flatParser.dummyParserCore } in let cfg : Lean.flatParser.ParserConfig := { filename := "test", input := input, FileMap := Lean.flatParser.FileMap.fromString input, tokens := Lean.Parser.Trie.mk } in let r := p ps cfg input.mkIterator {} in match r with | (Parsec.Result.ok _ it _, _) := "OK at " ++ toString it.offset | (Parsec.Result.error msg _, _) := "Error " ++ msg.toString def parsecP : Parser Unit := many1' (str "--" *> takeUntil (λ c, c = '\n') *> any *> pure ()) end @[noinline] def testFlatP (s : String) : IO Unit := IO.println (Lean.flatParser.testParser flatP s) @[noinline] def testParsecP (s : String) : IO Unit := IO.println (testParsec parsecP s) def prof {α : Type} (msg : String) (p : IO α) : IO α := let msg₁ := "Time for '" ++ msg ++ "':" in let msg₂ := "Memory usage for '" ++ msg ++ "':" in allocprof msg₂ (timeit msg₁ p) def main (xs : List String) : IO UInt32 := let s₁ := mkBigString xs.head.toNat "" in let s₂ := s₁ ++ "bad" ++ mkBigString 20 "" in prof "flat Parser 1" (testFlatP s₁) *> prof "flat Parser 2" (testFlatP s₂) *> -- prof "Parsec 1" (testParsecP s₁) *> -- prof "Parsec 2" (testParsecP s₂) *> pure 0
32d746b4f1b37de4f1565afff349a93a8cc0a377
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/preserves/shapes/kernels.lean
7f916b5db6c08ca01b1d8bac76f182ae1fcb3559
[ "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,750
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.kernels import category_theory.limits.preserves.shapes.zero /-! # Preserving (co)kernels > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Constructions to relate the notions of preserving (co)kernels and reflecting (co)kernels to concrete (co)forks. In particular, we show that `kernel_comparison f g G` is an isomorphism iff `G` preserves the limit of the parallel pair `f,0`, as well as the dual result. -/ noncomputable theory universes v₁ v₂ u₁ u₂ open category_theory category_theory.category category_theory.limits variables {C : Type u₁} [category.{v₁} C] [has_zero_morphisms C] variables {D : Type u₂} [category.{v₂} D] [has_zero_morphisms D] variables (G : C ⥤ D) [functor.preserves_zero_morphisms G] namespace category_theory.limits section kernels variables {X Y Z : C} {f : X ⟶ Y} {h : Z ⟶ X} (w : h ≫ f = 0) /-- The map of a kernel fork is a limit iff the kernel fork consisting of the mapped morphisms is a limit. This essentially lets us commute `kernel_fork.of_ι` with `functor.map_cone`. This is a variant of `is_limit_map_cone_fork_equiv` for equalizers, which we can't use directly between `G.map 0 = 0` does not hold definitionally. -/ def is_limit_map_cone_fork_equiv' : is_limit (G.map_cone (kernel_fork.of_ι h w)) ≃ is_limit (kernel_fork.of_ι (G.map h) (by simp only [←G.map_comp, w, functor.map_zero]) : fork (G.map f) 0) := begin refine (is_limit.postcompose_hom_equiv _ _).symm.trans (is_limit.equiv_iso_limit _), refine parallel_pair.ext (iso.refl _) (iso.refl _) _ _; simp, refine fork.ext (iso.refl _) _, simp [fork.ι] end /-- The property of preserving kernels expressed in terms of kernel forks. This is a variant of `is_limit_fork_map_of_is_limit` for equalizers, which we can't use directly between `G.map 0 = 0` does not hold definitionally. -/ def is_limit_fork_map_of_is_limit' [preserves_limit (parallel_pair f 0) G] (l : is_limit (kernel_fork.of_ι h w)) : is_limit (kernel_fork.of_ι (G.map h) (by simp only [←G.map_comp, w, functor.map_zero]) : fork (G.map f) 0) := is_limit_map_cone_fork_equiv' G w (preserves_limit.preserves l) variables (f) [has_kernel f] /-- If `G` preserves kernels and `C` has them, then the fork constructed of the mapped morphisms of a kernel fork is a limit. -/ def is_limit_of_has_kernel_of_preserves_limit [preserves_limit (parallel_pair f 0) G] : is_limit (fork.of_ι (G.map (kernel.ι f)) (by simp only [←G.map_comp, equalizer.condition, comp_zero, functor.map_zero]) : fork (G.map f) 0) := is_limit_fork_map_of_is_limit' G (kernel.condition f) (kernel_is_kernel f) instance [preserves_limit (parallel_pair f 0) G] : has_kernel (G.map f) := { exists_limit := ⟨⟨_, is_limit_of_has_kernel_of_preserves_limit G f⟩⟩, } variables [has_kernel (G.map f)] /-- If the kernel comparison map for `G` at `f` is an isomorphism, then `G` preserves the kernel of `f`. -/ def preserves_kernel.of_iso_comparison [i : is_iso (kernel_comparison f G)] : preserves_limit (parallel_pair f 0) G := begin apply preserves_limit_of_preserves_limit_cone (kernel_is_kernel f), apply (is_limit_map_cone_fork_equiv' G (kernel.condition f)).symm _, apply is_limit.of_point_iso (kernel_is_kernel (G.map f)), exact i, end variables [preserves_limit (parallel_pair f 0) G] /-- If `G` preserves the kernel of `f`, then the kernel comparison map for `G` at `f` is an isomorphism. -/ def preserves_kernel.iso : G.obj (kernel f) ≅ kernel (G.map f) := is_limit.cone_point_unique_up_to_iso (is_limit_of_has_kernel_of_preserves_limit G f) (kernel_is_kernel _) @[simp] lemma preserves_kernel.iso_hom : (preserves_kernel.iso G f).hom = kernel_comparison f G := rfl instance : is_iso (kernel_comparison f G) := begin rw ← preserves_kernel.iso_hom, apply_instance end @[reassoc] lemma kernel_map_comp_preserves_kernel_iso_inv {X' Y' : C} (g : X' ⟶ Y') [has_kernel g] [has_kernel (G.map g)] [preserves_limit (parallel_pair g 0) G] (p : X ⟶ X') (q : Y ⟶ Y') (hpq : f ≫ q = p ≫ g) : kernel.map (G.map f) (G.map g) (G.map p) (G.map q) (by rw [←G.map_comp, hpq, G.map_comp]) ≫ (preserves_kernel.iso G _).inv = (preserves_kernel.iso G _).inv ≫ G.map (kernel.map f g p q hpq) := begin rw [iso.comp_inv_eq, category.assoc, preserves_kernel.iso_hom, iso.eq_inv_comp], exact kernel_comparison_comp_kernel_map _ _ _ _ _ _, end end kernels section cokernels variables {X Y Z : C} {f : X ⟶ Y} {h : Y ⟶ Z} (w : f ≫ h = 0) /-- The map of a cokernel cofork is a colimit iff the cokernel cofork consisting of the mapped morphisms is a colimit. This essentially lets us commute `cokernel_cofork.of_π` with `functor.map_cocone`. This is a variant of `is_colimit_map_cocone_cofork_equiv` for equalizers, which we can't use directly between `G.map 0 = 0` does not hold definitionally. -/ def is_colimit_map_cocone_cofork_equiv' : is_colimit (G.map_cocone (cokernel_cofork.of_π h w)) ≃ is_colimit (cokernel_cofork.of_π (G.map h) (by simp only [←G.map_comp, w, functor.map_zero]) : cofork (G.map f) 0) := begin refine (is_colimit.precompose_hom_equiv _ _).symm.trans (is_colimit.equiv_iso_colimit _), refine parallel_pair.ext (iso.refl _) (iso.refl _) _ _; simp, refine cofork.ext (iso.refl _) _, simp only [cofork.π, iso.refl_hom, id_comp, cocones.precompose_obj_ι, nat_trans.comp_app, parallel_pair.ext_hom_app, functor.map_cocone_ι_app, cofork.of_π_ι_app], apply category.comp_id end /-- The property of preserving cokernels expressed in terms of cokernel coforks. This is a variant of `is_colimit_cofork_map_of_is_colimit` for equalizers, which we can't use directly between `G.map 0 = 0` does not hold definitionally. -/ def is_colimit_cofork_map_of_is_colimit' [preserves_colimit (parallel_pair f 0) G] (l : is_colimit (cokernel_cofork.of_π h w)) : is_colimit (cokernel_cofork.of_π (G.map h) (by simp only [←G.map_comp, w, functor.map_zero]) : cofork (G.map f) 0) := is_colimit_map_cocone_cofork_equiv' G w (preserves_colimit.preserves l) variables (f) [has_cokernel f] /-- If `G` preserves cokernels and `C` has them, then the cofork constructed of the mapped morphisms of a cokernel cofork is a colimit. -/ def is_colimit_of_has_cokernel_of_preserves_colimit [preserves_colimit (parallel_pair f 0) G] : is_colimit (cofork.of_π (G.map (cokernel.π f)) (by simp only [←G.map_comp, coequalizer.condition, zero_comp, functor.map_zero]) : cofork (G.map f) 0) := is_colimit_cofork_map_of_is_colimit' G (cokernel.condition f) (cokernel_is_cokernel f) instance [preserves_colimit (parallel_pair f 0) G] : has_cokernel (G.map f) := { exists_colimit := ⟨⟨_, is_colimit_of_has_cokernel_of_preserves_colimit G f⟩⟩, } variables [has_cokernel (G.map f)] /-- If the cokernel comparison map for `G` at `f` is an isomorphism, then `G` preserves the cokernel of `f`. -/ def preserves_cokernel.of_iso_comparison [i : is_iso (cokernel_comparison f G)] : preserves_colimit (parallel_pair f 0) G := begin apply preserves_colimit_of_preserves_colimit_cocone (cokernel_is_cokernel f), apply (is_colimit_map_cocone_cofork_equiv' G (cokernel.condition f)).symm _, apply is_colimit.of_point_iso (cokernel_is_cokernel (G.map f)), exact i, end variables [preserves_colimit (parallel_pair f 0) G] /-- If `G` preserves the cokernel of `f`, then the cokernel comparison map for `G` at `f` is an isomorphism. -/ def preserves_cokernel.iso : G.obj (cokernel f) ≅ cokernel (G.map f) := is_colimit.cocone_point_unique_up_to_iso (is_colimit_of_has_cokernel_of_preserves_colimit G f) (cokernel_is_cokernel _) @[simp] lemma preserves_cokernel.iso_inv : (preserves_cokernel.iso G f).inv = cokernel_comparison f G := rfl instance : is_iso (cokernel_comparison f G) := begin rw ← preserves_cokernel.iso_inv, apply_instance end @[reassoc] lemma preserves_cokernel_iso_comp_cokernel_map {X' Y' : C} (g : X' ⟶ Y') [has_cokernel g] [has_cokernel (G.map g)] [preserves_colimit (parallel_pair g 0) G] (p : X ⟶ X') (q : Y ⟶ Y') (hpq : f ≫ q = p ≫ g) : (preserves_cokernel.iso G _).hom ≫ cokernel.map (G.map f) (G.map g) (G.map p) (G.map q) (by rw [←G.map_comp, hpq, G.map_comp]) = G.map (cokernel.map f g p q hpq) ≫ (preserves_cokernel.iso G _).hom := begin rw [←iso.comp_inv_eq, category.assoc, ←iso.eq_inv_comp], exact cokernel_map_comp_cokernel_comparison _ _ _ _ _ _, end end cokernels end category_theory.limits
d14576e86597c54ecbd53c9bff9ad1d62a512b87
f6fc81bc8b5b766295e383d57865e4a9d2ea12c9
/exercise/1-exercise.lean
c7b8734fb89c28b2337ab2c8dba422e153c8d5d7
[ "CC-BY-4.0" ]
permissive
locnh2012/formalabstracts
ef43b9bbf31bc8c448bc6628a9b936253f351964
67bec3c68a962718528f5b968b739bd889be69b7
refs/heads/master
1,584,616,125,965
1,529,294,544,000
1,529,294,700,000
136,434,328
0
0
null
1,528,354,107,000
1,528,354,106,000
null
UTF-8
Lean
false
false
1,324
lean
open set -- Twin Prime Conjecture -- def isPrime (n : ℕ) : Prop := (n ≥ 2) ∧ (∀ m : ℕ, m ≥ 1 ∧ m ∣ n → (m = 1 ∨ m =n)) #check isPrime def twinPrime(p : ℕ) : Prop := isPrime(p) ∧ (∃ q : ℕ, (q = p + 2 ∨ q = p - 2) ∧ isPrime(q)) #check twinPrime theorem infinite_twin_prime: ∀ n : ℕ, ∃ p, p ≥ n ∧ twinPrime(p) := begin admit, end #check infinite_twin_prime -- Goldbach’s Conjecture -- def isEven(n : ℕ) : Prop := ∃ m, n = m * 2 theorem goldbach_conjecture(n : ℕ): isEven(n) → ∃ p q : ℕ, isPrime(p) ∧ isPrime(q) ∧ (p + q = n) := begin admit, end #check goldbach_conjecture -- The n^2 + 1 Conjecture -- theorem n2_1_conjecture(n : ℕ): ∃ p, (p = n^2 + 1) ∧ isPrime(p) := begin admit, end #check n2_1_conjecture -- The Polignac Conjecture -- -- syntax error? -- theorem polignac_conjecture(n : ℕ): isEven(n) -> -- ∃ p q : ℕ, isPrime(p) ∧ isPrime(q) ∧ abs(p - q) < 1 := -- begin -- admit, -- end theorem polignac_conjecture(n : ℕ): isEven(n) -> ∃ p q : ℕ, isPrime(p) ∧ isPrime(q) ∧ ((p-q=n) ∨ (q-p=n)) := begin admit, end #check polignac_conjecture -- The Opperman Conjecture -- theorem opperman_conjecture(n : ℕ): ∃ p : ℕ, isPrime(p) ∧ (n^2 ≤ p) ∧ (p ≤ (n+1)^2) := begin admit, end #check opperman_conjecture
7ef76c92924c0b9161b7e7a02c21c55e1b885f56
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/polyhedral_lattice/topology.lean
45817b13ca245a7c4aa41185b38ba578206f0d0a
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,072
lean
import polyhedral_lattice.basic import normed_group.pseudo_normed_group import pseudo_normed_group.profinitely_filtered noncomputable theory open_locale nnreal big_operators namespace polyhedral_lattice open pseudo_normed_group normed_group variables (Λ : Type*) [polyhedral_lattice Λ] lemma filtration_finite (ε : ℝ≥0) : (filtration Λ ε).finite := begin classical, obtain ⟨ι, _ι_inst, l, hl, hl'⟩ := polyhedral_lattice.polyhedral Λ, resetI, let n : ι → ℕ := λ i, ⌈(ε / ∥l i∥₊ : ℝ)⌉.nat_abs + 1, let S := finset.univ.pi (λ i, finset.range (n i)), let S' : finset Λ := S.image (λ x, ∑ i, x i (finset.mem_univ _) • l i), apply S'.finite_to_set.subset, intros l₀ H, obtain ⟨c, h1, h2⟩ := hl.generates_nnnorm l₀, simp only [S', set.mem_image, finset.mem_univ, finset.mem_pi, forall_true_left, finset.mem_range, finset.mem_coe, finset.coe_image], refine ⟨λ i _, c i, _, h1.symm⟩, rintro i -, rw finset.mem_range, apply nat.succ_le_succ, contrapose! H, simp only [not_le, semi_normed_group.mem_filtration_iff, h2], have aux : 0 < ∥l i∥₊, { rw [zero_lt_iff, ne.def, nnnorm_eq_zero], exact hl' i }, calc ε ≤ (⌈(ε / ∥l i∥₊ : ℝ)⌉.nat_abs : ℝ≥0) * ∥l i∥₊ : _ ... < ↑(c i) * ∥l i∥₊ : _ ... ≤ ∑ (i : ι), ↑(c i) * ∥l i∥₊ : _, { rw [← nnreal.div_le_iff aux.ne', ← nnreal.coe_le_coe], simp only [coe_nnnorm, nnreal.coe_nat_abs, nnreal.coe_div], refine (le_ceil _).trans (le_abs_self _), }, { rw mul_lt_mul_right aux, { exact_mod_cast H }, }, { refine @finset.single_le_sum _ _ _ _ _ _ i (finset.mem_univ _), exact λ _ _, zero_le', } end open metric semi_normed_group instance : discrete_topology Λ := discrete_topology_of_open_singleton_zero $ begin classical, have aux := filtration_finite Λ 1, let s := aux.to_finset, let s₀ := s.erase 0, by_cases hs₀ : s₀.nonempty, { let ε : ℝ≥0 := finset.min' (s₀.image $ nnnorm) (hs₀.image _), obtain ⟨a, has₀, ha⟩ : ∃ a ∈ s₀, ∥a∥₊ = ε, { rw ← finset.mem_image, apply finset.min'_mem }, have H : 0 < ∥a∥ := by simpa only [norm_pos_iff] using finset.ne_of_mem_erase has₀, have h0ε : 0 < ε, { simpa only [← ha] }, have hε1 : ε ≤ 1, { replace has₀ := finset.mem_of_mem_erase has₀, simp only [set.finite.mem_to_finset, mem_filtration_iff] at has₀, rwa [← ha] }, suffices : ({0} : set Λ) = ball (0:Λ) ε, { rw this, apply is_open_ball }, ext, simp only [metric.mem_ball, set.mem_singleton_iff, dist_zero_right], split, { rintro rfl, rw norm_zero, exact_mod_cast h0ε }, intro h, have hx : x ∈ s, { simp only [set.finite.mem_to_finset, mem_filtration_iff], exact le_of_lt (lt_of_lt_of_le h hε1) }, by_contra hx0, replace hx := finset.mem_erase_of_ne_of_mem hx0 hx, have := finset.min'_le (s₀.image $ nnnorm), refine not_lt.2 (this ∥x∥₊ _) h, simp only [exists_prop, set.finite.mem_to_finset, finset.mem_image], use ⟨x, ⟨hx, rfl⟩⟩ }, { suffices : ({0} : set Λ) = ball (0:Λ) 1, { rw this, apply is_open_ball }, ext, simp only [metric.mem_ball, set.mem_singleton_iff, dist_zero_right], split, { rintro rfl, rw norm_zero, exact zero_lt_one }, intro h, contrapose! hs₀, refine ⟨x, _⟩, simp only [set.finite.mem_to_finset, finset.mem_erase, mem_filtration_iff, nnreal.coe_one], exact ⟨hs₀, h.le⟩ } end instance filtration_fintype (c : ℝ≥0) : fintype (filtration Λ c) := (filtration_finite Λ c).fintype -- we don't need this instance : profinitely_filtered_pseudo_normed_group Λ := { compact := λ c, by apply_instance, -- compact of finite continuous_add' := λ _ _, continuous_of_discrete_topology, continuous_neg' := λ _, continuous_of_discrete_topology, continuous_cast_le := λ _ _ _, continuous_of_discrete_topology, .. (show pseudo_normed_group Λ, by apply_instance) } end polyhedral_lattice
413a8e7de264ba733759971b7865dede0370cde2
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/natural_isomorphism.lean
8f37c710cede0cb2ea7382e4f75a94af0f73c619
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
6,734
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import .isomorphism import .functor_categories open categories open categories.isomorphism open categories.functor open categories.functor_categories namespace categories.natural_transformation definition {u1 v1 u2 v2} NaturalIsomorphism { C : Category.{u1 v1} } { D : Category.{u2 v2} } ( F G : Functor C D ) := Isomorphism (FunctorCategory C D) F G -- It's a pity we need to separately define this coercion. -- Ideally the coercion from Isomorphism along .morphism would just apply here. -- Somehow we want the definition above to be more transparent? instance NaturalIsomorphism_coercion_to_NaturalTransformation { C D : Category } ( F G : Functor C D ) : has_coe (NaturalIsomorphism F G) (NaturalTransformation F G) := { coe := Isomorphism.morphism } @[simp,ematch] lemma {u1 v1 u2 v2} NaturalIsomorphism.componentwise_witness_1 { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G : Functor C D } ( α : NaturalIsomorphism F G ) ( X : C.Obj ) : D.compose (α.morphism.components X) (α.inverse.components X) = D.identity (F.onObjects X) := congr_arg (λ β, NaturalTransformation.components β X) α.witness_1 @[simp,ematch] lemma {u1 v1 u2 v2} NaturalIsomorphism.componentwise_witness_2 { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G : Functor C D } ( α : NaturalIsomorphism F G ) ( X : C.Obj ) : D.compose (α.inverse.components X) (α.morphism.components X) = D.identity (G.onObjects X) := congr_arg (λ β, NaturalTransformation.components β X) α.witness_2 @[ematch] lemma {u1 v1 u2 v2} NaturalIsomorphism.naturality_1 { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G : Functor C D } ( α : NaturalIsomorphism F G ) { X Y : C.Obj } ( f : C.Hom X Y ) : D.compose (D.compose (α.inverse.components X) (F.onMorphisms f)) (α.morphism.components Y) = G.onMorphisms f := begin -- PROJECT automation rewrite ← α.inverse.naturality, tidy end @[ematch] lemma {u1 v1 u2 v2} NaturalIsomorphism.naturality_2 { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G : Functor C D } ( α : NaturalIsomorphism F G ) { X Y : C.Obj } ( f : C.Hom X Y ) : D.compose (D.compose (α.morphism.components X) (G.onMorphisms f)) (α.inverse.components Y) = F.onMorphisms f := begin rewrite ← α.morphism.naturality, tidy end definition NaturalIsomorphism.from_components { C D : Category } { F G : Functor C D } ( components : ∀ X : C.Obj, Isomorphism D (F.onObjects X) (G.onObjects X) ) ( naturality : ∀ { X Y : C.Obj } ( f : C.Hom X Y ), D.compose (F.onMorphisms f) (components Y).morphism = D.compose (components X).morphism (G.onMorphisms f) ) : NaturalIsomorphism F G := { morphism := { components := λ X, (components X).morphism, naturality := λ _ _ f, naturality f }, inverse := { components := λ X, (components X).inverse, naturality := λ X Y f, begin let p := congr_arg (λ f : D.Hom (F.onObjects X) (G.onObjects Y), D.compose (components X).inverse (D.compose f (components Y).inverse)) (eq.symm (naturality f)), simp at p, rewrite ← D.associativity at p, simp at p, exact p, -- rewrite D.associativity at p, -- rewrite D.associativity at p, -- rewrite Isomorphism.witness_1 at p, -- rewrite ← D.associativity at p, -- rewrite D.right_identity at p, -- rewrite Isomorphism.witness_2 at p, -- rewrite D.left_identity at p, -- exact p end }, witness_1 := ♯, witness_2 := ♯ } definition {u1 v1 u2 v2} vertical_composition_of_NaturalIsomorphisms { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G H : Functor C D } ( α : NaturalIsomorphism F G ) ( β : NaturalIsomorphism G H ) : NaturalIsomorphism F H := IsomorphismComposition α β attribute [reducible] NaturalIsomorphism -- New type for isomorphisms in functor categories. This specialisation helps type inference. structure {u1 v1 u2 v2} NaturalIsomorphism' {C : Category.{u1 v1}} {D : Category.{u2 v2}} (F G : Functor C D) := mkNatIso :: (iso : Isomorphism (FunctorCategory C D) F G) infix `≅ₙ`:50 := NaturalIsomorphism' @[trans] definition {u1 v1 u2 v2} NaturalIsomorphismComposition { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G H : Functor C D } ( α : F ≅ₙ G ) ( β : G ≅ₙ H ) : F ≅ₙ H := NaturalIsomorphism'.mkNatIso (vertical_composition_of_NaturalIsomorphisms α.iso β.iso) open NaturalTransformation definition {u1 v1 u2 v2} is_NaturalIsomorphism { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G : Functor C D } ( α : NaturalTransformation F G ) := @is_Isomorphism (FunctorCategory C D) F G α @[ematch] lemma {u1 v1 u2 v2} is_NaturalIsomorphism_componentwise_witness_1 { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G : Functor C D } ( α : NaturalTransformation F G ) ( w : is_NaturalIsomorphism α ) ( X : C.Obj ) : D.compose (α.components X) (w.inverse.components X) = D.identity (F.onObjects X) := congr_arg (λ β, NaturalTransformation.components β X) w.witness_1 @[ematch] lemma {u1 v1 u2 v2} is_NaturalIsomorphism_componentwise_witness_2 { C : Category.{u1 v1} } { D : Category.{u2 v2} } { F G : Functor C D } ( α : NaturalTransformation F G ) ( w : is_NaturalIsomorphism α ) ( X : C.Obj ) : D.compose (w.inverse.components X) (α.components X) = D.identity (G.onObjects X) := congr_arg (λ β, NaturalTransformation.components β X) w.witness_2 lemma {u1 v1 u2 v2} IdentityNaturalTransformation_is_NaturalIsomorphism { C : Category.{u1 v1} } { D : Category.{u2 v2} } ( F : Functor C D ) : is_NaturalIsomorphism (IdentityNaturalTransformation F) := { inverse := IdentityNaturalTransformation F, witness_1 := ♯, witness_2 := ♯ } definition NaturalIsomorphism.components { C D : Category } { F G : Functor C D } ( α : NaturalIsomorphism F G ) ( X : C.Obj ) : Isomorphism D (F.onObjects X) (G.onObjects X) := { morphism := α.morphism.components X, inverse := α.inverse.components X, witness_1 := ♮, witness_2 := ♮ } end categories.natural_transformation
5b67ed7d313fb6d2e3ce42e7b5b8d3a897f74261
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/combinatorics/composition.lean
43062462382a20858e37b58b04e651dbab5edfe2
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
34,350
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.fintype.card import data.finset.sort /-! # Compositions A composition of an integer `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum of positive integers. Combinatorially, it corresponds to a decomposition of `{0, ..., n-1}` into non-empty blocks of consecutive integers, where the `iⱼ` are the lengths of the blocks. This notion is closely related to that of a partition of `n`, but in a composition of `n` the order of the `iⱼ`s matters. We implement two different structures covering these two viewpoints on compositions. The first one, made of a list of positive integers summing to `n`, is the main one and is called `composition n`. The second one is useful for combinatorial arguments (for instance to show that the number of compositions of `n` is `2^(n-1)`). It is given by a subset of `{0, ..., n}` containing `0` and `n`, where the elements of the subset (other than `n`) correspond to the leftmost points of each block. The main API is built on `composition n`, and we provide an equivalence between the two types. ## Main functions * `c : composition n` is a structure, made of a list of integers which are all positive and add up to `n`. * `composition_card` states that the cardinality of `composition n` is exactly `2^(n-1)`, which is proved by constructing an equiv with `composition_as_set n` (see below), which is itself in bijection with the subsets of `fin (n-1)` (this holds even for `n = 0`, where `-` is nat subtraction). Let `c : composition n` be a composition of `n`. Then * `c.blocks` is the list of blocks in `c`. * `c.length` is the number of blocks in the composition. * `c.blocks_fun : fin c.length → ℕ` is the realization of `c.blocks` as a function on `fin c.length`. This is the main object when using compositions to understand the composition of analytic functions. * `c.size_up_to : ℕ → ℕ` is the sum of the size of the blocks up to `i`.; * `c.embedding i : fin (c.blocks_fun i) → fin n` is the increasing embedding of the `i`-th block in `fin n`; * `c.index j`, for `j : fin n`, is the index of the block containing `j`. Compositions can also be used to split lists. Let `l` be a list of length `n` and `c` a composition of `n`. * `l.split_wrt_composition c` is a list of lists, made of the slices of `l` corresponding to the blocks of `c`. * `join_split_wrt_composition` states that splitting a list and then joining it gives back the original list. * `split_wrt_composition_join` states that joining a list of lists, and then splitting it back according to the right composition, gives back the original list of lists. We turn to the second viewpoint on compositions, that we realize as a finset of `fin (n+1)`. `c : composition_as_set n` is a structure made of a finset of `fin (n+1)` called `c.boundaries` and proofs that it contains `0` and `n`. (Taking a finset of `fin n` containing `0` would not make sense in the edge case `n = 0`, while the previous description works in all cases). The elements of this set (other than `n`) correspond to leftmost points of blocks. Thus, there is an equiv between `composition n` and `composition_as_set n`. We only construct basic API on `composition_as_set` (notably `c.length` and `c.blocks`) to be able to construct this equiv, called `composition_equiv n`. Since there is a straightforward equiv between `composition_as_set n` and finsets of `{1, ..., n-1}` (obtained by removing `0` and `n` from a `composition_as_set` and called `composition_as_set_equiv n`), we deduce that `composition_as_set n` and `composition n` are both fintypes of cardinality `2^(n - 1)` (see `composition_as_set_card` and `composition_card`). ## Implementation details The main motivation for this structure and its API is in the construction of the composition of formal multilinear series, and the proof that the composition of analytic functions is analytic. The representation of a composition as a list is very handy as lists are very flexible and already have a well-developed API. ## Tags Composition, partition ## References <https://en.wikipedia.org/wiki/Composition_(combinatorics)> -/ open list open_locale classical big_operators variable {n : ℕ} /-- A composition of `n` is a list of positive integers summing to `n`. -/ @[ext] structure composition (n : ℕ) := (blocks : list ℕ) (blocks_pos : ∀ {i}, i ∈ blocks → 0 < i) (blocks_sum : blocks.sum = n) /-- Combinatorial viewpoint on a composition of `n`, by seeing it as non-empty blocks of consecutive integers in `{0, ..., n-1}`. We register every block by its left end-point, yielding a finset containing `0`. As this does not make sense for `n = 0`, we add `n` to this finset, and get a finset of `{0, ..., n}` containing `0` and `n`. This is the data in the structure `composition_as_set n`. -/ @[ext] structure composition_as_set (n : ℕ) := (boundaries : finset (fin n.succ)) (zero_mem : (0 : fin n.succ) ∈ boundaries) (last_mem : (fin.last n ∈ boundaries)) instance {n : ℕ} : inhabited (composition_as_set n) := ⟨⟨finset.univ, finset.mem_univ _, finset.mem_univ _⟩⟩ /-! ### Compositions A composition of an integer `n` is a decomposition `n = i₀ + ... + i_{k-1}` of `n` into a sum of positive integers. -/ namespace composition variables (c : composition n) instance (n : ℕ) : has_to_string (composition n) := ⟨λ c, to_string c.blocks⟩ /-- The length of a composition, i.e., the number of blocks in the composition. -/ @[reducible] def length : ℕ := c.blocks.length lemma blocks_length : c.blocks.length = c.length := rfl /-- The blocks of a composition, seen as a function on `fin c.length`. When composing analytic functions using compositions, this is the main player. -/ def blocks_fun : fin c.length → ℕ := λ i, nth_le c.blocks i.1 i.2 lemma of_fn_blocks_fun : of_fn c.blocks_fun = c.blocks := of_fn_nth_le _ lemma sum_blocks_fun : ∑ i, c.blocks_fun i = n := by conv_rhs { rw [← c.blocks_sum, ← of_fn_blocks_fun, sum_of_fn] } @[simp] lemma one_le_blocks {i : ℕ} (h : i ∈ c.blocks) : 1 ≤ i := c.blocks_pos h @[simp] lemma one_le_blocks' {i : ℕ} (h : i < c.length) : 1 ≤ nth_le c.blocks i h:= c.one_le_blocks (nth_le_mem (blocks c) i h) @[simp] lemma blocks_pos' (i : ℕ) (h : i < c.length) : 0 < nth_le c.blocks i h:= c.one_le_blocks' h lemma length_le : c.length ≤ n := begin conv_rhs { rw ← c.blocks_sum }, exact length_le_sum_of_one_le _ (λ i hi, c.one_le_blocks hi) end lemma length_pos_of_pos (h : 0 < n) : 0 < c.length := begin apply length_pos_of_sum_pos, convert h, exact c.blocks_sum end /-- The sum of the sizes of the blocks in a composition up to `i`. -/ def size_up_to (i : ℕ) : ℕ := (c.blocks.take i).sum @[simp] lemma size_up_to_zero : c.size_up_to 0 = 0 := by simp [size_up_to] lemma size_up_to_of_length_le (i : ℕ) (h : c.length ≤ i) : c.size_up_to i = n := begin dsimp [size_up_to], convert c.blocks_sum, exact take_all_of_le h end @[simp] lemma size_up_to_length : c.size_up_to c.length = n := c.size_up_to_of_length_le c.length (le_refl _) lemma size_up_to_le (i : ℕ) : c.size_up_to i ≤ n := begin conv_rhs { rw [← c.blocks_sum, ← sum_take_add_sum_drop _ i] }, exact nat.le_add_right _ _ end lemma size_up_to_succ {i : ℕ} (h : i < c.length) : c.size_up_to (i+1) = c.size_up_to i + c.blocks.nth_le i h := by { simp only [size_up_to], rw sum_take_succ _ _ h } lemma size_up_to_succ' (i : fin c.length) : c.size_up_to ((i : ℕ) + 1) = c.size_up_to i + c.blocks_fun i := c.size_up_to_succ i.2 lemma size_up_to_strict_mono {i : ℕ} (h : i < c.length) : c.size_up_to i < c.size_up_to (i+1) := by { rw c.size_up_to_succ h, simp } lemma monotone_size_up_to : monotone c.size_up_to := monotone_sum_take _ /-- The `i`-th boundary of a composition, i.e., the leftmost point of the `i`-th block. We include a virtual point at the right of the last block, to make for a nice equiv with `composition_as_set n`. -/ def boundary : fin (c.length + 1) → fin (n+1) := λ i, ⟨c.size_up_to i, nat.lt_succ_of_le (c.size_up_to_le i)⟩ @[simp] lemma boundary_zero : c.boundary 0 = 0 := by simp [boundary, fin.ext_iff] @[simp] lemma boundary_last : c.boundary (fin.last c.length) = fin.last n := by simp [boundary, fin.ext_iff] lemma strict_mono_boundary : strict_mono c.boundary := begin apply fin.strict_mono_iff_lt_succ.2 (λ i hi, _), exact c.size_up_to_strict_mono ((add_lt_add_iff_right 1).mp hi) end /-- The boundaries of a composition, i.e., the leftmost point of all the blocks. We include a virtual point at the right of the last block, to make for a nice equiv with `composition_as_set n`. -/ def boundaries : finset (fin (n+1)) := finset.univ.image c.boundary lemma card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 := begin dsimp [boundaries], rw finset.card_image_of_injective finset.univ c.strict_mono_boundary.injective, simp end /-- To `c : composition n`, one can associate a `composition_as_set n` by registering the leftmost point of each block, and adding a virtual point at the right of the last block. -/ def to_composition_as_set : composition_as_set n := { boundaries := c.boundaries, zero_mem := begin simp only [boundaries, finset.mem_univ, exists_prop_of_true, finset.mem_image], exact ⟨0, rfl⟩, end, last_mem := begin simp only [boundaries, finset.mem_univ, exists_prop_of_true, finset.mem_image], exact ⟨fin.last c.length, c.boundary_last⟩, end } /-- The canonical increasing bijection between `fin (c.length + 1)` and `c.boundaries` is exactly `c.boundary`. -/ lemma mono_of_fin_boundaries : c.boundary = finset.mono_of_fin c.boundaries c.card_boundaries_eq_succ_length := begin apply finset.mono_of_fin_unique' _ _ c.strict_mono_boundary, assume i hi, simp [boundaries, - set.mem_range, set.mem_range_self] end /-- Embedding the `i`-th block of a composition (identified with `fin (c.blocks_fun i)`) into `fin n` at the relevant position. -/ def embedding (i : fin c.length) : fin (c.blocks_fun i) → fin n := λ j, ⟨c.size_up_to i.1 + j.val, calc c.size_up_to i.1 + j.val < c.size_up_to i.1 + c.blocks.nth_le i.1 i.2 : add_lt_add_left j.2 _ ... = c.size_up_to (i.1 + 1) : (c.size_up_to_succ _).symm ... ≤ n : by { conv_rhs { rw ← c.size_up_to_length }, exact monotone_sum_take _ i.2 } ⟩ lemma embedding_injective (i : fin c.length) : function.injective (c.embedding i) := λ a b hab, by simpa [embedding, fin.ext_iff] using hab /-- `index_exists` asserts there is some `i` so `j < c.size_up_to (i+1)`. In the next definition we use `nat.find` to produce the minimal such index. -/ lemma index_exists {j : ℕ} (h : j < n) : ∃ i : ℕ, j < c.size_up_to i.succ ∧ i < c.length := begin have n_pos : 0 < n := lt_of_le_of_lt (zero_le j) h, have : 0 < c.blocks.sum, by rwa [← c.blocks_sum] at n_pos, have length_pos : 0 < c.blocks.length := length_pos_of_sum_pos (blocks c) this, refine ⟨c.length.pred, _, nat.pred_lt (ne_of_gt length_pos)⟩, have : c.length.pred.succ = c.length := nat.succ_pred_eq_of_pos length_pos, simp [this, h] end /-- `c.index j` is the index of the block in the composition `c` containing `j`. -/ def index (j : fin n) : fin c.length := ⟨nat.find (c.index_exists j.2), (nat.find_spec (c.index_exists j.2)).2⟩ lemma lt_size_up_to_index_succ (j : fin n) : j.val < c.size_up_to (c.index j).succ := (nat.find_spec (c.index_exists j.2)).1 lemma size_up_to_index_le (j : fin n) : c.size_up_to (c.index j) ≤ j := begin by_contradiction H, set i := c.index j with hi, push_neg at H, have i_pos : (0 : ℕ) < i, { by_contradiction i_pos, push_neg at i_pos, simp [le_zero_iff_eq.mp i_pos, c.size_up_to_zero] at H, exact nat.not_succ_le_zero j H }, let i₁ := (i : ℕ).pred, have i₁_lt_i : i₁ < i := nat.pred_lt (ne_of_gt i_pos), have i₁_succ : i₁.succ = i := nat.succ_pred_eq_of_pos i_pos, have := nat.find_min (c.index_exists j.2) i₁_lt_i, simp [lt_trans i₁_lt_i (c.index j).2, i₁_succ] at this, exact nat.lt_le_antisymm H this end /-- Mapping an element `j` of `fin n` to the element in the block containing it, identified with `fin (c.blocks_fun (c.index j))` through the canonical increasing bijection. -/ def inv_embedding (j : fin n) : fin (c.blocks_fun (c.index j)) := ⟨j - c.size_up_to (c.index j), begin rw [nat.sub_lt_right_iff_lt_add, add_comm, ← size_up_to_succ'], { exact lt_size_up_to_index_succ _ _ }, { exact size_up_to_index_le _ _ } end⟩ lemma embedding_comp_inv (j : fin n) : c.embedding (c.index j) (c.inv_embedding j) = j := begin rw fin.ext_iff, apply nat.add_sub_cancel' (c.size_up_to_index_le j), end lemma mem_range_embedding_iff {j : fin n} {i : fin c.length} : j ∈ set.range (c.embedding i) ↔ c.size_up_to i ≤ j ∧ (j : ℕ) < c.size_up_to (i : ℕ).succ := begin split, { assume h, rcases set.mem_range.2 h with ⟨k, hk⟩, rw fin.ext_iff at hk, change c.size_up_to i + k.val = (j : ℕ) at hk, rw ← hk, simp [size_up_to_succ', k.2] }, { assume h, apply set.mem_range.2, refine ⟨⟨j.val - c.size_up_to i, _⟩, _⟩, { rw [nat.sub_lt_left_iff_lt_add, ← size_up_to_succ'], { exact h.2 }, { exact h.1 } }, { rw fin.ext_iff, exact nat.add_sub_cancel' h.1 } } end /-- The embeddings of different blocks of a composition are disjoint. -/ lemma disjoint_range {i₁ i₂ : fin c.length} (h : i₁ ≠ i₂) : disjoint (set.range (c.embedding i₁)) (set.range (c.embedding i₂)) := begin classical, wlog h' : i₁ ≤ i₂ using i₁ i₂, by_contradiction d, obtain ⟨x, hx₁, hx₂⟩ : ∃ x : fin n, (x ∈ set.range (c.embedding i₁) ∧ x ∈ set.range (c.embedding i₂)) := set.not_disjoint_iff.1 d, have : i₁ < i₂ := lt_of_le_of_ne h' h, have A : (i₁ : ℕ).succ ≤ i₂ := nat.succ_le_of_lt this, apply lt_irrefl (x : ℕ), calc (x : ℕ) < c.size_up_to (i₁ : ℕ).succ : (c.mem_range_embedding_iff.1 hx₁).2 ... ≤ c.size_up_to (i₂ : ℕ) : monotone_sum_take _ A ... ≤ x : (c.mem_range_embedding_iff.1 hx₂).1 end lemma mem_range_embedding (j : fin n) : j ∈ set.range (c.embedding (c.index j)) := begin have : c.embedding (c.index j) (c.inv_embedding j) ∈ set.range (c.embedding (c.index j)) := set.mem_range_self _, rwa c.embedding_comp_inv j at this end lemma mem_range_embedding_iff' {j : fin n} {i : fin c.length} : j ∈ set.range (c.embedding i) ↔ i = c.index j := begin split, { rw ← not_imp_not, assume h, exact set.disjoint_right.1 (c.disjoint_range h) (c.mem_range_embedding j) }, { assume h, rw h, exact c.mem_range_embedding j } end lemma index_embedding (i : fin c.length) (j : fin (c.blocks_fun i)) : c.index (c.embedding i j) = i := begin symmetry, rw ← mem_range_embedding_iff', apply set.mem_range_self end lemma inv_embedding_comp (i : fin c.length) (j : fin (c.blocks_fun i)) : (c.inv_embedding (c.embedding i j)).val = j.val := begin simp only [inv_embedding, index_embedding], simp [embedding, fin.coe_eq_val, index_embedding] end /-- Equivalence between the disjoint union of the blocks (each of them seen as `fin (c.blocks_fun i)`) with `fin n`. -/ def blocks_fin_equiv : (Σ i : fin c.length, fin (c.blocks_fun i)) ≃ fin n := { to_fun := λ x, c.embedding x.1 x.2, inv_fun := λ j, ⟨c.index j, c.inv_embedding j⟩, left_inv := λ x, begin rcases x with ⟨i, y⟩, dsimp, congr, { exact c.index_embedding _ _ }, rw fin.heq_ext_iff, { exact c.inv_embedding_comp _ _ }, { rw c.index_embedding } end, right_inv := λ j, c.embedding_comp_inv j } lemma blocks_fun_congr {n₁ n₂ : ℕ} (c₁ : composition n₁) (c₂ : composition n₂) (i₁ : fin c₁.length) (i₂ : fin c₂.length) (hn : n₁ = n₂) (hc : c₁.blocks = c₂.blocks) (hi : (i₁ : ℕ) = i₂) : c₁.blocks_fun i₁ = c₂.blocks_fun i₂ := by { cases hn, rw ← composition.ext_iff at hc, cases hc, congr, rwa fin.ext_iff } /-- Two compositions (possibly of different integers) coincide if and only if they have the same sequence of blocks. -/ lemma sigma_eq_iff_blocks_eq {c : Σ n, composition n} {c' : Σ n, composition n} : c = c' ↔ c.2.blocks = c'.2.blocks := begin refine ⟨λ H, by rw H, λ H, _⟩, rcases c with ⟨n, c⟩, rcases c' with ⟨n', c'⟩, have : n = n', by { rw [← c.blocks_sum, ← c'.blocks_sum, H] }, induction this, simp only [true_and, eq_self_iff_true, heq_iff_eq], ext1, exact H end /-- The composition made of blocks all of size `1`. -/ def ones (n : ℕ) : composition n := ⟨repeat (1 : ℕ) n, λ i hi, by simp [list.eq_of_mem_repeat hi], by simp⟩ instance {n : ℕ} : inhabited (composition n) := ⟨composition.ones n⟩ @[simp] lemma ones_length (n : ℕ) : (ones n).length = n := list.length_repeat 1 n @[simp] lemma ones_blocks (n : ℕ) : (ones n).blocks = repeat (1 : ℕ) n := by simp only [blocks, ones, map_repeat] @[simp] lemma ones_blocks_fun (n : ℕ) (i : fin (ones n).length) : (ones n).blocks_fun i = 1 := by simp [blocks_fun, ones, blocks, i.2] @[simp] lemma ones_size_up_to (n : ℕ) (i : ℕ) : (ones n).size_up_to i = min i n := by simp [size_up_to, ones_blocks, take_repeat] @[simp] lemma ones_embedding (i : fin (ones n).length) (h : 0 < (ones n).blocks_fun i) : (ones n).embedding i ⟨0, h⟩ = ⟨i.1, lt_of_lt_of_le i.2 (ones n).length_le⟩ := begin have : i.val < n, by { convert i.2, exact (ones_length n).symm }, simp [embedding, le_of_lt this] end lemma eq_ones_iff {c : composition n} : c = ones n ↔ ∀ i ∈ c.blocks, i = 1 := begin split, { assume H, rw [H, ones_blocks], exact λ i, eq_of_mem_repeat }, { assume H, ext1, have A : c.blocks = repeat 1 c.blocks.length := eq_repeat_of_mem H, have : c.blocks.length = n, by { conv_rhs { rw [← c.blocks_sum, A] }, simp }, rw [A, this, ones_blocks] }, end lemma ne_ones_iff {c : composition n} : c ≠ ones n ↔ ∃ i ∈ c.blocks, 1 < i := begin rw ← not_iff_not, push_neg, rw eq_ones_iff, have : ∀ j ∈ c.blocks, j = 1 ↔ j ≤ 1 := λ j hj, by simp [le_antisymm_iff, c.one_le_blocks hj], simp [this] {contextual := tt} end /-- The composition made of a single block of size `n`. -/ def single (n : ℕ) (h : 0 < n) : composition n := ⟨[n], by simp [h], by simp⟩ @[simp] lemma single_length {n : ℕ} (h : 0 < n) : (single n h).length = 1 := by simp [single, length] @[simp] lemma single_blocks {n : ℕ} (h : 0 < n) : (single n h).blocks = [n] := by simp [blocks, single] @[simp] lemma single_blocks_fun {n : ℕ} (h : 0 < n) (i : fin (single n h).length) : (single n h).blocks_fun i = n := by simp [blocks_fun, single, blocks, i.2] @[simp] lemma single_embedding {n : ℕ} (h : 0 < n) (i : fin n) : (single n h).embedding ⟨0, single_length h ▸ zero_lt_one⟩ i = i := by simp [embedding] lemma eq_single_iff {n : ℕ} {h : 0 < n} {c : composition n } : c = single n h ↔ c.length = 1 := begin split, { assume H, rw H, exact single_length h }, { assume H, ext1, have A : c.blocks.length = 1 := H ▸ c.blocks_length, have B : c.blocks.sum = n := c.blocks_sum, rw eq_cons_of_length_one A at B ⊢, simpa [single_blocks] using B } end end composition /-! ### Splitting a list Given a list of length `n` and a composition `c` of `n`, one can split `l` into `c.length` sublists of respective lengths `c.blocks_fun 0`, ..., `c.blocks_fun (c.length-1)`. This is inverse to the join operation. -/ namespace list variable {α : Type*} /-- Auxiliary for `list.split_wrt_composition`. -/ def split_wrt_composition_aux : list α → list ℕ → list (list α) | l [] := [] | l (n :: ns) := let (l₁, l₂) := l.split_at n in l₁ :: split_wrt_composition_aux l₂ ns /-- Given a list of length `n` and a composition `[i₁, ..., iₖ]` of `n`, split `l` into a list of `k` lists corresponding to the blocks of the composition, of respective lengths `i₁`, ..., `iₖ`. This makes sense mostly when `n = l.length`, but this is not necessary for the definition. -/ def split_wrt_composition (l : list α) (c : composition n) : list (list α) := split_wrt_composition_aux l c.blocks local attribute [simp] split_wrt_composition_aux.equations._eqn_1 local attribute [simp] lemma split_wrt_composition_aux_cons (l : list α) (n ns) : l.split_wrt_composition_aux (n :: ns) = take n l :: (drop n l).split_wrt_composition_aux ns := by simp [split_wrt_composition_aux] lemma length_split_wrt_composition_aux (l : list α) (ns) : length (l.split_wrt_composition_aux ns) = ns.length := by induction ns generalizing l; simp * /-- When one splits a list along a composition `c`, the number of sublists thus created is `c.length`. -/ @[simp] lemma length_split_wrt_composition (l : list α) (c : composition n) : length (l.split_wrt_composition c) = c.length := length_split_wrt_composition_aux _ _ lemma map_length_split_wrt_composition_aux {ns : list ℕ} : ∀ {l : list α}, ns.sum ≤ l.length → map length (l.split_wrt_composition_aux ns) = ns := begin induction ns with n ns IH; intros l h; simp at h ⊢, have := le_trans (nat.le_add_right _ _) h, rw IH, {simp [this]}, rwa [length_drop, nat.le_sub_left_iff_add_le this] end /-- When one splits a list along a composition `c`, the lengths of the sublists thus created are given by the block sizes in `c`. -/ lemma map_length_split_wrt_composition (l : list α) (c : composition l.length) : map length (l.split_wrt_composition c) = c.blocks := map_length_split_wrt_composition_aux (le_of_eq c.blocks_sum) lemma length_pos_of_mem_split_wrt_composition {l l' : list α} {c : composition l.length} (h : l' ∈ l.split_wrt_composition c) : 0 < length l' := begin have : l'.length ∈ (l.split_wrt_composition c).map list.length := list.mem_map_of_mem list.length h, rw map_length_split_wrt_composition at this, exact c.blocks_pos this end lemma sum_take_map_length_split_wrt_composition (l : list α) (c : composition l.length) (i : ℕ) : (((l.split_wrt_composition c).map length).take i).sum = c.size_up_to i := by { congr, exact map_length_split_wrt_composition l c } lemma nth_le_split_wrt_composition_aux (l : list α) (ns : list ℕ) {i : ℕ} (hi) : nth_le (l.split_wrt_composition_aux ns) i hi = (l.take (ns.take (i+1)).sum).drop (ns.take i).sum := begin induction ns with n ns IH generalizing l i, {cases hi}, cases i; simp [IH], rw [add_comm n, drop_add, drop_take], end /-- The `i`-th sublist in the splitting of a list `l` along a composition `c`, is the slice of `l` between the indices `c.size_up_to i` and `c.size_up_to (i+1)`, i.e., the indices in the `i`-th block of the composition. -/ lemma nth_le_split_wrt_composition (l : list α) (c : composition n) {i : ℕ} (hi : i < (l.split_wrt_composition c).length) : nth_le (l.split_wrt_composition c) i hi = (l.take (c.size_up_to (i+1))).drop (c.size_up_to i) := nth_le_split_wrt_composition_aux _ _ _ theorem join_split_wrt_composition_aux {ns : list ℕ} : ∀ {l : list α}, ns.sum = l.length → (l.split_wrt_composition_aux ns).join = l := begin induction ns with n ns IH; intros l h; simp at h ⊢, { exact (length_eq_zero.1 h.symm).symm }, rw IH, {simp}, rwa [length_drop, ← h, nat.add_sub_cancel_left] end /-- If one splits a list along a composition, and then joins the sublists, one gets back the original list. -/ @[simp] theorem join_split_wrt_composition (l : list α) (c : composition l.length) : (l.split_wrt_composition c).join = l := join_split_wrt_composition_aux c.blocks_sum /-- If one joins a list of lists and then splits the join along the right composition, one gets back the original list of lists. -/ @[simp] theorem split_wrt_composition_join (L : list (list α)) (c : composition L.join.length) (h : map length L = c.blocks) : split_wrt_composition (join L) c = L := by simp only [eq_self_iff_true, and_self, eq_iff_join_eq, join_split_wrt_composition, map_length_split_wrt_composition, h] end list /-! ### Compositions as sets Combinatorial viewpoints on compositions, seen as finite subsets of `fin (n+1)` containing `0` and `n`, where the points of the set (other than `n`) correspond to the leftmost points of each block. -/ /-- Bijection between compositions of `n` and subsets of `{0, ..., n-2}`, defined by considering the restriction of the subset to `{1, ..., n-1}` and shifting to the left by one. -/ def composition_as_set_equiv (n : ℕ) : composition_as_set n ≃ finset (fin (n - 1)) := { to_fun := λ c, {i : fin (n-1) | (⟨1 + i.val, by { have := i.2, omega }⟩ : fin n.succ) ∈ c.boundaries}.to_finset, inv_fun := λ s, { boundaries := {i : fin n.succ | (i = 0) ∨ (i = fin.last n) ∨ (∃ (j : fin (n-1)) (hj : j ∈ s), i.val = j.val + 1)}.to_finset, zero_mem := by simp, last_mem := by simp }, left_inv := begin assume c, ext i, simp only [exists_prop, add_comm, set.mem_to_finset, true_or, or_true, set.mem_set_of_eq, fin.last_val], split, { rintro (rfl | rfl | ⟨j, hj1, hj2⟩), { exact c.zero_mem }, { exact c.last_mem }, { convert hj1, rwa fin.ext_iff } }, { simp only [classical.or_iff_not_imp_left], assume i_mem i_ne_zero i_ne_last, simp [fin.ext_iff] at i_ne_zero i_ne_last, refine ⟨⟨i.val - 1, _⟩, _, _⟩, { have : i.val < n + 1 := i.2, omega }, { convert i_mem, rw fin.ext_iff, simp, omega }, { simp, omega } }, end, right_inv := begin assume s, ext i, have : 1 + i.val ≠ n, by { apply ne_of_lt, have := i.2, omega }, simp only [fin.ext_iff, this, exists_prop, fin.val_zero, false_or, add_right_inj, add_comm, set.mem_to_finset, true_or, add_eq_zero_iff, or_true, one_ne_zero, set.mem_set_of_eq, fin.last_val, false_and], split, { rintros ⟨j, js, hj⟩, convert js, exact (fin.ext_iff _ _).2 hj }, { assume h, exact ⟨i, h, rfl⟩ } end } instance composition_as_set_fintype (n : ℕ) : fintype (composition_as_set n) := fintype.of_equiv _ (composition_as_set_equiv n).symm lemma composition_as_set_card (n : ℕ) : fintype.card (composition_as_set n) = 2 ^ (n - 1) := begin have : fintype.card (finset (fin (n-1))) = 2 ^ (n - 1), by simp, rw ← this, exact fintype.card_congr (composition_as_set_equiv n) end namespace composition_as_set variables (c : composition_as_set n) lemma boundaries_nonempty : c.boundaries.nonempty := ⟨0, c.zero_mem⟩ lemma card_boundaries_pos : 0 < finset.card c.boundaries := finset.card_pos.mpr c.boundaries_nonempty /-- Number of blocks in a `composition_as_set`. -/ def length : ℕ := finset.card c.boundaries - 1 lemma card_boundaries_eq_succ_length : c.boundaries.card = c.length + 1 := (nat.sub_eq_iff_eq_add c.card_boundaries_pos).mp rfl lemma length_lt_card_boundaries : c.length < c.boundaries.card := by { rw c.card_boundaries_eq_succ_length, exact lt_add_one _ } lemma lt_length (i : fin c.length) : i.val + 1 < c.boundaries.card := nat.add_lt_of_lt_sub_right i.2 lemma lt_length' (i : fin c.length) : i.val < c.boundaries.card := lt_of_le_of_lt (nat.le_succ i.val) (c.lt_length i) /-- Canonical increasing bijection from `fin c.boundaries.card` to `c.boundaries`. -/ def boundary : fin c.boundaries.card → fin (n+1) := finset.mono_of_fin c.boundaries rfl @[simp] lemma boundary_zero : c.boundary ⟨0, c.card_boundaries_pos⟩ = 0 := begin rw [boundary, finset.mono_of_fin_zero rfl c.boundaries_nonempty c.card_boundaries_pos], exact le_antisymm (finset.min'_le _ _ _ c.zero_mem) (fin.zero_le _), end @[simp] lemma boundary_length : c.boundary ⟨c.length, c.length_lt_card_boundaries⟩ = fin.last n := begin convert finset.mono_of_fin_last rfl c.boundaries_nonempty c.card_boundaries_pos, exact le_antisymm (finset.le_max' _ _ _ c.last_mem) (fin.le_last _) end /-- Size of the `i`-th block in a `composition_as_set`, seen as a function on `fin c.length`. -/ def blocks_fun (i : fin c.length) : ℕ := (c.boundary ⟨i.val + 1, c.lt_length i⟩).val - (c.boundary ⟨i.val, c.lt_length' i⟩).val lemma blocks_fun_pos (i : fin c.length) : 0 < c.blocks_fun i := begin have : (⟨i.val, c.lt_length' i⟩ : fin c.boundaries.card) < ⟨i.val + 1, c.lt_length i⟩ := nat.lt_succ_self _, exact nat.lt_sub_left_of_add_lt (finset.mono_of_fin_strict_mono c.boundaries rfl this) end /-- List of the sizes of the blocks in a `composition_as_set`. -/ def blocks (c : composition_as_set n) : list ℕ := of_fn c.blocks_fun @[simp] lemma blocks_length : c.blocks.length = c.length := length_of_fn _ lemma blocks_partial_sum {i : ℕ} (h : i < c.boundaries.card) : (c.blocks.take i).sum = c.boundary ⟨i, h⟩ := begin induction i with i IH, { simp }, have A : i < c.blocks.length, { rw c.card_boundaries_eq_succ_length at h, simp [blocks, nat.lt_of_succ_lt_succ h] }, have B : i < c.boundaries.card := lt_of_lt_of_le A (by simp [blocks, length, nat.sub_le]), rw [sum_take_succ _ _ A, IH B], simp only [blocks, blocks_fun, fin.coe_eq_val, nth_le_of_fn'], rw nat.add_sub_cancel', refine le_of_lt (@finset.mono_of_fin_strict_mono _ _ c.boundaries _ rfl (⟨i, B⟩ : fin c.boundaries.card) _ _), exact nat.lt_succ_self _ end lemma mem_boundaries_iff_exists_blocks_sum_take_eq {j : fin (n+1)} : j ∈ c.boundaries ↔ ∃ i < c.boundaries.card, (c.blocks.take i).sum = j.val := begin split, { assume hj, rcases (c.boundaries.mono_of_fin_bij_on rfl).surj_on hj with ⟨i, _, hi⟩, refine ⟨i.1, i.2, _⟩, rw [← hi, c.blocks_partial_sum i.2], refl }, { rintros ⟨i, hi, H⟩, convert (c.boundaries.mono_of_fin_bij_on rfl).maps_to (set.mem_univ ⟨i, hi⟩), have : c.boundary ⟨i, hi⟩ = j, by rwa [fin.ext_iff, ← fin.coe_eq_val, ← c.blocks_partial_sum hi], exact this.symm } end lemma blocks_sum : c.blocks.sum = n := begin have : c.blocks.take c.length = c.blocks := take_all_of_le (by simp [blocks]), rw [← this, c.blocks_partial_sum c.length_lt_card_boundaries, c.boundary_length], refl end /-- Associating a `composition n` to a `composition_as_set n`, by registering the sizes of the blocks as a list of positive integers. -/ def to_composition : composition n := { blocks := c.blocks, blocks_pos := by simp only [blocks, forall_mem_of_fn_iff, blocks_fun_pos c, forall_true_iff], blocks_sum := c.blocks_sum } end composition_as_set /-! ### Equivalence between compositions and compositions as sets In this section, we explain how to go back and forth between a `composition` and a `composition_as_set`, by showing that their `blocks` and `length` and `boundaries` correspond to each other, and construct an equivalence between them called `composition_equiv`. -/ @[simp] lemma composition.to_composition_as_set_length (c : composition n) : c.to_composition_as_set.length = c.length := by simp [composition.to_composition_as_set, composition_as_set.length, c.card_boundaries_eq_succ_length] @[simp] lemma composition_as_set.to_composition_length (c : composition_as_set n) : c.to_composition.length = c.length := by simp [composition_as_set.to_composition, composition.length, composition.blocks] @[simp] lemma composition.to_composition_as_set_blocks (c : composition n) : c.to_composition_as_set.blocks = c.blocks := begin let d := c.to_composition_as_set, change d.blocks = c.blocks, have length_eq : d.blocks.length = c.blocks.length, { convert c.to_composition_as_set_length, simp [composition_as_set.blocks] }, suffices H : ∀ (i ≤ d.blocks.length), (d.blocks.take i).sum = (c.blocks.take i).sum, from eq_of_sum_take_eq length_eq H, assume i hi, have i_lt : i < d.boundaries.card, { convert nat.lt_succ_iff.2 hi, convert d.card_boundaries_eq_succ_length, exact length_of_fn _ }, have i_lt' : i < c.boundaries.card := i_lt, have i_lt'' : i < c.length + 1, by rwa c.card_boundaries_eq_succ_length at i_lt', have A : finset.mono_of_fin d.boundaries rfl ⟨i, i_lt⟩ = finset.mono_of_fin c.boundaries rfl ⟨i, i_lt'⟩ := rfl, have B : c.size_up_to i = c.boundary ⟨i, i_lt''⟩ := rfl, rw [d.blocks_partial_sum i_lt, composition_as_set.boundary, A, ← composition.size_up_to, B, fin.coe_eq_val, fin.coe_eq_val, ← fin.ext_iff, c.mono_of_fin_boundaries, finset.mono_of_fin_eq_mono_of_fin_iff] end @[simp] lemma composition_as_set.to_composition_blocks (c : composition_as_set n) : c.to_composition.blocks = c.blocks := rfl @[simp] lemma composition_as_set.to_composition_boundaries (c : composition_as_set n) : c.to_composition.boundaries = c.boundaries := begin ext j, simp [c.mem_boundaries_iff_exists_blocks_sum_take_eq, c.card_boundaries_eq_succ_length, composition.boundary, fin.ext_iff, composition.size_up_to, exists_prop, finset.mem_univ, take, exists_prop_of_true, finset.mem_image, composition_as_set.to_composition_blocks, composition.boundaries], split, { rintros ⟨i, hi⟩, refine ⟨i.1, _, hi⟩, convert i.2, simp }, { rintros ⟨i, i_lt, hi⟩, have : i < c.to_composition.length + 1, by simpa using i_lt, exact ⟨⟨i, this⟩, hi⟩ } end @[simp] lemma composition.to_composition_as_set_boundaries (c : composition n) : c.to_composition_as_set.boundaries = c.boundaries := rfl /-- Equivalence between `composition n` and `composition_as_set n`. -/ def composition_equiv (n : ℕ) : composition n ≃ composition_as_set n := { to_fun := λ c, c.to_composition_as_set, inv_fun := λ c, c.to_composition, left_inv := λ c, by { ext1, exact c.to_composition_as_set_blocks }, right_inv := λ c, by { ext1, exact c.to_composition_boundaries } } instance composition_fintype (n : ℕ) : fintype (composition n) := fintype.of_equiv _ (composition_equiv n).symm lemma composition_card (n : ℕ) : fintype.card (composition n) = 2 ^ (n - 1) := begin rw ← composition_as_set_card n, exact fintype.card_congr (composition_equiv n) end
d0ac15496249d1b34056bda9c453552256feb7bd
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/hott/algebra/homotopy_group.hlean
272bbab7961ef21243a8076b297c09e057817dd7
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,182
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 homotopy groups of a pointed space -/ import types.pointed .trunc_group .hott types.trunc open nat eq pointed trunc is_trunc algebra namespace eq definition phomotopy_group [constructor] (n : ℕ) (A : Type*) : Set* := ptrunc 0 (Ω[n] A) definition homotopy_group [reducible] (n : ℕ) (A : Type*) : Type := phomotopy_group n A notation `π*[`:95 n:0 `] `:0 A:95 := phomotopy_group n A notation `π[`:95 n:0 `] `:0 A:95 := homotopy_group n A definition group_homotopy_group [instance] [constructor] (n : ℕ) (A : Type*) : group (π[succ n] A) := trunc_group concat inverse idp con.assoc idp_con con_idp con.left_inv definition comm_group_homotopy_group [constructor] (n : ℕ) (A : Type*) : comm_group (π[succ (succ n)] A) := trunc_comm_group concat inverse idp con.assoc idp_con con_idp con.left_inv eckmann_hilton local attribute comm_group_homotopy_group [instance] definition ghomotopy_group [constructor] (n : ℕ) (A : Type*) : Group := Group.mk (π[succ n] A) _ definition cghomotopy_group [constructor] (n : ℕ) (A : Type*) : CommGroup := CommGroup.mk (π[succ (succ n)] A) _ definition fundamental_group [constructor] (A : Type*) : Group := ghomotopy_group zero A notation `πG[`:95 n:0 ` +1] `:0 A:95 := ghomotopy_group n A notation `πaG[`:95 n:0 ` +2] `:0 A:95 := cghomotopy_group n A prefix `π₁`:95 := fundamental_group open equiv unit theorem trivial_homotopy_of_is_set (A : Type*) [H : is_set A] (n : ℕ) : πG[n+1] A = G0 := begin apply trivial_group_of_is_contr, apply is_trunc_trunc_of_is_trunc, apply is_contr_loop_of_is_trunc, apply is_trunc_succ_succ_of_is_set end definition homotopy_group_succ_out (A : Type*) (n : ℕ) : πG[ n +1] A = π₁ Ω[n] A := idp definition homotopy_group_succ_in (A : Type*) (n : ℕ) : πG[succ n +1] A = πG[n +1] Ω A := begin fapply Group_eq, { apply equiv_of_eq, exact ap (λ(X : Type*), trunc 0 X) (loop_space_succ_eq_in A (succ n))}, { exact abstract [irreducible] begin refine trunc.rec _, intro p, refine trunc.rec _, intro q, rewrite [▸*,-+tr_eq_cast_ap, +trunc_transport], refine !trunc_transport ⬝ _, apply ap tr, apply loop_space_succ_eq_in_concat end end}, end definition homotopy_group_add (A : Type*) (n m : ℕ) : πG[n+m +1] A = πG[n +1] Ω[m] A := begin revert A, induction m with m IH: intro A, { reflexivity}, { esimp [iterated_ploop_space, nat.add], refine !homotopy_group_succ_in ⬝ _, refine !IH ⬝ _, exact ap (ghomotopy_group n) !loop_space_succ_eq_in⁻¹} end theorem trivial_homotopy_of_is_set_loop_space {A : Type*} {n : ℕ} (m : ℕ) (H : is_set (Ω[n] A)) : πG[m+n+1] A = G0 := !homotopy_group_add ⬝ !trivial_homotopy_of_is_set definition phomotopy_group_functor [constructor] (n : ℕ) {A B : Type*} (f : A →* B) : π*[n] A →* π*[n] B := ptrunc_functor 0 (apn n f) notation `π→*[`:95 n:0 `] `:0 f:95 := phomotopy_group_functor n f end eq
328a75b8ca050be812f847ebb6ced0d779f577b3
94e33a31faa76775069b071adea97e86e218a8ee
/src/number_theory/liouville/basic.lean
4b8f19321aa89fe0b44b807061d08bbf9e874968
[ "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
12,389
lean
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Jujian Zhang -/ import analysis.calculus.mean_value import data.polynomial.denoms_clearable import data.real.irrational /-! # Liouville's theorem This file contains a proof of Liouville's theorem stating that all Liouville numbers are transcendental. To obtain this result, there is first a proof that Liouville numbers are irrational and two technical lemmas. These lemmas exploit the fact that a polynomial with integer coefficients takes integer values at integers. When evaluating at a rational number, we can clear denominators and obtain precise inequalities that ultimately allow us to prove transcendence of Liouville numbers. -/ /-- A Liouville number is a real number `x` such that for every natural number `n`, there exist `a, b ∈ ℤ` with `1 < b` such that `0 < |x - a/b| < 1/bⁿ`. In the implementation, the condition `x ≠ a/b` replaces the traditional equivalent `0 < |x - a/b|`. -/ def liouville (x : ℝ) := ∀ n : ℕ, ∃ a b : ℤ, 1 < b ∧ x ≠ a / b ∧ |x - a / b| < 1 / b ^ n namespace liouville @[protected] lemma irrational {x : ℝ} (h : liouville x) : irrational x := begin -- By contradiction, `x = a / b`, with `a ∈ ℤ`, `0 < b ∈ ℕ` is a Liouville number, rintros ⟨⟨a, b, bN0, cop⟩, rfl⟩, -- clear up the mess of constructions of rationals change (liouville (a / b)) at h, -- Since `a / b` is a Liouville number, there are `p, q ∈ ℤ`, with `q1 : 1 < q`, -- `a0 : a / b ≠ p / q` and `a1 : |a / b - p / q| < 1 / q ^ (b + 1)` rcases h (b + 1) with ⟨p, q, q1, a0, a1⟩, -- A few useful inequalities have qR0 : (0 : ℝ) < q := int.cast_pos.mpr (zero_lt_one.trans q1), have b0 : (b : ℝ) ≠ 0 := ne_of_gt (nat.cast_pos.mpr bN0), have bq0 : (0 : ℝ) < b * q := mul_pos (nat.cast_pos.mpr bN0) qR0, -- At a1, clear denominators... replace a1 : |a * q - b * p| * q ^ (b + 1) < b * q, by rwa [div_sub_div _ _ b0 (ne_of_gt qR0), abs_div, div_lt_div_iff (abs_pos.mpr (ne_of_gt bq0)) (pow_pos qR0 _), abs_of_pos bq0, one_mul, -- ... and revert to integers ← int.cast_pow, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_mul, ← int.cast_sub, ← int.cast_abs, ← int.cast_mul, int.cast_lt] at a1, -- At a0, clear denominators... replace a0 : ¬a * q - ↑b * p = 0, by rwa [ne.def, div_eq_div_iff b0 (ne_of_gt qR0), mul_comm ↑p, ← sub_eq_zero, -- ... and revert to integers ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_mul, ← int.cast_sub, int.cast_eq_zero] at a0, -- Actually, `q` is a natural number lift q to ℕ using (zero_lt_one.trans q1).le, -- Looks innocuous, but we now have an integer with non-zero absolute value: this is at -- least one away from zero. The gain here is what gets the proof going. have ap : 0 < |a * ↑q - ↑b * p| := abs_pos.mpr a0, -- Actually, the absolute value of an integer is a natural number lift (|a * ↑q - ↑b * p|) to ℕ using (abs_nonneg (a * ↑q - ↑b * p)), -- At a1, revert to natural numbers rw [← int.coe_nat_mul, ← int.coe_nat_pow, ← int.coe_nat_mul, int.coe_nat_lt] at a1, -- Recall this is by contradiction: we obtained the inequality `b * q ≤ x * q ^ (b + 1)`, so -- we are done. exact not_le.mpr a1 (nat.mul_lt_mul_pow_succ (int.coe_nat_pos.mp ap) (int.coe_nat_lt.mp q1)).le, end open polynomial metric set real ring_hom /-- Let `Z, N` be types, let `R` be a metric space, let `α : R` be a point and let `j : Z → N → R` be a function. We aim to estimate how close we can get to `α`, while staying in the image of `j`. The points `j z a` of `R` in the image of `j` come with a "cost" equal to `d a`. As we get closer to `α` while staying in the image of `j`, we are interested in bounding the quantity `d a * dist α (j z a)` from below by a strictly positive amount `1 / A`: the intuition is that approximating well `α` with the points in the image of `j` should come at a high cost. The hypotheses on the function `f : R → R` provide us with sufficient conditions to ensure our goal. The first hypothesis is that `f` is Lipschitz at `α`: this yields a bound on the distance. The second hypothesis is specific to the Liouville argument and provides the missing bound involving the cost function `d`. This lemma collects the properties used in the proof of `exists_pos_real_of_irrational_root`. It is stated in more general form than needed: in the intended application, `Z = ℤ`, `N = ℕ`, `R = ℝ`, `d a = (a + 1) ^ f.nat_degree`, `j z a = z / (a + 1)`, `f ∈ ℤ[x]`, `α` is an irrational root of `f`, `ε` is small, `M` is a bound on the Lipschitz constant of `f` near `α`, `n` is the degree of the polynomial `f`. -/ lemma exists_one_le_pow_mul_dist {Z N R : Type*} [pseudo_metric_space R] {d : N → ℝ} {j : Z → N → R} {f : R → R} {α : R} {ε M : ℝ} -- denominators are positive (d0 : ∀ (a : N), 1 ≤ d a) (e0 : 0 < ε) -- function is Lipschitz at α (B : ∀ ⦃y : R⦄, y ∈ closed_ball α ε → dist (f α) (f y) ≤ (dist α y) * M) -- clear denominators (L : ∀ ⦃z : Z⦄, ∀ ⦃a : N⦄, j z a ∈ closed_ball α ε → 1 ≤ (d a) * dist (f α) (f (j z a))) : ∃ A : ℝ, 0 < A ∧ ∀ (z : Z), ∀ (a : N), 1 ≤ (d a) * (dist α (j z a) * A) := begin -- A useful inequality to keep at hand have me0 : 0 < max (1 / ε) M := lt_max_iff.mpr (or.inl (one_div_pos.mpr e0)), -- The maximum between `1 / ε` and `M` works refine ⟨max (1 / ε) M, me0, λ z a, _⟩, -- First, let's deal with the easy case in which we are far away from `α` by_cases dm1 : 1 ≤ (dist α (j z a) * max (1 / ε) M), { exact one_le_mul_of_one_le_of_one_le (d0 a) dm1 }, { -- `j z a = z / (a + 1)`: we prove that this ratio is close to `α` have : j z a ∈ closed_ball α ε, { refine mem_closed_ball'.mp (le_trans _ ((one_div_le me0 e0).mpr (le_max_left _ _))), exact ((le_div_iff me0).mpr (not_le.mp dm1).le) }, -- use the "separation from `1`" (assumption `L`) for numerators, refine (L this).trans _, -- remove a common factor and use the Lipschitz assumption `B` refine mul_le_mul_of_nonneg_left ((B this).trans _) (zero_le_one.trans (d0 a)), exact mul_le_mul_of_nonneg_left (le_max_right _ M) dist_nonneg } end lemma exists_pos_real_of_irrational_root {α : ℝ} (ha : irrational α) {f : polynomial ℤ} (f0 : f ≠ 0) (fa : eval α (map (algebra_map ℤ ℝ) f) = 0): ∃ A : ℝ, 0 < A ∧ ∀ (a : ℤ), ∀ (b : ℕ), (1 : ℝ) ≤ (b + 1) ^ f.nat_degree * (|α - (a / (b + 1))| * A) := begin -- `fR` is `f` viewed as a polynomial with `ℝ` coefficients. set fR : polynomial ℝ := map (algebra_map ℤ ℝ) f, -- `fR` is non-zero, since `f` is non-zero. obtain fR0 : fR ≠ 0 := λ fR0, (map_injective (algebra_map ℤ ℝ) (λ _ _ A, int.cast_inj.mp A)).ne f0 (fR0.trans (polynomial.map_zero _).symm), -- reformulating assumption `fa`: `α` is a root of `fR`. have ar : α ∈ (fR.roots.to_finset : set ℝ) := finset.mem_coe.mpr (multiset.mem_to_finset.mpr ((mem_roots fR0).mpr (is_root.def.mpr fa))), -- Since the polynomial `fR` has finitely many roots, there is a closed interval centered at `α` -- such that `α` is the only root of `fR` in the interval. obtain ⟨ζ, z0, U⟩ : ∃ ζ > 0, closed_ball α ζ ∩ (fR.roots.to_finset) = {α} := @exists_closed_ball_inter_eq_singleton_of_discrete _ _ _ discrete_of_t1_of_finite _ ar, -- Since `fR` is continuous, it is bounded on the interval above. obtain ⟨xm, -, hM⟩ : ∃ (xm : ℝ) (H : xm ∈ Icc (α - ζ) (α + ζ)), ∀ (y : ℝ), y ∈ Icc (α - ζ) (α + ζ) → |fR.derivative.eval y| ≤ |fR.derivative.eval xm| := is_compact.exists_forall_ge is_compact_Icc ⟨α, (sub_lt_self α z0).le, (lt_add_of_pos_right α z0).le⟩ (continuous_abs.comp fR.derivative.continuous_aeval).continuous_on, -- Use the key lemma `exists_one_le_pow_mul_dist`: we are left to show that ... refine @exists_one_le_pow_mul_dist ℤ ℕ ℝ _ _ _ (λ y, fR.eval y) α ζ (|fR.derivative.eval xm|) _ z0 (λ y hy, _) (λ z a hq, _), -- 1: the denominators are positive -- essentially by definition; { exact λ a, one_le_pow_of_one_le ((le_add_iff_nonneg_left 1).mpr a.cast_nonneg) _ }, -- 2: the polynomial `fR` is Lipschitz at `α` -- as its derivative continuous; { rw mul_comm, rw real.closed_ball_eq_Icc at hy, -- apply the Mean Value Theorem: the bound on the derivative comes from differentiability. refine convex.norm_image_sub_le_of_norm_deriv_le (λ _ _, fR.differentiable_at) (λ y h, by { rw fR.deriv, exact hM _ h }) (convex_Icc _ _) hy (mem_Icc_iff_abs_le.mp _), exact @mem_closed_ball_self ℝ _ α ζ (le_of_lt z0) }, -- 3: the weird inequality of Liouville type with powers of the denominators. { show 1 ≤ (a + 1 : ℝ) ^ f.nat_degree * |eval α fR - eval (z / (a + 1)) fR|, rw [fa, zero_sub, abs_neg], rw [show (a + 1 : ℝ) = ((a + 1 : ℕ) : ℤ), by norm_cast] at hq ⊢, -- key observation: the right-hand side of the inequality is an *integer*. Therefore, -- if its absolute value is not at least one, then it vanishes. Proceed by contradiction refine one_le_pow_mul_abs_eval_div (int.coe_nat_succ_pos a) (λ hy, _), -- As the evaluation of the polynomial vanishes, we found a root of `fR` that is rational. -- We know that `α` is the only root of `fR` in our interval, and `α` is irrational: -- follow your nose. refine (irrational_iff_ne_rational α).mp ha z (a + 1) ((mem_singleton_iff.mp _).symm), refine U.subset _, refine ⟨hq, finset.mem_coe.mp (multiset.mem_to_finset.mpr _)⟩, exact (mem_roots fR0).mpr (is_root.def.mpr hy) } end /-- **Liouville's Theorem** -/ theorem transcendental {x : ℝ} (lx : liouville x) : transcendental ℤ x := begin -- Proceed by contradiction: if `x` is algebraic, then `x` is the root (`ef0`) of a -- non-zero (`f0`) polynomial `f` rintros ⟨f : polynomial ℤ, f0, ef0⟩, -- Change `aeval x f = 0` to `eval (map _ f) = 0`, who knew. replace ef0 : (f.map (algebra_map ℤ ℝ)).eval x = 0, { rwa [aeval_def, ← eval_map] at ef0 }, -- There is a "large" real number `A` such that `(b + 1) ^ (deg f) * |f (x - a / (b + 1))| * A` -- is at least one. This is obtained from lemma `exists_pos_real_of_irrational_root`. obtain ⟨A, hA, h⟩ : ∃ (A : ℝ), 0 < A ∧ ∀ (a : ℤ) (b : ℕ), (1 : ℝ) ≤ (b + 1) ^ f.nat_degree * (|x - a / (b + 1)| * A) := exists_pos_real_of_irrational_root lx.irrational f0 ef0, -- Since the real numbers are Archimedean, a power of `2` exceeds `A`: `hn : A < 2 ^ r`. rcases pow_unbounded_of_one_lt A (lt_add_one 1) with ⟨r, hn⟩, -- Use the Liouville property, with exponent `r + deg f`. obtain ⟨a, b, b1, -, a1⟩ : ∃ (a b : ℤ), 1 < b ∧ x ≠ a / b ∧ |x - a / b| < 1 / b ^ (r + f.nat_degree) := lx (r + f.nat_degree), have b0 : (0 : ℝ) < b := zero_lt_one.trans (by { rw ← int.cast_one, exact int.cast_lt.mpr b1 }), -- Prove that `b ^ f.nat_degree * abs (x - a / b)` is strictly smaller than itself -- recall, this is a proof by contradiction! refine lt_irrefl ((b : ℝ) ^ f.nat_degree * |x - ↑a / ↑b|) _, -- clear denominators at `a1` rw [lt_div_iff' (pow_pos b0 _), pow_add, mul_assoc] at a1, -- split the inequality via `1 / A`. refine ((_ : (b : ℝ) ^ f.nat_degree * |x - a / b| < 1 / A).trans_le _), -- This branch of the proof uses the Liouville condition and the Archimedean property { refine (lt_div_iff' hA).mpr _, refine lt_of_le_of_lt _ a1, refine mul_le_mul_of_nonneg_right _ (mul_nonneg (pow_nonneg b0.le _) (abs_nonneg _)), refine hn.le.trans _, refine pow_le_pow_of_le_left zero_le_two _ _, exact int.cast_two.symm.le.trans (int.cast_le.mpr (int.add_one_le_iff.mpr b1)) }, -- this branch of the proof exploits the "integrality" of evaluations of polynomials -- at ratios of integers. { lift b to ℕ using zero_le_one.trans b1.le, specialize h a b.pred, rwa [← nat.cast_succ, nat.succ_pred_eq_of_pos (zero_lt_one.trans _), ← mul_assoc, ← (div_le_iff hA)] at h, exact int.coe_nat_lt.mp b1 } end end liouville
16a2149237e0ce16bb46e61e611c6a4fe655b3ee
5719a16e23dfc08cdea7a5bf035b81690f307965
/src/Init/Lean/Elab/Command.lean
2f784b319e11f47241232e04ebbf90cd25745fe2
[ "Apache-2.0" ]
permissive
postmasters/lean4
488b03969a371e1507e1e8a4df9ebf63c7cbe7ac
f3976fc53a883ac7606fc59357d43f4b51016ca7
refs/heads/master
1,655,582,707,480
1,588,682,595,000
1,588,682,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,701
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Elab.Alias import Init.Lean.Elab.Log import Init.Lean.Elab.ResolveName import Init.Lean.Elab.Term import Init.Lean.Elab.Binders import Init.Lean.Elab.SyntheticMVars namespace Lean namespace Elab namespace Command structure Scope := (kind : String) (header : String) (opts : Options := {}) (currNamespace : Name := Name.anonymous) (openDecls : List OpenDecl := []) (levelNames : List Name := []) (varDecls : Array Syntax := #[]) instance Scope.inhabited : Inhabited Scope := ⟨{ kind := "", header := "" }⟩ structure State := (env : Environment) (messages : MessageLog := {}) (scopes : List Scope := [{ kind := "root", header := "" }]) (nextMacroScope : Nat := firstFrontendMacroScope + 1) (maxRecDepth : Nat) instance State.inhabited : Inhabited State := ⟨{ env := arbitrary _, maxRecDepth := 0 }⟩ def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := { env := env, messages := messages, scopes := [{ kind := "root", header := "", opts := opts }], maxRecDepth := getMaxRecDepth opts } structure Context := (fileName : String) (fileMap : FileMap) (stateRef : IO.Ref State) (currRecDepth : Nat := 0) (cmdPos : String.Pos := 0) (macroStack : MacroStack := []) (currMacroScope : MacroScope := firstFrontendMacroScope) instance Exception.inhabited : Inhabited Exception := ⟨Exception.error $ arbitrary _⟩ abbrev CommandElabCoreM (ε) := ReaderT Context (EIO ε) abbrev CommandElabM := CommandElabCoreM Exception abbrev CommandElab := Syntax → CommandElabM Unit def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message := mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos.getD ctx.cmdPos) private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message := let ref := getBetterRef ref ctx.macroStack; mkMessageAux ctx ref (addMacroStack (toString err) ctx.macroStack) MessageSeverity.error @[inline] def liftIOCore {α} (ctx : Context) (ref : Syntax) (x : IO α) : EIO Exception α := EIO.adaptExcept (fun ex => Exception.error $ ioErrorToMessage ctx ref ex) x @[inline] def liftIO {α} (ref : Syntax) (x : IO α) : CommandElabM α := fun ctx => liftIOCore ctx ref x private def getState : CommandElabM State := fun ctx => liftIOCore ctx Syntax.missing $ ctx.stateRef.get private def setState (s : State) : CommandElabM Unit := fun ctx => liftIOCore ctx Syntax.missing $ ctx.stateRef.set s @[inline] private def modifyGetState {α} (f : State → α × State) : CommandElabM α := do s ← getState; let (a, s) := f s; setState s; pure a instance CommandElabCoreM.monadState : MonadState State CommandElabM := { get := getState, set := setState, modifyGet := @modifyGetState } def getEnv : CommandElabM Environment := do s ← get; pure s.env def getScope : CommandElabM Scope := do s ← get; pure s.scopes.head! def getOptions : CommandElabM Options := do scope ← getScope; pure scope.opts def addContext (msg : MessageData) : CommandElabM MessageData := do env ← getEnv; opts ← getOptions; pure (MessageData.withContext { env := env, mctx := {}, lctx := {}, opts := opts } msg) instance CommandElabM.monadLog : MonadLog CommandElabM := { getCmdPos := do ctx ← read; pure ctx.cmdPos, getFileMap := do ctx ← read; pure ctx.fileMap, getFileName := do ctx ← read; pure ctx.fileName, addContext := addContext, logMessage := fun msg => modify $ fun s => { messages := s.messages.add msg, .. s } } /-- Throws an error with the given `msgData` and extracting position information from `ref`. If `ref` does not contain position information, then use `cmdPos` -/ def throwError {α} (ref : Syntax) (msgData : MessageData) : CommandElabM α := do ctx ← read; let ref := getBetterRef ref ctx.macroStack; let msgData := addMacroStack msgData ctx.macroStack; msg ← mkMessage msgData MessageSeverity.error ref; throw (Exception.error msg) def logTrace (cls : Name) (ref : Syntax) (msg : MessageData) : CommandElabM Unit := do msg ← addContext $ MessageData.tagged cls msg; logInfo ref msg @[inline] def trace (cls : Name) (ref : Syntax) (msg : Unit → MessageData) : CommandElabM Unit := do opts ← getOptions; when (checkTraceOption opts cls) $ logTrace cls ref (msg ()) def throwUnsupportedSyntax {α} : CommandElabM α := throw Elab.Exception.unsupportedSyntax protected def getCurrMacroScope : CommandElabM Nat := do ctx ← read; pure ctx.currMacroScope protected def getMainModule : CommandElabM Name := do env ← getEnv; pure env.mainModule @[inline] protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })); adaptReader (fun (ctx : Context) => { ctx with currMacroScope := fresh }) x instance CommandElabM.MonadQuotation : MonadQuotation CommandElabM := { getCurrMacroScope := Command.getCurrMacroScope, getMainModule := Command.getMainModule, withFreshMacroScope := @Command.withFreshMacroScope } unsafe def mkCommandElabAttribute : IO (KeyedDeclsAttribute CommandElab) := mkElabAttribute CommandElab `Lean.Elab.Command.commandElabAttribute `builtinCommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command" @[init mkCommandElabAttribute] constant commandElabAttribute : KeyedDeclsAttribute CommandElab := arbitrary _ @[inline] def withIncRecDepth {α} (ref : Syntax) (x : CommandElabM α) : CommandElabM α := do ctx ← read; s ← get; when (ctx.currRecDepth == s.maxRecDepth) $ throwError ref maxRecDepthErrorMessage; adaptReader (fun (ctx : Context) => { currRecDepth := ctx.currRecDepth + 1, .. ctx }) x private def elabCommandUsing (s : State) (stx : Syntax) : List CommandElab → CommandElabM Unit | [] => do let refFmt := stx.prettyPrint; throwError stx ("unexpected syntax" ++ MessageData.nest 2 (Format.line ++ refFmt)) | (elabFn::elabFns) => catch (elabFn stx) (fun ex => match ex with | Exception.error _ => throw ex | Exception.unsupportedSyntax => do set s; elabCommandUsing elabFns) /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α := adaptReader (fun (ctx : Context) => { macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack, .. ctx }) x instance : MonadMacroAdapter CommandElabM := { getEnv := getEnv, getCurrMacroScope := getCurrMacroScope, getNextMacroScope := do s ← get; pure s.nextMacroScope, setNextMacroScope := fun next => modify $ fun s => { nextMacroScope := next, .. s }, throwError := @throwError, throwUnsupportedSyntax := @throwUnsupportedSyntax} partial def elabCommand : Syntax → CommandElabM Unit | stx => withIncRecDepth stx $ withFreshMacroScope $ match stx with | Syntax.node k args => if k == nullKind then -- list of commands => elaborate in order -- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones args.forM elabCommand else do trace `Elab.step stx $ fun _ => stx; s ← get; stxNew? ← catch (do newStx ← adaptMacro (getMacros s.env) stx; pure (some newStx)) (fun ex => match ex with | Exception.unsupportedSyntax => pure none | _ => throw ex); match stxNew? with | some stxNew => withMacroExpansion stx stxNew $ elabCommand stxNew | _ => do let table := (commandElabAttribute.ext.getState s.env).table; let k := stx.getKind; match table.find? k with | some elabFns => elabCommandUsing s stx elabFns | none => throwError stx ("elaboration function for '" ++ toString k ++ "' has not been implemented") | _ => throwError stx "unexpected command" /-- Adapt a syntax transformation to a regular, command-producing elaborator. -/ def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab := fun stx => do stx' ← exp stx; withMacroExpansion stx stx' $ elabCommand stx' private def mkTermContext (ctx : Context) (s : State) (declName? : Option Name) : Term.Context := let scope := s.scopes.head!; { config := { opts := scope.opts, foApprox := true, ctxApprox := true, quasiPatternApprox := true, isDefEqStuckEx := true }, fileName := ctx.fileName, fileMap := ctx.fileMap, currRecDepth := ctx.currRecDepth, maxRecDepth := s.maxRecDepth, cmdPos := ctx.cmdPos, declName? := declName?, macroStack := ctx.macroStack, currMacroScope := ctx.currMacroScope, currNamespace := scope.currNamespace, levelNames := scope.levelNames, openDecls := scope.openDecls } private def mkTermState (s : State) : Term.State := { env := s.env, messages := s.messages, nextMacroScope := s.nextMacroScope } private def updateState (s : State) (newS : Term.State) : State := { env := newS.env, messages := newS.messages, nextMacroScope := newS.nextMacroScope, .. s } private def getVarDecls (s : State) : Array Syntax := s.scopes.head!.varDecls private def toCommandResult {α} (ctx : Context) (s : State) (result : EStateM.Result Term.Exception Term.State α) : EStateM.Result Exception State α := match result with | EStateM.Result.ok a newS => EStateM.Result.ok a (updateState s newS) | EStateM.Result.error (Term.Exception.ex ex) newS => EStateM.Result.error ex (updateState s newS) | EStateM.Result.error Term.Exception.postpone newS => unreachable! instance CommandElabM.inhabited {α} : Inhabited (CommandElabM α) := ⟨throw $ arbitrary _⟩ @[inline] def liftTermElabM {α} (declName? : Option Name) (x : TermElabM α) : CommandElabM α := do ctx ← read; s ← get; match (x $ mkTermContext ctx s declName?).run (mkTermState s) with | EStateM.Result.ok a newS => do modify $ fun s => { env := newS.env, messages := newS.messages, .. s }; pure a | EStateM.Result.error (Term.Exception.ex ex) newS => do modify $ fun s => { env := newS.env, messages := newS.messages, .. s }; throw ex | EStateM.Result.error Term.Exception.postpone newS => unreachable! @[inline] def runTermElabM {α} (declName? : Option Name) (elab : Array Expr → TermElabM α) : CommandElabM α := do s ← get; liftTermElabM declName? (Term.elabBinders (getVarDecls s) elab) @[inline] def withLogging (x : CommandElabM Unit) : CommandElabM Unit := catch x (fun ex => match ex with | Exception.error ex => do logMessage ex; pure () | Exception.unsupportedSyntax => unreachable!) @[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit := fun ctx => EIO.catchExceptions (withLogging x ctx) (fun _ => pure ()) def dbgTrace {α} [HasToString α] (a : α) : CommandElabM Unit := _root_.dbgTrace (toString a) $ fun _ => pure () def setEnv (newEnv : Environment) : CommandElabM Unit := modify $ fun s => { env := newEnv, .. s } def getCurrNamespace : CommandElabM Name := do scope ← getScope; pure scope.currNamespace private def addScope (kind : String) (header : String) (newNamespace : Name) : CommandElabM Unit := modify $ fun s => { env := s.env.registerNamespace newNamespace, scopes := { kind := kind, header := header, currNamespace := newNamespace, .. s.scopes.head! } :: s.scopes, .. s } private def addScopes (ref : Syntax) (kind : String) (updateNamespace : Bool) : Name → CommandElabM Unit | Name.anonymous => pure () | Name.str p header _ => do addScopes p; currNamespace ← getCurrNamespace; addScope kind header (if updateNamespace then currNamespace ++ header else currNamespace) | _ => throwError ref "invalid scope" private def addNamespace (ref : Syntax) (header : Name) : CommandElabM Unit := addScopes ref "namespace" true header @[builtinCommandElab «namespace»] def elabNamespace : CommandElab := fun stx => match_syntax stx with | `(namespace $n) => addNamespace stx n.getId | _ => throw Exception.unsupportedSyntax @[builtinCommandElab «section»] def elabSection : CommandElab := fun stx => match_syntax stx with | `(section $header:ident) => addScopes stx "section" false header.getId | `(section) => do currNamespace ← getCurrNamespace; addScope "section" "" currNamespace | _ => throw Exception.unsupportedSyntax def getScopes : CommandElabM (List Scope) := do s ← get; pure s.scopes private def checkAnonymousScope : List Scope → Bool | { header := "", .. } :: _ => true | _ => false private def checkEndHeader : Name → List Scope → Bool | Name.anonymous, _ => true | Name.str p s _, { header := h, .. } :: scopes => h == s && checkEndHeader p scopes | _, _ => false @[builtinCommandElab «end»] def elabEnd : CommandElab := fun stx => do let header? := (stx.getArg 1).getOptionalIdent?; let endSize := match header? with | none => 1 | some n => n.getNumParts; scopes ← getScopes; if endSize < scopes.length then modify $ fun s => { scopes := s.scopes.drop endSize, .. s } else do { -- we keep "root" scope modify $ fun s => { scopes := s.scopes.drop (s.scopes.length - 1), .. s }; throwError stx "invalid 'end', insufficient scopes" }; match header? with | none => unless (checkAnonymousScope scopes) $ throwError stx "invalid 'end', name is missing" | some header => unless (checkEndHeader header scopes) $ throwError stx "invalid 'end', name mismatch" @[inline] def withNamespace {α} (ref : Syntax) (ns : Name) (elab : CommandElabM α) : CommandElabM α := do addNamespace ref ns; a ← elab; modify $ fun s => { scopes := s.scopes.drop ns.getNumParts, .. s }; pure a @[specialize] def modifyScope (f : Scope → Scope) : CommandElabM Unit := modify $ fun s => { scopes := match s.scopes with | h::t => f h :: t | [] => unreachable!, .. s } def getLevelNames : CommandElabM (List Name) := do scope ← getScope; pure scope.levelNames def throwAlreadyDeclaredUniverseLevel {α} (ref : Syntax) (u : Name) : CommandElabM α := throwError ref ("a universe level named '" ++ toString u ++ "' has already been declared") def addUnivLevel (idStx : Syntax) : CommandElabM Unit := do let id := idStx.getId; levelNames ← getLevelNames; if levelNames.elem id then throwAlreadyDeclaredUniverseLevel idStx id else modifyScope $ fun scope => { levelNames := id :: scope.levelNames, .. scope } partial def elabChoiceAux (cmds : Array Syntax) : Nat → CommandElabM Unit | i => if h : i < cmds.size then let cmd := cmds.get ⟨i, h⟩; catch (elabCommand cmd) (fun ex => match ex with | Exception.unsupportedSyntax => elabChoiceAux (i+1) | _ => throw ex) else throwUnsupportedSyntax @[builtinCommandElab choice] def elbChoice : CommandElab := fun stx => elabChoiceAux stx.getArgs 0 @[builtinCommandElab «universe»] def elabUniverse : CommandElab := fun n => do addUnivLevel (n.getArg 1) @[builtinCommandElab «universes»] def elabUniverses : CommandElab := fun n => do let idsStx := n.getArg 1; idsStx.forArgsM addUnivLevel @[builtinCommandElab «init_quot»] def elabInitQuot : CommandElab := fun stx => do env ← getEnv; match env.addDecl Declaration.quotDecl with | Except.ok env => setEnv env | Except.error ex => do opts ← getOptions; throwError stx (ex.toMessageData opts) def getOpenDecls : CommandElabM (List OpenDecl) := do scope ← getScope; pure scope.openDecls def logUnknownDecl (stx : Syntax) (declName : Name) : CommandElabM Unit := logError stx ("unknown declaration '" ++ toString declName ++ "'") def resolveNamespace (id : Name) : CommandElabM Name := do env ← getEnv; currNamespace ← getCurrNamespace; openDecls ← getOpenDecls; match Elab.resolveNamespace env currNamespace openDecls id with | some ns => pure ns | none => throw Exception.unsupportedSyntax @[builtinCommandElab «export»] def elabExport : CommandElab := fun stx => do -- `stx` is of the form (Command.export "export" <namespace> "(" (null <ids>*) ")") let id := stx.getIdAt 1; ns ← resolveNamespace id; currNamespace ← getCurrNamespace; when (ns == currNamespace) $ throwError stx "invalid 'export', self export"; env ← getEnv; let ids := (stx.getArg 3).getArgs; aliases ← ids.foldlM (fun (aliases : List (Name × Name)) (idStx : Syntax) => do { let id := idStx.getId; let declName := ns ++ id; if env.contains declName then pure $ (currNamespace ++ id, declName) :: aliases else do logUnknownDecl idStx declName; pure aliases }) []; modify $ fun s => { env := aliases.foldl (fun env p => addAlias env p.1 p.2) s.env, .. s } def addOpenDecl (d : OpenDecl) : CommandElabM Unit := modifyScope $ fun scope => { openDecls := d :: scope.openDecls, .. scope } def elabOpenSimple (n : SyntaxNode) : CommandElabM Unit := -- `open` id+ let nss := n.getArg 0; nss.forArgsM $ fun ns => do ns ← resolveNamespace ns.getId; addOpenDecl (OpenDecl.simple ns []) -- `open` id `(` id+ `)` def elabOpenOnly (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0; ns ← resolveNamespace ns; let ids := n.getArg 2; ids.forArgsM $ fun idStx => do let id := idStx.getId; let declName := ns ++ id; env ← getEnv; if env.contains declName then addOpenDecl (OpenDecl.explicit id declName) else logUnknownDecl idStx declName -- `open` id `hiding` id+ def elabOpenHiding (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0; ns ← resolveNamespace ns; let idsStx := n.getArg 2; env ← getEnv; ids : List Name ← idsStx.foldArgsM (fun idStx ids => do let id := idStx.getId; let declName := ns ++ id; if env.contains declName then pure (id::ids) else do logUnknownDecl idStx declName; pure ids) []; addOpenDecl (OpenDecl.simple ns ids) -- `open` id `renaming` sepBy (id `->` id) `,` def elabOpenRenaming (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0; ns ← resolveNamespace ns; let rs := (n.getArg 2); rs.forSepArgsM $ fun stx => do let fromId := stx.getIdAt 0; let toId := stx.getIdAt 2; let declName := ns ++ fromId; env ← getEnv; if env.contains declName then addOpenDecl (OpenDecl.explicit toId declName) else logUnknownDecl stx declName @[builtinCommandElab «open»] def elabOpen : CommandElab := fun n => do let body := (n.getArg 1).asNode; let k := body.getKind; if k == `Lean.Parser.Command.openSimple then elabOpenSimple body else if k == `Lean.Parser.Command.openOnly then elabOpenOnly body else if k == `Lean.Parser.Command.openHiding then elabOpenHiding body else elabOpenRenaming body @[builtinCommandElab «variable»] def elabVariable : CommandElab := fun n => do -- `variable` bracketedBinder let binder := n.getArg 1; -- Try to elaborate `binder` for sanity checking runTermElabM none $ fun _ => Term.elabBinder binder $ fun _ => pure (); modifyScope $ fun scope => { varDecls := scope.varDecls.push binder, .. scope } @[builtinCommandElab «variables»] def elabVariables : CommandElab := fun n => do -- `variables` bracketedBinder+ let binders := (n.getArg 1).getArgs; -- Try to elaborate `binders` for sanity checking runTermElabM none $ fun _ => Term.elabBinders binders $ fun _ => pure (); modifyScope $ fun scope => { varDecls := scope.varDecls ++ binders, .. scope } @[inline] def withoutModifyingEnv {α} (x : CommandElabM α) : CommandElabM α := do env ← getEnv; finally x (setEnv env) @[builtinCommandElab «check»] def elabCheck : CommandElab := fun stx => do let term := stx.getArg 1; withoutModifyingEnv $ runTermElabM (some `_check) $ fun _ => do e ← Term.elabTerm term none; Term.synthesizeSyntheticMVars false; type ← Term.inferType stx e; logInfo stx (e ++ " : " ++ type); pure () def hasNoErrorMessages : CommandElabM Bool := do s ← get; pure $ !s.messages.hasErrors def failIfSucceeds (ref : Syntax) (x : CommandElabM Unit) : CommandElabM Unit := do let resetMessages : CommandElabM MessageLog := do { s ← get; let messages := s.messages; modify $ fun s => { messages := {}, .. s }; pure messages }; let restoreMessages (prevMessages : MessageLog) : CommandElabM Unit := do { modify $ fun s => { messages := prevMessages ++ s.messages.errorsToWarnings, .. s } }; prevMessages ← resetMessages; succeeded ← finally (catch (do x; hasNoErrorMessages) (fun ex => match ex with | Exception.error msg => do modify (fun s => { messages := s.messages.add msg, .. s }); pure false | Exception.unsupportedSyntax => do logError ref "unsupported syntax"; pure false)) (restoreMessages prevMessages); when succeeded $ throwError ref "unexpected success" @[builtinCommandElab «check_failure»] def elabCheckFailure : CommandElab := fun stx => failIfSucceeds stx $ elabCheck stx @[builtinCommandElab «synth»] def elabSynth : CommandElab := fun stx => do let ref := stx; let term := stx.getArg 1; withoutModifyingEnv $ runTermElabM `_synth_cmd $ fun _ => do inst ← Term.elabTerm term none; Term.synthesizeSyntheticMVars false; inst ← Term.instantiateMVars ref inst; val ← Term.liftMetaM ref $ Meta.synthInstance inst; logInfo stx val; pure () def setOption (ref : Syntax) (optionName : Name) (val : DataValue) : CommandElabM Unit := do decl ← liftIO ref $ getOptionDecl optionName; unless (decl.defValue.sameCtor val) $ throwError ref "type mismatch at set_option"; modifyScope $ fun scope => { opts := scope.opts.insert optionName val, .. scope }; match optionName, val with | `maxRecDepth, DataValue.ofNat max => modify $ fun s => { maxRecDepth := max, .. s} | _, _ => pure () @[builtinCommandElab «set_option»] def elabSetOption : CommandElab := fun stx => do let ref := stx; let optionName := stx.getIdAt 1; let val := stx.getArg 2; match val.isStrLit? with | some str => setOption ref optionName (DataValue.ofString str) | none => match val.isNatLit? with | some num => setOption ref optionName (DataValue.ofNat num) | none => match val with | Syntax.atom _ "true" => setOption ref optionName (DataValue.ofBool true) | Syntax.atom _ "false" => setOption ref optionName (DataValue.ofBool false) | _ => logError val ("unexpected set_option value " ++ toString val) /- `declId` is of the form ``` parser! ident >> optional (".{" >> sepBy1 ident ", " >> "}") ``` but we also accept a single identifier to users to make macro writing more convenient . -/ def expandDeclId (declId : Syntax) : Name × Syntax := if declId.isIdent then (declId.getId, mkNullNode) else let id := declId.getIdAt 0; let optUnivDeclStx := declId.getArg 1; (id, optUnivDeclStx) @[inline] def withDeclId (declId : Syntax) (f : Name → CommandElabM Unit) : CommandElabM Unit := do -- ident >> optional (".{" >> sepBy1 ident ", " >> "}") let (id, optUnivDeclStx) := expandDeclId declId; savedLevelNames ← getLevelNames; levelNames ← if optUnivDeclStx.isNone then pure savedLevelNames else do { let extraLevels := (optUnivDeclStx.getArg 1).getArgs.getEvenElems; extraLevels.foldlM (fun levelNames idStx => let id := idStx.getId; if levelNames.elem id then throwAlreadyDeclaredUniverseLevel idStx id else pure (id :: levelNames)) savedLevelNames }; let ref := declId; -- extract (optional) namespace part of id, after decoding macro scopes that would interfere with the check let scpView := extractMacroScopes id; match scpView.name with | Name.str pre s _ => /- Add back macro scopes. We assume a declaration like `def a.b[1,2] ...` with macro scopes `[1,2]` is always meant to mean `namespace a def b[1,2] ...`. -/ let id := { name := mkNameSimple s, .. scpView }.review; withNamespace ref pre $ do modifyScope $ fun scope => { levelNames := levelNames, .. scope }; finally (f id) (modifyScope $ fun scope => { levelNames := savedLevelNames, .. scope }) | _ => throwError ref "invalid declaration name" /-- Sort the given list of `usedParams` using the following order: - If it is an explicit level `explicitParams`, then use user given order. - Otherwise, use lexicographical. Remark: `explicitParams` are in reverse declaration order. That is, the head is the last declared parameter. -/ def sortDeclLevelParams (explicitParams : List Name) (usedParams : Array Name) : List Name := let result := explicitParams.foldl (fun result levelName => if usedParams.elem levelName then levelName :: result else result) []; let remaining := usedParams.filter (fun levelParam => !explicitParams.elem levelParam); let remaining := remaining.qsort Name.lt; result ++ remaining.toList def addDecl (ref : Syntax) (decl : Declaration) : CommandElabM Unit := liftTermElabM none $ Term.addDecl ref decl def compileDecl (ref : Syntax) (decl : Declaration) : CommandElabM Unit := liftTermElabM none $ Term.compileDecl ref decl end Command end Elab end Lean
27d5d4bbf14a8a8531e1f6f8399e63fde0aaefad
2c41ae31b2b771ad5646ad880201393f5269a7f0
/Lean/Qualities/Adaptable.lean
3222c3bac50c917a7718470eb9385c1418e0b1b3
[]
no_license
kevinsullivan/Boehm
926f25bc6f1a8b6bd47d333d936fdfc278228312
55208395bff20d48a598b7fa33a4d55a2447a9cf
refs/heads/master
1,586,127,134,302
1,488,252,326,000
1,488,252,326,000
32,836,930
0
0
null
null
null
null
UTF-8
Lean
false
false
659
lean
-- Adaptable /- [Adaptable] is parameterized by an instance of type [SystemType], and it's a sub-attribute to [Flexible]. An instance of type [SystemType] is deemed [Adaptable] if and only if all the requirements are satisfied. -/ import SystemModel.System inductive Adaptable (sys_type: SystemType): Prop | intro : (exists adaptable: sys_type ^.Contexts -> sys_type ^.Phases -> sys_type ^.Stakeholders -> @SystemInstance sys_type -> Prop, forall c: sys_type ^.Contexts, forall p: sys_type ^.Phases, forall s: sys_type ^.Stakeholders, forall st: @SystemInstance sys_type, adaptable c p s st) -> Adaptable
d6528be175729597c809c830bbd174f2f7bbbb63
a07fc1a5c10c8dc40360ecb554c3aed54740f945
/src/mwe1.lean
b638a325aef09d43a466793ab16aae7d140d74e3
[]
no_license
mkummini/ideal-membership
2a39b4b07d61f2177d7e584a53b5b2279097b150
59f823e657939e386d0e53a5d9be47392bab3e41
refs/heads/master
1,690,298,605,933
1,629,856,697,000
1,629,856,697,000
384,842,535
0
0
null
null
null
null
UTF-8
Lean
false
false
548
lean
import data.mv_polynomial.basic import data.mv_polynomial.comm_ring import data.zmod.basic open mv_polynomial noncomputable theory section abbreviation R := mv_polynomial (fin 6) (zmod 101) def f : R := (X 0)*(X 1)*(X 2) - (X 3)*(X 4)*(X 5) def g : R := (X 0)*(X 1)*(X 2) def h : R := (X 3)*(X 4)*(X 5) #check R #check f #check g #check h lemma g_minus_h_eq_f : g - h = f := rfl lemma g_eq_h_plus_f : g = h + f := begin rw [f, g, h], ring, end lemma g_eq_h_plus_f_one : g = (1:R)*h + (1:R)*f := begin rw [f, g, h], ring, end end
e16fcc7cb86e18ccb33516774f6fd8ccfd609591
94e33a31faa76775069b071adea97e86e218a8ee
/src/algebra/hom/units.lean
6cc9dfd51b438fdef7474bcee2724401454940e7
[ "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
12,075
lean
/- Copyright (c) 2018 Johan Commelin All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Chris Hughes, Kevin Buzzard -/ import algebra.hom.group /-! # Monoid homomorphisms and units This file allows to lift monoid homomorphisms to group homomorphisms of their units subgroups. It also contains unrelated results about `units` that depend on `monoid_hom`. ## Main declarations * `units.map`: Turn an homomorphism from `α` to `β` monoids into an homomorphism from `αˣ` to `βˣ`. * `monoid_hom.to_hom_units`: Turn an homomorphism from a group `α` to `β` into an homomorphism from `α` to `βˣ`. ## TODO The results that don't mention homomorphisms should be proved (earlier?) in a different file and be used to golf the basic `group` lemmas. -/ open function universes u v w namespace units variables {α : Type*} {M : Type u} {N : Type v} {P : Type w} [monoid M] [monoid N] [monoid P] /-- The group homomorphism on units induced by a `monoid_hom`. -/ @[to_additive "The `add_group` homomorphism on `add_unit`s induced by an `add_monoid_hom`."] def map (f : M →* N) : Mˣ →* Nˣ := monoid_hom.mk' (λ u, ⟨f u.val, f u.inv, by rw [← f.map_mul, u.val_inv, f.map_one], by rw [← f.map_mul, u.inv_val, f.map_one]⟩) (λ x y, ext (f.map_mul x y)) @[simp, to_additive] lemma coe_map (f : M →* N) (x : Mˣ) : ↑(map f x) = f x := rfl @[simp, to_additive] lemma coe_map_inv (f : M →* N) (u : Mˣ) : ↑(map f u)⁻¹ = f ↑u⁻¹ := rfl @[simp, to_additive] lemma map_comp (f : M →* N) (g : N →* P) : map (g.comp f) = (map g).comp (map f) := rfl variables (M) @[simp, to_additive] lemma map_id : map (monoid_hom.id M) = monoid_hom.id Mˣ := by ext; refl /-- Coercion `Mˣ → M` as a monoid homomorphism. -/ @[to_additive "Coercion `add_units M → M` as an add_monoid homomorphism."] def coe_hom : Mˣ →* M := ⟨coe, coe_one, coe_mul⟩ variable {M} @[simp, to_additive] lemma coe_hom_apply (x : Mˣ) : coe_hom M x = ↑x := rfl @[simp, norm_cast, to_additive] lemma coe_pow (u : Mˣ) (n : ℕ) : ((u ^ n : Mˣ) : M) = u ^ n := (units.coe_hom M).map_pow u n section division_monoid variables [division_monoid α] @[simp, norm_cast, to_additive] lemma coe_inv : ∀ u : αˣ, ↑u⁻¹ = (u⁻¹ : α) := (units.coe_hom α).map_inv @[simp, norm_cast, to_additive] lemma coe_zpow : ∀ (u : αˣ) (n : ℤ), ((u ^ n : αˣ) : α) = u ^ n := (units.coe_hom α).map_zpow lemma _root_.divp_eq_div (a : α) (u : αˣ) : a /ₚ u = a / u := by rw [div_eq_mul_inv, divp, u.coe_inv] end division_monoid /-- If a map `g : M → Nˣ` agrees with a homomorphism `f : M →* N`, then this map is a monoid homomorphism too. -/ @[to_additive "If a map `g : M → add_units N` agrees with a homomorphism `f : M →+ N`, then this map is an add_monoid homomorphism too."] def lift_right (f : M →* N) (g : M → Nˣ) (h : ∀ x, ↑(g x) = f x) : M →* Nˣ := { to_fun := g, map_one' := units.ext $ (h 1).symm ▸ f.map_one, map_mul' := λ x y, units.ext $ by simp only [h, coe_mul, f.map_mul] } @[simp, to_additive] lemma coe_lift_right {f : M →* N} {g : M → Nˣ} (h : ∀ x, ↑(g x) = f x) (x) : (lift_right f g h x : N) = f x := h x @[simp, to_additive] lemma mul_lift_right_inv {f : M →* N} {g : M → Nˣ} (h : ∀ x, ↑(g x) = f x) (x) : f x * ↑(lift_right f g h x)⁻¹ = 1 := by rw [units.mul_inv_eq_iff_eq_mul, one_mul, coe_lift_right] @[simp, to_additive] lemma lift_right_inv_mul {f : M →* N} {g : M → Nˣ} (h : ∀ x, ↑(g x) = f x) (x) : ↑(lift_right f g h x)⁻¹ * f x = 1 := by rw [units.inv_mul_eq_iff_eq_mul, mul_one, coe_lift_right] end units namespace monoid_hom /-- If `f` is a homomorphism from a group `G` to a monoid `M`, then its image lies in the units of `M`, and `f.to_hom_units` is the corresponding monoid homomorphism from `G` to `Mˣ`. -/ @[to_additive "If `f` is a homomorphism from an additive group `G` to an additive monoid `M`, then its image lies in the `add_units` of `M`, and `f.to_hom_units` is the corresponding homomorphism from `G` to `add_units M`."] def to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) : G →* Mˣ := { to_fun := λ g, ⟨f g, f (g⁻¹), by rw [← f.map_mul, mul_inv_self, f.map_one], by rw [← f.map_mul, inv_mul_self, f.map_one]⟩, map_one' := units.ext (f.map_one), map_mul' := λ _ _, units.ext (f.map_mul _ _) } @[simp] lemma coe_to_hom_units {G M : Type*} [group G] [monoid M] (f : G →* M) (g : G): (f.to_hom_units g : M) = f g := rfl end monoid_hom namespace is_unit variables {F α M N : Type*} section monoid variables [monoid M] [monoid N] @[to_additive] lemma map [monoid_hom_class F M N] (f : F) {x : M} (h : is_unit x) : is_unit (f x) := by rcases h with ⟨y, rfl⟩; exact (units.map (f : M →* N) y).is_unit /-- If a homomorphism `f : M →* N` sends each element to an `is_unit`, then it can be lifted to `f : M →* Nˣ`. See also `units.lift_right` for a computable version. -/ @[to_additive "If a homomorphism `f : M →+ N` sends each element to an `is_add_unit`, then it can be lifted to `f : M →+ add_units N`. See also `add_units.lift_right` for a computable version."] noncomputable def lift_right (f : M →* N) (hf : ∀ x, is_unit (f x)) : M →* Nˣ := units.lift_right f (λ x, (hf x).unit) $ λ x, rfl @[to_additive] lemma coe_lift_right (f : M →* N) (hf : ∀ x, is_unit (f x)) (x) : (is_unit.lift_right f hf x : N) = f x := rfl @[simp, to_additive] lemma mul_lift_right_inv (f : M →* N) (h : ∀ x, is_unit (f x)) (x) : f x * ↑(is_unit.lift_right f h x)⁻¹ = 1 := units.mul_lift_right_inv (λ y, rfl) x @[simp, to_additive] lemma lift_right_inv_mul (f : M →* N) (h : ∀ x, is_unit (f x)) (x) : ↑(is_unit.lift_right f h x)⁻¹ * f x = 1 := units.lift_right_inv_mul (λ y, rfl) x end monoid section division_monoid variables [division_monoid α] {a b c : α} @[simp, to_additive] protected lemma inv_mul_cancel : is_unit a → a⁻¹ * a = 1 := by { rintro ⟨u, rfl⟩, rw [←units.coe_inv, units.inv_mul] } @[simp, to_additive] protected lemma mul_inv_cancel : is_unit a → a * a⁻¹ = 1 := by { rintro ⟨u, rfl⟩, rw [←units.coe_inv, units.mul_inv] } /-- The element of the group of units, corresponding to an element of a monoid which is a unit. As opposed to `is_unit.unit`, the inverse is computable and comes from the inversion on `α`. This is useful to transfer properties of inversion in `units α` to `α`. See also `to_units`. -/ @[to_additive "The element of the additive group of additive units, corresponding to an element of an additive monoid which is an additive unit. As opposed to `is_add_unit.add_unit`, the negation is computable and comes from the negation on `α`. This is useful to transfer properties of negation in `add_units α` to `α`. See also `to_add_units`.", simps] def unit' (h : is_unit a) : αˣ := ⟨a, a⁻¹, h.mul_inv_cancel, h.inv_mul_cancel⟩ @[simp, to_additive] protected lemma mul_inv_cancel_left (h : is_unit a) : ∀ b, a * (a⁻¹ * b) = b := h.unit'.mul_inv_cancel_left @[simp, to_additive] protected lemma inv_mul_cancel_left (h : is_unit a) : ∀ b, a⁻¹ * (a * b) = b := h.unit'.inv_mul_cancel_left @[simp, to_additive] protected lemma mul_inv_cancel_right (h : is_unit b) (a : α) : a * b * b⁻¹ = a := h.unit'.mul_inv_cancel_right _ @[simp, to_additive] protected lemma inv_mul_cancel_right (h : is_unit b) (a : α) : a * b⁻¹ * b = a := h.unit'.inv_mul_cancel_right _ @[to_additive] protected lemma div_self (h : is_unit a) : a / a = 1 := by rw [div_eq_mul_inv, h.mul_inv_cancel] @[to_additive] protected lemma eq_mul_inv_iff_mul_eq (h : is_unit c) : a = b * c⁻¹ ↔ a * c = b := h.unit'.eq_mul_inv_iff_mul_eq @[to_additive] protected lemma eq_inv_mul_iff_mul_eq (h : is_unit b) : a = b⁻¹ * c ↔ b * a = c := h.unit'.eq_inv_mul_iff_mul_eq @[to_additive] protected lemma inv_mul_eq_iff_eq_mul (h : is_unit a) : a⁻¹ * b = c ↔ b = a * c := h.unit'.inv_mul_eq_iff_eq_mul @[to_additive] protected lemma mul_inv_eq_iff_eq_mul (h : is_unit b) : a * b⁻¹ = c ↔ a = c * b := h.unit'.mul_inv_eq_iff_eq_mul @[to_additive] protected lemma mul_inv_eq_one (h : is_unit b) : a * b⁻¹ = 1 ↔ a = b := @units.mul_inv_eq_one _ _ h.unit' _ @[to_additive] protected lemma inv_mul_eq_one (h : is_unit a) : a⁻¹ * b = 1 ↔ a = b := @units.inv_mul_eq_one _ _ h.unit' _ @[to_additive] protected lemma mul_eq_one_iff_eq_inv (h : is_unit b) : a * b = 1 ↔ a = b⁻¹ := @units.mul_eq_one_iff_eq_inv _ _ h.unit' _ @[to_additive] protected lemma mul_eq_one_iff_inv_eq (h : is_unit a) : a * b = 1 ↔ a⁻¹ = b := @units.mul_eq_one_iff_inv_eq _ _ h.unit' _ @[simp, to_additive] protected lemma div_mul_cancel (h : is_unit b) (a : α) : a / b * b = a := by rw [div_eq_mul_inv, h.inv_mul_cancel_right] @[simp, to_additive] protected lemma mul_div_cancel (h : is_unit b) (a : α) : a * b / b = a := by rw [div_eq_mul_inv, h.mul_inv_cancel_right] @[to_additive] protected lemma mul_one_div_cancel (h : is_unit a) : a * (1 / a) = 1 := by simp [h] @[to_additive] protected lemma one_div_mul_cancel (h : is_unit a) : (1 / a) * a = 1 := by simp [h] @[to_additive] lemma inv : is_unit a → is_unit a⁻¹ := by { rintro ⟨u, rfl⟩, rw ←units.coe_inv, exact units.is_unit _ } @[to_additive] lemma div (ha : is_unit a) (hb : is_unit b) : is_unit (a / b) := by { rw div_eq_mul_inv, exact ha.mul hb.inv } @[to_additive] protected lemma div_left_inj (h : is_unit c) : a / c = b / c ↔ a = b := by { simp_rw div_eq_mul_inv, exact units.mul_left_inj h.inv.unit' } @[to_additive] protected lemma div_eq_iff (h : is_unit b) : a / b = c ↔ a = c * b := by rw [div_eq_mul_inv, h.mul_inv_eq_iff_eq_mul] @[to_additive] protected lemma eq_div_iff (h : is_unit c) : a = b / c ↔ a * c = b := by rw [div_eq_mul_inv, h.eq_mul_inv_iff_mul_eq] @[to_additive] protected lemma div_eq_of_eq_mul (h : is_unit b) : a = c * b → a / b = c := h.div_eq_iff.2 @[to_additive] protected lemma eq_div_of_mul_eq (h : is_unit c) : a * c = b → a = b / c := h.eq_div_iff.2 @[to_additive] protected lemma div_eq_one_iff_eq (h : is_unit b) : a / b = 1 ↔ a = b := ⟨eq_of_div_eq_one, λ hab, hab.symm ▸ h.div_self⟩ @[to_additive] protected lemma div_mul_left (h : is_unit b) : b / (a * b) = 1 / a := by rw [div_eq_mul_inv, mul_inv_rev, h.mul_inv_cancel_left, one_div] @[to_additive] protected lemma mul_div_mul_right (h : is_unit c) (a b : α) : (a * c) / (b * c) = a / b := by simp only [div_eq_mul_inv, mul_inv_rev, mul_assoc, h.mul_inv_cancel_left] @[to_additive] protected lemma mul_mul_div (a : α) (h : is_unit b) : a * b * (1 / b) = a := by simp [h] end division_monoid section division_comm_monoid variables [division_comm_monoid α] {a b c d : α} @[to_additive] protected lemma div_mul_right (h : is_unit a) (b : α) : a / (a * b) = 1 / b := by rw [mul_comm, h.div_mul_left] @[to_additive] protected lemma mul_div_cancel_left (h : is_unit a) (b : α) : a * b / a = b := by rw [mul_comm, h.mul_div_cancel] @[to_additive] protected lemma mul_div_cancel' (h : is_unit a) (b : α) : a * (b / a) = b := by rw [mul_comm, h.div_mul_cancel] @[to_additive] protected lemma mul_div_mul_left (h : is_unit c) (a b : α) : (c * a) / (c * b) = a / b := by rw [mul_comm c, mul_comm c, h.mul_div_mul_right] @[to_additive] protected lemma mul_eq_mul_of_div_eq_div (hb : is_unit b) (hd : is_unit d) (a c : α) (h : a / b = c / d) : a * d = c * b := by rw [←mul_one a, ←hb.div_self, ←mul_comm_div, h, div_mul_eq_mul_div, hd.div_mul_cancel] @[to_additive] protected lemma div_eq_div_iff (hb : is_unit b) (hd : is_unit d) : a / b = c / d ↔ a * d = c * b := by rw [←(hb.mul hd).mul_left_inj, ←mul_assoc, hb.div_mul_cancel, ←mul_assoc, mul_right_comm, hd.div_mul_cancel] @[to_additive] protected lemma div_div_cancel (h : is_unit a) : a / (a / b) = b := by rw [div_div_eq_mul_div, h.mul_div_cancel_left] end division_comm_monoid end is_unit
9668d372da5f3c2276f483367c731e5343f9bf92
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/category_theory/limits/shapes/pullbacks.lean
bf75ebb90eff0ebc98bf8c1e6523a78ec48595ad
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
25,588
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 -/ import category_theory.limits.shapes.finite_limits import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.binary_products import category_theory.sparse /-! # 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. Typeclasses `has_pullbacks` and `has_pushouts` assert the existence of (co)limits shaped as walking (co)spans. -/ open category_theory namespace category_theory.limits universes v 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. -/ abbreviation walking_cospan.left : walking_cospan := some walking_pair.left /-- The right point of the walking cospan. -/ abbreviation walking_cospan.right : walking_cospan := some walking_pair.right /-- The central point of the walking cospan. -/ 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. -/ abbreviation walking_span.left : walking_span := some walking_pair.left /-- The right point of the walking span. -/ abbreviation walking_span.right : walking_span := some walking_pair.right /-- The central point of the walking span. -/ 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. -/ abbreviation hom.inl : left ⟶ one := wide_pullback_shape.hom.term _ /-- The right arrow of the walking cospan. -/ abbreviation hom.inr : right ⟶ one := wide_pullback_shape.hom.term _ /-- The identity arrows of the walking cospan. -/ 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. -/ abbreviation hom.fst : zero ⟶ left := wide_pushout_shape.hom.init _ /-- The right arrow of the walking span. -/ abbreviation hom.snd : zero ⟶ right := wide_pushout_shape.hom.init _ /-- The identity arrows of the walking span. -/ 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 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` -/ 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` -/ 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 {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 /-- 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₁ /-- 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 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.mk (t : pullback_cone f g) (lift : Π (s : cone (cospan f g)), s.X ⟶ t.X) (fac_left : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app walking_cospan.left = s.π.app walking_cospan.left) (fac_right : ∀ (s : cone (cospan f g)), lift s ≫ t.π.app walking_cospan.right = s.π.app walking_cospan.right) (uniq : ∀ (s : cone (cospan 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 { simp [← s.w inl, ← t.w inl, ← 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.mk' (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}) : is_limit t := pullback_cone.is_limit.mk 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)) /-- 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.mk' _ $ λ 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 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 /-- 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 _ _⟩ /-- 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.mk (t : pushout_cocone f g) (desc : Π (s : cocone (span f g)), t.X ⟶ s.X) (fac_left : ∀ (s : cocone (span f g)), t.ι.app walking_span.left ≫ desc s = s.ι.app walking_span.left) (fac_right : ∀ (s : cocone (span f g)), t.ι.app walking_span.right ≫ desc s = s.ι.app walking_span.right) (uniq : ∀ (s : cocone (span 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.mk' (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.mk 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)) /-- 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.mk' _ $ λ 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 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 } /-- 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.ι } /-- `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_limit (cospan 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_colimit (span 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_limit (cospan 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_limit (cospan 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_colimit (span 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_colimit (span 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_limit (cospan 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_colimit (span 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_limit (cospan 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_limit (cospan 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_colimit (span 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_colimit (span 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_limit (cospan 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_colimit (span 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_limit (cospan 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_colimit (span f g)] : f ≫ (pushout.inl : Y ⟶ pushout f g) = g ≫ pushout.inr := pushout_cocone.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_limit (cospan 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 of a monomorphism is a monomorphism -/ instance pullback.fst_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono g] : mono (pullback.fst : pullback f g ⟶ X) := ⟨λ W u v h, pullback.hom_ext h $ (cancel_mono g).1 $ by simp [← pullback.condition, reassoc_of h]⟩ /-- The pullback of a monomorphism is a monomorphism -/ instance pullback.snd_of_mono {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} [has_limit (cospan f g)] [mono f] : mono (pullback.snd : pullback f g ⟶ Y) := ⟨λ W u v h, pullback.hom_ext ((cancel_mono f).1 $ by simp [pullback.condition, reassoc_of h]) h⟩ /-- 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_colimit (span 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 of an epimorphism is an epimorphism -/ instance pushout.inl_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi g] : epi (pushout.inl : Y ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext h $ (cancel_epi g).1 $ by simp [← pushout.condition_assoc, h] ⟩ /-- The pushout of an epimorphism is an epimorphism -/ instance pushout.inr_of_epi {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} [has_colimit (span f g)] [epi f] : epi (pushout.inr : Z ⟶ pushout f g) := ⟨λ W u v h, pushout.hom_ext ((cancel_epi f).1 $ by simp [pushout.condition_assoc, h]) h⟩ variables (C) /-- `has_pullbacks` represents a choice of pullback for every pair of morphisms -/ class has_pullbacks := (has_limits_of_shape : has_limits_of_shape walking_cospan C) /-- `has_pushouts` represents a choice of pushout for every pair of morphisms -/ class has_pushouts := (has_colimits_of_shape : has_colimits_of_shape walking_span C) attribute [instance] has_pullbacks.has_limits_of_shape has_pushouts.has_colimits_of_shape /-- Pullbacks are finite limits, so if `C` has all finite limits, it also has all pullbacks -/ def has_pullbacks_of_has_finite_limits [has_finite_limits C] : has_pullbacks C := { has_limits_of_shape := infer_instance } /-- Pushouts are finite colimits, so if `C` has all finite colimits, it also has all pushouts -/ def has_pushouts_of_has_finite_colimits [has_finite_colimits C] : has_pushouts C := { has_colimits_of_shape := infer_instance } /-- If `C` has all limits of diagrams `cospan f g`, then it has all pullbacks -/ def 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_limits_of_shape := { 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 -/ def 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_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_span F) } } end category_theory.limits
e0f22c9b2963b6c0df61d13d17b6f4f208f1dc3b
a726f88081e44db9edfd14d32cfe9c4393ee56a4
/world_experiments/world9/level1.lean
dea71adf970d9bb1f4c1d904e44b2a4b35618797
[]
no_license
b-mehta/natural_number_game
80451bf10277adc89a55dbe8581692c36d822462
9faf799d0ab48ecbc89b3d70babb65ba64beee3b
refs/heads/master
1,598,525,389,186
1,573,516,674,000
1,573,516,674,000
217,339,684
0
0
null
1,571,933,100,000
1,571,933,099,000
null
UTF-8
Lean
false
false
3,032
lean
import game.world4.level7 -- hide import mynat.le namespace mynat -- hide -- World name : Inequality world /- Axiom : le_def (a b : mynat) : a ≤ b ↔ ∃ c, b = a + c -/ /- # World 5 : Inequality world A new level, a new import. By the way, you can take a look at the actual files being imported by going to the source code for this game, which is available at <a href="https://github.com/ImperialCollegeLondon/natural_number_game" target="blank"> GitHub</a>. The game files are in `src/game` and the imports are in `src/mynat`. Here's what you get from the import: 1) The following data: * a binary relation called mynat.le, and notation a ≤ b for this relation. The definition is: `a ≤ b ↔ ∃ c : mynat, b = a + c` 2) The following axiom: * `le_def (a b : mynat) : a ≤ b ↔ ∃ (c : mynat), b = a + c` So `rw le_def` will change $a \leq b$ to `∃ c : mynat b = a + c`. You'll now have to know what to do with terms which have an ∃ in them! There are two new tactics you'll need immediately, but even with those we will not be able to get much further -- we really need to learn about some sort of Propositions-as-Types thing at some point. But let's press on anyway by introducing the `use` tactic. ## The `use` tactic. If your *goal* is of the form `∃ c, ...` then to make progress you can use the `use` tactic. Note of course that you have to decide what to use! You are going to prove a theorem of the form "there exists $c$ such that blahblahblah" by actually saying "look -- this explicit choice of $c$ works". For example if your local context is this: ``` x y : mynat ⊢ ∃ c : mynat, c + y = x + y ``` then we want to set `c = x` so we write `use x`, and this will remove the `∃` and change `t` to `x`, so the goal will become `⊢ x + y = x + y` which you can solve with `refl`. Note that `use` is a tactic that can go wrong -- if you `use` the wrong value then your goal might become *impossible* to solve and you'll have to go back and change your mind. -/ /- Tactic : use If your goal is of the form ``` ⊢ ∃ c : P(c)` ``` where `P` is some proposition which depends on `c`, then you might want to prove it by coming up with an explicit value of `c` for which you can prove `P(c)`. The way you supply this value is with the `use` tactic. For example if the goal is ``` ⊢ ∃ c : c = 6 ``` then you can prove this with ``` use 6, refl, ``` -/ /- ## Level 1: `le_refl` To get started on this level, you can `rw le_def`. Once you have proved it, we will know that `≤` is reflexive. -/ /- Lemma For all naturals $a$, $a \leq a$. -/ theorem le_refl (a : mynat) : a ≤ a := begin [less_leaky] rw le_def, use 0, rw add_zero, refl, end /- Now we write some magical incantation (thanks to Reid Barton for correcting my spell)... -/ attribute [refl] mynat.le_refl /- ...and now the `refl` tactic will close all goals of the form `a ≤ a` as well as all goals of the form `a = a`. -/ example : (0 : mynat) ≤ 0 := begin refl end end mynat --hide
f0415d3e7f9484377c266fdfabd1bd60f68f3d4b
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebra/quaternion.lean
c465eb0e0fb6850d5d410960445a7c3e66874f34
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
35,448
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.algebra.equiv import linear_algebra.finrank import linear_algebra.free_module.basic import linear_algebra.free_module.finite.basic import set_theory.cardinal.ordinal import tactic.ring_exp /-! # Quaternions In this file we define quaternions `ℍ[R]` over a commutative ring `R`, and define some algebraic structures on `ℍ[R]`. ## Main definitions * `quaternion_algebra R a b`, `ℍ[R, a, b]` : [quaternion algebra](https://en.wikipedia.org/wiki/Quaternion_algebra) with coefficients `a`, `b` * `quaternion R`, `ℍ[R]` : the space of quaternions, a.k.a. `quaternion_algebra R (-1) (-1)`; * `quaternion.norm_sq` : square of the norm of a quaternion; * `quaternion.star_ring` : provides the conjugate of a quaternion as `has_star.star`; We also define the following algebraic structures on `ℍ[R]`: * `ring ℍ[R, a, b]` and `algebra R ℍ[R, a, b]` : for any commutative ring `R`; * `ring ℍ[R]` and `algebra R ℍ[R]` : for any commutative ring `R`; * `domain ℍ[R]` : for a linear ordered commutative ring `R`; * `division_algebra ℍ[R]` : for a linear ordered field `R`. ## Notation The following notation is available with `open_locale quaternion`. * `ℍ[R, c₁, c₂]` : `quaternion_algebra R c₁ c₂` * `ℍ[R]` : quaternions over `R`. ## Implementation notes We define quaternions over any ring `R`, not just `ℝ` to be able to deal with, e.g., integer or rational quaternions without using real numbers. In particular, all definitions in this file are computable. ## Tags quaternion -/ /-- Quaternion algebra over a type with fixed coefficients $a=i^2$ and $b=j^2$. Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/ @[nolint unused_arguments, ext] structure quaternion_algebra (R : Type*) (a b : R) := mk {} :: (re : R) (im_i : R) (im_j : R) (im_k : R) localized "notation (name := quaternion_algebra) `ℍ[` R`,` a`,` b `]` := quaternion_algebra R a b" in quaternion namespace quaternion_algebra /-- The equivalence between a quaternion algebra over R and R × R × R × R. -/ @[simps] def equiv_prod {R : Type*} (c₁ c₂ : R) : ℍ[R, c₁, c₂] ≃ R × R × R × R := { to_fun := λ a, ⟨a.1, a.2, a.3, a.4⟩, inv_fun := λ a, ⟨a.1, a.2.1, a.2.2.1, a.2.2.2⟩, left_inv := λ ⟨a₁, a₂, a₃, a₄⟩, rfl, right_inv := λ ⟨a₁, a₂, a₃, a₄⟩, rfl } /-- The equivalence between a quaternion algebra over `R` and `fin 4 → R`. -/ @[simps symm_apply] def equiv_tuple {R : Type*} (c₁ c₂ : R) : ℍ[R, c₁, c₂] ≃ (fin 4 → R) := { to_fun := λ a, ![a.1, a.2, a.3, a.4], inv_fun := λ a, ⟨a 0, a 1, a 2, a 3⟩, left_inv := λ ⟨a₁, a₂, a₃, a₄⟩, rfl, right_inv := λ f, by ext ⟨_, _|_|_|_|_|⟨⟩⟩; refl } @[simp] lemma equiv_tuple_apply {R : Type*} (c₁ c₂ : R) (x : ℍ[R, c₁, c₂]) : equiv_tuple c₁ c₂ x = ![x.re, x.im_i, x.im_j, x.im_k] := rfl @[simp] lemma mk.eta {R : Type*} {c₁ c₂} : ∀ a : ℍ[R, c₁, c₂], mk a.1 a.2 a.3 a.4 = a | ⟨a₁, a₂, a₃, a₄⟩ := rfl variables {S T R : Type*} [comm_ring R] {c₁ c₂ : R} (r x y z : R) (a b c : ℍ[R, c₁, c₂]) /-- The imaginary part of a quaternion. -/ def im (x : ℍ[R, c₁, c₂]) : ℍ[R, c₁, c₂] := ⟨0, x.im_i, x.im_j, x.im_k⟩ @[simp] lemma im_re : a.im.re = 0 := rfl @[simp] lemma im_im_i : a.im.im_i = a.im_i := rfl @[simp] lemma im_im_j : a.im.im_j = a.im_j := rfl @[simp] lemma im_im_k : a.im.im_k = a.im_k := rfl @[simp] lemma im_idem : a.im.im = a.im := rfl instance : has_coe_t R (ℍ[R, c₁, c₂]) := ⟨λ x, ⟨x, 0, 0, 0⟩⟩ @[simp, norm_cast] lemma coe_re : (x : ℍ[R, c₁, c₂]).re = x := rfl @[simp, norm_cast] lemma coe_im_i : (x : ℍ[R, c₁, c₂]).im_i = 0 := rfl @[simp, norm_cast] lemma coe_im_j : (x : ℍ[R, c₁, c₂]).im_j = 0 := rfl @[simp, norm_cast] lemma coe_im_k : (x : ℍ[R, c₁, c₂]).im_k = 0 := rfl lemma coe_injective : function.injective (coe : R → ℍ[R, c₁, c₂]) := λ x y h, congr_arg re h @[simp] lemma coe_inj {x y : R} : (x : ℍ[R, c₁, c₂]) = y ↔ x = y := coe_injective.eq_iff @[simps] instance : has_zero ℍ[R, c₁, c₂] := ⟨⟨0, 0, 0, 0⟩⟩ @[simp, norm_cast] lemma coe_zero : ((0 : R) : ℍ[R, c₁, c₂]) = 0 := rfl instance : inhabited ℍ[R, c₁, c₂] := ⟨0⟩ @[simps] instance : has_one ℍ[R, c₁, c₂] := ⟨⟨1, 0, 0, 0⟩⟩ @[simp, norm_cast] lemma coe_one : ((1 : R) : ℍ[R, c₁, c₂]) = 1 := rfl @[simps] instance : has_add ℍ[R, c₁, c₂] := ⟨λ a b, ⟨a.1 + b.1, a.2 + b.2, a.3 + b.3, a.4 + b.4⟩⟩ @[simp] lemma mk_add_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) : (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) + mk b₁ b₂ b₃ b₄ = mk (a₁ + b₁) (a₂ + b₂) (a₃ + b₃) (a₄ + b₄) := rfl @[norm_cast, simp] lemma coe_add : ((x + y : R) : ℍ[R, c₁, c₂]) = x + y := by ext; simp @[simps] instance : has_neg ℍ[R, c₁, c₂] := ⟨λ a, ⟨-a.1, -a.2, -a.3, -a.4⟩⟩ @[simp] lemma neg_mk (a₁ a₂ a₃ a₄ : R) : -(mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) = ⟨-a₁, -a₂, -a₃, -a₄⟩ := rfl @[norm_cast, simp] lemma coe_neg : ((-x : R) : ℍ[R, c₁, c₂]) = -x := by ext; simp @[simps] instance : has_sub ℍ[R, c₁, c₂] := ⟨λ a b, ⟨a.1 - b.1, a.2 - b.2, a.3 - b.3, a.4 - b.4⟩⟩ @[simp] lemma mk_sub_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) : (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) - mk b₁ b₂ b₃ b₄ = mk (a₁ - b₁) (a₂ - b₂) (a₃ - b₃) (a₄ - b₄) := rfl @[simp, norm_cast] lemma coe_im : (x : ℍ[R, c₁, c₂]).im = 0 := rfl @[simp] lemma re_add_im : ↑a.re + a.im = a := ext _ _ (add_zero _) (zero_add _) (zero_add _) (zero_add _) @[simp] lemma sub_self_im : a - a.im = a.re := ext _ _ (sub_zero _) (sub_self _) (sub_self _) (sub_self _) @[simp] lemma sub_self_re : a - a.re = a.im := ext _ _ (sub_self _) (sub_zero _) (sub_zero _) (sub_zero _) /-- Multiplication is given by * `1 * x = x * 1 = x`; * `i * i = c₁`; * `j * j = c₂`; * `i * j = k`, `j * i = -k`; * `k * k = -c₁ * c₂`; * `i * k = c₁ * j`, `k * i = `-c₁ * j`; * `j * k = -c₂ * i`, `k * j = c₂ * i`. -/ @[simps] instance : has_mul ℍ[R, c₁, c₂] := ⟨λ a b, ⟨a.1 * b.1 + c₁ * a.2 * b.2 + c₂ * a.3 * b.3 - c₁ * c₂ * a.4 * b.4, a.1 * b.2 + a.2 * b.1 - c₂ * a.3 * b.4 + c₂ * a.4 * b.3, a.1 * b.3 + c₁ * a.2 * b.4 + a.3 * b.1 - c₁ * a.4 * b.2, a.1 * b.4 + a.2 * b.3 - a.3 * b.2 + a.4 * b.1⟩⟩ @[simp] lemma mk_mul_mk (a₁ a₂ a₃ a₄ b₁ b₂ b₃ b₄ : R) : (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) * mk b₁ b₂ b₃ b₄ = ⟨a₁ * b₁ + c₁ * a₂ * b₂ + c₂ * a₃ * b₃ - c₁ * c₂ * a₄ * b₄, a₁ * b₂ + a₂ * b₁ - c₂ * a₃ * b₄ + c₂ * a₄ * b₃, a₁ * b₃ + c₁ * a₂ * b₄ + a₃ * b₁ - c₁ * a₄ * b₂, a₁ * b₄ + a₂ * b₃ - a₃ * b₂ + a₄ * b₁⟩ := rfl section variables [has_smul S R] [has_smul T R] (s : S) /- The `ring R` argument is not used, but it's also much stronger than the other definitions in this file need; for instance `quaternion_algebra.has_zero` only really needs `has_zero R`. For simplicity we just keep things consistent. -/ @[nolint unused_arguments] instance : has_smul S ℍ[R, c₁, c₂] := { smul := λ s a, ⟨s • a.1, s • a.2, s • a.3, s • a.4⟩ } instance [has_smul S T] [is_scalar_tower S T R] : is_scalar_tower S T ℍ[R, c₁, c₂] := { smul_assoc := λ s t x, by ext; exact smul_assoc _ _ _ } instance [smul_comm_class S T R] : smul_comm_class S T ℍ[R, c₁, c₂] := { smul_comm := λ s t x, by ext; exact smul_comm _ _ _ } @[simp] lemma smul_re : (s • a).re = s • a.re := rfl @[simp] lemma smul_im_i : (s • a).im_i = s • a.im_i := rfl @[simp] lemma smul_im_j : (s • a).im_j = s • a.im_j := rfl @[simp] lemma smul_im_k : (s • a).im_k = s • a.im_k := rfl @[simp] lemma smul_mk (re im_i im_j im_k : R) : s • (⟨re, im_i, im_j, im_k⟩ : ℍ[R, c₁, c₂]) = ⟨s • re, s • im_i, s • im_j, s • im_k⟩ := rfl end @[simp, norm_cast] lemma coe_smul [smul_zero_class S R] (s : S) (r : R) : (↑(s • r) : ℍ[R, c₁, c₂]) = s • ↑r := ext _ _ rfl (smul_zero s).symm (smul_zero s).symm (smul_zero s).symm instance : add_comm_group ℍ[R, c₁, c₂] := by refine_struct { add := (+), neg := has_neg.neg, sub := has_sub.sub, zero := (0 : ℍ[R, c₁, c₂]), nsmul := (•), zsmul := (•), }; intros; try { refl }; ext; simp; ring_exp instance : add_group_with_one ℍ[R, c₁, c₂] := { nat_cast := λ n, ((n : R) : ℍ[R, c₁, c₂]), nat_cast_zero := by simp, nat_cast_succ := by simp, int_cast := λ n, ((n : R) : ℍ[R, c₁, c₂]), int_cast_of_nat := λ _, congr_arg coe (int.cast_of_nat _), int_cast_neg_succ_of_nat := λ n, show ↑↑_ = -↑↑_, by rw [int.cast_neg, int.cast_coe_nat, coe_neg], one := 1, .. quaternion_algebra.add_comm_group } @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℍ[R, c₁, c₂]).re = n := rfl @[simp, norm_cast] lemma nat_cast_im_i (n : ℕ) : (n : ℍ[R, c₁, c₂]).im_i = 0 := rfl @[simp, norm_cast] lemma nat_cast_im_j (n : ℕ) : (n : ℍ[R, c₁, c₂]).im_j = 0 := rfl @[simp, norm_cast] lemma nat_cast_im_k (n : ℕ) : (n : ℍ[R, c₁, c₂]).im_k = 0 := rfl @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℍ[R, c₁, c₂]).im = 0 := rfl @[norm_cast] lemma coe_nat_cast (n : ℕ) : ↑(n : R) = (n : ℍ[R, c₁, c₂]) := rfl @[simp, norm_cast] lemma int_cast_re (z : ℤ) : (z : ℍ[R, c₁, c₂]).re = z := rfl @[simp, norm_cast] lemma int_cast_im_i (z : ℤ) : (z : ℍ[R, c₁, c₂]).im_i = 0 := rfl @[simp, norm_cast] lemma int_cast_im_j (z : ℤ) : (z : ℍ[R, c₁, c₂]).im_j = 0 := rfl @[simp, norm_cast] lemma int_cast_im_k (z : ℤ) : (z : ℍ[R, c₁, c₂]).im_k = 0 := rfl @[simp, norm_cast] lemma int_cast_im (z : ℤ) : (z : ℍ[R, c₁, c₂]).im = 0 := rfl @[norm_cast] lemma coe_int_cast (z : ℤ) : ↑(z : R) = (z : ℍ[R, c₁, c₂]) := rfl instance : ring ℍ[R, c₁, c₂] := by refine_struct { add := (+), mul := (*), one := 1, npow := @npow_rec _ ⟨(1 : ℍ[R, c₁, c₂])⟩ ⟨(*)⟩, .. quaternion_algebra.add_group_with_one, .. quaternion_algebra.add_comm_group }; intros; try { refl }; ext; simp; ring_exp @[norm_cast, simp] lemma coe_mul : ((x * y : R) : ℍ[R, c₁, c₂]) = x * y := by ext; simp -- TODO: add weaker `mul_action`, `distrib_mul_action`, and `module` instances (and repeat them -- for `ℍ[R]`) instance [comm_semiring S] [algebra S R] : algebra S ℍ[R, c₁, c₂] := { smul := (•), to_fun := λ s, coe (algebra_map S R s), map_one' := by simpa only [map_one], map_zero' := by simpa only [map_zero], map_mul' := λ x y, by rw [map_mul, coe_mul], map_add' := λ x y, by rw [map_add, coe_add], smul_def' := λ s x, by ext; simp [algebra.smul_def], commutes' := λ s x, by ext; simp [algebra.commutes] } lemma algebra_map_eq (r : R) : algebra_map R ℍ[R,c₁,c₂] r = ⟨r, 0, 0, 0⟩ := rfl section variables (c₁ c₂) /-- `quaternion_algebra.re` as a `linear_map`-/ @[simps] def re_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := re, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } /-- `quaternion_algebra.im_i` as a `linear_map`-/ @[simps] def im_i_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := im_i, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } /-- `quaternion_algebra.im_j` as a `linear_map`-/ @[simps] def im_j_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := im_j, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } /-- `quaternion_algebra.im_k` as a `linear_map`-/ @[simps] def im_k_lm : ℍ[R, c₁, c₂] →ₗ[R] R := { to_fun := im_k, map_add' := λ x y, rfl, map_smul' := λ r x, rfl } /-- `quaternion_algebra.equiv_tuple` as a linear equivalence. -/ def linear_equiv_tuple : ℍ[R,c₁,c₂] ≃ₗ[R] (fin 4 → R) := linear_equiv.symm -- proofs are not `rfl` in the forward direction { to_fun := (equiv_tuple c₁ c₂).symm, inv_fun := equiv_tuple c₁ c₂, map_add' := λ v₁ v₂, rfl, map_smul' := λ v₁ v₂, rfl, .. (equiv_tuple c₁ c₂).symm } @[simp] lemma coe_linear_equiv_tuple : ⇑(linear_equiv_tuple c₁ c₂) = equiv_tuple c₁ c₂ := rfl @[simp] lemma coe_linear_equiv_tuple_symm : ⇑(linear_equiv_tuple c₁ c₂).symm = (equiv_tuple c₁ c₂).symm := rfl /-- `ℍ[R, c₁, c₂]` has a basis over `R` given by `1`, `i`, `j`, and `k`. -/ noncomputable def basis_one_i_j_k : basis (fin 4) R ℍ[R, c₁, c₂] := basis.of_equiv_fun $ linear_equiv_tuple c₁ c₂ @[simp] lemma coe_basis_one_i_j_k_repr (q : ℍ[R, c₁, c₂]) : ⇑((basis_one_i_j_k c₁ c₂).repr q) = ![q.re, q.im_i, q.im_j, q.im_k] := rfl instance : module.finite R ℍ[R, c₁, c₂] := module.finite.of_basis (basis_one_i_j_k c₁ c₂) instance : module.free R ℍ[R, c₁, c₂] := module.free.of_basis (basis_one_i_j_k c₁ c₂) lemma rank_eq_four [strong_rank_condition R] : module.rank R ℍ[R, c₁, c₂] = 4 := by { rw [rank_eq_card_basis (basis_one_i_j_k c₁ c₂), fintype.card_fin], norm_num } lemma finrank_eq_four [strong_rank_condition R] : finite_dimensional.finrank R ℍ[R, c₁, c₂] = 4 := have cardinal.to_nat 4 = 4, by rw [←cardinal.to_nat_cast 4, nat.cast_bit0, nat.cast_bit0, nat.cast_one], by rw [finite_dimensional.finrank, rank_eq_four, this] end @[norm_cast, simp] lemma coe_sub : ((x - y : R) : ℍ[R, c₁, c₂]) = x - y := (algebra_map R ℍ[R, c₁, c₂]).map_sub x y @[norm_cast, simp] lemma coe_pow (n : ℕ) : (↑(x ^ n) : ℍ[R, c₁, c₂]) = ↑x ^ n := (algebra_map R ℍ[R, c₁, c₂]).map_pow x n lemma coe_commutes : ↑r * a = a * r := algebra.commutes r a lemma coe_commute : commute ↑r a := coe_commutes r a lemma coe_mul_eq_smul : ↑r * a = r • a := (algebra.smul_def r a).symm lemma mul_coe_eq_smul : a * r = r • a := by rw [← coe_commutes, coe_mul_eq_smul] @[norm_cast, simp] lemma coe_algebra_map : ⇑(algebra_map R ℍ[R, c₁, c₂]) = coe := rfl lemma smul_coe : x • (y : ℍ[R, c₁, c₂]) = ↑(x * y) := by rw [coe_mul, coe_mul_eq_smul] /-- Quaternion conjugate. -/ instance : has_star ℍ[R, c₁, c₂] := { star := λ a, ⟨a.1, -a.2, -a.3, -a.4⟩ } @[simp] lemma re_star : (star a).re = a.re := rfl @[simp] lemma im_i_star : (star a).im_i = - a.im_i := rfl @[simp] lemma im_j_star : (star a).im_j = - a.im_j := rfl @[simp] lemma im_k_star : (star a).im_k = - a.im_k := rfl @[simp] lemma im_star : (star a).im = - a.im := ext _ _ neg_zero.symm rfl rfl rfl @[simp] lemma star_mk (a₁ a₂ a₃ a₄ : R) : star (mk a₁ a₂ a₃ a₄ : ℍ[R, c₁, c₂]) = ⟨a₁, -a₂, -a₃, -a₄⟩ := rfl instance : star_ring ℍ[R, c₁, c₂] := { star_involutive := λ x, by simp [has_star.star], star_add := λ a b, by ext; simp [neg_add], star_mul := λ a b, by ext; simp; ring_exp } lemma self_add_star' : a + star a = ↑(2 * a.re) := by ext; simp [two_mul] lemma self_add_star : a + star a = 2 * a.re := by simp only [self_add_star', two_mul, coe_add] lemma star_add_self' : star a + a = ↑(2 * a.re) := by rw [add_comm, self_add_star'] lemma star_add_self : star a + a = 2 * a.re := by rw [add_comm, self_add_star] lemma star_eq_two_re_sub : star a = ↑(2 * a.re) - a := eq_sub_iff_add_eq.2 a.star_add_self' instance : is_star_normal a := ⟨begin rw [a.star_eq_two_re_sub], exact (coe_commute (2 * a.re) a).sub_left (commute.refl a) end⟩ @[simp, norm_cast] lemma star_coe : star (x : ℍ[R, c₁, c₂]) = x := by ext; simp @[simp] lemma star_im : star a.im = - a.im := im_star _ @[simp] lemma star_smul [monoid S] [distrib_mul_action S R] (s : S) (a : ℍ[R, c₁, c₂]) : star (s • a) = s • star a := ext _ _ rfl (smul_neg _ _).symm (smul_neg _ _).symm (smul_neg _ _).symm lemma eq_re_of_eq_coe {a : ℍ[R, c₁, c₂]} {x : R} (h : a = x) : a = a.re := by rw [h, coe_re] lemma eq_re_iff_mem_range_coe {a : ℍ[R, c₁, c₂]} : a = a.re ↔ a ∈ set.range (coe : R → ℍ[R, c₁, c₂]) := ⟨λ h, ⟨a.re, h.symm⟩, λ ⟨x, h⟩, eq_re_of_eq_coe h.symm⟩ section char_zero variables [no_zero_divisors R] [char_zero R] @[simp] lemma star_eq_self {c₁ c₂ : R} {a : ℍ[R, c₁, c₂]} : star a = a ↔ a = a.re := by simp [ext_iff, neg_eq_iff_add_eq_zero, add_self_eq_zero] lemma star_eq_neg {c₁ c₂ : R} {a : ℍ[R, c₁, c₂]} : star a = -a ↔ a.re = 0 := by simp [ext_iff, eq_neg_iff_add_eq_zero] end char_zero -- Can't use `rw ← star_eq_self` in the proof without additional assumptions lemma star_mul_eq_coe : star a * a = (star a * a).re := by ext; simp; ring_exp lemma mul_star_eq_coe : a * star a = (a * star a).re := by { rw ←star_comm_self', exact a.star_mul_eq_coe } open mul_opposite /-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/ def star_ae : ℍ[R, c₁, c₂] ≃ₐ[R] (ℍ[R, c₁, c₂]ᵐᵒᵖ) := { to_fun := op ∘ star, inv_fun := star ∘ unop, map_mul' := λ x y, by simp, commutes' := λ r, by simp, .. star_add_equiv.trans op_add_equiv } @[simp] lemma coe_star_ae : ⇑(star_ae : ℍ[R, c₁, c₂] ≃ₐ[R] _) = op ∘ star := rfl end quaternion_algebra /-- Space of quaternions over a type. Implemented as a structure with four fields: `re`, `im_i`, `im_j`, and `im_k`. -/ def quaternion (R : Type*) [has_one R] [has_neg R] := quaternion_algebra R (-1) (-1) localized "notation (name := quaternion) `ℍ[` R `]` := quaternion R" in quaternion /-- The equivalence between the quaternions over `R` and `R × R × R × R`. -/ @[simps] def quaternion.equiv_prod (R : Type*) [has_one R] [has_neg R] : ℍ[R] ≃ R × R × R × R := quaternion_algebra.equiv_prod _ _ /-- The equivalence between the quaternions over `R` and `fin 4 → R`. -/ @[simps symm_apply] def quaternion.equiv_tuple (R : Type*) [has_one R] [has_neg R] : ℍ[R] ≃ (fin 4 → R) := quaternion_algebra.equiv_tuple _ _ @[simp] lemma quaternion.equiv_tuple_apply (R : Type*) [has_one R] [has_neg R] (x : ℍ[R]) : quaternion.equiv_tuple R x = ![x.re, x.im_i, x.im_j, x.im_k] := rfl namespace quaternion variables {S T R : Type*} [comm_ring R] (r x y z : R) (a b c : ℍ[R]) export quaternion_algebra (re im_i im_j im_k) instance : has_coe_t R ℍ[R] := quaternion_algebra.has_coe_t instance : ring ℍ[R] := quaternion_algebra.ring instance : inhabited ℍ[R] := quaternion_algebra.inhabited instance [has_smul S R] : has_smul S ℍ[R] := quaternion_algebra.has_smul instance [has_smul S T] [has_smul S R] [has_smul T R] [is_scalar_tower S T R] : is_scalar_tower S T ℍ[R] := quaternion_algebra.is_scalar_tower instance [has_smul S R] [has_smul T R] [smul_comm_class S T R] : smul_comm_class S T ℍ[R] := quaternion_algebra.smul_comm_class instance [comm_semiring S] [algebra S R] : algebra S ℍ[R] := quaternion_algebra.algebra instance : star_ring ℍ[R] := quaternion_algebra.star_ring @[ext] lemma ext : a.re = b.re → a.im_i = b.im_i → a.im_j = b.im_j → a.im_k = b.im_k → a = b := quaternion_algebra.ext a b lemma ext_iff {a b : ℍ[R]} : a = b ↔ a.re = b.re ∧ a.im_i = b.im_i ∧ a.im_j = b.im_j ∧ a.im_k = b.im_k := quaternion_algebra.ext_iff a b /-- The imaginary part of a quaternion. -/ def im (x : ℍ[R]) : ℍ[R] := x.im @[simp] lemma im_re : a.im.re = 0 := rfl @[simp] lemma im_im_i : a.im.im_i = a.im_i := rfl @[simp] lemma im_im_j : a.im.im_j = a.im_j := rfl @[simp] lemma im_im_k : a.im.im_k = a.im_k := rfl @[simp] lemma im_idem : a.im.im = a.im := rfl @[simp] lemma re_add_im : ↑a.re + a.im = a := a.re_add_im @[simp] lemma sub_self_im : a - a.im = a.re := a.sub_self_im @[simp] lemma sub_self_re : a - a.re = a.im := a.sub_self_re @[simp, norm_cast] lemma coe_re : (x : ℍ[R]).re = x := rfl @[simp, norm_cast] lemma coe_im_i : (x : ℍ[R]).im_i = 0 := rfl @[simp, norm_cast] lemma coe_im_j : (x : ℍ[R]).im_j = 0 := rfl @[simp, norm_cast] lemma coe_im_k : (x : ℍ[R]).im_k = 0 := rfl @[simp, norm_cast] lemma coe_im : (x : ℍ[R]).im = 0 := rfl @[simp] lemma zero_re : (0 : ℍ[R]).re = 0 := rfl @[simp] lemma zero_im_i : (0 : ℍ[R]).im_i = 0 := rfl @[simp] lemma zero_im_j : (0 : ℍ[R]).im_j = 0 := rfl @[simp] lemma zero_im_k : (0 : ℍ[R]).im_k = 0 := rfl @[simp] lemma zero_im : (0 : ℍ[R]).im = 0 := rfl @[simp, norm_cast] lemma coe_zero : ((0 : R) : ℍ[R]) = 0 := rfl @[simp] lemma one_re : (1 : ℍ[R]).re = 1 := rfl @[simp] lemma one_im_i : (1 : ℍ[R]).im_i = 0 := rfl @[simp] lemma one_im_j : (1 : ℍ[R]).im_j = 0 := rfl @[simp] lemma one_im_k : (1 : ℍ[R]).im_k = 0 := rfl @[simp] lemma one_im : (1 : ℍ[R]).im = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : R) : ℍ[R]) = 1 := rfl @[simp] lemma add_re : (a + b).re = a.re + b.re := rfl @[simp] lemma add_im_i : (a + b).im_i = a.im_i + b.im_i := rfl @[simp] lemma add_im_j : (a + b).im_j = a.im_j + b.im_j := rfl @[simp] lemma add_im_k : (a + b).im_k = a.im_k + b.im_k := rfl @[simp] lemma add_im : (a + b).im = a.im + b.im := ext _ _ (add_zero _).symm rfl rfl rfl @[simp, norm_cast] lemma coe_add : ((x + y : R) : ℍ[R]) = x + y := quaternion_algebra.coe_add x y @[simp] lemma neg_re : (-a).re = -a.re := rfl @[simp] lemma neg_im_i : (-a).im_i = -a.im_i := rfl @[simp] lemma neg_im_j : (-a).im_j = -a.im_j := rfl @[simp] lemma neg_im_k : (-a).im_k = -a.im_k := rfl @[simp] lemma neg_im : (-a).im = -a.im := ext _ _ neg_zero.symm rfl rfl rfl @[simp, norm_cast] lemma coe_neg : ((-x : R) : ℍ[R]) = -x := quaternion_algebra.coe_neg x @[simp] lemma sub_re : (a - b).re = a.re - b.re := rfl @[simp] lemma sub_im_i : (a - b).im_i = a.im_i - b.im_i := rfl @[simp] lemma sub_im_j : (a - b).im_j = a.im_j - b.im_j := rfl @[simp] lemma sub_im_k : (a - b).im_k = a.im_k - b.im_k := rfl @[simp] lemma sub_im : (a - b).im = a.im - b.im := ext _ _ (sub_zero _).symm rfl rfl rfl @[simp, norm_cast] lemma coe_sub : ((x - y : R) : ℍ[R]) = x - y := quaternion_algebra.coe_sub x y @[simp] lemma mul_re : (a * b).re = a.re * b.re - a.im_i * b.im_i - a.im_j * b.im_j - a.im_k * b.im_k := (quaternion_algebra.has_mul_mul_re a b).trans $ by simp only [one_mul, neg_mul, sub_eq_add_neg, neg_neg] @[simp] lemma mul_im_i : (a * b).im_i = a.re * b.im_i + a.im_i * b.re + a.im_j * b.im_k - a.im_k * b.im_j := (quaternion_algebra.has_mul_mul_im_i a b).trans $ by simp only [one_mul, neg_mul, sub_eq_add_neg, neg_neg] @[simp] lemma mul_im_j : (a * b).im_j = a.re * b.im_j - a.im_i * b.im_k + a.im_j * b.re + a.im_k * b.im_i := (quaternion_algebra.has_mul_mul_im_j a b).trans $ by simp only [one_mul, neg_mul, sub_eq_add_neg, neg_neg] @[simp] lemma mul_im_k : (a * b).im_k = a.re * b.im_k + a.im_i * b.im_j - a.im_j * b.im_i + a.im_k * b.re := (quaternion_algebra.has_mul_mul_im_k a b).trans $ by simp only [one_mul, neg_mul, sub_eq_add_neg, neg_neg] @[simp, norm_cast] lemma coe_mul : ((x * y : R) : ℍ[R]) = x * y := quaternion_algebra.coe_mul x y @[norm_cast, simp] lemma coe_pow (n : ℕ) : (↑(x ^ n) : ℍ[R]) = ↑x ^ n := quaternion_algebra.coe_pow x n @[simp, norm_cast] lemma nat_cast_re (n : ℕ) : (n : ℍ[R]).re = n := rfl @[simp, norm_cast] lemma nat_cast_im_i (n : ℕ) : (n : ℍ[R]).im_i = 0 := rfl @[simp, norm_cast] lemma nat_cast_im_j (n : ℕ) : (n : ℍ[R]).im_j = 0 := rfl @[simp, norm_cast] lemma nat_cast_im_k (n : ℕ) : (n : ℍ[R]).im_k = 0 := rfl @[simp, norm_cast] lemma nat_cast_im (n : ℕ) : (n : ℍ[R]).im = 0 := rfl @[norm_cast] lemma coe_nat_cast (n : ℕ) : ↑(n : R) = (n : ℍ[R]) := rfl @[simp, norm_cast] lemma int_cast_re (z : ℤ) : (z : ℍ[R]).re = z := rfl @[simp, norm_cast] lemma int_cast_im_i (z : ℤ) : (z : ℍ[R]).im_i = 0 := rfl @[simp, norm_cast] lemma int_cast_im_j (z : ℤ) : (z : ℍ[R]).im_j = 0 := rfl @[simp, norm_cast] lemma int_cast_im_k (z : ℤ) : (z : ℍ[R]).im_k = 0 := rfl @[simp, norm_cast] lemma int_cast_im (z : ℤ) : (z : ℍ[R]).im = 0 := rfl @[norm_cast] lemma coe_int_cast (z : ℤ) : ↑(z : R) = (z : ℍ[R]) := rfl lemma coe_injective : function.injective (coe : R → ℍ[R]) := quaternion_algebra.coe_injective @[simp] lemma coe_inj {x y : R} : (x : ℍ[R]) = y ↔ x = y := coe_injective.eq_iff @[simp] lemma smul_re [has_smul S R] (s : S) : (s • a).re = s • a.re := rfl @[simp] lemma smul_im_i [has_smul S R] (s : S) : (s • a).im_i = s • a.im_i := rfl @[simp] lemma smul_im_j [has_smul S R] (s : S) : (s • a).im_j = s • a.im_j := rfl @[simp] lemma smul_im_k [has_smul S R] (s : S) : (s • a).im_k = s • a.im_k := rfl @[simp] lemma smul_im [smul_zero_class S R] (s : S) : (s • a).im = s • a.im := ext _ _ (smul_zero _).symm rfl rfl rfl @[simp, norm_cast] lemma coe_smul [smul_zero_class S R] (s : S) (r : R) : (↑(s • r) : ℍ[R]) = s • ↑r := quaternion_algebra.coe_smul _ _ lemma coe_commutes : ↑r * a = a * r := quaternion_algebra.coe_commutes r a lemma coe_commute : commute ↑r a := quaternion_algebra.coe_commute r a lemma coe_mul_eq_smul : ↑r * a = r • a := quaternion_algebra.coe_mul_eq_smul r a lemma mul_coe_eq_smul : a * r = r • a := quaternion_algebra.mul_coe_eq_smul r a @[simp] lemma algebra_map_def : ⇑(algebra_map R ℍ[R]) = coe := rfl lemma smul_coe : x • (y : ℍ[R]) = ↑(x * y) := quaternion_algebra.smul_coe x y instance : module.finite R ℍ[R] := quaternion_algebra.module.finite _ _ instance : module.free R ℍ[R] := quaternion_algebra.module.free _ _ lemma rank_eq_four [strong_rank_condition R] : module.rank R ℍ[R] = 4 := quaternion_algebra.rank_eq_four _ _ lemma finrank_eq_four [strong_rank_condition R] : finite_dimensional.finrank R ℍ[R] = 4 := quaternion_algebra.finrank_eq_four _ _ @[simp] lemma star_re : (star a).re = a.re := rfl @[simp] lemma star_im_i : (star a).im_i = - a.im_i := rfl @[simp] lemma star_im_j : (star a).im_j = - a.im_j := rfl @[simp] lemma star_im_k : (star a).im_k = - a.im_k := rfl @[simp] lemma star_im : (star a).im = - a.im := a.im_star lemma self_add_star' : a + star a = ↑(2 * a.re) := a.self_add_star' lemma self_add_star : a + star a = 2 * a.re := a.self_add_star lemma star_add_self' : star a + a = ↑(2 * a.re) := a.star_add_self' lemma star_add_self : star a + a = 2 * a.re := a.star_add_self lemma star_eq_two_re_sub : star a = ↑(2 * a.re) - a := a.star_eq_two_re_sub @[simp, norm_cast] lemma star_coe : star (x : ℍ[R]) = x := quaternion_algebra.star_coe x @[simp] lemma im_star : star a.im = - a.im := quaternion_algebra.im_star _ @[simp] lemma star_smul [monoid S] [distrib_mul_action S R] (s : S) (a : ℍ[R]) : star (s • a) = s • star a := quaternion_algebra.star_smul _ _ lemma eq_re_of_eq_coe {a : ℍ[R]} {x : R} (h : a = x) : a = a.re := quaternion_algebra.eq_re_of_eq_coe h lemma eq_re_iff_mem_range_coe {a : ℍ[R]} : a = a.re ↔ a ∈ set.range (coe : R → ℍ[R]) := quaternion_algebra.eq_re_iff_mem_range_coe section char_zero variables [no_zero_divisors R] [char_zero R] @[simp] lemma star_eq_self {a : ℍ[R]} : star a = a ↔ a = a.re := quaternion_algebra.star_eq_self @[simp] lemma star_eq_neg {a : ℍ[R]} : star a = -a ↔ a.re = 0 := quaternion_algebra.star_eq_neg end char_zero lemma star_mul_eq_coe : star a * a = (star a * a).re := a.star_mul_eq_coe lemma mul_star_eq_coe : a * star a = (a * star a).re := a.mul_star_eq_coe open mul_opposite /-- Quaternion conjugate as an `alg_equiv` to the opposite ring. -/ def star_ae : ℍ[R] ≃ₐ[R] (ℍ[R]ᵐᵒᵖ) := quaternion_algebra.star_ae @[simp] lemma coe_star_ae : ⇑(star_ae : ℍ[R] ≃ₐ[R] ℍ[R]ᵐᵒᵖ) = op ∘ star := rfl /-- Square of the norm. -/ def norm_sq : ℍ[R] →*₀ R := { to_fun := λ a, (a * star a).re, map_zero' := by rw [star_zero, zero_mul, zero_re], map_one' := by rw [star_one, one_mul, one_re], map_mul' := λ x y, coe_injective $ by conv_lhs { rw [← mul_star_eq_coe, star_mul, mul_assoc, ← mul_assoc y, y.mul_star_eq_coe, coe_commutes, ← mul_assoc, x.mul_star_eq_coe, ← coe_mul] } } lemma norm_sq_def : norm_sq a = (a * star a).re := rfl lemma norm_sq_def' : norm_sq a = a.1^2 + a.2^2 + a.3^2 + a.4^2 := by simp only [norm_sq_def, sq, mul_neg, sub_neg_eq_add, mul_re, star_re, star_im_i, star_im_j, star_im_k] lemma norm_sq_coe : norm_sq (x : ℍ[R]) = x^2 := by rw [norm_sq_def, star_coe, ← coe_mul, coe_re, sq] @[simp] lemma norm_sq_star : norm_sq (star a) = norm_sq a := by simp [norm_sq_def'] @[norm_cast] lemma norm_sq_nat_cast (n : ℕ) : norm_sq (n : ℍ[R]) = n^2 := by rw [←coe_nat_cast, norm_sq_coe] @[norm_cast] lemma norm_sq_int_cast (z : ℤ) : norm_sq (z : ℍ[R]) = z^2 := by rw [←coe_int_cast, norm_sq_coe] @[simp] lemma norm_sq_neg : norm_sq (-a) = norm_sq a := by simp only [norm_sq_def, star_neg, neg_mul_neg] lemma self_mul_star : a * star a = norm_sq a := by rw [mul_star_eq_coe, norm_sq_def] lemma star_mul_self : star a * a = norm_sq a := by rw [star_comm_self', self_mul_star] lemma im_sq : a.im^2 = -norm_sq a.im := by simp_rw [sq, ←star_mul_self, im_star, neg_mul, neg_neg] lemma coe_norm_sq_add : (norm_sq (a + b) : ℍ[R]) = norm_sq a + a * star b + b * star a + norm_sq b := by simp [← self_mul_star, mul_add, add_mul, add_assoc] lemma norm_sq_smul (r : R) (q : ℍ[R]) : norm_sq (r • q) = r^2 * norm_sq q := by simp_rw [norm_sq_def, star_smul, smul_mul_smul, smul_re, sq, smul_eq_mul] lemma norm_sq_add (a b : ℍ[R]) : norm_sq (a + b) = norm_sq a + norm_sq b + 2 * (a * star b).re := calc norm_sq (a + b) = (norm_sq a + (a * star b).re) + ((b * star a).re + norm_sq b) : by simp_rw [norm_sq_def, star_add, add_mul, mul_add, add_re] ... = norm_sq a + norm_sq b + ((a * star b).re + (b * star a).re) : by abel ... = norm_sq a + norm_sq b + 2 * (a * star b).re : by rw [←add_re, ←star_mul_star a b, self_add_star', coe_re] end quaternion namespace quaternion variables {R : Type*} section linear_ordered_comm_ring variables [linear_ordered_comm_ring R] {a : ℍ[R]} @[simp] lemma norm_sq_eq_zero : norm_sq a = 0 ↔ a = 0 := begin refine ⟨λ h, _, λ h, h.symm ▸ norm_sq.map_zero⟩, rw [norm_sq_def', add_eq_zero_iff', add_eq_zero_iff', add_eq_zero_iff'] at h, exact ext a 0 (pow_eq_zero h.1.1.1) (pow_eq_zero h.1.1.2) (pow_eq_zero h.1.2) (pow_eq_zero h.2), all_goals { apply_rules [sq_nonneg, add_nonneg] } end lemma norm_sq_ne_zero : norm_sq a ≠ 0 ↔ a ≠ 0 := not_congr norm_sq_eq_zero @[simp] lemma norm_sq_nonneg : 0 ≤ norm_sq a := by { rw norm_sq_def', apply_rules [sq_nonneg, add_nonneg] } @[simp] lemma norm_sq_le_zero : norm_sq a ≤ 0 ↔ a = 0 := by simpa only [le_antisymm_iff, norm_sq_nonneg, and_true] using @norm_sq_eq_zero _ _ a instance : nontrivial ℍ[R] := { exists_pair_ne := ⟨0, 1, mt (congr_arg re) zero_ne_one⟩, } instance : no_zero_divisors ℍ[R] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b hab, have norm_sq a * norm_sq b = 0, by rwa [← norm_sq.map_mul, norm_sq_eq_zero], (eq_zero_or_eq_zero_of_mul_eq_zero this).imp norm_sq_eq_zero.1 norm_sq_eq_zero.1, ..quaternion.nontrivial, } instance : is_domain ℍ[R] := no_zero_divisors.to_is_domain _ lemma sq_eq_norm_sq : a^2 = norm_sq a ↔ a = a.re := begin simp_rw [←star_eq_self], obtain rfl | hq0 := eq_or_ne a 0, { simp }, { rw [←star_mul_self, sq, mul_left_inj' hq0, eq_comm] } end lemma sq_eq_neg_norm_sq : a^2 = -norm_sq a ↔ a.re = 0 := begin simp_rw [←star_eq_neg], obtain rfl | hq0 := eq_or_ne a 0, { simp }, rw [←star_mul_self, ←mul_neg, ←neg_sq, sq, mul_left_inj' (neg_ne_zero.mpr hq0), eq_comm], end end linear_ordered_comm_ring section field variables [linear_ordered_field R] (a b : ℍ[R]) @[simps { attrs := [] }] instance : has_inv ℍ[R] := ⟨λ a, (norm_sq a)⁻¹ • star a⟩ instance : group_with_zero ℍ[R] := { inv := has_inv.inv, inv_zero := by rw [has_inv_inv, star_zero, smul_zero], mul_inv_cancel := λ a ha, by rw [has_inv_inv, algebra.mul_smul_comm, self_mul_star, smul_coe, inv_mul_cancel (norm_sq_ne_zero.2 ha), coe_one], .. quaternion.nontrivial, .. (by apply_instance : monoid_with_zero ℍ[R]) } @[norm_cast, simp] lemma coe_inv (x : R) : ((x⁻¹ : R) : ℍ[R]) = x⁻¹ := map_inv₀ (algebra_map R ℍ[R]) _ @[norm_cast, simp] lemma coe_div (x y : R) : ((x / y : R) : ℍ[R]) = x / y := map_div₀ (algebra_map R ℍ[R]) x y @[norm_cast, simp] lemma coe_zpow (x : R) (z : ℤ) : ((x ^ z : R) : ℍ[R]) = x ^ z := map_zpow₀ (algebra_map R ℍ[R]) x z instance : division_ring ℍ[R] := { rat_cast := λ q, ↑(q : R), rat_cast_mk := λ n d hd h, by rw [rat.cast_mk', coe_mul, coe_int_cast, coe_inv, coe_nat_cast], qsmul := (•), qsmul_eq_mul' := λ q x, begin rw coe_mul_eq_smul, ext; exact division_ring.qsmul_eq_mul' _ _, end, .. quaternion.group_with_zero, .. quaternion.ring } @[simp, norm_cast] lemma rat_cast_re (q : ℚ) : (q : ℍ[R]).re = q := rfl @[simp, norm_cast] lemma rat_cast_im_i (q : ℚ) : (q : ℍ[R]).im_i = 0 := rfl @[simp, norm_cast] lemma rat_cast_im_j (q : ℚ) : (q : ℍ[R]).im_j = 0 := rfl @[simp, norm_cast] lemma rat_cast_im_k (q : ℚ) : (q : ℍ[R]).im_k = 0 := rfl @[simp, norm_cast] lemma rat_cast_im (q : ℚ) : (q : ℍ[R]).im = 0 := rfl @[norm_cast] lemma coe_rat_cast (q : ℚ) : ↑(q : R) = (q : ℍ[R]) := rfl @[simp] lemma norm_sq_inv : norm_sq a⁻¹ = (norm_sq a)⁻¹ := map_inv₀ norm_sq _ @[simp] lemma norm_sq_div : norm_sq (a / b) = norm_sq a / norm_sq b := map_div₀ norm_sq a b @[simp] lemma norm_sq_zpow (z : ℤ) : norm_sq (a ^ z) = norm_sq a ^ z := map_zpow₀ norm_sq a z @[norm_cast] lemma norm_sq_rat_cast (q : ℚ) : norm_sq (q : ℍ[R]) = q^2 := by rw [←coe_rat_cast, norm_sq_coe] end field end quaternion namespace cardinal open_locale cardinal quaternion section quaternion_algebra variables {R : Type*} (c₁ c₂ : R) private theorem pow_four [infinite R] : #R ^ 4 = #R := power_nat_eq (aleph_0_le_mk R) $ by simp /-- The cardinality of a quaternion algebra, as a type. -/ lemma mk_quaternion_algebra : #ℍ[R, c₁, c₂] = #R ^ 4 := by { rw mk_congr (quaternion_algebra.equiv_prod c₁ c₂), simp only [mk_prod, lift_id], ring } @[simp] lemma mk_quaternion_algebra_of_infinite [infinite R] : #ℍ[R, c₁, c₂] = #R := by rw [mk_quaternion_algebra, pow_four] /-- The cardinality of a quaternion algebra, as a set. -/ lemma mk_univ_quaternion_algebra : #(set.univ : set ℍ[R, c₁, c₂]) = #R ^ 4 := by rw [mk_univ, mk_quaternion_algebra] @[simp] lemma mk_univ_quaternion_algebra_of_infinite [infinite R] : #(set.univ : set ℍ[R, c₁, c₂]) = #R := by rw [mk_univ_quaternion_algebra, pow_four] end quaternion_algebra section quaternion variables (R : Type*) [has_one R] [has_neg R] /-- The cardinality of the quaternions, as a type. -/ @[simp] lemma mk_quaternion : #ℍ[R] = #R ^ 4 := mk_quaternion_algebra _ _ @[simp] lemma mk_quaternion_of_infinite [infinite R] : #ℍ[R] = #R := by rw [mk_quaternion, pow_four] /-- The cardinality of the quaternions, as a set. -/ @[simp] lemma mk_univ_quaternion : #(set.univ : set ℍ[R]) = #R ^ 4 := mk_univ_quaternion_algebra _ _ @[simp] lemma mk_univ_quaternion_of_infinite [infinite R] : #(set.univ : set ℍ[R]) = #R := by rw [mk_univ_quaternion, pow_four] end quaternion end cardinal
25bab4f7d8c4341ec14248bc4121c7fbc2fee2ff
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/uintCtors.lean
b19594c36a6feb2513c90bbf23026c60e61e061b
[ "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,391
lean
def UInt32.ofNatCore' (n : Nat) (h : n < UInt32.size) : UInt32 := { val := { val := n, isLt := h } } #eval UInt32.ofNatCore' 10 (by decide) def UInt64.ofNatCore' (n : Nat) (h : n < UInt64.size) : UInt64 := { val := { val := n, isLt := h } } #eval UInt64.ofNatCore' 3 (by decide) #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt8 } #eval (3 : UInt8).val #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt16 } #eval (3 : UInt16).val #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt32 } #eval (3 : UInt32).val #eval toString $ { val := { val := 3, isLt := (by decide) } : UInt64 } #eval (3 : UInt64).val #eval toString $ { val := { val := 3, isLt := (match USize.size, usizeSzEq with | _, Or.inl rfl => (by decide) | _, Or.inr rfl => (by decide)) } : USize } #eval (3 : USize).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt8 } #eval (4 : UInt8).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt16 } #eval (4 : UInt16).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt32 } #eval (4 : UInt32).val #eval toString $ { val := { val := 4, isLt := (by decide) } : UInt64 } #eval (4 : UInt64).val #eval toString $ { val := { val := 4, isLt := (match USize.size, usizeSzEq with | _, Or.inl rfl => (by decide) | _, Or.inr rfl => (by decide)) } : USize } #eval (4 : USize).val
f3524e9d761e3046ab77ca2bd2df9216643ca0bb
b7fc5b86b12212bea5542eb2c9d9f0988fd78697
/src/solutions/thursday/category_theory/exercise2.lean
b8569373a585b80fb9b6741686a5333eebd3da72
[]
no_license
stjordanis/lftcm2020
3b16591aec853c8546d9c8b69c0bf3f5f3956fee
1f3485e4dafdc587b451ec5144a1d8d3ec9b411e
refs/heads/master
1,675,958,865,413
1,609,901,722,000
1,609,901,722,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,762
lean
import algebra.category.CommRing.basic import data.polynomial /-! Let's show that taking polynomials over a ring is functor `Ring ⥤ Ring`. -/ noncomputable theory -- the default implementation of polynomials is noncomputable -- Just ignore this for now: it's a hack that prevents an annoying problem, -- and a cleaner fix is on its way to mathlib. local attribute [irreducible] polynomial.eval₂ /-! mathlib is undergoing a transition at the moment from using "unbundled" homomorphisms (e.g. we talk about a bare function `f : R → S`, along with a typeclass `[is_semiring_hom f]`) to using "bundled" homomorphisms (e.g. a structure `f : R →+* S`, which has a coercion to a bare function). The category `Ring` uses bundled homomorphisms (and in future all of mathlib will). However at present the polynomial library hasn't been updated. You may find the `ring_hom.of` useful -- this upgrades an unbundled homomorphism to a bundled homomorphism. -/ /-! Hints: * use `polynomial.map` -/ def Ring.polynomial : Ring ⥤ Ring := -- sorry { obj := λ R, Ring.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), } -- sorry def CommRing.polynomial : CommRing ⥤ CommRing := -- sorry { obj := λ R, CommRing.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), } -- sorry open category_theory def commutes : (forget₂ CommRing Ring) ⋙ Ring.polynomial ≅ CommRing.polynomial ⋙ (forget₂ CommRing Ring) := -- Hint: You can do this in two lines, ≤ 33 columns! -- sorry { hom := { app := λ R, 𝟙 _, }, inv := { app := λ R, 𝟙 _, }, }. -- sorry /-! There are some further hints in `hints/category_theory/exercise2/` -/ /-! Bonus problem: Why did we set `local attribute [irreducible] polynomial.eval₂`? What goes wrong without it? Why? -/ -- omit local attribute [semireducible] polynomial.eval₂ /- def Ring.polynomial' : Ring ⥤ Ring := { obj := λ R, Ring.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), map_comp' := λ R S T f g, begin refl end, }. -/ -- fails, but takes >5s seconds to do so! /-! What's going on? For some reason trying to solve the goal in `map_comp'` using `refl` takes a huge amount of time. This causes the automation which is responsible for automatically proving functoriality of functors to time out, and fail. How can `refl` take so long? Isn't it just checking if two things are the same? The problem is that when we work in type theory, in principle no definition is "opaque", and Lean sometimes has to unfold definitions in order to compare if two things are actually the same. Usually it's pretty conservative about this, and manages to avoid unfolding too deeply before coming up with an answer, but in bad cases it can get really bad. Somehow this is happening here! The solution we have available is to mark definitions as `[irreducible]`, which (almost, but not quite completely) prevents Lean from unfolding when checking definitional equality. Of course, this has a consequence --- Lean will sometimes fail to prove things by `refl` now! The solution to this is to provide a thorough API for our important definitions, so that after some point in the development one never needs to unfold the actual definition again, but one can work through theorems proved about the definition (e.g. characterisations and universal properties). An important example of this is that we have marked `real` as `[irreducible]` in Lean --- after you've got things working, no one should ever have to know whether the "actual definition" is in terms of Cauchy sequences or Dedekind cuts. Unfortunately at this point we don't use `[irreducible]` often enough in Lean, and improving this aspect of mathlib is an ongoin project. -/ -- omit
71e49a878e67ba4a2430343a58eed4ac198f3f39
6e44fda625e48340c6ffc7b1109a9e3b208e5384
/src/metric_spaces/connected.lean
ae06e4ee182478733e2f84b586f389f801116bea
[]
no_license
JasonKYi/learn_mspaces
9f998a265b907af6be6a54061637fcf1f6d1ee9d
54083e81da420d2d362a7024a8c86bea8529fe66
refs/heads/master
1,619,008,842,896
1,609,897,382,000
1,609,897,382,000
249,780,600
5
0
null
null
null
null
UTF-8
Lean
false
false
11,084
lean
import metric_spaces.basic noncomputable theory local attribute [instance] classical.prop_decidable open set definitions variables {α X : Type*} [metric_space X] variables {Y : Type*} [metric_space Y] namespace connected /- We have some equivalent definitions for connected sets - X is connected ↔ ∃ f : X → {0, 1}, f is continuous then f is a constant function ↔ the only sets that are both open and closed are X and ∅ -/ /- Since working with the set {0, 1} is a hassle, we will define the inductive type binary containing terms: val_a and val_b -/ inductive binary : Type* | val_a : binary | val_b : binary lemma binary_cases (y : binary) : y = binary.val_a ∨ y = binary.val_b := by cases y; finish /- We need to show that binary form a metric space so we will define a discrete metric on binary -/ private def binary_metric : binary → binary → ℝ := λ x y, if (x = y) then 0 else 1 /- We need to prove all the metric axioms -/ private lemma binary_dist_self : ∀ x, binary_metric x x = 0 := λ x, by unfold binary_metric; simp private lemma binary_eq_of_dist_eq_zero : ∀ x y, binary_metric x y = 0 → x = y := λ x y h, begin cases x; cases y; try { refl <|> { exfalso, apply @zero_ne_one ℝ _, rw ←h, unfold binary_metric, simp } } end private lemma binary_dist_comm : ∀ x y, binary_metric x y = binary_metric y x := λ x y, by cases x; cases y; try { unfold binary_metric, simp }; refl private lemma binary_dist_triangle : ∀ x y z, binary_metric x z ≤ binary_metric x y + binary_metric y z := λ x y z, begin cases x; cases y; cases z; try { unfold binary_metric, simp }; norm_num end instance metric_space_of_binary : metric_space binary := { dist := binary_metric, dist_self := binary_dist_self, eq_of_dist_eq_zero := binary_eq_of_dist_eq_zero, dist_comm := binary_dist_comm, dist_triangle := binary_dist_triangle } lemma notempty {S : set α} (h : S ≠ ∅) : ∃ s : α, s ∈ S := begin by_contra hs, push_neg at hs, exact (push_neg.not_eq _ _).1 h (set.eq_empty_iff_forall_not_mem.2 hs) end private def aux_fun (U : set X) : X → binary := λ x, if (x ∈ U) then binary.val_a else binary.val_b private lemma aux_fun_eq_val_a {U : set X} : ∀ u ∈ U, aux_fun U u = binary.val_a := λ u hu, by unfold aux_fun; split_ifs; refl private lemma aux_fun_eq_val_b {U : set X} : ∀ u ∉ U, aux_fun U u = binary.val_b := λ u hu, by unfold aux_fun; split_ifs; refl lemma disj_if_inter_empty {U V : set X} (hdisj : U ∩ V = ∅) : ∀ v ∈ V, v ∉ U := λ v hv hu, by rw [←(mem_empty_eq v), ←hdisj]; exact ⟨hu, hv⟩ private lemma aux_fun_is_continuous {U V : set X} (hU₀ : is_open' U) (hV₀ : is_open' V) (hU₁ : U ≠ ∅) (hV₁ : V ≠ ∅) (hdisj : U ∩ V = ∅) (hcover : U ∪ V = univ) : is_continuous (aux_fun U) := begin intros x ε hε, have := mem_univ x, rw ←hcover at this, cases this, { rcases hU₀ _ this with ⟨δ, hδ₀, hδ₁⟩, refine ⟨δ, hδ₀, λ y hy, _⟩, convert hε, have hyU : y ∈ U, apply hδ₁, rw dist_comm at hy, exact hy, rw aux_fun_eq_val_a _ this, rw aux_fun_eq_val_a _ hyU, exact dist_self _ }, { rcases hV₀ _ this with ⟨δ, hδ₀, hδ₁⟩, refine ⟨δ, hδ₀, λ y hy, _⟩, convert hε, have hyV : y ∈ V, apply hδ₁, rw dist_comm at hy, exact hy, rw aux_fun_eq_val_b x (disj_if_inter_empty hdisj _ this), rw aux_fun_eq_val_b y (disj_if_inter_empty hdisj _ hyV), exact dist_self _ } end lemma connected_of_const_func (h : ∀ f : X → binary, is_continuous f → (f = λ _, binary.val_a) ∨ (f = λ _, binary.val_b)) : is_connected' X := begin rintro ⟨U, V, hU₀, hV₀, hU₁, hV₁, hdisj, hcover⟩, have := h (aux_fun U) _, cases notempty hU₁ with u hu, cases notempty hV₁ with v hv, apply (show binary.val_a ≠ binary.val_b, by finish), cases this; rw function.funext_iff at this, { rw ←(this v), show (λ (x : X), ite (x ∈ U) binary.val_a binary.val_b) v = binary.val_b, simp, split_ifs with hvU, exact eq_empty_iff_forall_not_mem.1 hdisj v ⟨hvU, hv⟩, refl }, { rw ←(this u), show binary.val_a = (λ (x : X), ite (x ∈ U) binary.val_a binary.val_b) u, simp, split_ifs, refl }, exact aux_fun_is_continuous hU₀ hV₀ hU₁ hV₁ hdisj hcover end private lemma binary_singleton_is_open (x : binary) : is_open' ({ x } : set binary) := begin intros y hy, refine ⟨1, (by norm_num), _⟩, rw mem_singleton_iff.1 hy, intros z hz, simp [dist, binary_metric] at hz, split_ifs at hz, { exact h ▸ mem_singleton _ }, { linarith } end private lemma not_constant_a {f : X → binary} : (¬ f = λ x, binary.val_a) → ∃ x, f x = binary.val_b := λ hf, begin by_contra h, push_neg at h, apply hf, ext, have := h x, cases f x; finish, end private lemma not_constant_b {f : X → binary} : (¬ f = λ x, binary.val_b) → ∃ x, f x = binary.val_a := λ hf, begin by_contra h, push_neg at h, apply hf, ext, have := h x, cases f x; finish, end lemma const_func_of_connected (h : is_connected' X) : ∀ f : X → binary, is_continuous f → (f = λ _, binary.val_a) ∨ (f = λ _, binary.val_b) := begin by_contra hf, push_neg at hf, rcases hf with ⟨f, hf₀, hf₁, hf₂⟩, apply h, refine ⟨f ⁻¹' { binary.val_a }, f ⁻¹' { binary.val_b }, _, _, _⟩; try { exact open_closed.contin_to_preimg_open _ (binary_singleton_is_open _) hf₀ }, cases not_constant_a hf₁ with b hb', cases not_constant_b hf₂ with a ha', refine ⟨_, _, _, _⟩, { intro ha, apply not_mem_empty a, rwa ←ha }, { intro hb, apply not_mem_empty b, rwa ←hb }, { by_contra hpre, cases notempty hpre with x hx, apply (show binary.val_a ≠ binary.val_b, by finish), rw ←(mem_singleton_iff.1 hx.1), exact mem_singleton_iff.1 hx.2 }, ext, split; intro _, { exact mem_univ _ }, { suffices : f x = binary.val_a ∨ f x = binary.val_b, cases this, left, exact this, right, exact this, cases f x; finish } end theorem connected_iff_const_func : is_connected' X ↔ ∀ f : X → binary, is_continuous f → (f = λ _, binary.val_a) ∨ (f = λ _, binary.val_b) := ⟨λ h , const_func_of_connected h, λ h, connected_of_const_func h⟩ /- Furthermore, X is connected is equivalent to the only open sets in X are univ and ∅ -/ lemma compl_nempty_of_not_univ {S : set X} : ¬S = univ → Sᶜ ≠ ∅ := λ h hn, h $ by rw ← compl_univ at hn; exact compl_inj_iff.mp hn lemma eq_union_sub {S T : set X} (h : S = S ∪ T) : T ⊆ S := by intros t ht; rw h; right; assumption lemma sub_disj_eq_empty {S T : set X} (h : T ⊆ S) (hinter : S ∩ T = ∅) : T = ∅ := by rw ←hinter; ext; exact ⟨λ hx, ⟨h hx, hx⟩, λ hx, hx.2 ⟩ lemma compl_eq_disj_cover {S T : set X} (hinter : S ∩ T = ∅) (hcover : S ∪ T = univ) : Sᶜ = T := begin ext, split; intro hx, { have := mem_univ x, rw ←hcover at this, cases this; finish }, { intro hS, rw [←mem_empty_eq x, ←hinter], exact ⟨hS, hx⟩ } end lemma open_and_closed_of_connected (h : is_connected' X) (S : set X) (hS : is_open' S ∧ is_closed' S) : S = ∅ ∨ S = univ := begin cases hS with hS₀ hS₁, by_contra hp, push_neg at hp, apply h, cases notempty hp.1 with x hx, exact ⟨S, Sᶜ, hS₀, hS₁, hp.1, compl_nempty_of_not_univ hp.2, by finish⟩ end lemma connected_of_open_and_closed (h : ∀ S : set X, is_open' S ∧ is_closed' S → S = ∅ ∨ S = univ) : is_connected' X := begin rintro ⟨U, V, hU₀, hV₀, hU₁, hV₁, hinter, hcover⟩, cases h U ⟨hU₀, _⟩ with hempt huniv, { contradiction }, { rw ←hcover at huniv, refine hV₁ (sub_disj_eq_empty (eq_union_sub huniv) hinter) }, unfold is_closed', rwa compl_eq_disj_cover hinter hcover end theorem connected_iff_open_and_closed : is_connected' X ↔ ∀ S : set X, is_open' S ∧ is_closed' S → S = ∅ ∨ S = univ := ⟨λ h, open_and_closed_of_connected h, λ h, connected_of_open_and_closed h⟩ lemma image_factorization_contin {U : set X} {f : X → Y} (hf : is_continuous f) : is_continuous $ image_factorization f U := begin unfold image_factorization, intros u ε hε, rcases hf u.1 ε hε with ⟨δ, hδ₀, hδ₁⟩, exact ⟨δ, hδ₀, λ x hx, by simp; exact hδ₁ x.1 hx⟩ end /- The image of a connected space is connected -/ theorem image_of_connected_is_connected {U : set X} {f : X → Y} (hU : is_connected' U) (hf : is_continuous f) : is_connected' $ f '' U := begin rw connected_iff_const_func at *, intros g hg, have := hU (g ∘ image_factorization f U) (continuity.comp_continuous _ hg), cases this, left, swap, right, all_goals { try { ext y, rcases (mem_image f U y.1).1 y.2 with ⟨x, hx₀, hx₁⟩, rw (show g y = (g ∘ image_factorization f U) ⟨x, hx₀⟩, by simp [function.comp, image_factorization, hx₁]), simp [this] } }, exact image_factorization_contin hf end /- ARGGG! This is messy :( -/ theorem between_closure_is_connected_of_connected {U : set X} (hU : is_connected' U) : ∀ V, U ⊆ V ∧ V ⊆ closure' U → is_connected' V := begin rintros V ⟨hV₀, hV₁⟩, rw connected_iff_const_func at *, rw open_closed.closure'.with_limit_points_is_closure U at hV₁, intros f hf, let g : U → binary := λ u, f ⟨u.1, hV₀ u.2⟩, cases hU g (open_closed.subset_contin_of_contin hV₀ f g hf rfl), left, swap, right, all_goals { ext, cases hV₁ x.2 with hinU hlp, { try { rw [show binary.val_a = g ⟨x.1, hinU⟩, by simp [h]] <|> rw [show binary.val_b = g ⟨x.1, hinU⟩, by simp [h]] }, show f x = (λ (u : U), f ⟨u.1, hV₀ u.2⟩) ⟨x.val, hinU⟩, simp }, { choose s h₀ h₁ h₂ using λ n : ℕ, hlp (1 / (n + 1) : ℝ) nat.one_div_pos_of_nat, have ha : (λ n, g $ ⟨s n, h₀ n⟩) ⇒ f x := λ ε' hε', by { rcases hf x ε' hε' with ⟨δ, hδ₀, hδ₁⟩, cases exists_nat_gt (1 / δ) with N hN, refine ⟨N, λ n hn, _⟩, rw dist_comm, refine hδ₁ ⟨s n, _⟩ (lt_trans _ ((one_div_lt _ hδ₀).2 hN)), rw dist_comm, refine lt_of_lt_of_le (h₂ n) _, rw [one_div_le, one_div_one_div], norm_cast, exact le_add_right hn, norm_cast, exact nat.succ_pos n, rw one_div_pos, all_goals { refine lt_trans (inv_pos.2 hδ₀) _, rw inv_eq_one_div, exact hN } }, refine convergence.limit_unique _ _ ha _, rw h, simp [convergence.const_converge] } } end /- A direct corollary is that the closure of a connected set is connected -/ theorem closure_is_connected_of_connected {U : set X} (hU : is_connected' U) : is_connected' $ closure' U := between_closure_is_connected_of_connected hU _ ⟨open_closed.closure'.subset_closure', subset.refl $ closure' U⟩ end connected
c9fc33cd44706df83ed396f24d34d07b0b73219a
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Parser/Level.lean
3c5ccd40d826af9d91004707cf296f4eebc0ce92
[ "Apache-2.0" ]
permissive
SCKelemen/lean4
140dc63a80539f7c61c8e43e1c174d8500ec3230
e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc
refs/heads/master
1,660,973,595,917
1,590,278,033,000
1,590,278,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,033
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Lean.Parser.Parser namespace Lean namespace Parser @[init] def regBuiltinLevelParserAttr : IO Unit := registerBuiltinParserAttribute `builtinLevelParser `level @[inline] def levelParser (rbp : Nat := 0) : Parser := categoryParser `level rbp namespace Level @[builtinLevelParser] def paren := parser! symbol "(" appPrec >> levelParser >> ")" @[builtinLevelParser] def max := parser! nonReservedSymbol "max " true >> many1 (levelParser appPrec) @[builtinLevelParser] def imax := parser! nonReservedSymbol "imax " true >> many1 (levelParser appPrec) @[builtinLevelParser] def hole := parser! symbol "_" appPrec @[builtinLevelParser] def num := parser! numLit @[builtinLevelParser] def ident := parser! ident @[builtinLevelParser] def addLit := tparser! symbol "+" (65:Nat) >> numLit end Level end Parser end Lean
a4ea915ee57a139139680fedafac97529c83a158
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/calculus/conformal/normed_space.lean
a187e8103b8b76d84376ec1f76e3e70058eb3d31
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
4,735
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import analysis.normed_space.conformal_linear_map import analysis.calculus.fderiv.basic /-! # Conformal Maps A continuous linear map between real normed spaces `X` and `Y` is `conformal_at` some point `x` if it is real differentiable at that point and its differential `is_conformal_linear_map`. ## Main definitions * `conformal_at`: the main definition of conformal maps * `conformal`: maps that are conformal at every point * `conformal_factor_at`: the conformal factor of a conformal map at some point ## Main results * The conformality of the composition of two conformal maps, the identity map and multiplications by nonzero constants * `conformal_at_iff_is_conformal_map_fderiv`: an equivalent definition of the conformality of a map In `analysis.calculus.conformal.inner_product`: * `conformal_at_iff`: an equivalent definition of the conformality of a map In `geometry.euclidean.angle.unoriented.conformal`: * `conformal_at.preserves_angle`: if a map is conformal at `x`, then its differential preserves all angles at `x` ## Tags conformal ## Warning The definition of conformality in this file does NOT require the maps to be orientation-preserving. Maps such as the complex conjugate are considered to be conformal. -/ noncomputable theory variables {X Y Z : Type*} [normed_add_comm_group X] [normed_add_comm_group Y] [normed_add_comm_group Z] [normed_space ℝ X] [normed_space ℝ Y] [normed_space ℝ Z] section loc_conformality open linear_isometry continuous_linear_map /-- A map `f` is said to be conformal if it has a conformal differential `f'`. -/ def conformal_at (f : X → Y) (x : X) := ∃ (f' : X →L[ℝ] Y), has_fderiv_at f f' x ∧ is_conformal_map f' lemma conformal_at_id (x : X) : conformal_at id x := ⟨id ℝ X, has_fderiv_at_id _, is_conformal_map_id⟩ lemma conformal_at_const_smul {c : ℝ} (h : c ≠ 0) (x : X) : conformal_at (λ (x': X), c • x') x := ⟨c • continuous_linear_map.id ℝ X, (has_fderiv_at_id x).const_smul c, is_conformal_map_const_smul h⟩ @[nontriviality] lemma subsingleton.conformal_at [subsingleton X] (f : X → Y) (x : X) : conformal_at f x := ⟨0, has_fderiv_at_of_subsingleton _ _, is_conformal_map_of_subsingleton _⟩ /-- A function is a conformal map if and only if its differential is a conformal linear map-/ lemma conformal_at_iff_is_conformal_map_fderiv {f : X → Y} {x : X} : conformal_at f x ↔ is_conformal_map (fderiv ℝ f x) := begin split, { rintros ⟨f', hf, hf'⟩, rwa hf.fderiv }, { intros H, by_cases h : differentiable_at ℝ f x, { exact ⟨fderiv ℝ f x, h.has_fderiv_at, H⟩, }, { nontriviality X, exact absurd (fderiv_zero_of_not_differentiable_at h) H.ne_zero } }, end namespace conformal_at lemma differentiable_at {f : X → Y} {x : X} (h : conformal_at f x) : differentiable_at ℝ f x := let ⟨_, h₁, _⟩ := h in h₁.differentiable_at lemma congr {f g : X → Y} {x : X} {u : set X} (hx : x ∈ u) (hu : is_open u) (hf : conformal_at f x) (h : ∀ (x : X), x ∈ u → g x = f x) : conformal_at g x := let ⟨f', hfderiv, hf'⟩ := hf in ⟨f', hfderiv.congr_of_eventually_eq ((hu.eventually_mem hx).mono h), hf'⟩ lemma comp {f : X → Y} {g : Y → Z} (x : X) (hg : conformal_at g (f x)) (hf : conformal_at f x) : conformal_at (g ∘ f) x := begin rcases hf with ⟨f', hf₁, cf⟩, rcases hg with ⟨g', hg₁, cg⟩, exact ⟨g'.comp f', hg₁.comp x hf₁, cg.comp cf⟩, end lemma const_smul {f : X → Y} {x : X} {c : ℝ} (hc : c ≠ 0) (hf : conformal_at f x) : conformal_at (c • f) x := (conformal_at_const_smul hc $ f x).comp x hf end conformal_at end loc_conformality section global_conformality /-- A map `f` is conformal if it's conformal at every point. -/ def conformal (f : X → Y) := ∀ (x : X), conformal_at f x lemma conformal_id : conformal (id : X → X) := λ x, conformal_at_id x lemma conformal_const_smul {c : ℝ} (h : c ≠ 0) : conformal (λ (x : X), c • x) := λ x, conformal_at_const_smul h x namespace conformal lemma conformal_at {f : X → Y} (h : conformal f) (x : X) : conformal_at f x := h x lemma differentiable {f : X → Y} (h : conformal f) : differentiable ℝ f := λ x, (h x).differentiable_at lemma comp {f : X → Y} {g : Y → Z} (hf : conformal f) (hg : conformal g) : conformal (g ∘ f) := λ x, (hg $ f x).comp x (hf x) lemma const_smul {f : X → Y} (hf : conformal f) {c : ℝ} (hc : c ≠ 0) : conformal (c • f) := λ x, (hf x).const_smul hc end conformal end global_conformality
638c58e8ccd4b7b42a0ed65d6b118d4f437312e0
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/algebra/geom_sum.lean
0b1b7a89682eeb627ebfa56f69db77e2fcca09b9
[ "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
6,260
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Sums of finite geometric series -/ import algebra.big_operators algebra.commute universe u variable {α : Type u} open finset /-- Sum of the finite geometric series $∑_{i=0}^{n-1} x^i$. -/ def geom_series [semiring α] (x : α) (n : ℕ) := (range n).sum (λ i, x ^ i) theorem geom_series_def [semiring α] (x : α) (n : ℕ) : geom_series x n = (range n).sum (λ i, x ^ i) := rfl @[simp] theorem geom_series_zero [semiring α] (x : α) : geom_series x 0 = 0 := rfl @[simp] theorem geom_series_one [semiring α] (x : α) : geom_series x 1 = 1 := by { rw [geom_series_def, sum_range_one, pow_zero] } /-- Sum of the finite geometric series $∑_{i=0}^{n-1} x^i y^{n-1-i}$. -/ def geom_series₂ [semiring α] (x y : α) (n : ℕ) := (range n).sum (λ i, x ^ i * (y ^ (n - 1 - i))) theorem geom_series₂_def [semiring α] (x y : α) (n : ℕ) : geom_series₂ x y n = (range n).sum (λ i, x ^ i * y ^ (n - 1 - i)) := rfl @[simp] theorem geom_series₂_zero [semiring α] (x y : α) : geom_series₂ x y 0 = 0 := rfl @[simp] theorem geom_series₂_one [semiring α] (x y : α) : geom_series₂ x y 1 = 1 := by { have : 1 - 1 - 0 = 0 := rfl, rw [geom_series₂_def, sum_range_one, this, pow_zero, pow_zero, mul_one] } @[simp] theorem geom_series₂_with_one [semiring α] (x : α) (n : ℕ) : geom_series₂ x 1 n = geom_series x n := sum_congr rfl (λ i _, by { rw [one_pow, mul_one] }) /-- $x^n-y^n=(x-y)∑x^ky^{n-1-k}$ reformulated without `-` signs. -/ protected theorem commute.geom_sum₂_mul_add [semiring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_series₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := begin let f := λ (m i : ℕ), (x + y) ^ i * y ^ (m - 1 - i), change ((range n).sum (f n)) * x + y ^ n = (x + y) ^ n, induction n with n ih, { rw [range_zero, sum_empty, zero_mul, zero_add, pow_zero, pow_zero] }, { have f_last : f n.succ n = (x + y) ^ n := by { dsimp [f], rw [nat.sub_sub, nat.add_comm, nat.sub_self, pow_zero, mul_one] }, have f_succ : ∀ i, i ∈ range n → f n.succ i = y * f n i := λ i hi, by { dsimp [f], have : commute y ((x + y) ^ i) := (h.symm.add_right (commute.refl y)).pow_right i, rw [← mul_assoc, this.eq, mul_assoc, ← pow_succ y (n - 1 - i)], congr' 2, rw [nat.succ_eq_add_one, nat.add_sub_cancel, nat.sub_sub, add_comm 1 i], have := nat.add_sub_of_le (mem_range.mp hi), rw [add_comm, nat.succ_eq_add_one] at this, rw [← this, nat.add_sub_cancel, add_comm i 1, ← add_assoc, nat.add_sub_cancel] }, rw [pow_succ (x + y), add_mul, sum_range_succ, f_last, add_mul, add_assoc], rw [(((commute.refl x).add_right h).pow_right n).eq], congr' 1, rw[sum_congr rfl f_succ, ← mul_sum, pow_succ y], rw[mul_assoc, ← mul_add y, ih] } end /-- $x^n-y^n=(x-y)∑x^ky^{n-1-k}$ reformulated without `-` signs. -/ theorem geom_sum₂_mul_add [comm_semiring α] (x y : α) (n : ℕ) : (geom_series₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := (commute.all x y).geom_sum₂_mul_add n theorem geom_sum_mul_add [semiring α] (x : α) (n : ℕ) : (geom_series (x + 1) n) * x + 1 = (x + 1) ^ n := begin have := (commute.one_right x).geom_sum₂_mul_add n, rw [one_pow, geom_series₂_with_one] at this, exact this end theorem geom_sum₂_mul_comm [ring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_series₂ x y n) * (x - y) = x ^ n - y ^ n := begin have := (h.sub_left (commute.refl y)).geom_sum₂_mul_add n, rw [sub_add_cancel] at this, rw [← this, add_sub_cancel] end theorem geom_sum₂_mul [comm_ring α] (x y : α) (n : ℕ) : (geom_series₂ x y n) * (x - y) = x ^ n - y ^ n := geom_sum₂_mul_comm (commute.all x y) n theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : (geom_series x n) * (x - 1) = x ^ n - 1 := begin have := geom_sum₂_mul_comm (commute.one_right x) n, rw [one_pow, geom_series₂_with_one] at this, exact this end theorem geom_sum_mul_neg [ring α] (x : α) (n : ℕ) : (geom_series x n) * (1 - x) = 1 - x ^ n := begin have := congr_arg has_neg.neg (geom_sum_mul x n), rw [neg_sub, ← mul_neg_eq_neg_mul_symm, neg_sub] at this, exact this end theorem geom_sum [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (geom_series x n) = (x ^ n - 1) / (x - 1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] theorem geom_sum_Ico_mul [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : ((finset.Ico m n).sum (pow x)) * (x - 1) = x^n - x^m := by rw [sum_Ico_eq_sub _ hmn, ← geom_series_def, ← geom_series_def, sub_mul, geom_sum_mul, geom_sum_mul, sub_sub_sub_cancel_right] theorem geom_sum_Ico_mul_neg [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : ((finset.Ico m n).sum (pow x)) * (1 - x) = x^m - x^n := by rw [sum_Ico_eq_sub _ hmn, ← geom_series_def, ← geom_series_def, sub_mul, geom_sum_mul_neg, geom_sum_mul_neg, sub_sub_sub_cancel_left] theorem geom_sum_Ico [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : (finset.Ico m n).sum (λ i, x ^ i) = (x ^ n - x ^ m) / (x - 1) := by simp only [sum_Ico_eq_sub _ hmn, (geom_series_def _ _).symm, geom_sum hx, div_sub_div_same, sub_sub_sub_cancel_right] lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (geom_series x⁻¹ n) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * (x ^ n)⁻¹ = (x ^ n)⁻¹ * x := nat.rec_on n (by simp) (λ n h, by rw [pow_succ, mul_inv', ←mul_assoc, h, mul_assoc, mul_inv_cancel hx0, mul_assoc, inv_mul_cancel hx0]), begin rw [geom_sum h₁, div_eq_iff_mul_eq h₂, ← domain.mul_left_inj h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃], simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄, sub_eq_add_neg, add_comm, add_left_comm], end
a5c5ec236e98e7ac0d2b53dabadeadc942398a69
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/tactic/lint.lean
f45eca9c1a2a2228f6d2d5f192cc6e27758f3588
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
22,638
lean
/- Copyright (c) 2019 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 -/ import tactic.core /-! # lint command This file defines the following 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. `illegal_constant` 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. Another linter, `doc_blame_thm`, checks for missing doc strings on lemmas and theorems. This is not run by default. 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 of passing checks. A silent lint will fail if any test fails. 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]` to a declaration omits it from all linter checks. ## Tags sanity check, lint, cleanup, command, tactic -/ universe variable u open expr tactic native reserve notation `#lint` reserve notation `#lint_mathlib` reserve notation `#lint_all` reserve notation `#list_linters` run_cmd tactic.skip -- apparently doc strings can't come directly after `reserve notation` /-- Defines the user attribute `nolint` for skipping `#lint` -/ @[user_attribute] meta def nolint_attr : user_attribute := { name := "nolint", descr := "Do not report this declaration in any of the tests of `#lint`" } attribute [nolint] imp_intro classical.dec classical.dec_pred classical.dec_rel classical.dec_eq /-- A linting test for the `#lint` command. `test` defines a test to perform on every declaration. It should never fail. Returning `none` signifies a passing test. Returning `some msg` reports a failing test with error `msg`. `no_errors_found` is the message printed when all tests are negative, and `errors_found` is printed when at least one test is positive. If `is_fast` is false, this test will be omitted from `#lint-`. -/ meta structure linter := (test : declaration → tactic (option string)) (no_errors_found : string) (errors_found : string) (is_fast : bool := tt) /-- Takes a list of names that resolve to declarations of type `linter`, and produces a list of linters. -/ meta def get_linters (l : list name) : tactic (list linter) := l.mmap (λ n, mk_const n >>= eval_expr linter <|> fail format!"invalid linter: {n}") /-- Defines the user attribute `linter` for adding a linter to the default set. Linters should be defined in the `linter` namespace. A linter `linter.my_new_linter` is referred to as `my_new_linter` (without the `linter` namespace) when used in `#lint`. -/ @[user_attribute] meta def linter_attr : user_attribute unit unit := { name := "linter", descr := "Use this declaration as a linting test in #lint", after_set := some $ λ nm _ _, mk_const nm >>= infer_type >>= unify `(linter) } setup_tactic_parser universe variable v /-- Find all declarations in `l` where tac returns `some x` and list them. -/ meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (declaration × α)) := l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d /-- Find all declarations in `l` where tac returns `some x` and sort the resulting list by file name. -/ meta def fold_over_with_cond_sorted {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (string × list (declaration × α))) := do e ← get_env, ds ← fold_over_with_cond l tac, let ds₂ := rb_lmap.of_list (ds.map (λ x, ((e.decl_olean x.1.to_name).iget, x))), return $ ds₂.to_list /-- Make the output of `fold_over_with_cond` printable, in the following form: `#print <name> <open multiline comment> <elt of α> <close multiline comment>` -/ meta def print_decls {α} [has_to_format α] (ds : list (declaration × α)) : format := ds.foldl (λ f x, f ++ "\n" ++ to_fmt "#print " ++ to_fmt x.1.to_name ++ " /- " ++ to_fmt x.2 ++ " -/") format.nil /-- Make the output of `fold_over_with_cond_sorted` printable, with the file path + name inserted.-/ meta def print_decls_sorted {α} [has_to_format α] (ds : list (string × list (declaration × α))) : format := ds.foldl (λ f x, f ++ "\n\n" ++ to_fmt "-- " ++ to_fmt x.1 ++ print_decls x.2) format.nil /-- Same as `print_decls_sorted`, but removing the first `n` characters from the string. Useful for omitting the mathlib directory from the output. -/ meta def print_decls_sorted_mathlib {α} [has_to_format α] (n : ℕ) (ds : list (string × list (declaration × α))) : format := ds.foldl (λ f x, f ++ "\n\n" ++ to_fmt "-- " ++ to_fmt (x.1.popn n) ++ print_decls x.2) format.nil /-- Auxilliary definition for `check_unused_arguments` -/ meta def check_unused_arguments_aux : list ℕ → ℕ → ℕ → expr → list ℕ | l n n_max e := if n > n_max then l else if ¬ is_lambda e ∧ ¬ is_pi e then l else let b := e.binding_body in let l' := if b.has_var_idx 0 then l else n :: l in check_unused_arguments_aux l' (n+1) n_max b /-- Check which arguments of a declaration are not used. Prints a list of natural numbers corresponding to which arguments are not used (e.g. this outputs [1, 4] if the first and fourth arguments are unused). Checks both the type and the value of `d` for whether the argument is used (in rare cases an argument is used in the type but not in the value). We return [] if the declaration was automatically generated. We print arguments that are larger than the arity of the type of the declaration (without unfolding definitions). -/ meta def check_unused_arguments (d : declaration) : option (list ℕ) := let l := check_unused_arguments_aux [] 1 d.type.pi_arity d.value in if l = [] then none else let l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type in (l.filter $ λ n, n ∈ l2).reverse /-- Check for unused arguments, and print them with their position, variable name, type and whether the argument is a duplicate. See also `check_unused_arguments`. This tactic additionally filters out all unused arguments of type `parse _` -/ meta def unused_arguments (d : declaration) : tactic (option string) := do let ns := check_unused_arguments d, if ¬ ns.is_some then return none else do let ns := ns.iget, (ds, _) ← get_pi_binders d.type, let ns := ns.map (λ n, (n, (ds.nth $ n - 1).iget)), let ns := ns.filter (λ x, x.2.type.get_app_fn ≠ const `interactive.parse []), if ns = [] then return none else do ds' ← ds.mmap pp, ns ← ns.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt n ++ ": " ++ s ++ (if ds.countp (λ b', b.type = b'.type) ≥ 2 then " (duplicate)" else "")) <$> pp b), return $ some $ ns.to_string_aux tt /-- A linter object for checking for unused arguments. This is in the default linter set. -/ @[linter, priority 1500] meta def linter.unused_arguments : linter := { test := unused_arguments, no_errors_found := "No unused arguments", errors_found := "UNUSED ARGUMENTS" } /-- Checks whether the correct declaration constructor (definition or theorem) by comparing it to its sort. Instances will not be printed. -/ /- This test is not very quick: maybe we can speed-up testing that something is a proposition? This takes almost all of the execution time. -/ meta def incorrect_def_lemma (d : declaration) : tactic (option string) := if d.is_constant ∨ d.is_axiom then return none else do is_instance_d ← is_instance d.to_name, if is_instance_d then return none else do -- the following seems to be a little quicker than `is_prop d.type`. expr.sort n ← infer_type d.type, return $ if d.is_theorem ↔ n = level.zero then none else if (d.is_definition : bool) then "is a def, should be a lemma/theorem" else "is a lemma/theorem, should be a def" /-- A linter for checking whether the correct declaration constructor (definition or theorem) has been used. -/ @[linter, priority 1490] meta def linter.def_lemma : linter := { test := incorrect_def_lemma, no_errors_found := "All declarations correctly marked as def/lemma", errors_found := "INCORRECT DEF/LEMMA" } /-- Checks whether a declaration has a namespace twice consecutively in its name -/ meta def dup_namespace (d : declaration) : tactic (option string) := is_instance d.to_name >>= λ is_inst, return $ let nm := d.to_name.components in if nm.chain' (≠) ∨ is_inst then none else let s := (nm.find $ λ n, nm.count n ≥ 2).iget.to_string in some $ "The namespace `" ++ s ++ "` is duplicated in the name" /-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/ @[linter, priority 1480] meta def linter.dup_namespace : linter := { test := dup_namespace, no_errors_found := "No declarations have a duplicate namespace", errors_found := "DUPLICATED NAMESPACES IN NAME" } /-- Checks whether a `>`/`≥` is used in the statement of `d`. -/ -- TODO: the commented out code also checks for classicality in statements, but needs fixing -- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _ -- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) := -- return $ if d.type.contains_constant (λ n, (n.get_prefix = `classical ∧ -- n.last ∈ ["prop_decidable", "dec", "dec_rel", "dec_eq"]) ∨ n ∈ [`gt, `ge]) -- then -- let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel, `classical.dec_eq], -- illegal2 := [`gt, `ge], -- occur1 := illegal1.filter (λ n, d.type.contains_constant (eq n)), -- occur2 := illegal2.filter (λ n, d.type.contains_constant (eq n)) in -- some $ sformat!"the type contains the following declarations: {occur1 ++ occur2}." ++ -- (if occur1 = [] then "" else " Add decidability type-class arguments instead.") ++ -- (if occur2 = [] then "" else " Use ≤/< instead.") -- else none meta def illegal_constants_in_statement (d : declaration) : tactic (option string) := return $ let illegal := [`gt, `ge] in if d.type.contains_constant (λ n, n ∈ illegal) then some "the type contains ≥/>. Use ≤/< instead." else none /-- A linter for checking whether illegal constants (≥, >) appear in a declaration's type. -/ @[linter, priority 1470] meta def linter.illegal_constants : linter := { test := illegal_constants_in_statement, no_errors_found := "No illegal constants in declarations", errors_found := "ILLEGAL CONSTANTS IN DECLARATIONS", is_fast := ff } /-- checks whether an instance that always applies has priority ≥ 1000. -/ meta def instance_priority (d : declaration) : tactic (option string) := do let nm := d.to_name, b ← is_instance nm, /- return `none` if `d` is not an instance -/ if ¬ b then return none else do prio ← has_attribute `instance nm, /- return `none` if `d` is has low priority -/ if prio < 1000 then return none else do let (fn, args) := d.type.pi_codomain.get_app_fn_args, cls ← get_decl fn.const_name, let (pi_args, _) := cls.type.pi_binders, guard (args.length = pi_args.length), /- List all the arguments of the class that block type-class inference from firing (if they are metavariables). These are all the arguments except instance-arguments and out-params. -/ let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩, if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param then none else some e, let always_applies := relevant_args.all expr.is_var ∧ relevant_args.nodup, if always_applies then return $ some "" else return none /-- A linter object for checking instance priorities of instances that always apply. This is in the default linter set. -/ @[linter, priority 1460] meta def linter.instance_priority : linter := { test := instance_priority, no_errors_found := "All instance priorities are good", errors_found := "DANGEROUS INSTANCE PRIORITIES.\n The following instances always apply, and therefore should have a priority < 1000" } /-- Reports definitions and constants that are missing doc strings -/ meta def doc_blame_report_defn : declaration → tactic (option string) | (declaration.defn n _ _ _ _ _) := doc_string n >> return none <|> return "def missing doc string" | (declaration.cnst n _ _ _) := doc_string n >> return none <|> return "constant missing doc string" | _ := return none /-- Reports definitions and constants that are missing doc strings -/ meta def doc_blame_report_thm : declaration → tactic (option string) | (declaration.thm n _ _ _) := doc_string n >> return none <|> return "theorem missing doc string" | _ := return none /-- A linter for checking definition doc strings -/ @[linter, priority 1450] meta def linter.doc_blame : linter := { test := λ d, mcond (bnot <$> has_attribute' `instance d.to_name) (doc_blame_report_defn d) (return none), no_errors_found := "No definitions are missing documentation.", errors_found := "DEFINITIONS ARE MISSING DOCUMENTATION STRINGS" } /-- A linter for checking theorem doc strings. This is not in the default linter set. -/ meta def linter.doc_blame_thm : linter := { test := doc_blame_report_thm, no_errors_found := "No theorems are missing documentation.", errors_found := "THEOREMS ARE MISSING DOCUMENTATION STRINGS", is_fast := ff } /-- `get_checks slow extra use_only` produces a list of linters. `extras` is a list of names that should resolve to declarations with type `linter`. If `use_only` is true, it only uses the linters in `extra`. Otherwise, it uses all linters in the environment tagged with `@[linter]`. If `slow` is false, it only uses the fast default tests. -/ meta def get_checks (slow : bool) (extra : list name) (use_only : bool) : tactic (list linter) := do default ← if use_only then return [] else attribute.get_instances `linter >>= get_linters, let default := if slow then default else default.filter (λ l, l.is_fast), list.append default <$> get_linters extra /-- If `verbose` is true, return `old ++ new`, else return `old`. -/ private meta def append_when (verbose : bool) (old new : format) : format := cond verbose (old ++ new) old private meta def check_fold (printer : (declaration → tactic (option string)) → tactic (name_set × format)) (verbose : bool) : name_set × format → linter → tactic (name_set × format) | (ns, s) ⟨tac, ok_string, warning_string, _⟩ := do (new_ns, f) ← printer tac, if f.is_nil then return $ (ns, append_when verbose s format!"/- OK: {ok_string}. -/\n") else return $ (ns.union new_ns, s ++ format!"/- {warning_string}: -/" ++ f ++ "\n\n") /-- The common denominator of `#lint[|mathlib|all]`. The different commands have different configurations for `l`, `printer` and `where_desc`. If `slow` is false, doesn't do the checks that take a lot of time. If `verbose` is false, it will suppress messages from passing checks. By setting `checks` you can customize which checks are performed. Returns a `name_set` containing the names of all declarations that fail any check in `check`, and a `format` object describing the failures. -/ meta def lint_aux (l : list declaration) (printer : (declaration → tactic (option string)) → tactic (name_set × format)) (where_desc : string) (slow verbose : bool) (checks : list linter) : tactic (name_set × format) := do let s : format := append_when verbose format.nil "/- Note: This command is still in development. -/\n", let s := append_when verbose s format!"/- Checking {l.length} declarations {where_desc} -/\n\n", (ns, s) ← checks.mfoldl (check_fold printer verbose) (mk_name_set, s), return $ (ns, if slow then s else append_when verbose s "/- (slow tests skipped) -/\n") /-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/ meta def lint (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, l ← e.mfilter (λ d, if e.in_current_file' d.to_name ∧ ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e then bnot <$> has_attribute' `nolint d.to_name else return ff), lint_aux l (λ t, do lst ← fold_over_with_cond l t, return (name_set.of_list (lst.map (declaration.to_name ∘ prod.fst)), print_decls lst)) "in the current file" slow verbose checks private meta def name_list_of_decl_lists (l : list (string × list (declaration × string))) : name_set := name_set.of_list $ list.join $ l.map $ λ ⟨_, l'⟩, l'.map $ declaration.to_name ∘ prod.fst /-- Return the message printed by `#lint_mathlib` and a `name_set` containing all declarations that fail. -/ meta def lint_mathlib (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, ml ← get_mathlib_dir, /- note: we don't separate out some of these tests in `lint_aux` because that causes a performance hit. That is also the reason for the current formulation using if then else. -/ l ← e.mfilter (λ d, if e.is_prefix_of_file ml d.to_name ∧ ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e then bnot <$> has_attribute' `nolint d.to_name else return ff), let ml' := ml.length, lint_aux l (λ t, do lst ← fold_over_with_cond_sorted l t, return (name_list_of_decl_lists lst, print_decls_sorted_mathlib ml' lst)) "in mathlib (only in imported files)" slow verbose checks /-- Return the message printed by `#lint_all` and a `name_set` containing all declarations that fail. -/ meta def lint_all (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, l ← e.mfilter (λ d, if ¬ d.to_name.is_internal ∧ ¬ d.is_auto_generated e then bnot <$> has_attribute' `nolint d.to_name else return ff), lint_aux l (λ t, do lst ← fold_over_with_cond_sorted l t, return (name_list_of_decl_lists lst, print_decls_sorted lst)) "in all imported files (including this one)" slow verbose checks /-- Parses an optional `only`, followed by a sequence of zero or more identifiers. Prepends `linter.` to each of these identifiers. -/ private meta def parse_lint_additions : parser (bool × list name) := prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident_*) /-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/ private meta def lint_cmd_aux (scope : bool → bool → list name → bool → tactic (name_set × format)) : parser unit := do silent ← optional (tk "-"), fast_only ← optional (tk "*"), silent ← if silent.is_some then return silent else optional (tk "-"), -- allow either order of *- (use_only, extra) ← parse_lint_additions, (_, s) ← scope fast_only.is_none silent.is_none extra use_only, when (¬ s.is_nil) $ do trace s, when silent.is_some $ fail "Linting did not succeed" /-- The command `#lint` at the bottom of a file will warn you about some common mistakes in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`. `#lint-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit := lint_cmd_aux @lint /-- The command `#lint_mathlib` checks all of mathlib for certain mistakes. Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`. `#lint_mathlib-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit := lint_cmd_aux @lint_mathlib /-- The command `#lint_all` checks all imported files for certain mistakes. Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`. `#lint_all-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit := lint_cmd_aux @lint_all /-- The command `#list_linters` prints a list of all available linters. -/ @[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit := do env ← get_env, let ns := env.decl_filter_map $ λ dcl, if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none, trace "Available linters:\n linters marked with (*) are in the default lint set\n", ns.mmap' $ λ n, do b ← has_attribute' `linter n, trace $ n.pop_prefix.to_string ++ if b then " (*)" else "" /-- Use `lint` as a hole command. Note: In a large file, there might be some delay between choosing the option and the information appearing -/ @[hole_command] meta def lint_hole_cmd : hole_command := { name := "Lint", descr := "Lint: Find common mistakes in current file.", action := λ es, do (_, s) ← lint, return [(s.to_string,"")] }
3c735b98fab2ab6a506c6e9602decad6bd86b62c
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/algebra/ring.lean
62546e8ad3cc629bed96d78ac63147749ed8d5c6
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
22,062
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston -/ import algebra.group /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines homomorphisms of semirings and rings, both unbundled (e.g. `is_semiring_hom f`) and bundled (e.g. `ring_hom a β`, a.k.a. `α →+* β`). The unbundled ones are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions is_semiring_hom (deprecated), is_ring_hom (deprecated), ring_hom, nonzero_comm_semiring, nonzero_comm_ring, domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. ## Tags is_ring_hom, is_semiring_hom, ring_hom, semiring_hom, semiring, comm_semiring, ring, comm_ring, domain, integral_domain, nonzero_comm_semiring, nonzero_comm_ring, units -/ universes u v variable {α : Type u} section variable [semiring α] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm variable (α) /-- Either zero and one are nonequal in a semiring, or the semiring is the zero ring. -/ lemma zero_ne_one_or_forall_eq_0 : (0 : α) ≠ 1 ∨ (∀a:α, a = 0) := by haveI := classical.dec; refine not_or_of_imp (λ h a, _); simpa using congr_arg ((*) a) h.symm /-- If zero equals one in a semiring, the semiring is the zero ring. -/ lemma eq_zero_of_zero_eq_one (h : (0 : α) = 1) : (∀a:α, a = 0) := (zero_ne_one_or_forall_eq_0 α).neg_resolve_left h /-- If zero equals one in a semiring, all elements of that semiring are equal. -/ theorem subsingleton_of_zero_eq_one (h : (0 : α) = 1) : subsingleton α := ⟨λa b, by rw [eq_zero_of_zero_eq_one α h a, eq_zero_of_zero_eq_one α h b]⟩ end namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units instance [semiring α] : semiring (with_zero α) := { left_distrib := λ a b c, begin cases a with a, {refl}, cases b with b; cases c with c; try {refl}, exact congr_arg some (left_distrib _ _ _) end, right_distrib := λ a b c, begin cases c with c, { change (a + b) * 0 = a * 0 + b * 0, simp }, cases a with a; cases b with b; try {refl}, exact congr_arg some (right_distrib _ _ _) end, ..with_zero.add_comm_monoid, ..with_zero.mul_zero_class, ..with_zero.monoid } attribute [refl] dvd_refl attribute [trans] dvd.trans /-- Predicate for semiring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/ class is_semiring_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) : Prop := (map_zero : f 0 = 0) (map_one : f 1 = 1) (map_add : ∀ {x y}, f (x + y) = f x + f y) (map_mul : ∀ {x y}, f (x * y) = f x * f y) namespace is_semiring_hom variables {β : Type v} [semiring α] [semiring β] variables (f : α → β) [is_semiring_hom f] {x y : α} /-- The identity map is a semiring homomorphism. -/ instance id : is_semiring_hom (@id α) := by refine {..}; intros; refl /-- The composition of two semiring homomorphisms is a semiring homomorphism. -/ instance comp {γ} [semiring γ] (g : β → γ) [is_semiring_hom g] : is_semiring_hom (g ∘ f) := { map_zero := by simp [map_zero f]; exact map_zero g, map_one := by simp [map_one f]; exact map_one g, map_add := λ x y, by simp [map_add f]; rw map_add g; refl, map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl } /-- A semiring homomorphism is an additive monoid homomorphism. -/ instance : is_add_monoid_hom f := { ..‹is_semiring_hom f› } /-- A semiring homomorphism is a monoid homomorphism. -/ instance : is_monoid_hom f := { ..‹is_semiring_hom f› } end is_semiring_hom section variables [ring α] (a b c d e : α) /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin simp [h] end) (λ h, begin simp [h.symm] end) ... ↔ (a - b) * e + c = d : begin simp [@sub_eq_add_neg α, @right_distrib α] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [@sub_eq_add_neg α, @right_distrib α] end ... = d : begin rw h, simp [@add_sub_cancel α] end /-- If the product of two elements of a ring is nonzero, both elements are nonzero. -/ theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : α} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := begin split, { intro ha, apply h, simp [ha] }, { intro hb, apply h, simp [hb] } end end /-- Given an element a of a commutative semiring, there exists another element whose product with zero equals a iff a equals zero. -/ @[simp] lemma zero_dvd_iff [comm_semiring α] {a : α} : 0 ∣ a ↔ a = 0 := ⟨eq_zero_of_zero_dvd, λ h, by rw h⟩ section comm_ring variable [comm_ring α] /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left {a b c : α} (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right {a b c : α} (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = b * x - x * x, { apply eq_of_sub_eq_zero, simpa using h }, use b - x, simp [left_distrib, mul_comm, this], end end comm_ring /-- Predicate for ring homomorphisms (deprecated -- use the bundled `ring_hom` version). -/ class is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) : Prop := (map_one : f 1 = 1) (map_mul : ∀ {x y}, f (x * y) = f x * f y) (map_add : ∀ {x y}, f (x + y) = f x + f y) namespace is_ring_hom variables {β : Type v} [ring α] [ring β] /-- A map of rings that is a semiring homomorphism is also a ring homomorphism. -/ def of_semiring (f : α → β) [H : is_semiring_hom f] : is_ring_hom f := {..H} variables (f : α → β) [is_ring_hom f] {x y : α} /-- Ring homomorphisms map zero to zero. -/ lemma map_zero : f 0 = 0 := calc f 0 = f (0 + 0) - f 0 : by rw [map_add f]; simp ... = 0 : by simp /-- Ring homomorphisms preserve additive inverses. -/ lemma map_neg : f (-x) = -f x := calc f (-x) = f (-x + x) - f x : by rw [map_add f]; simp ... = -f x : by simp [map_zero f] /-- Ring homomorphisms preserve subtraction. -/ lemma map_sub : f (x - y) = f x - f y := by simp [map_add f, map_neg f] /-- The identity map is a ring homomorphism. -/ instance id : is_ring_hom (@id α) := by refine {..}; intros; refl /-- The composition of two ring homomorphisms is a ring homomorphism. -/ instance comp {γ} [ring γ] (g : β → γ) [is_ring_hom g] : is_ring_hom (g ∘ f) := { map_add := λ x y, by simp [map_add f]; rw map_add g; refl, map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl, map_one := by simp [map_one f]; exact map_one g } /-- A ring homomorphism is also a semiring homomorphism. -/ instance : is_semiring_hom f := { map_zero := map_zero f, ..‹is_ring_hom f› } instance : is_add_group_hom f := { } end is_ring_hom set_option old_structure_cmd true /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. -/ structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β infixr ` →+* `:25 := ring_hom instance {α : Type*} {β : Type*} [semiring α] [semiring β] : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ namespace ring_hom variables {β : Type v} [semiring α] [semiring β] variables (f : α →+* β) {x y : α} @[extensionality] theorem ext (f g : α →+* β) (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b instance {α : Type*} {β : Type*} [semiring α] [semiring β] (f : α →+* β) : is_semiring_hom f := { map_zero := f.map_zero, map_one := f.map_one, map_add := f.map_add, map_mul := f.map_mul } instance {α γ} [ring α] [ring γ] {g : α →+* γ} : is_ring_hom g := is_ring_hom.of_semiring g /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp {γ} [semiring γ] (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := eq_neg_of_add_eq_zero $ by rw [←f.map_add, neg_add_self, f.map_zero] /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := by simp /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, map_zero' := add_self_iff_eq_zero.1 $ by rw [←map_add, add_zero], map_one' := f.map_one, map_mul' := f.map_mul, map_add' := map_add } end ring_hom /-- Predicate for commutative semirings in which zero does not equal one. -/ class nonzero_comm_semiring (α : Type*) extends comm_semiring α, zero_ne_one_class α /-- Predicate for commutative rings in which zero does not equal one. -/ class nonzero_comm_ring (α : Type*) extends comm_ring α, zero_ne_one_class α /-- A nonzero commutative ring is a nonzero commutative semiring. -/ instance nonzero_comm_ring.to_nonzero_comm_semiring {α : Type*} [I : nonzero_comm_ring α] : nonzero_comm_semiring α := { zero_ne_one := by convert zero_ne_one, ..show comm_semiring α, by apply_instance } /-- An integral domain is a nonzero commutative ring. -/ instance integral_domain.to_nonzero_comm_ring (α : Type*) [id : integral_domain α] : nonzero_comm_ring α := { ..id } /-- An element of the unit group of a nonzero commutative semiring represented as an element of the semiring is nonzero. -/ lemma units.coe_ne_zero [nonzero_comm_semiring α] (u : units α) : (u : α) ≠ 0 := λ h : u.1 = 0, by simpa [h, zero_ne_one] using u.3 /-- Makes a nonzero commutative ring from a commutative ring containing at least two distinct elements. -/ def nonzero_comm_ring.of_ne [comm_ring α] {x y : α} (h : x ≠ y) : nonzero_comm_ring α := { one := 1, zero := 0, zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul], ..show comm_ring α, by apply_instance } /-- Makes a nonzero commutative semiring from a commutative semiring containing at least two distinct elements. -/ def nonzero_comm_semiring.of_ne [comm_semiring α] {x y : α} (h : x ≠ y) : nonzero_comm_semiring α := { one := 1, zero := 0, zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul], ..show comm_semiring α, by apply_instance } /-- this is needed for compatibility between Lean 3.4.2 and Lean 3.5.0c -/ def has_div_of_division_ring [division_ring α] : has_div α := division_ring_has_div /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ class domain (α : Type u) extends ring α, no_zero_divisors α, zero_ne_one_class α section domain variable [domain α] /-- Simplification theorems for the definition of a domain. -/ @[simp] theorem mul_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩ @[simp] theorem zero_eq_mul {a b : α} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, mul_eq_zero] lemma mul_self_eq_zero {α} [domain α] {x : α} : x * x = 0 ↔ x = 0 := by simp lemma zero_eq_mul_self {α} [domain α] {x : α} : 0 = x * x ↔ x = 0 := by simp /-- The product of two nonzero elements of a domain is nonzero. -/ theorem mul_ne_zero' {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) h₁ h₂ /-- Right multiplication by a nonzero element in a domain is injective. -/ theorem domain.mul_right_inj {a b c : α} (ha : a ≠ 0) : b * a = c * a ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_right_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero /-- Left multiplication by a nonzero element in a domain is injective. -/ theorem domain.mul_left_inj {a b c : α} (ha : a ≠ 0) : a * b = a * c ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_left_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero /-- An element of a domain fixed by right multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_right' {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_right (sub_ne_zero.2 h₁); rw [mul_sub_left_distrib, mul_one, sub_eq_zero, h₂] /-- An element of a domain fixed by left multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_left' {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_left (sub_ne_zero.2 h₁); rw [mul_sub_right_distrib, one_mul, sub_eq_zero, h₂] /-- For elements a, b of a domain, if a*b is nonzero, so is b*a. -/ theorem mul_ne_zero_comm' {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 := mul_ne_zero' (ne_zero_of_mul_ne_zero_left h) (ne_zero_of_mul_ne_zero_right h) end domain /- integral domains -/ section variables [s : integral_domain α] (a b c d e : α) include s /-- An integral domain is a domain. -/ instance integral_domain.to_domain : domain α := {..s} /-- Right multiplcation by a nonzero element of an integral domain is injective. -/ theorem eq_of_mul_eq_mul_right_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, by simp [h], have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this /-- Left multiplication by a nonzero element of an integral domain is injective. -/ theorem eq_of_mul_eq_mul_left_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, by simp [h], have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this /-- Given two elements b, c of an integral domain and a nonzero element a, a*b divides a*c iff b divides c. -/ theorem mul_dvd_mul_iff_left {a b c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, domain.mul_left_inj ha] /-- Given two elements a, b of an integral domain and a nonzero element c, a*c divides b*c iff a divides b. -/ theorem mul_dvd_mul_iff_right {a b c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, domain.mul_right_inj hc] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by conv {to_lhs, rw [inv_eq_iff_mul_eq_one, ← mul_one (1 : units α), units.ext_iff, units.coe_mul, units.coe_mul, mul_self_eq_mul_self_iff, ← units.ext_iff, ← units.coe_neg, ← units.ext_iff] } end /- units in various rings -/ namespace units section comm_semiring variables [comm_semiring α] (a b : α) (u : units α) /-- Elements of the unit group of a commutative semiring represented as elements of the semiring divide any element of the semiring. -/ @[simp] lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩ /-- In a commutative semiring, an element a divides an element b iff a divides all associates of b. -/ @[simp] lemma dvd_coe_mul : a ∣ b * u ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩) (assume ⟨c, eq⟩, eq.symm ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) /-- An element of a commutative semiring divides a unit iff the element divides one. -/ @[simp] lemma dvd_coe : a ∣ ↑u ↔ a ∣ 1 := suffices a ∣ 1 * ↑u ↔ a ∣ 1, by simpa, dvd_coe_mul _ _ _ /-- In a commutative semiring, an element a divides an element b iff all associates of a divide b.-/ @[simp] lemma coe_mul_dvd : a * u ∣ b ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u, eq.symm ▸ by ac_refl⟩) (assume h, suffices a * ↑u ∣ b * 1, by simpa, mul_dvd_mul h (coe_dvd _ _)) end comm_semiring section domain variables [domain α] /-- Every unit in a domain is nonzero. -/ @[simp] theorem ne_zero : ∀(u : units α), (↑u : α) ≠ 0 | ⟨u, v, (huv : 0 * v = 1), hvu⟩ rfl := by simpa using huv end domain end units
70077ce60f5797ca2c272f4d7cf985cc971b97e3
626e312b5c1cb2d88fca108f5933076012633192
/src/group_theory/subgroup.lean
524149b495fa9300349ddfd949f1432a1fa95b5c
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
92,258
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid import group_theory.submonoid.center import algebra.group.conj import algebra.pointwise import order.atoms /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are `group`s - `A` is an `add_group` - `H K` are `subgroup`s of `G` or `add_subgroup`s of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `subgroup.closure k` : the minimal subgroup that includes the set `k` * `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set * `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` * `is_simple_group G` : a class indicating that a group has exactly two normal subgroups ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ open_locale big_operators pointwise variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid namespace subgroup @[to_additive] instance : set_like (subgroup G) G := ⟨subgroup.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp, to_additive] lemma mem_carrier {s : subgroup G} {x : G} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- See Note [custom simps projection] -/ @[to_additive "See Note [custom simps projection]"] def simps.coe (S : subgroup G) : set G := S initialize_simps_projections subgroup (carrier → coe) initialize_simps_projections add_subgroup (carrier → coe) @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[simp, to_additive] lemma mem_to_submonoid (K : subgroup G) (x : G) : x ∈ K.to_submonoid ↔ x ∈ K := iff.rfl @[to_additive] instance (K : subgroup G) [d : decidable_pred (∈ K)] [fintype G] : fintype K := show fintype {g : G // g ∈ K}, from infer_instance @[to_additive] theorem to_submonoid_injective : function.injective (to_submonoid : subgroup G → submonoid G) := λ p q h, set_like.ext'_iff.2 (show _, from set_like.ext'_iff.1 h) @[simp, to_additive] theorem to_submonoid_eq {p q : subgroup G} : p.to_submonoid = q.to_submonoid ↔ p = q := to_submonoid_injective.eq_iff @[mono, to_additive] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subgroup G → submonoid G) := λ _ _, id @[mono, to_additive] lemma to_submonoid_mono : monotone (to_submonoid : subgroup G → submonoid G) := to_submonoid_strict_mono.monotone @[simp, to_additive] lemma to_submonoid_le {p q : subgroup G} : p.to_submonoid ≤ q.to_submonoid ↔ p ≤ q := iff.rfl end subgroup /-! ### Conversion to/from `additive`/`multiplicative` -/ section mul_add /-- Supgroups of a group `G` are isomorphic to additive subgroups of `additive G`. -/ @[simps] def subgroup.to_add_subgroup : subgroup G ≃o add_subgroup (additive G) := { to_fun := λ S, { neg_mem' := S.inv_mem', ..S.to_submonoid.to_add_submonoid }, inv_fun := λ S, { inv_mem' := S.neg_mem', ..S.to_add_submonoid.to_submonoid' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Additive subgroup of an additive group `additive G` are isomorphic to subgroup of `G`. -/ abbreviation add_subgroup.to_subgroup' : add_subgroup (additive G) ≃o subgroup G := subgroup.to_add_subgroup.symm /-- Additive supgroups of an additive group `A` are isomorphic to subgroups of `multiplicative A`. -/ @[simps] def add_subgroup.to_subgroup : add_subgroup A ≃o subgroup (multiplicative A) := { to_fun := λ S, { inv_mem' := S.neg_mem', ..S.to_add_submonoid.to_submonoid }, inv_fun := λ S, { neg_mem' := S.inv_mem', ..S.to_submonoid.to_add_submonoid' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Subgroups of an additive group `multiplicative A` are isomorphic to additive subgroups of `A`. -/ abbreviation subgroup.to_add_subgroup' : subgroup (multiplicative A) ≃o add_subgroup A := add_subgroup.to_subgroup.symm end mul_add namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := set_like.ext h attribute [ext] add_subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx /-- A subgroup is closed under division. -/ @[to_additive "An `add_subgroup` is closed under subtraction."] theorem div_mem {x y : G} (hx : x ∈ H) (hy : y ∈ H) : x / y ∈ H := by simpa only [div_eq_mul_inv] using H.mul_mem' hx (H.inv_mem' hy) @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩ @[to_additive] lemma div_mem_comm_iff {a b : G} : a / b ∈ H ↔ b / a ∈ H := by rw [← H.inv_mem_iff, div_eq_mul_inv, div_eq_mul_inv, mul_inv_rev, inv_inv] @[simp, to_additive] theorem inv_coe_set : (H : set G)⁻¹ = H := by { ext, simp, } @[simp, to_additive] lemma exists_inv_mem_iff_exists_mem (K : subgroup G) {P : G → Prop} : (∃ (x : G), x ∈ K ∧ P x⁻¹) ↔ ∃ x ∈ K, P x := by split; { rintros ⟨x, x_in, hx⟩, exact ⟨x⁻¹, inv_mem K x_in, by simp [hx]⟩ } @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩ /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : ∏ c in t, f c ∈ K := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (n : ℕ) := by { rw [gpow_coe_nat], exact pow_mem _ hx n } | -[1+ n] := by { rw [gpow_neg_succ_of_nat], exact K.inv_mem (K.pow_mem hx n.succ) } /-- Construct a subgroup from a nonempty set that is closed under division. -/ @[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"] def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G := have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) } /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ /-- A subgroup of a group inherits a division -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a subtraction."] instance has_div : has_div H := ⟨λ a b, ⟨a / b, H.div_mem a.2 b.2⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, norm_cast, to_additive] lemma coe_div (x y : H) : (↑(x / y) : G) = ↑x / ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero add_subgroup.coe_neg add_subgroup.coe_mk /-- A subgroup of a group inherits a group structure. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := subtype.coe_injective.group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := subtype.coe_injective.comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subgroup of an `ordered_comm_group` is an `ordered_comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_ordered_comm_group` is an `add_ordered_comm_group`."] instance to_ordered_comm_group {G : Type*} [ordered_comm_group G] (H : subgroup G) : ordered_comm_group H := subtype.coe_injective.ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- A subgroup of a `linear_ordered_comm_group` is a `linear_ordered_comm_group`. -/ @[to_additive "An `add_subgroup` of a `linear_ordered_add_comm_group` is a `linear_ordered_add_comm_group`."] instance to_linear_ordered_comm_group {G : Type*} [linear_ordered_comm_group G] (H : subgroup G) : linear_ordered_comm_group H := subtype.coe_injective.linear_ordered_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_pow _ _ _ @[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_gpow _ _ _ /-- The inclusion homomorphism from a subgroup `H` contained in `K` to `K`. -/ @[to_additive "The inclusion homomorphism from a additive subgroup `H` contained in `K` to `K`."] def inclusion {H K : subgroup G} (h : H ≤ K) : H →* K := monoid_hom.mk' (λ x, ⟨x, h x.prop⟩) (λ ⟨a, ha⟩ ⟨b, hb⟩, rfl) @[simp, to_additive] lemma coe_inclusion {H K : subgroup G} {h : H ≤ K} (a : H) : (inclusion h a : G) = a := by { cases a, simp only [inclusion, coe_mk, monoid_hom.mk'_apply] } @[simp, to_additive] lemma subtype_comp_inclusion {H K : subgroup G} (hH : H ≤ K) : K.subtype.comp (inclusion hH) = H.subtype := by { ext, simp } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl @[to_additive] lemma eq_bot_iff_forall : H = ⊥ ↔ ∀ x ∈ H, x = (1 : G) := begin rw set_like.ext'_iff, simp only [coe_bot, set.eq_singleton_iff_unique_mem, set_like.mem_coe, H.one_mem, true_and], end @[to_additive] lemma eq_bot_of_subsingleton [subsingleton H] : H = ⊥ := begin rw subgroup.eq_bot_iff_forall, intros y hy, rw [← subgroup.coe_mk H y hy, subsingleton.elim (⟨y, hy⟩ : H) 1, subgroup.coe_one], end @[to_additive] instance fintype_bot : fintype (⊥ : subgroup G) := ⟨{1}, by {rintro ⟨x, ⟨hx⟩⟩, exact finset.mem_singleton_self _}⟩ /- curly brackets `{}` are used here instead of instance brackets `[]` because the instance in a goal is often not the same as the one inferred by type class inference. -/ @[simp, to_additive] lemma card_bot {_ : fintype ↥(⊥ : subgroup G)} : fintype.card (⊥ : subgroup G) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : G), set.mem_singleton 1⟩, λ ⟨y, hy⟩, subtype.eq $ subgroup.mem_bot.1 hy⟩ @[to_additive] lemma eq_top_of_card_eq [fintype H] [fintype G] (h : fintype.card H = fintype.card G) : H = ⊤ := begin haveI : fintype (H : set G) := ‹fintype H›, rw [set_like.ext'_iff, coe_top, ← finset.coe_univ, ← (H : set G).coe_to_finset, finset.coe_inj, ← finset.card_eq_iff_eq_univ, ← h, set.to_finset_card], congr end @[to_additive] lemma eq_top_of_le_card [fintype H] [fintype G] (h : fintype.card G ≤ fintype.card H) : H = ⊤ := eq_top_of_card_eq H (le_antisymm (fintype.card_le_of_injective coe subtype.coe_injective) h) @[to_additive] lemma eq_bot_of_card_le [fintype H] (h : fintype.card H ≤ 1) : H = ⊥ := let _ := fintype.card_le_one_iff_subsingleton.mp h in by exactI eq_bot_of_subsingleton H @[to_additive] lemma eq_bot_of_card_eq [fintype H] (h : fintype.card H = 1) : H = ⊥ := H.eq_bot_of_card_le (le_of_eq h) @[to_additive] lemma nontrivial_iff_exists_ne_one (H : subgroup G) : nontrivial H ↔ ∃ x ∈ H, x ≠ (1:G) := subtype.nontrivial_iff_exists_ne (λ x, x ∈ H) (1 : H) /-- A subgroup is either the trivial subgroup or nontrivial. -/ @[to_additive] lemma bot_or_nontrivial (H : subgroup G) : H = ⊥ ∨ nontrivial H := begin classical, by_cases h : ∀ x ∈ H, x = (1 : G), { left, exact H.eq_bot_iff_forall.mpr h }, { right, push_neg at h, simpa [nontrivial_iff_exists_ne_one] using h }, end /-- A subgroup is either the trivial subgroup or contains a nonzero element. -/ @[to_additive] lemma bot_or_exists_ne_one (H : subgroup G) : H = ⊥ ∨ ∃ x ∈ H, x ≠ (1:G) := begin convert H.bot_or_nontrivial, rw nontrivial_iff_exists_ne_one end @[to_additive] lemma card_le_one_iff_eq_bot [fintype H] : fintype.card H ≤ 1 ↔ H = ⊥ := ⟨λ h, (eq_bot_iff_forall _).2 (λ x hx, by simpa [subtype.ext_iff] using fintype.card_le_one_iff.1 h ⟨x, hx⟩ 1), λ h, by simp [h]⟩ /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_infi add_subgroup.coe_infi /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from set_like.coe_subset_coe) is_glb_binfi } @[to_additive] lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → subgroup G} (i : ι) : ∀ {x : G}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G} (hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs @[simp, to_additive] lemma subsingleton_iff : subsingleton (subgroup G) ↔ subsingleton G := ⟨ λ h, by exactI ⟨λ x y, have ∀ i : G, i = 1 := λ i, mem_bot.mp $ subsingleton.elim (⊤ : subgroup G) ⊥ ▸ mem_top i, (this x).trans (this y).symm⟩, λ h, by exactI ⟨λ x y, subgroup.ext $ λ i, subsingleton.elim 1 i ▸ by simp [subgroup.one_mem]⟩⟩ @[simp, to_additive] lemma nontrivial_iff : nontrivial (subgroup G) ↔ nontrivial G := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans subsingleton_iff).trans not_nontrivial_iff_subsingleton.symm) @[to_additive] instance [subsingleton G] : unique (subgroup G) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ (subsingleton_iff.mpr ‹_›) a _⟩ @[to_additive] instance [nontrivial G] : nontrivial (subgroup G) := nontrivial_iff.mpr ‹_› @[to_additive] lemma eq_top_iff' : H = ⊤ ↔ ∀ x : G, x ∈ H := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and inverses, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction /-- An induction principle on elements of the subtype `subgroup.closure`. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements `x : closure k`. The difference with `subgroup.closure_induction` is that this acts on the subtype. -/ @[to_additive "An induction principle on elements of the subtype `add_subgroup.closure`. If `p` holds for `0` and all elements of `k`, and is preserved under addition and negation, then `p` holds for all elements `x : closure k`. The difference with `add_subgroup.closure_induction` is that this acts on the subtype."] lemma closure_induction' (k : set G) {p : closure k → Prop} (Hk : ∀ x (h : x ∈ k), p ⟨x, subset_closure h⟩) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) (x : closure k) : p x := subtype.rec_on x $ λ x hx, begin refine exists.elim _ (λ (hx : x ∈ closure k) (hc : p ⟨x, hx⟩), hc), exact closure_induction hx (λ x hx, ⟨subset_closure hx, Hk x hx⟩) ⟨one_mem _, H1⟩ (λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy, ⟨mul_mem _ hx' hy', Hmul _ _ hx hy⟩) (λ x hx, exists.elim hx $ λ hx' hx, ⟨inv_mem _ hx', Hinv _ hx⟩), end attribute [elab_as_eliminator] subgroup.closure_induction' add_subgroup.closure_induction' variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr @[to_additive] lemma closure_eq_bot_iff (G : Type*) [group G] (S : set G) : closure S = ⊥ ↔ S ⊆ {1} := by { rw [← le_bot_iff], exact closure_le _} /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, gpow_zero x⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end lemma closure_singleton_one : closure ({1} : set G) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] @[simp, to_additive] lemma inv_subset_closure (S : set G) : S⁻¹ ⊆ closure S := begin intros s hs, rw [set_like.mem_coe, ←subgroup.inv_mem_iff], exact subset_closure (mem_inv.mp hs), end @[simp, to_additive] lemma closure_inv (S : set G) : closure S⁻¹ = closure S := begin refine le_antisymm ((subgroup.closure_le _).2 _) ((subgroup.closure_le _).2 _), { exact inv_subset_closure S }, { simpa only [set.inv_inv] using inv_subset_closure S⁻¹ }, end @[to_additive] lemma closure_to_submonoid (S : set G) : (closure S).to_submonoid = submonoid.closure (S ∪ S⁻¹) := begin refine le_antisymm _ (submonoid.closure_le.2 _), { intros x hx, refine closure_induction hx (λ x hx, submonoid.closure_mono (subset_union_left S S⁻¹) (submonoid.subset_closure hx)) (submonoid.one_mem _) (λ x y hx hy, submonoid.mul_mem _ hx hy) (λ x hx, _), rwa [←submonoid.mem_closure_inv, set.union_inv, set.inv_inv, set.union_comm] }, { simp only [true_and, coe_to_submonoid, union_subset_iff, subset_closure, inv_subset_closure] } end /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k` and their inverse, and is preserved under multiplication, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k` and their negation, and is preserved under addition, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction'' {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (Hk_inv : ∀ x ∈ k, p x⁻¹) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := begin rw [← mem_to_submonoid, closure_to_submonoid k] at h, refine submonoid.closure_induction h (λ x hx, _) H1 (λ x y hx hy, Hmul x y hx hy), { rw [mem_union, mem_inv] at hx, cases hx with mem invmem, { exact Hk x mem }, { rw [← inv_inv x], exact Hk_inv _ invmem } }, end @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) : ((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk] end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_mono {f : G →* N} {K K' : subgroup N} : K ≤ K' → comap f K ≤ comap f K' := preimage_mono @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma mem_map_of_mem (f : G →* N) {K : subgroup G} {x : G} (hx : x ∈ K) : f x ∈ K.map f := mem_image_of_mem f hx @[to_additive] lemma apply_coe_mem_map (f : G →* N) (K : subgroup G) (x : K) : f x ∈ K.map f := mem_map_of_mem f x.prop @[to_additive] lemma map_mono {f : G →* N} {K K' : subgroup G} : K ≤ K' → map f K ≤ map f K' := image_subset _ @[simp, to_additive] lemma map_id : K.map (monoid_hom.id G) = K := set_like.coe_injective $ image_id _ @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := set_like.coe_injective $ image_image _ _ _ @[to_additive] lemma mem_map_equiv {f : G ≃* N} {K : subgroup G} {x : N} : x ∈ K.map f.to_monoid_hom ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x @[to_additive] lemma map_equiv_eq_comap_symm (f : G ≃* N) (K : subgroup G) : K.map f.to_monoid_hom = K.comap f.symm.to_monoid_hom := set_like.coe_injective (f.to_equiv.image_eq_preimage K) @[to_additive] lemma comap_equiv_eq_map_symm (f : N ≃* G) (K : subgroup G) : K.comap f.to_monoid_hom = K.map f.symm.to_monoid_hom := (map_equiv_eq_comap_symm f.symm K).symm @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_sup_comap_le (H K : subgroup N) (f : G →* N) : comap f H ⊔ comap f K ≤ comap f (H ⊔ K) := monotone.le_map_sup (λ _ _, comap_mono) H K @[to_additive] lemma supr_comap_le {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (⨆ i, (s i).comap f) ≤ (supr s).comap f := monotone.le_map_supr (λ _ _, comap_mono) @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[to_additive] lemma map_inf_le (H K : subgroup G) (f : G →* N) : map f (H ⊓ K) ≤ map f H ⊓ map f K := le_inf (map_mono inf_le_left) (map_mono inf_le_right) @[to_additive] lemma map_inf_eq (H K : subgroup G) (f : G →* N) (hf : function.injective f) : map f (H ⊓ K) = map f H ⊓ map f K := begin rw ← set_like.coe_set_eq, simp [set.image_inter hf], end @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top @[simp, to_additive] lemma comap_subtype_inf_left {H K : subgroup G} : comap H.subtype (H ⊓ K) = comap H.subtype K := ext $ λ x, and_iff_right_of_imp (λ _, x.prop) @[simp, to_additive] lemma comap_subtype_inf_right {H K : subgroup G} : comap K.subtype (H ⊓ K) = comap K.subtype H := ext $ λ x, and_iff_left_of_imp (λ _, x.prop) /-- For any subgroups `H` and `K`, view `H ⊓ K` as a subgroup of `K`. -/ @[to_additive "For any subgroups `H` and `K`, view `H ⊓ K` as a subgroup of `K`."] def subgroup_of (H K : subgroup G) : subgroup K := H.comap K.subtype @[to_additive] lemma coe_subgroup_of (H K : subgroup G) : (H.subgroup_of K : set K) = K.subtype ⁻¹' H := rfl @[to_additive] lemma mem_subgroup_of {H K : subgroup G} {h : K} : h ∈ H.subgroup_of K ↔ (h : G) ∈ H := iff.rfl @[to_additive] lemma subgroup_of_map_subtype (H K : subgroup G) : (H.subgroup_of K).map K.subtype = H ⊓ K := set_like.ext' begin convert set.image_preimage_eq_inter_range, simp only [subtype.range_coe_subtype, coe_subtype, coe_inf], refl, end /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ structure normal : Prop := (conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) attribute [class] normal end subgroup namespace add_subgroup /-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/ structure normal (H : add_subgroup A) : Prop := (conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n + -g ∈ H) attribute [to_additive add_subgroup.normal] subgroup.normal attribute [class] normal end add_subgroup namespace subgroup variables {H K : subgroup G} @[priority 100, to_additive] instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := ⟨by simp [mul_comm, mul_left_comm]⟩ namespace normal variable (nH : H.normal) @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal @[priority 100, to_additive] instance bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩ @[priority 100, to_additive] instance top_normal : normal (⊤ : subgroup G) := ⟨λ _ _, mem_top⟩ variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of an additive group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := set.center G, inv_mem' := λ a, set.inv_mem_center, .. submonoid.center G } @[to_additive] lemma coe_center : ↑(center G) = set.center G := rfl @[simp, to_additive] lemma center_to_submonoid : (center G).to_submonoid = submonoid.center G := rfl variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl @[priority 100, to_additive] instance center_normal : (center G).normal := ⟨begin assume n hn g h, assoc_rw [hn (h * g), hn g], simp end⟩ variables {G} (H) /-- The `normalizer` of `H` is the largest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the largest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } -- variant for sets. -- TODO should this replace `normalizer`? /-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/ @[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g+S-g=S`."] def set_normalizer (S : set G) : subgroup G := { carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } lemma mem_normalizer_fintype {S : set G} [fintype S] {x : G} (h : ∀ n, n ∈ S → x * n * x⁻¹ ∈ S) : x ∈ subgroup.set_normalizer S := by haveI := classical.prop_decidable; haveI := set.fintype_image S (λ n, x * n * x⁻¹); exact λ n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' S = S := set.eq_of_subset_of_card_le (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective S conj_injective), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' S := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_injective hy.2 ▸ hy.1⟩ variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH] @[priority 100, to_additive] instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal := ⟨λ x xH g, by simpa using (g.2 x).1 xH⟩ open_locale classical @[to_additive] lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ variables {N : Type*} [group N] /-- The preimage of the normalizer is contained in the normalizer of the preimage. -/ @[to_additive "The preimage of the normalizer is contained in the normalizer of the preimage."] lemma le_normalizer_comap (f : N →* G) : H.normalizer.comap f ≤ (H.comap f).normalizer := λ x, begin simp only [mem_normalizer_iff, mem_comap], assume h n, simp [h (f n)] end /-- The image of the normalizer is contained in the normalizer of the image. -/ @[to_additive "The image of the normalizer is contained in the normalizer of the image."] lemma le_normalizer_map (f : G →* N) : H.normalizer.map f ≤ (H.map f).normalizer := λ _, begin simp only [and_imp, exists_prop, mem_map, exists_imp_distrib, mem_normalizer_iff], rintros x hx rfl n, split, { rintros ⟨y, hy, rfl⟩, use [x * y * x⁻¹, (hx y).1 hy], simp }, { rintros ⟨y, hyH, hy⟩, use [x⁻¹ * y * x], rw [hx], simp [hy, hyH, mul_assoc] } end variable (H) /-- Commutivity of a subgroup -/ structure is_commutative : Prop := (is_comm : _root_.is_commutative H (*)) attribute [class] is_commutative /-- Commutivity of an additive subgroup -/ structure _root_.add_subgroup.is_commutative (H : add_subgroup A) : Prop := (is_comm : _root_.is_commutative H (+)) attribute [to_additive add_subgroup.is_commutative] subgroup.is_commutative attribute [class] add_subgroup.is_commutative /-- A commutative subgroup is commutative -/ @[to_additive] instance is_commutative.comm_group [h : H.is_commutative] : comm_group H := { mul_comm := h.is_comm.comm, .. H.to_group } instance center.is_commutative : (center G).is_commutative := ⟨⟨λ a b, subtype.ext (b.2 a)⟩⟩ end subgroup namespace group variables {s : set G} /-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of the elements of `s`. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates_of a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) : conjugates_of a ⊆ N := by { rintros a hc, obtain ⟨c, rfl⟩ := is_conj_iff.1 hc, exact tn.conj_mem a h c } theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) : conjugates_of_set s ⊆ N := set.bUnion_subset (λ x H, conjugates_subset_normal (h H)) /-- The set of conjugates of `s` is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ (is_conj_iff.2 ⟨c,rfl⟩)⟩, end end group namespace subgroup open group variable {s : set G} /-- The normal closure of a set `s` is the subgroup closure of all the conjugates of elements of `s`. It is the smallest normal subgroup containing `s`. -/ def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure theorem le_normal_closure {H : subgroup G} : H ≤ normal_closure ↑H := λ _ h, subset_normal_closure h /-- The normal closure of `s` is a normal subgroup. -/ instance normal_closure_normal : (normal_closure s).normal := ⟨λ n h g, begin refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) }, { simpa using (normal_closure s).one_mem }, { rw ← conj_mul, exact mul_mem _ ihx ihy }, { rw ← conj_inv, exact inv_mem _ ihx } end⟩ /-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/ theorem normal_closure_le_normal {N : subgroup G} [N.normal] (h : s ⊆ N) : normal_closure s ≤ N := begin assume a w, refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset h hx) }, { exact subgroup.one_mem _ }, { exact subgroup.mul_mem _ ihx ihy }, { exact subgroup.inv_mem _ ihx } end lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N := ⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t := normal_closure_le_normal (set.subset.trans h subset_normal_closure) theorem normal_closure_eq_infi : normal_closure s = ⨅ (N : subgroup G) [normal N] (hs : s ⊆ N), N := le_antisymm (le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal)))) (infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance) (infi_le_of_le subset_normal_closure (le_refl _)))) @[simp] theorem normal_closure_eq_self (H : subgroup G) [H.normal] : normal_closure ↑H = H := le_antisymm (normal_closure_le_normal rfl.subset) (le_normal_closure) @[simp] theorem normal_closure_idempotent : normal_closure ↑(normal_closure s) = normal_closure s := normal_closure_eq_self _ theorem closure_le_normal_closure {s : set G} : closure s ≤ normal_closure s := by simp only [subset_normal_closure, closure_le] @[simp] theorem normal_closure_closure_eq_normal_closure {s : set G} : normal_closure ↑(closure s) = normal_closure s := le_antisymm (normal_closure_le_normal closure_le_normal_closure) (normal_closure_mono subset_closure) /-- The normal core of a subgroup `H` is the largest normal subgroup of `G` contained in `H`, as shown by `subgroup.normal_core_eq_supr`. -/ def normal_core (H : subgroup G) : subgroup G := { carrier := {a : G | ∀ b : G, b * a * b⁻¹ ∈ H}, one_mem' := λ a, by rw [mul_one, mul_inv_self]; exact H.one_mem, inv_mem' := λ a h b, (congr_arg (∈ H) conj_inv).mp (H.inv_mem (h b)), mul_mem' := λ a b ha hb c, (congr_arg (∈ H) conj_mul).mp (H.mul_mem (ha c) (hb c)) } lemma normal_core_le (H : subgroup G) : H.normal_core ≤ H := λ a h, by { rw [←mul_one a, ←one_inv, ←one_mul a], exact h 1 } instance normal_core_normal (H : subgroup G) : H.normal_core.normal := ⟨λ a h b c, by rw [mul_assoc, mul_assoc, ←mul_inv_rev, ←mul_assoc, ←mul_assoc]; exact h (c * b)⟩ lemma normal_le_normal_core {H : subgroup G} {N : subgroup G} [hN : N.normal] : N ≤ H.normal_core ↔ N ≤ H := ⟨ge_trans H.normal_core_le, λ h_le n hn g, h_le (hN.conj_mem n hn g)⟩ lemma normal_core_mono {H K : subgroup G} (h : H ≤ K) : H.normal_core ≤ K.normal_core := normal_le_normal_core.mpr (H.normal_core_le.trans h) lemma normal_core_eq_supr (H : subgroup G) : H.normal_core = ⨆ (N : subgroup G) [normal N] (hs : N ≤ H), N := le_antisymm (le_supr_of_le H.normal_core (le_supr_of_le H.normal_core_normal (le_supr_of_le H.normal_core_le le_rfl))) (supr_le (λ N, supr_le (λ hN, supr_le (by exactI normal_le_normal_core.mpr)))) @[simp] lemma normal_core_eq_self (H : subgroup G) [H.normal] : H.normal_core = H := le_antisymm H.normal_core_le (normal_le_normal_core.mpr le_rfl) @[simp] theorem normal_core_idempotent (H : subgroup G) : H.normal_core.normal_core = H.normal_core := H.normal_core.normal_core_eq_self end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, n • x ∈ H | (n : ℕ) := by { rw [gsmul_coe_nat], exact add_submonoid.nsmul_mem H.to_add_submonoid hx n } | -[1+ n] := begin rw gsmul_neg_succ_of_nat, apply H.neg_mem', exact add_submonoid.nsmul_mem H.to_add_submonoid hx n.succ end /-- The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, n • x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, zero_gsmul x⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end lemma closure_singleton_zero : closure ({0} : set A) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] variable (H : add_subgroup A) @[simp] lemma coe_smul (x : H) (n : ℕ) : ((n • x : H) : A) = n • x := coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _ @[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n • x : H) : A) = n • x := coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _ attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow end add_subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff]) @[to_additive] instance decidable_mem_range (f : G →* N) [fintype G] [decidable_eq N] : decidable_pred (∈ f.range) := λ x, fintype.decidable_exists_fintype @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := rfl @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f := by ext; simp /-- The canonical surjective group homomorphism `G →* f(G)` induced by a group homomorphism `G →* N`. -/ @[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group homomorphism `G →+ N`."] def range_restrict (f : G →* N) : G →* f.range := monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _} @[simp, to_additive] lemma coe_range_restrict (f : G →* N) (g : G) : (f.range_restrict g : N) = f g := rfl @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf @[simp, to_additive] lemma _root_.subgroup.subtype_range (H : subgroup G) : H.subtype.range = H := by { rw [range_eq_map, ← set_like.coe_set_eq, coe_map, subgroup.coe_subtype], ext, simp } /-- Restriction of a group hom to a subgroup of the domain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the domain."] def restrict (f : G →* N) (H : subgroup G) : H →* N := f.comp H.subtype @[simp, to_additive] lemma restrict_apply {H : subgroup G} (f : G →* N) (x : H) : f.restrict H x = f (x : G) := rfl /-- Restriction of a group hom to a subgroup of the codomain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."] def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } @[simp, to_additive] lemma cod_restrict_apply {G : Type*} [group G] {N : Type*} [group N] (f : G →* N) (S : subgroup N) (h : ∀ (x : G), f x ∈ S) {x : G} : f.cod_restrict S h x = ⟨f x, h x⟩ := rfl @[to_additive] lemma subgroup_of_range_eq_of_le {G₁ G₂ : Type*} [group G₁] [group G₂] {K : subgroup G₂} (f : G₁ →* G₂) (h : f.range ≤ K) : f.range.subgroup_of K = (f.cod_restrict K (λ x, h ⟨x, rfl⟩)).range := begin ext k, refine exists_congr _, simp [subtype.ext_iff], end /-- Computable alternative to `monoid_hom.of_injective`. -/ def of_left_inverse {f : G →* N} {g : N →* G} (h : function.left_inverse g f) : G ≃* f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.subtype, left_inv := h, right_inv := by { rintros ⟨x, y, rfl⟩, apply subtype.ext, rw [coe_range_restrict, function.comp_apply, subgroup.coe_subtype, subtype.coe_mk, h] }, .. f.range_restrict } @[simp] lemma of_left_inverse_apply {f : G →* N} {g : N →* G} (h : function.left_inverse g f) (x : G) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply {f : G →* N} {g : N →* G} (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl /-- The range of an injective group homomorphism is isomorphic to its domain. -/ noncomputable def of_injective {f : G →* N} (hf : function.injective f) : G ≃* f.range := (mul_equiv.of_bijective (f.cod_restrict f.range (λ x, ⟨x, rfl⟩)) ⟨λ x y h, hf (subtype.ext_iff.mp h), by { rintros ⟨x, y, rfl⟩, exact ⟨y, rfl⟩ }⟩) lemma of_injective_apply {f : G →* N} (hf : function.injective f) {x : G} : ↑(of_injective hf x) = f x := rfl section ker variables {M : Type*} [mul_one_class M] /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* M) : subgroup G := { inv_mem' := λ x (hx : f x = 1), calc f x⁻¹ = f x * f x⁻¹ : by rw [hx, one_mul] ... = f (x * x⁻¹) : by rw [f.map_mul] ... = f 1 : by rw [mul_right_inv] ... = 1 : f.map_one, ..f.mker } @[to_additive] lemma mem_ker (f : G →* M) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl @[to_additive] lemma coe_ker (f : G →* M) : (f.ker : set G) = (f : G → M) ⁻¹' {1} := rfl @[to_additive] lemma eq_iff (f : G →* N) {x y : G} : f x = f y ↔ y⁻¹ * x ∈ f.ker := by rw [f.mem_ker, f.map_mul, f.map_inv, inv_mul_eq_one, eq_comm] @[to_additive] instance decidable_mem_ker [decidable_eq M] (f : G →* M) : decidable_pred (∈ f.ker) := λ x, decidable_of_iff (f x = 1) f.mem_ker @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl @[simp, to_additive] lemma comap_bot (f : G →* N) : (⊥ : subgroup N).comap f = f.ker := rfl @[to_additive] lemma range_restrict_ker (f : G →* N) : ker (range_restrict f) = ker f := begin ext, change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end @[simp, to_additive] lemma ker_one : (1 : G →* M).ker = ⊤ := by { ext, simp [mem_ker] } @[to_additive] lemma ker_eq_bot_iff (f : G →* N) : f.ker = ⊥ ↔ function.injective f := begin split, { intros h x y hxy, rwa [←mul_inv_eq_one, ←map_inv, ←map_mul, ←mem_ker, h, mem_bot, mul_inv_eq_one] at hxy }, { exact λ h, le_bot_iff.mp (λ x hx, h (hx.trans f.map_one.symm)) }, end @[to_additive] lemma prod_map_comap_prod {G' : Type*} {N' : Type*} [group G'] [group N'] (f : G →* N) (g : G' →* N') (S : subgroup N) (S' : subgroup N') : (S.prod S').comap (prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ @[to_additive] lemma ker_prod_map {G' : Type*} {N' : Type*} [group G'] [group N'] (f : G →* N) (g : G' →* N') : (prod_map f g).ker = f.ker.prod g.ker := by rw [←comap_bot, ←comap_bot, ←comap_bot, ←prod_map_comap_prod, bot_prod_bot] end ker /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [set_like.mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) -- this instance can't go just after the definition of `mrange` because `fintype` is -- not imported at that stage /-- The range of a finite monoid under a monoid homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype N`. -/ @[to_additive "The range of a finite additive monoid under an additive monoid homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the presence of `fintype N`."] instance fintype_mrange {M N : Type*} [monoid M] [monoid N] [fintype M] [decidable_eq N] (f : M →* N) : fintype (mrange f) := set.fintype_range f /-- The range of a finite group under a group homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the presence of `fintype N`. -/ @[to_additive "The range of a finite additive group under an additive group homomorphism is finite. Note: this instance can form a diamond with `subtype.fintype` or `subgroup.fintype` in the presence of `fintype N`."] instance fintype_range [fintype G] [decidable_eq N] (f : G →* N) : fintype (range f) := set.fintype_range f end monoid_hom namespace subgroup variables {N : Type*} [group N] (H : subgroup G) @[to_additive] lemma map_eq_bot_iff {f : G →* N} : H.map f = ⊥ ↔ H ≤ f.ker := begin rw eq_bot_iff, split, { exact λ h x hx, h ⟨x, hx, rfl⟩ }, { intros h x hx, obtain ⟨y, hy, rfl⟩ := hx, exact h hy }, end @[to_additive] lemma map_eq_bot_iff_of_injective {f : G →* N} (hf : function.injective f) : H.map f = ⊥ ↔ H = ⊥ := by rw [map_eq_bot_iff, f.ker_eq_bot_iff.mpr hf, le_bot_iff] end subgroup namespace subgroup open monoid_hom variables {N : Type*} [group N] (f : G →* N) @[to_additive] lemma map_le_range (H : subgroup G) : map f H ≤ f.range := (range_eq_map f).symm ▸ map_mono le_top @[to_additive] lemma ker_le_comap (H : subgroup N) : f.ker ≤ comap f H := (comap_bot f) ▸ comap_mono bot_le @[to_additive] lemma map_comap_le (H : subgroup N) : map f (comap f H) ≤ H := (gc_map_comap f).l_u_le _ @[to_additive] lemma le_comap_map (H : subgroup G) : H ≤ comap f (map f H) := (gc_map_comap f).le_u_l _ @[to_additive] lemma map_comap_eq (H : subgroup N) : map f (comap f H) = f.range ⊓ H := set_like.ext' begin convert set.image_preimage_eq_inter_range, simp [set.inter_comm], end @[to_additive] lemma comap_map_eq (H : subgroup G) : comap f (map f H) = H ⊔ f.ker := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (ker_le_comap _ _)), intros x hx, simp only [exists_prop, mem_map, mem_comap] at hx, rcases hx with ⟨y, hy, hy'⟩, have : y⁻¹ * x ∈ f.ker, { rw mem_ker, simp [hy'] }, convert mul_mem _ (mem_sup_left hy) (mem_sup_right this), simp, end @[to_additive] lemma map_comap_eq_self {f : G →* N} {H : subgroup N} (h : H ≤ f.range) : map f (comap f H) = H := by rwa [map_comap_eq, inf_eq_right] @[to_additive] lemma map_comap_eq_self_of_surjective {f : G →* N} (h : function.surjective f) (H : subgroup N) : map f (comap f H) = H := map_comap_eq_self ((range_top_of_surjective _ h).symm ▸ le_top) @[to_additive] lemma comap_injective {f : G →* N} (h : function.surjective f) : function.injective (comap f) := λ K L hKL, by { apply_fun map f at hKL, simpa [map_comap_eq_self_of_surjective h] using hKL } @[to_additive] lemma comap_map_eq_self {f : G →* N} {H : subgroup G} (h : f.ker ≤ H) : comap f (map f H) = H := by rwa [comap_map_eq, sup_eq_left] @[to_additive] lemma comap_map_eq_self_of_injective {f : G →* N} (h : function.injective f) (H : subgroup G) : comap f (map f H) = H := comap_map_eq_self (((ker_eq_bot_iff _).mpr h).symm ▸ bot_le) @[to_additive] lemma map_injective {f : G →* N} (h : function.injective f) : function.injective (map f) := λ K L hKL, by { apply_fun comap f at hKL, simpa [comap_map_eq_self_of_injective h] using hKL } @[to_additive] lemma map_eq_comap_of_inverse {f : G →* N} {g : N →* G} (hl : function.left_inverse g f) (hr : function.right_inverse g f) (H : subgroup G) : map f H = comap g H := set_like.ext' $ by rw [coe_map, coe_comap, set.image_eq_preimage_of_inverse hl hr] /-- Given `f(A) = f(B)`, `ker f ≤ A`, and `ker f ≤ B`, deduce that `A = B` -/ @[to_additive] lemma map_injective_of_ker_le {H K : subgroup G} (hH : f.ker ≤ H) (hK : f.ker ≤ K) (hf : map f H = map f K) : H = K := begin apply_fun comap f at hf, rwa [comap_map_eq, comap_map_eq, sup_of_le_left hH, sup_of_le_left hK] at hf, end @[to_additive] lemma comap_sup_eq (H K : subgroup N) (hf : function.surjective f): comap f H ⊔ comap f K = comap f (H ⊔ K) := begin have : map f (comap f H ⊔ comap f K) = map f (comap f (H ⊔ K)), { simp [subgroup.map_comap_eq, map_sup, f.range_top_of_surjective hf], }, refine map_injective_of_ker_le f _ _ this, { calc f.ker ≤ comap f H : ker_le_comap f _ ... ≤ comap f H ⊔ comap f K : le_sup_left, }, exact ker_le_comap _ _, end /-- A subgroup is isomorphic to its image under an injective function -/ @[to_additive "An additive subgroup is isomorphic to its image under an injective function"] noncomputable def equiv_map_of_injective (H : subgroup G) (f : G →* N) (hf : function.injective f) : H ≃* H.map f := { map_mul' := λ _ _, subtype.ext (f.map_mul _ _), ..equiv.set.image f H hf } @[simp, to_additive] lemma coe_equiv_map_of_injective_apply (H : subgroup G) (f : G →* N) (hf : function.injective f) (h : H) : (equiv_map_of_injective H f hf h : N) = f h := rfl /-- The preimage of the normalizer is equal to the normalizer of the preimage of a surjective function. -/ @[to_additive "The preimage of the normalizer is equal to the normalizer of the preimage of a surjective function."] lemma comap_normalizer_eq_of_surjective (H : subgroup G) {f : N →* G} (hf : function.surjective f) : H.normalizer.comap f = (H.comap f).normalizer := le_antisymm (le_normalizer_comap f) begin assume x hx, simp only [mem_comap, mem_normalizer_iff] at *, assume n, rcases hf n with ⟨y, rfl⟩, simp [hx y] end /-- The image of the normalizer is equal to the normalizer of the image of an isomorphism. -/ @[to_additive "The image of the normalizer is equal to the normalizer of the image of an isomorphism."] lemma map_equiv_normalizer_eq (H : subgroup G) (f : G ≃* N) : H.normalizer.map f.to_monoid_hom = (H.map f.to_monoid_hom).normalizer := begin ext x, simp only [mem_normalizer_iff, mem_map_equiv], rw [f.to_equiv.forall_congr], simp end /-- The image of the normalizer is equal to the normalizer of the image of a bijective function. -/ @[to_additive "The image of the normalizer is equal to the normalizer of the image of a bijective function."] lemma map_normalizer_eq_of_bijective (H : subgroup G) {f : G →* N} (hf : function.bijective f) : H.normalizer.map f = (H.map f).normalizer := map_equiv_normalizer_eq H (mul_equiv.of_bijective f hf) end subgroup namespace monoid_hom variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃] variables (f : G₁ →* G₂) (f_inv : G₂ → G₁) /-- Auxiliary definition used to define `lift_of_right_inverse` -/ @[to_additive "Auxiliary definition used to define `lift_of_right_inverse`"] def lift_of_right_inverse_aux (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : G₂ →* G₃ := { to_fun := λ b, g (f_inv b), map_one' := hg (hf 1), map_mul' := begin intros x y, rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul], simp only [hf _], end } @[simp, to_additive] lemma lift_of_right_inverse_aux_comp_apply (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) : (f.lift_of_right_inverse_aux f_inv hf g hg) (f x) = g x := begin dsimp [lift_of_right_inverse_aux], rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one], simp only [hf _], end /-- `lift_of_right_inverse f hf g hg` is the unique group homomorphism `φ` * such that `φ.comp f = g` (`monoid_hom.lift_of_right_inverse_comp`), * where `f : G₁ →+* G₂` has a right_inverse `f_inv` (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `monoid_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` G₁. | \ f | \ g | \ v \⌟ G₂----> G₃ ∃!φ ``` -/ @[to_additive "`lift_of_right_inverse f f_inv hf g hg` is the unique additive group homomorphism `φ` * such that `φ.comp f = g` (`add_monoid_hom.lift_of_right_inverse_comp`), * where `f : G₁ →+ G₂` has a right_inverse `f_inv` (`hf`), * and `g : G₂ →+ G₃` satisfies `hg : f.ker ≤ g.ker`. See `add_monoid_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` G₁. | \\ f | \\ g | \\ v \\⌟ G₂----> G₃ ∃!φ ```"] def lift_of_right_inverse (hf : function.right_inverse f_inv f) : {g : G₁ →* G₃ // f.ker ≤ g.ker} ≃ (G₂ →* G₃) := { to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2, inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩, left_inv := λ g, by { ext, simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk, subtype.val_eq_coe], }, right_inv := λ φ, by { ext b, simp [lift_of_right_inverse_aux, hf b], } } /-- A non-computable version of `monoid_hom.lift_of_right_inverse` for when no computable right inverse is available, that uses `function.surj_inv`. -/ @[simp, to_additive "A non-computable version of `add_monoid_hom.lift_of_right_inverse` for when no computable right inverse is available."] noncomputable abbreviation lift_of_surjective (hf : function.surjective f) : {g : G₁ →* G₃ // f.ker ≤ g.ker} ≃ (G₂ →* G₃) := f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf) @[simp, to_additive] lemma lift_of_right_inverse_comp_apply (hf : function.right_inverse f_inv f) (g : {g : G₁ →* G₃ // f.ker ≤ g.ker}) (x : G₁) : (f.lift_of_right_inverse f_inv hf g) (f x) = g x := f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x @[simp, to_additive] lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f) (g : {g : G₁ →* G₃ // f.ker ≤ g.ker}) : (f.lift_of_right_inverse f_inv hf g).comp f = g := monoid_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g @[to_additive] lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (h : G₂ →* G₃) (hh : h.comp f = g) : h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) := begin simp_rw ←hh, exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm, end end monoid_hom variables {N : Type*} [group N] -- Here `H.normal` is an explicit argument so we can use dot notation with `comap`. @[to_additive] lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) : (H.comap f).normal := ⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩ @[priority 100, to_additive] instance subgroup.normal_comap {H : subgroup N} [nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _ @[priority 100, to_additive] instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal := by { rw [←f.comap_bot], apply_instance } @[priority 100, to_additive] instance subgroup.normal_inf (H N : subgroup G) [hN : N.normal] : ((H ⊓ N).comap H.subtype).normal := ⟨λ x hx g, begin simp only [subgroup.mem_inf, coe_subtype, subgroup.mem_comap] at hx, simp only [subgroup.coe_mul, subgroup.mem_inf, coe_subtype, subgroup.coe_inv, subgroup.mem_comap], exact ⟨H.mul_mem (H.mul_mem g.2 hx.1) (H.inv_mem g.2), hN.1 x hx.2 g⟩, end⟩ namespace subgroup /-- The subgroup generated by an element. -/ def gpowers (g : G) : subgroup G := subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩ lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gpowers_hom (g : G) : (gpowers_hom G g).range = gpowers g := rfl lemma gpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : gpowers a ≤ K := λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.gpow_mem h i end lemma mem_gpowers_iff {g h : G} : h ∈ gpowers g ↔ ∃ (k : ℤ), g ^ k = h := iff.rfl @[simp] lemma forall_gpowers {x : G} {p : gpowers x → Prop} : (∀ g, p g) ↔ ∀ m : ℤ, p ⟨x ^ m, m, rfl⟩ := set.forall_subtype_range_iff @[simp] lemma exists_gpowers {x : G} {p : gpowers x → Prop} : (∃ g, p g) ↔ ∃ m : ℤ, p ⟨x ^ m, m, rfl⟩ := set.exists_subtype_range_iff lemma forall_mem_gpowers {x : G} {p : G → Prop} : (∀ g ∈ gpowers x, p g) ↔ ∀ m : ℤ, p (x ^ m) := set.forall_range_iff lemma exists_mem_gpowers {x : G} {p : G → Prop} : (∃ g ∈ gpowers x, p g) ↔ ∃ m : ℤ, p (x ^ m) := set.exists_range_iff end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def gmultiples (a : A) : add_subgroup A := add_subgroup.copy (gmultiples_hom A a).range (set.range ((• a) : ℤ → A)) rfl @[simp] lemma range_gmultiples_hom (a : A) : (gmultiples_hom A a).range = gmultiples a := rfl lemma gmultiples_subset {a : A} {B : add_subgroup A} (h : a ∈ B) : gmultiples a ≤ B := @subgroup.gpowers_subset (multiplicative A) _ _ (B.to_subgroup) h attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure attribute [to_additive add_subgroup.range_gmultiples_hom] subgroup.range_gpowers_hom attribute [to_additive add_subgroup.gmultiples_subset] subgroup.gpowers_subset attribute [to_additive add_subgroup.mem_gmultiples_iff] subgroup.mem_gpowers_iff attribute [to_additive add_subgroup.forall_gmultiples] subgroup.forall_gpowers attribute [to_additive add_subgroup.forall_mem_gmultiples] subgroup.forall_mem_gpowers attribute [to_additive add_subgroup.exists_gmultiples] subgroup.exists_gpowers attribute [to_additive add_subgroup.exists_mem_gmultiples] subgroup.exists_mem_gpowers end add_subgroup lemma int.mem_gmultiples_iff {a b : ℤ} : b ∈ add_subgroup.gmultiples a ↔ a ∣ b := exists_congr (λ k, by rw [mul_comm, eq_comm, ← smul_eq_mul]) lemma of_mul_image_gpowers_eq_gmultiples_of_mul { x : G } : additive.of_mul '' ((subgroup.gpowers x) : set G) = add_subgroup.gmultiples (additive.of_mul x) := begin ext y, split, { rintro ⟨z, ⟨m, hm⟩, hz2⟩, use m, simp only, rwa [← of_mul_gpow, hm] }, { rintros ⟨n, hn⟩, refine ⟨x ^ n, ⟨n, rfl⟩, _⟩, rwa of_mul_gpow } end lemma of_add_image_gmultiples_eq_gpowers_of_add {x : A} : multiplicative.of_add '' ((add_subgroup.gmultiples x) : set A) = subgroup.gpowers (multiplicative.of_add x) := begin symmetry, rw equiv.eq_image_iff_symm_image_eq, exact of_mul_image_gpowers_eq_gmultiples_of_mul, end namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- A `mul_equiv` `φ` between two groups `G` and `G'` induces a `mul_equiv` between a subgroup `H ≤ G` and the subgroup `φ(H) ≤ G'`. -/ @[to_additive "An `add_equiv` `φ` between two additive groups `G` and `G'` induces an `add_equiv` between a subgroup `H ≤ G` and the subgroup `φ(H) ≤ G'`. "] def subgroup_equiv_map {G'} [group G'] (e : G ≃* G') (H : subgroup G) : H ≃* H.map e.to_monoid_hom := e.submonoid_equiv_map H.to_submonoid end mul_equiv -- TODO : ↥(⊤ : subgroup H) ≃* H ? namespace subgroup variables {C : Type*} [comm_group C] {s t : subgroup C} {x : C} @[to_additive] lemma mem_sup : x ∈ s ⊔ t ↔ ∃ (y ∈ s) (z ∈ t), y * z = x := ⟨λ h, begin rw [← closure_eq s, ← closure_eq t, ← closure_union] at h, apply closure_induction h, { rintro y (h | h), { exact ⟨y, h, 1, t.one_mem, by simp⟩ }, { exact ⟨1, s.one_mem, y, h, by simp⟩ } }, { exact ⟨1, s.one_mem, 1, ⟨t.one_mem, mul_one 1⟩⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, mul_mem _ hy₁ hy₂, _, mul_mem _ hz₁ hz₂, by simp [mul_assoc]; cc⟩ }, { rintro _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, inv_mem _ hy, _, inv_mem _ hz, mul_comm z y ▸ (mul_inv_rev z y).symm⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact mul_mem _ ((le_sup_left : s ≤ s ⊔ t) hy) ((le_sup_right : t ≤ s ⊔ t) hz)⟩ @[to_additive] lemma mem_sup' : x ∈ s ⊔ t ↔ ∃ (y : s) (z : t), (y:C) * z = x := mem_sup.trans $ by simp only [set_like.exists, coe_mk] @[to_additive] instance : is_modular_lattice (subgroup C) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw ← inv_mul_cancel_left b c, apply z.mul_mem (z.inv_mem (xz hb)) haz, end⟩ end subgroup section variables (G) (A) /-- A `group` is simple when it has exactly two normal `subgroup`s. -/ class is_simple_group extends nontrivial G : Prop := (eq_bot_or_eq_top_of_normal : ∀ H : subgroup G, H.normal → H = ⊥ ∨ H = ⊤) /-- An `add_group` is simple when it has exactly two normal `add_subgroup`s. -/ class is_simple_add_group extends nontrivial A : Prop := (eq_bot_or_eq_top_of_normal : ∀ H : add_subgroup A, H.normal → H = ⊥ ∨ H = ⊤) attribute [to_additive] is_simple_group variables {G} {A} @[to_additive] lemma subgroup.normal.eq_bot_or_eq_top [is_simple_group G] {H : subgroup G} (Hn : H.normal) : H = ⊥ ∨ H = ⊤ := is_simple_group.eq_bot_or_eq_top_of_normal H Hn namespace is_simple_group @[to_additive] instance {C : Type*} [comm_group C] [is_simple_group C] : is_simple_lattice (subgroup C) := ⟨λ H, H.normal_of_comm.eq_bot_or_eq_top⟩ open subgroup @[to_additive] lemma is_simple_group_of_surjective {H : Type*} [group H] [is_simple_group G] [nontrivial H] (f : G →* H) (hf : function.surjective f) : is_simple_group H := ⟨nontrivial.exists_pair_ne, λ H iH, begin refine ((iH.comap f).eq_bot_or_eq_top).imp (λ h, _) (λ h, _), { rw [←map_bot f, ←h, map_comap_eq_self_of_surjective hf] }, { rw [←comap_top f] at h, exact comap_injective hf h } end⟩ end is_simple_group end namespace subgroup section pointwise @[to_additive] lemma closure_mul_le (S T : set G) : closure (S * T) ≤ closure S ⊔ closure T := Inf_le $ λ x ⟨s, t, hs, ht, hx⟩, hx ▸ (closure S ⊔ closure T).mul_mem (set_like.le_def.mp le_sup_left $ subset_closure hs) (set_like.le_def.mp le_sup_right $ subset_closure ht) @[to_additive] lemma sup_eq_closure (H K : subgroup G) : H ⊔ K = closure (H * K) := le_antisymm (sup_le (λ h hh, subset_closure ⟨h, 1, hh, K.one_mem, mul_one h⟩) (λ k hk, subset_closure ⟨1, k, H.one_mem, hk, one_mul k⟩)) (by conv_rhs { rw [← closure_eq H, ← closure_eq K] }; apply closure_mul_le) @[to_additive] private def mul_normal_aux (H N : subgroup G) [hN : N.normal] : subgroup G := { carrier := (H : set G) * N, one_mem' := ⟨1, 1, H.one_mem, N.one_mem, by rw mul_one⟩, mul_mem' := λ a b ⟨h, n, hh, hn, ha⟩ ⟨h', n', hh', hn', hb⟩, ⟨h * h', h'⁻¹ * n * h' * n', H.mul_mem hh hh', N.mul_mem (by simpa using hN.conj_mem _ hn h'⁻¹) hn', by simp [← ha, ← hb, mul_assoc]⟩, inv_mem' := λ x ⟨h, n, hh, hn, hx⟩, ⟨h⁻¹, h * n⁻¹ * h⁻¹, H.inv_mem hh, hN.conj_mem _ (N.inv_mem hn) h, by rw [mul_assoc h, inv_mul_cancel_left, ← hx, mul_inv_rev]⟩ } /-- The carrier of `H ⊔ N` is just `↑H * ↑N` (pointwise set product) when `N` is normal. -/ @[to_additive "The carrier of `H ⊔ N` is just `↑H + ↑N` (pointwise set addition) when `N` is normal."] lemma mul_normal (H N : subgroup G) [N.normal] : (↑(H ⊔ N) : set G) = H * N := set.subset.antisymm (show H ⊔ N ≤ mul_normal_aux H N, by { rw sup_eq_closure, apply Inf_le _, dsimp, refl }) ((sup_eq_closure H N).symm ▸ subset_closure) @[to_additive] private def normal_mul_aux (N H : subgroup G) [hN : N.normal] : subgroup G := { carrier := (N : set G) * H, one_mem' := ⟨1, 1, N.one_mem, H.one_mem, by rw mul_one⟩, mul_mem' := λ a b ⟨n, h, hn, hh, ha⟩ ⟨n', h', hn', hh', hb⟩, ⟨n * (h * n' * h⁻¹), h * h', N.mul_mem hn (hN.conj_mem _ hn' _), H.mul_mem hh hh', by simp [← ha, ← hb, mul_assoc]⟩, inv_mem' := λ x ⟨n, h, hn, hh, hx⟩, ⟨h⁻¹ * n⁻¹ * h, h⁻¹, by simpa using hN.conj_mem _ (N.inv_mem hn) h⁻¹, H.inv_mem hh, by rw [mul_inv_cancel_right, ← mul_inv_rev, hx]⟩ } /-- The carrier of `N ⊔ H` is just `↑N * ↑H` (pointwise set product) when `N` is normal. -/ @[to_additive "The carrier of `N ⊔ H` is just `↑N + ↑H` (pointwise set addition) when `N` is normal."] lemma normal_mul (N H : subgroup G) [N.normal] : (↑(N ⊔ H) : set G) = N * H := set.subset.antisymm (show N ⊔ H ≤ normal_mul_aux N H, by { rw sup_eq_closure, apply Inf_le _, dsimp, refl }) ((sup_eq_closure N H).symm ▸ subset_closure) @[to_additive] lemma mul_inf_assoc (A B C : subgroup G) (h : A ≤ C) : (A : set G) * ↑(B ⊓ C) = (A * B) ⊓ C := begin ext, simp only [coe_inf, set.inf_eq_inter, set.mem_mul, set.mem_inter_iff], split, { rintros ⟨y, z, hy, ⟨hzB, hzC⟩, rfl⟩, refine ⟨_, mul_mem C (h hy) hzC⟩, exact ⟨y, z, hy, hzB, rfl⟩ }, rintros ⟨⟨y, z, hy, hz, rfl⟩, hyz⟩, refine ⟨y, z, hy, ⟨hz, _⟩, rfl⟩, suffices : y⁻¹ * (y * z) ∈ C, { simpa }, exact mul_mem C (inv_mem C (h hy)) hyz end @[to_additive] lemma inf_mul_assoc (A B C : subgroup G) (h : C ≤ A) : ((A ⊓ B : subgroup G) : set G) * C = A ⊓ (B * C) := begin ext, simp only [coe_inf, set.inf_eq_inter, set.mem_mul, set.mem_inter_iff], split, { rintros ⟨y, z, ⟨hyA, hyB⟩, hz, rfl⟩, refine ⟨mul_mem A hyA (h hz), _⟩, exact ⟨y, z, hyB, hz, rfl⟩ }, rintros ⟨hyz, y, z, hy, hz, rfl⟩, refine ⟨y, z, ⟨_, hy⟩, hz, rfl⟩, suffices : (y * z) * z⁻¹ ∈ A, { simpa }, exact mul_mem A hyz (inv_mem A (h hz)) end end pointwise section subgroup_normal @[to_additive] lemma normal_subgroup_of_iff {H K : subgroup G} (hHK : H ≤ K) : (H.subgroup_of K).normal ↔ ∀ h k, h ∈ H → k ∈ K → k * h * k⁻¹ ∈ H := ⟨λ hN h k hH hK, hN.conj_mem ⟨h, hHK hH⟩ hH ⟨k, hK⟩, λ hN, { conj_mem := λ h hm k, (hN h.1 k.1 hm k.2) }⟩ @[to_additive] instance prod_subgroup_of_prod_normal {H₁ K₁ : subgroup G} {H₂ K₂ : subgroup N} [h₁ : (H₁.subgroup_of K₁).normal] [h₂ : (H₂.subgroup_of K₂).normal] : ((H₁.prod H₂).subgroup_of (K₁.prod K₂)).normal := { conj_mem := λ n hgHK g, ⟨h₁.conj_mem ⟨(n : G × N).fst, (mem_prod.mp n.2).1⟩ hgHK.1 ⟨(g : G × N).fst, (mem_prod.mp g.2).1⟩, h₂.conj_mem ⟨(n : G × N).snd, (mem_prod.mp n.2).2⟩ hgHK.2 ⟨(g : G × N).snd, (mem_prod.mp g.2).2⟩⟩ } @[to_additive] instance prod_normal (H : subgroup G) (K : subgroup N) [hH : H.normal] [hK : K.normal] : (H.prod K).normal := { conj_mem := λ n hg g, ⟨hH.conj_mem n.fst (subgroup.mem_prod.mp hg).1 g.fst, hK.conj_mem n.snd (subgroup.mem_prod.mp hg).2 g.snd⟩ } @[to_additive] lemma inf_subgroup_of_inf_normal_of_right (A B' B : subgroup G) (hB : B' ≤ B) [hN : (B'.subgroup_of B).normal] : ((A ⊓ B').subgroup_of (A ⊓ B)).normal := { conj_mem := λ n hn g, ⟨mul_mem A (mul_mem A (mem_inf.1 g.2).1 (mem_inf.1 n.2).1) (inv_mem A (mem_inf.1 g.2).1), (normal_subgroup_of_iff hB).mp hN n g hn.2 (mem_inf.mp g.2).2⟩ } @[to_additive] lemma inf_subgroup_of_inf_normal_of_left {A' A : subgroup G} (B : subgroup G) (hA : A' ≤ A) [hN : (A'.subgroup_of A).normal] : ((A' ⊓ B).subgroup_of (A ⊓ B)).normal := { conj_mem := λ n hn g, ⟨(normal_subgroup_of_iff hA).mp hN n g hn.1 (mem_inf.mp g.2).1, mul_mem B (mul_mem B (mem_inf.1 g.2).2 (mem_inf.1 n.2).2) (inv_mem B (mem_inf.1 g.2).2)⟩ } instance sup_normal (H K : subgroup G) [hH : H.normal] [hK : K.normal] : (H ⊔ K).normal := { conj_mem := λ n hmem g, begin change n ∈ ↑(H ⊔ K) at hmem, change g * n * g⁻¹ ∈ ↑(H ⊔ K), rw [normal_mul, set.mem_mul] at *, rcases hmem with ⟨h, k, hh, hk, rfl⟩, refine ⟨g * h * g⁻¹, g * k * g⁻¹, hH.conj_mem h hh g, hK.conj_mem k hk g, _⟩, simp end } @[to_additive] instance normal_inf_normal (H K : subgroup G) [hH : H.normal] [hK : K.normal] : (H ⊓ K).normal := { conj_mem := λ n hmem g, by { rw mem_inf at *, exact ⟨hH.conj_mem n hmem.1 g, hK.conj_mem n hmem.2 g⟩ } } @[to_additive] lemma subgroup_of_sup (A A' B : subgroup G) (hA : A ≤ B) (hA' : A' ≤ B) : (A ⊔ A').subgroup_of B = A.subgroup_of B ⊔ A'.subgroup_of B := begin refine map_injective_of_ker_le B.subtype (ker_le_comap _ _) (le_trans (ker_le_comap B.subtype _) le_sup_left) _, { simp only [subgroup_of, map_comap_eq, map_sup, subtype_range], rw [inf_of_le_right (sup_le hA hA'), inf_of_le_right hA', inf_of_le_right hA] }, end @[to_additive] lemma subgroup_normal.mem_comm {H K : subgroup G} (hK : H ≤ K) [hN : (H.subgroup_of K).normal] {a b : G} (hb : b ∈ K) (h : a * b ∈ H) : b * a ∈ H := begin have := (normal_subgroup_of_iff hK).mp hN (a * b) b h hb, rwa [mul_assoc, mul_assoc, mul_right_inv, mul_one] at this, end end subgroup_normal end subgroup namespace is_conj open subgroup lemma normal_closure_eq_top_of {N : subgroup G} [hn : N.normal] {g g' : G} {hg : g ∈ N} {hg' : g' ∈ N} (hc : is_conj g g') (ht : normal_closure ({⟨g, hg⟩} : set N) = ⊤) : normal_closure ({⟨g', hg'⟩} : set N) = ⊤ := begin obtain ⟨c, rfl⟩ := is_conj_iff.1 hc, have h : ∀ x : N, (mul_aut.conj c) x ∈ N, { rintro ⟨x, hx⟩, exact hn.conj_mem _ hx c }, have hs : function.surjective (((mul_aut.conj c).to_monoid_hom.restrict N).cod_restrict _ h), { rintro ⟨x, hx⟩, refine ⟨⟨c⁻¹ * x * c, _⟩, _⟩, { have h := hn.conj_mem _ hx c⁻¹, rwa [inv_inv] at h }, simp only [monoid_hom.cod_restrict_apply, mul_equiv.coe_to_monoid_hom, mul_aut.conj_apply, coe_mk, monoid_hom.restrict_apply, subtype.mk_eq_mk, ← mul_assoc, mul_inv_self, one_mul], rw [mul_assoc, mul_inv_self, mul_one] }, have ht' := map_mono (eq_top_iff.1 ht), rw [← monoid_hom.range_eq_map, monoid_hom.range_top_of_surjective _ hs] at ht', refine eq_top_iff.2 (le_trans ht' (map_le_iff_le_comap.2 (normal_closure_le_normal _))), rw [set.singleton_subset_iff, set_like.mem_coe], simp only [monoid_hom.cod_restrict_apply, mul_equiv.coe_to_monoid_hom, mul_aut.conj_apply, coe_mk, monoid_hom.restrict_apply, mem_comap], exact subset_normal_closure (set.mem_singleton _), end end is_conj /-! ### Actions by `subgroup`s These are just copies of the definitions about `submonoid` starting from `submonoid.mul_action`. -/ section actions namespace subgroup variables {α β : Type*} /-- The action by a subgroup is the action by the underlying group. -/ @[to_additive /-"The additive action by an add_subgroup is the action by the underlying add_group. "-/] instance [mul_action G α] (S : subgroup G) : mul_action S α := S.to_submonoid.mul_action @[to_additive] lemma smul_def [mul_action G α] {S : subgroup G} (g : S) (m : α) : g • m = (g : G) • m := rfl @[to_additive] instance smul_comm_class_left [mul_action G β] [has_scalar α β] [smul_comm_class G α β] (S : subgroup G) : smul_comm_class S α β := S.to_submonoid.smul_comm_class_left @[to_additive] instance smul_comm_class_right [has_scalar α β] [mul_action G β] [smul_comm_class α G β] (S : subgroup G) : smul_comm_class α S β := S.to_submonoid.smul_comm_class_right /-- Note that this provides `is_scalar_tower S G G` which is needed by `smul_mul_assoc`. -/ instance [has_scalar α β] [mul_action G α] [mul_action G β] [is_scalar_tower G α β] (S : subgroup G) : is_scalar_tower S α β := S.to_submonoid.is_scalar_tower instance [mul_action G α] [has_faithful_scalar G α] (S : subgroup G) : has_faithful_scalar S α := S.to_submonoid.has_faithful_scalar /-- The action by a subgroup is the action by the underlying group. -/ instance [add_monoid α] [distrib_mul_action G α] (S : subgroup G) : distrib_mul_action S α := S.to_submonoid.distrib_mul_action end subgroup end actions /-! ### Saturated subgroups -/ section saturated namespace subgroup /-- A subgroup `H` of `G` is *saturated* if for all `n : ℕ` and `g : G` with `g^n ∈ H` we have `n = 0` or `g ∈ H`. -/ @[to_additive "An additive subgroup `H` of `G` is *saturated* if for all `n : ℕ` and `g : G` with `n•g ∈ H` we have `n = 0` or `g ∈ H`."] def saturated (H : subgroup G) : Prop := ∀ ⦃n g⦄, npow n g ∈ H → n = 0 ∨ g ∈ H @[to_additive] lemma saturated_iff_npow {H : subgroup G} : saturated H ↔ (∀ (n : ℕ) (g : G), g^n ∈ H → n = 0 ∨ g ∈ H) := iff.rfl @[to_additive] lemma saturated_iff_gpow {H : subgroup G} : saturated H ↔ (∀ (n : ℤ) (g : G), g^n ∈ H → n = 0 ∨ g ∈ H) := begin split, { rintros hH ⟨n⟩ g hgn, { simp only [int.coe_nat_eq_zero, int.of_nat_eq_coe, gpow_coe_nat] at hgn ⊢, exact hH hgn }, { suffices : g ^ (n+1) ∈ H, { refine (hH this).imp _ id, simp only [forall_false_left, nat.succ_ne_zero], }, simpa only [inv_mem_iff, gpow_neg_succ_of_nat] using hgn, } }, { intros h n g hgn, specialize h n g, simp only [int.coe_nat_eq_zero, gpow_coe_nat] at h, apply h hgn } end end subgroup namespace add_subgroup lemma ker_saturated {A₁ A₂ : Type*} [add_comm_group A₁] [add_comm_group A₂] [no_zero_smul_divisors ℕ A₂] (f : A₁ →+ A₂) : (f.ker).saturated := begin intros n g hg, simpa only [f.mem_ker, nsmul_eq_smul, f.map_nsmul, smul_eq_zero] using hg end end add_subgroup end saturated
72fba5ec7c755bfc95f479ee13b2fa648f4ee7fc
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/integral/interval_integral.lean
b87b6813b61be7a90a7ea60a93c60ca9b01f9895
[ "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
129,543
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov, Patrick Massot, Sébastien Gouëzel -/ import analysis.normed_space.dual import data.set.intervals.disjoint import measure_theory.measure.haar_lebesgue import analysis.calculus.extend_deriv import measure_theory.function.locally_integrable import measure_theory.integral.set_integral import measure_theory.integral.vitali_caratheodory /-! # Integral over an interval In this file we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ` if `a ≤ b` and `-∫ x in Ioc b a, f x ∂μ` if `b ≤ a`. We prove a few simple properties and several versions of the [fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus). Recall that its first version states that the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(δu, δv) ↦ δv • f b - δu • f a` at `(a, b)` provided that `f` is continuous at `a` and `b`, and its second version states that, if `f` has an integrable derivative on `[a, b]`, then `∫ x in a..b, f' x = f b - f a`. ## Main statements ### FTC-1 for Lebesgue measure We prove several versions of FTC-1, all in the `interval_integral` namespace. Many of them follow the naming scheme `integral_has(_strict?)_(f?)deriv(_within?)_at(_of_tendsto_ae?)(_right|_left?)`. They formulate FTC in terms of `has(_strict?)_(f?)deriv(_within?)_at`. Let us explain the meaning of each part of the name: * `_strict` means that the theorem is about strict differentiability; * `f` means that the theorem is about differentiability in both endpoints; incompatible with `_right|_left`; * `_within` means that the theorem is about one-sided derivatives, see below for details; * `_of_tendsto_ae` means that instead of continuity the theorem assumes that `f` has a finite limit almost surely as `x` tends to `a` and/or `b`; * `_right` or `_left` mean that the theorem is about differentiability in the right (resp., left) endpoint. We also reformulate these theorems in terms of `(f?)deriv(_within?)`. These theorems are named `(f?)deriv(_within?)_integral(_of_tendsto_ae?)(_right|_left?)` with the same meaning of parts of the name. ### One-sided derivatives Theorem `integral_has_fderiv_within_at_of_tendsto_ae` states that `(u, v) ↦ ∫ x in u..v, f x` has a derivative `(δu, δv) ↦ δv • cb - δu • ca` within the set `s × t` at `(a, b)` provided that `f` tends to `ca` (resp., `cb`) almost surely at `la` (resp., `lb`), where possible values of `s`, `t`, and corresponding filters `la`, `lb` are given in the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` | | `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | We use a typeclass `FTC_filter` to make Lean automatically find `la`/`lb` based on `s`/`t`. This way we can formulate one theorem instead of `16` (or `8` if we leave only non-trivial ones not covered by `integral_has_deriv_within_at_of_tendsto_ae_(left|right)` and `integral_has_fderiv_at_of_tendsto_ae`). Similarly, `integral_has_deriv_within_at_of_tendsto_ae_right` works for both one-sided derivatives using the same typeclass to find an appropriate filter. ### FTC for a locally finite measure Before proving FTC for the Lebesgue measure, we prove a few statements that can be seen as FTC for any measure. The most general of them, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae`, states the following. Let `(la, la')` be an `FTC_filter` pair of filters around `a` (i.e., `FTC_filter a la la'`) and let `(lb, lb')` be an `FTC_filter` pair of filters around `b`. If `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. ### FTC-2 and corollaries We use FTC-1 to prove several versions of FTC-2 for the Lebesgue measure, using a similar naming scheme as for the versions of FTC-1. They include: * `interval_integral.integral_eq_sub_of_has_deriv_right_of_le` - most general version, for functions with a right derivative * `interval_integral.integral_eq_sub_of_has_deriv_at'` - version for functions with a derivative on an open set * `interval_integral.integral_deriv_eq_sub'` - version that is easiest to use when computing the integral of a specific function We then derive additional integration techniques from FTC-2: * `interval_integral.integral_mul_deriv_eq_deriv_mul` - integration by parts * `interval_integral.integral_comp_mul_deriv''` - integration by substitution Many applications of these theorems can be found in the file `analysis.special_functions.integrals`. Note that the assumptions of FTC-2 are formulated in the form that `f'` is integrable. To use it in a context with the stronger assumption that `f'` is continuous, one can use `continuous_on.interval_integrable` or `continuous_on.integrable_on_Icc` or `continuous_on.integrable_on_interval`. ## Implementation notes ### Avoiding `if`, `min`, and `max` In order to avoid `if`s in the definition, we define `interval_integrable f μ a b` as `integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ`. For any `a`, `b` one of these intervals is empty and the other coincides with `set.interval_oc a b = set.Ioc (min a b) (max a b)`. Similarly, we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. Again, for any `a`, `b` one of these integrals is zero, and the other gives the expected result. This way some properties can be translated from integrals over sets without dealing with the cases `a ≤ b` and `b ≤ a` separately. ### Choice of the interval We use integral over `set.interval_oc a b = set.Ioc (min a b) (max a b)` instead of one of the other three possible intervals with the same endpoints for two reasons: * this way `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` holds whenever `f` is integrable on each interval; in particular, it works even if the measure `μ` has an atom at `b`; this rules out `set.Ioo` and `set.Icc` intervals; * with this definition for a probability measure `μ`, the integral `∫ x in a..b, 1 ∂μ` equals the difference $F_μ(b)-F_μ(a)$, where $F_μ(a)=μ(-∞, a]$ is the [cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) of `μ`. ### `FTC_filter` class As explained above, many theorems in this file rely on the typeclass `FTC_filter (a : ℝ) (l l' : filter ℝ)` to avoid code duplication. This typeclass combines four assumptions: - `pure a ≤ l`; - `l' ≤ 𝓝 a`; - `l'` has a basis of measurable sets; - if `u n` and `v n` tend to `l`, then for any `s ∈ l'`, `Ioc (u n) (v n)` is eventually included in `s`. This typeclass has the following “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[≥] a, 𝓝[>] a)`, `(a, 𝓝[≤] a, 𝓝[≤] a)`, `(a, 𝓝 a, 𝓝 a)`. Furthermore, we have the following instances that are equal to the previously mentioned instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. While the difference between `Ici a` and `Ioi a` doesn't matter for theorems about Lebesgue measure, it becomes important in the versions of FTC about any locally finite measure if this measure has an atom at one of the endpoints. ### Combining one-sided and two-sided derivatives There are some `FTC_filter` instances where the fact that it is one-sided or two-sided depends on the point, namely `(x, 𝓝[Icc a b] x, 𝓝[Icc a b] x)` (resp. `(x, 𝓝[[a, b]] x, 𝓝[[a, b]] x)`, where `[a, b] = set.interval a b`), with `x ∈ Icc a b` (resp. `x ∈ [a, b]`). This results in a two-sided derivatives for `x ∈ Ioo a b` and one-sided derivatives for `x ∈ {a, b}`. Other instances could be added when needed (in that case, one also needs to add instances for `filter.is_measurably_generated` and `filter.tendsto_Ixx_class`). ## Tags integral, fundamental theorem of calculus, FTC-1, FTC-2, change of variables in integrals -/ noncomputable theory open topological_space (second_countable_topology) open measure_theory set classical filter function open_locale classical topological_space filter ennreal big_operators interval variables {ι 𝕜 E F : Type*} [normed_group E] /-! ### Integrability at an interval -/ /-- A function `f` is called *interval integrable* with respect to a measure `μ` on an unordered interval `a..b` if it is integrable on both intervals `(a, b]` and `(b, a]`. One of these intervals is always empty, so this property is equivalent to `f` being integrable on `(min a b, max a b]`. -/ def interval_integrable (f : ℝ → E) (μ : measure ℝ) (a b : ℝ) := integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ section variables {f : ℝ → E} {a b : ℝ} {μ : measure ℝ} /-- A function is interval integrable with respect to a given measure `μ` on `a..b` if and only if it is integrable on `interval_oc a b` with respect to `μ`. This is an equivalent defintion of `interval_integrable`. -/ lemma interval_integrable_iff : interval_integrable f μ a b ↔ integrable_on f (Ι a b) μ := by rw [interval_oc_eq_union, integrable_on_union, interval_integrable] /-- If a function is interval integrable with respect to a given measure `μ` on `a..b` then it is integrable on `interval_oc a b` with respect to `μ`. -/ lemma interval_integrable.def (h : interval_integrable f μ a b) : integrable_on f (Ι a b) μ := interval_integrable_iff.mp h lemma interval_integrable_iff_integrable_Ioc_of_le (hab : a ≤ b) : interval_integrable f μ a b ↔ integrable_on f (Ioc a b) μ := by rw [interval_integrable_iff, interval_oc_of_le hab] /-- If a function is integrable with respect to a given measure `μ` then it is interval integrable with respect to `μ` on `interval a b`. -/ lemma measure_theory.integrable.interval_integrable (hf : integrable f μ) : interval_integrable f μ a b := ⟨hf.integrable_on, hf.integrable_on⟩ lemma measure_theory.integrable_on.interval_integrable (hf : integrable_on f [a, b] μ) : interval_integrable f μ a b := ⟨measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_interval), measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_interval')⟩ lemma interval_integrable_const_iff {c : E} : interval_integrable (λ _, c) μ a b ↔ c = 0 ∨ μ (Ι a b) < ∞ := by simp only [interval_integrable_iff, integrable_on_const] @[simp] lemma interval_integrable_const [is_locally_finite_measure μ] {c : E} : interval_integrable (λ _, c) μ a b := interval_integrable_const_iff.2 $ or.inr measure_Ioc_lt_top end namespace interval_integrable section variables {f : ℝ → E} {a b c d : ℝ} {μ ν : measure ℝ} @[symm] lemma symm (h : interval_integrable f μ a b) : interval_integrable f μ b a := h.symm @[refl] lemma refl : interval_integrable f μ a a := by split; simp @[trans] lemma trans {a b c : ℝ} (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : interval_integrable f μ a c := ⟨(hab.1.union hbc.1).mono_set Ioc_subset_Ioc_union_Ioc, (hbc.2.union hab.2).mono_set Ioc_subset_Ioc_union_Ioc⟩ lemma trans_iterate_Ico {a : ℕ → ℝ} {m n : ℕ} (hmn : m ≤ n) (hint : ∀ k ∈ Ico m n, interval_integrable f μ (a k) (a $ k+1)) : interval_integrable f μ (a m) (a n) := begin revert hint, refine nat.le_induction _ _ n hmn, { simp }, { assume p hp IH h, exact (IH (λ k hk, h k (Ico_subset_Ico_right p.le_succ hk))).trans (h p (by simp [hp])) } end lemma trans_iterate {a : ℕ → ℝ} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : interval_integrable f μ (a 0) (a n) := trans_iterate_Ico bot_le (λ k hk, hint k hk.2) lemma neg (h : interval_integrable f μ a b) : interval_integrable (-f) μ a b := ⟨h.1.neg, h.2.neg⟩ lemma norm (h : interval_integrable f μ a b) : interval_integrable (λ x, ∥f x∥) μ a b := ⟨h.1.norm, h.2.norm⟩ lemma abs {f : ℝ → ℝ} (h : interval_integrable f μ a b) : interval_integrable (λ x, |f x|) μ a b := h.norm lemma mono (hf : interval_integrable f ν a b) (h1 : [c, d] ⊆ [a, b]) (h2 : μ ≤ ν) : interval_integrable f μ c d := interval_integrable_iff.mpr $ hf.def.mono (interval_oc_subset_interval_oc_of_interval_subset_interval h1) h2 lemma mono_set (hf : interval_integrable f μ a b) (h : [c, d] ⊆ [a, b]) : interval_integrable f μ c d := hf.mono h rfl.le lemma mono_measure (hf : interval_integrable f ν a b) (h : μ ≤ ν) : interval_integrable f μ a b := hf.mono rfl.subset h lemma mono_set_ae (hf : interval_integrable f μ a b) (h : Ι c d ≤ᵐ[μ] Ι a b) : interval_integrable f μ c d := interval_integrable_iff.mpr $ hf.def.mono_set_ae h lemma mono_fun [normed_group F] {g : ℝ → F} (hf : interval_integrable f μ a b) (hgm : ae_strongly_measurable g (μ.restrict (Ι a b))) (hle : (λ x, ∥g x∥) ≤ᵐ[μ.restrict (Ι a b)] (λ x, ∥f x∥)) : interval_integrable g μ a b := interval_integrable_iff.2 $ hf.def.integrable.mono hgm hle lemma mono_fun' {g : ℝ → ℝ} (hg : interval_integrable g μ a b) (hfm : ae_strongly_measurable f (μ.restrict (Ι a b))) (hle : (λ x, ∥f x∥) ≤ᵐ[μ.restrict (Ι a b)] g) : interval_integrable f μ a b := interval_integrable_iff.2 $ hg.def.integrable.mono' hfm hle protected lemma ae_strongly_measurable (h : interval_integrable f μ a b) : ae_strongly_measurable f (μ.restrict (Ioc a b)):= h.1.ae_strongly_measurable protected lemma ae_strongly_measurable' (h : interval_integrable f μ a b) : ae_strongly_measurable f (μ.restrict (Ioc b a)):= h.2.ae_strongly_measurable end variables {f g : ℝ → E} {a b : ℝ} {μ : measure ℝ} lemma smul [normed_field 𝕜] [normed_space 𝕜 E] {f : ℝ → E} {a b : ℝ} {μ : measure ℝ} (h : interval_integrable f μ a b) (r : 𝕜) : interval_integrable (r • f) μ a b := ⟨h.1.smul r, h.2.smul r⟩ @[simp] lemma add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x + g x) μ a b := ⟨hf.1.add hg.1, hf.2.add hg.2⟩ @[simp] lemma sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : interval_integrable (λ x, f x - g x) μ a b := ⟨hf.1.sub hg.1, hf.2.sub hg.2⟩ lemma mul_continuous_on {f g : ℝ → ℝ} (hf : interval_integrable f μ a b) (hg : continuous_on g [a, b]) : interval_integrable (λ x, f x * g x) μ a b := begin rw interval_integrable_iff at hf ⊢, exact hf.mul_continuous_on_of_subset hg measurable_set_Ioc is_compact_interval Ioc_subset_Icc_self end lemma continuous_on_mul {f g : ℝ → ℝ} (hf : interval_integrable f μ a b) (hg : continuous_on g [a, b]) : interval_integrable (λ x, g x * f x) μ a b := by simpa [mul_comm] using hf.mul_continuous_on hg end interval_integrable section variables {μ : measure ℝ} [is_locally_finite_measure μ] lemma continuous_on.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : continuous_on u (interval a b)) : interval_integrable u μ a b := (continuous_on.integrable_on_Icc hu).interval_integrable lemma continuous_on.interval_integrable_of_Icc {u : ℝ → E} {a b : ℝ} (h : a ≤ b) (hu : continuous_on u (Icc a b)) : interval_integrable u μ a b := continuous_on.interval_integrable ((interval_of_le h).symm ▸ hu) /-- A continuous function on `ℝ` is `interval_integrable` with respect to any locally finite measure `ν` on ℝ. -/ lemma continuous.interval_integrable {u : ℝ → E} (hu : continuous u) (a b : ℝ) : interval_integrable u μ a b := hu.continuous_on.interval_integrable end section variables {μ : measure ℝ} [is_locally_finite_measure μ] [conditionally_complete_linear_order E] [order_topology E] [second_countable_topology E] lemma monotone_on.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : monotone_on u (interval a b)) : interval_integrable u μ a b := begin rw interval_integrable_iff, exact (hu.integrable_on_compact is_compact_interval).mono_set Ioc_subset_Icc_self, end lemma antitone_on.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : antitone_on u (interval a b)) : interval_integrable u μ a b := hu.dual_right.interval_integrable lemma monotone.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : monotone u) : interval_integrable u μ a b := (hu.monotone_on _).interval_integrable lemma antitone.interval_integrable {u : ℝ → E} {a b : ℝ} (hu : antitone u) : interval_integrable u μ a b := (hu.antitone_on _).interval_integrable end /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : ℝ → E` has a finite limit at `l' ⊓ μ.ae`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter ℝ` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable_ae {f : ℝ → E} {μ : measure ℝ} {l l' : filter ℝ} (hfm : strongly_measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) {u v : ι → ℝ} {lt : filter ι} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := have _ := (hf.integrable_at_filter_ae hfm hμ).eventually, ((hu.Ioc hv).eventually this).and $ (hv.Ioc hu).eventually this /-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'` eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`. Suppose that `f : ℝ → E` has a finite limit at `l`. Then `f` is interval integrable on `u..v` provided that both `u` and `v` tend to `l`. Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so `apply tendsto.eventually_interval_integrable_ae` will generate goals `filter ℝ` and `tendsto_Ixx_class Ioc ?m_1 l'`. -/ lemma filter.tendsto.eventually_interval_integrable {f : ℝ → E} {μ : measure ℝ} {l l' : filter ℝ} (hfm : strongly_measurable_at_filter f l' μ) [tendsto_Ixx_class Ioc l l'] [is_measurably_generated l'] (hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f l' (𝓝 c)) {u v : ι → ℝ} {lt : filter ι} (hu : tendsto u lt l) (hv : tendsto v lt l) : ∀ᶠ t in lt, interval_integrable f μ (u t) (v t) := (hf.mono_left inf_le_left).eventually_interval_integrable_ae hfm hμ hu hv /-! ### Interval integral: definition and basic properties In this section we define `∫ x in a..b, f x ∂μ` as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ` and prove some basic properties. -/ variables [complete_space E] [normed_space ℝ E] /-- The interval integral `∫ x in a..b, f x ∂μ` is defined as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. If `a ≤ b`, then it equals `∫ x in Ioc a b, f x ∂μ`, otherwise it equals `-∫ x in Ioc b a, f x ∂μ`. -/ def interval_integral (f : ℝ → E) (a b : ℝ) (μ : measure ℝ) := ∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, f) ` ∂` μ:70 := interval_integral r a b μ notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, interval_integral f a b volume) := r namespace interval_integral section basic variables {a b : ℝ} {f g : ℝ → E} {μ : measure ℝ} @[simp] lemma integral_zero : ∫ x in a..b, (0 : E) ∂μ = 0 := by simp [interval_integral] lemma integral_of_le (h : a ≤ b) : ∫ x in a..b, f x ∂μ = ∫ x in Ioc a b, f x ∂μ := by simp [interval_integral, h] @[simp] lemma integral_same : ∫ x in a..a, f x ∂μ = 0 := sub_self _ lemma integral_symm (a b) : ∫ x in b..a, f x ∂μ = -∫ x in a..b, f x ∂μ := by simp only [interval_integral, neg_sub] lemma integral_of_ge (h : b ≤ a) : ∫ x in a..b, f x ∂μ = -∫ x in Ioc b a, f x ∂μ := by simp only [integral_symm b, integral_of_le h] lemma interval_integral_eq_integral_interval_oc (f : ℝ → E) (a b : ℝ) (μ : measure ℝ) : ∫ x in a..b, f x ∂μ = (if a ≤ b then 1 else -1 : ℝ) • ∫ x in Ι a b, f x ∂μ := begin split_ifs with h, { simp only [integral_of_le h, interval_oc_of_le h, one_smul] }, { simp only [integral_of_ge (not_le.1 h).le, interval_oc_of_lt (not_le.1 h), neg_one_smul] } end lemma integral_cases (f : ℝ → E) (a b) : ∫ x in a..b, f x ∂μ ∈ ({∫ x in Ι a b, f x ∂μ, -∫ x in Ι a b, f x ∂μ} : set E) := by { rw interval_integral_eq_integral_interval_oc, split_ifs; simp } lemma integral_undef (h : ¬ interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 := by cases le_total a b with hab hab; simp only [integral_of_le, integral_of_ge, hab, neg_eq_zero]; refine integral_undef (not_imp_not.mpr integrable.integrable_on' _); simpa [hab] using not_and_distrib.mp h lemma integral_non_ae_strongly_measurable (hf : ¬ ae_strongly_measurable f (μ.restrict (Ι a b))) : ∫ x in a..b, f x ∂μ = 0 := by rw [interval_integral_eq_integral_interval_oc, integral_non_ae_strongly_measurable hf, smul_zero] lemma integral_non_ae_strongly_measurable_of_le (h : a ≤ b) (hf : ¬ ae_strongly_measurable f (μ.restrict (Ioc a b))) : ∫ x in a..b, f x ∂μ = 0 := integral_non_ae_strongly_measurable $ by rwa [interval_oc_of_le h] lemma norm_integral_min_max (f : ℝ → E) : ∥∫ x in min a b..max a b, f x ∂μ∥ = ∥∫ x in a..b, f x ∂μ∥ := by cases le_total a b; simp [*, integral_symm a b] lemma norm_integral_eq_norm_integral_Ioc (f : ℝ → E) : ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ι a b, f x ∂μ∥ := by rw [← norm_integral_min_max, integral_of_le min_le_max, interval_oc] lemma abs_integral_eq_abs_integral_interval_oc (f : ℝ → ℝ) : |∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| := norm_integral_eq_norm_integral_Ioc f lemma norm_integral_le_integral_norm_Ioc : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in Ι a b, ∥f x∥ ∂μ := calc ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ι a b, f x ∂μ∥ : norm_integral_eq_norm_integral_Ioc f ... ≤ ∫ x in Ι a b, ∥f x∥ ∂μ : norm_integral_le_integral_norm f lemma norm_integral_le_abs_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ |∫ x in a..b, ∥f x∥ ∂μ| := begin simp only [← real.norm_eq_abs, norm_integral_eq_norm_integral_Ioc], exact le_trans (norm_integral_le_integral_norm _) (le_abs_self _) end lemma norm_integral_le_integral_norm (h : a ≤ b) : ∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in a..b, ∥f x∥ ∂μ := norm_integral_le_integral_norm_Ioc.trans_eq $ by rw [interval_oc_of_le h, integral_of_le h] lemma norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E} (h : ∀ᵐ x, x ∈ Ι a b → ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * |b - a| := begin rw [norm_integral_eq_norm_integral_Ioc], convert norm_set_integral_le_of_norm_le_const_ae'' _ measurable_set_Ioc h, { rw [real.volume_Ioc, max_sub_min_eq_abs, ennreal.to_real_of_real (abs_nonneg _)] }, { simp only [real.volume_Ioc, ennreal.of_real_lt_top] }, end lemma norm_integral_le_of_norm_le_const {a b C : ℝ} {f : ℝ → E} (h : ∀ x ∈ Ι a b, ∥f x∥ ≤ C) : ∥∫ x in a..b, f x∥ ≤ C * |b - a| := norm_integral_le_of_norm_le_const_ae $ eventually_of_forall h @[simp] lemma integral_add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x + g x ∂μ = ∫ x in a..b, f x ∂μ + ∫ x in a..b, g x ∂μ := by simp only [interval_integral_eq_integral_interval_oc, integral_add hf.def hg.def, smul_add] lemma integral_finset_sum {ι} {s : finset ι} {f : ι → ℝ → E} (h : ∀ i ∈ s, interval_integrable (f i) μ a b) : ∫ x in a..b, ∑ i in s, f i x ∂μ = ∑ i in s, ∫ x in a..b, f i x ∂μ := by simp only [interval_integral_eq_integral_interval_oc, integral_finset_sum s (λ i hi, (h i hi).def), finset.smul_sum] @[simp] lemma integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ := by { simp only [interval_integral, integral_neg], abel } @[simp] lemma integral_sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) : ∫ x in a..b, f x - g x ∂μ = ∫ x in a..b, f x ∂μ - ∫ x in a..b, g x ∂μ := by simpa only [sub_eq_add_neg] using (integral_add hf hg.neg).trans (congr_arg _ integral_neg) @[simp] lemma integral_smul {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] (r : 𝕜) (f : ℝ → E) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, integral_smul, smul_sub] @[simp] lemma integral_smul_const {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] (f : ℝ → 𝕜) (c : E) : ∫ x in a..b, f x • c ∂μ = (∫ x in a..b, f x ∂μ) • c := by simp only [interval_integral_eq_integral_interval_oc, integral_smul_const, smul_assoc] @[simp] lemma integral_const_mul {𝕜 : Type*} [is_R_or_C 𝕜] (r : 𝕜) (f : ℝ → 𝕜) : ∫ x in a..b, r * f x ∂μ = r * ∫ x in a..b, f x ∂μ := integral_smul r f @[simp] lemma integral_mul_const {𝕜 : Type*} [is_R_or_C 𝕜] (r : 𝕜) (f : ℝ → 𝕜) : ∫ x in a..b, f x * r ∂μ = ∫ x in a..b, f x ∂μ * r := by simpa only [mul_comm r] using integral_const_mul r f @[simp] lemma integral_div {𝕜 : Type*} [is_R_or_C 𝕜] (r : 𝕜) (f : ℝ → 𝕜) : ∫ x in a..b, f x / r ∂μ = ∫ x in a..b, f x ∂μ / r := by simpa only [div_eq_mul_inv] using integral_mul_const r⁻¹ f lemma integral_const' (c : E) : ∫ x in a..b, c ∂μ = ((μ $ Ioc a b).to_real - (μ $ Ioc b a).to_real) • c := by simp only [interval_integral, set_integral_const, sub_smul] @[simp] lemma integral_const (c : E) : ∫ x in a..b, c = (b - a) • c := by simp only [integral_const', real.volume_Ioc, ennreal.to_real_of_real', ← neg_sub b, max_zero_sub_eq_self] lemma integral_smul_measure (c : ℝ≥0∞) : ∫ x in a..b, f x ∂(c • μ) = c.to_real • ∫ x in a..b, f x ∂μ := by simp only [interval_integral, measure.restrict_smul, integral_smul_measure, smul_sub] variables [normed_group F] [complete_space F] [normed_space ℝ F] lemma _root_.continuous_linear_map.interval_integral_comp_comm (L : E →L[ℝ] F) (hf : interval_integrable f μ a b) : ∫ x in a..b, L (f x) ∂μ = L (∫ x in a..b, f x ∂μ) := begin rw [interval_integral, interval_integral, L.integral_comp_comm, L.integral_comp_comm, L.map_sub], exacts [hf.2, hf.1] end end basic section comp variables {a b c d : ℝ} (f : ℝ → E) @[simp] lemma integral_comp_mul_right (hc : c ≠ 0) : ∫ x in a..b, f (x * c) = c⁻¹ • ∫ x in a*c..b*c, f x := begin have A : measurable_embedding (λ x, x * c) := (homeomorph.mul_right₀ c hc).closed_embedding.measurable_embedding, conv_rhs { rw [← real.smul_map_volume_mul_right hc] }, simp_rw [integral_smul_measure, interval_integral, A.set_integral_map, ennreal.to_real_of_real (abs_nonneg c)], cases hc.lt_or_lt, { simp [h, mul_div_cancel, hc, abs_of_neg, measure.restrict_congr_set Ico_ae_eq_Ioc] }, { simp [h, mul_div_cancel, hc, abs_of_pos] } end @[simp] lemma smul_integral_comp_mul_right (c) : c • ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_left (hc : c ≠ 0) : ∫ x in a..b, f (c * x) = c⁻¹ • ∫ x in c*a..c*b, f x := by simpa only [mul_comm c] using integral_comp_mul_right f hc @[simp] lemma smul_integral_comp_mul_left (c) : c • ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div (hc : c ≠ 0) : ∫ x in a..b, f (x / c) = c • ∫ x in a/c..b/c, f x := by simpa only [inv_inv] using integral_comp_mul_right f (inv_ne_zero hc) @[simp] lemma inv_smul_integral_comp_div (c) : c⁻¹ • ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_right (d) : ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x := have A : measurable_embedding (λ x, x + d) := (homeomorph.add_right d).closed_embedding.measurable_embedding, calc ∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x ∂(measure.map (λ x, x + d) volume) : by simp [interval_integral, A.set_integral_map] ... = ∫ x in a+d..b+d, f x : by rw [map_add_right_eq_self] @[simp] lemma integral_comp_add_left (d) : ∫ x in a..b, f (d + x) = ∫ x in d+a..d+b, f x := by simpa only [add_comm] using integral_comp_add_right f d @[simp] lemma integral_comp_mul_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x + d) = c⁻¹ • ∫ x in c*a+d..c*b+d, f x := by rw [← integral_comp_add_right, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_mul_add (c d) : c • ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + c * x) = c⁻¹ • ∫ x in d+c*a..d+c*b, f x := by rw [← integral_comp_add_left, ← integral_comp_mul_left _ hc] @[simp] lemma smul_integral_comp_add_mul (c d) : c • ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_add (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c + d) = c • ∫ x in a/c+d..b/c+d, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_mul_add f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_add (c d) : c⁻¹ • ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_add_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d + x / c) = c • ∫ x in d+a/c..d+b/c, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_add_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_add_div (c d) : c⁻¹ • ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_mul_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (c * x - d) = c⁻¹ • ∫ x in c*a-d..c*b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_mul_add f hc (-d) @[simp] lemma smul_integral_comp_mul_sub (c d) : c • ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_mul (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - c * x) = c⁻¹ • ∫ x in d-c*b..d-c*a, f x := begin simp only [sub_eq_add_neg, neg_mul_eq_neg_mul], rw [integral_comp_add_mul f (neg_ne_zero.mpr hc) d, integral_symm], simp only [inv_neg, smul_neg, neg_neg, neg_smul], end @[simp] lemma smul_integral_comp_sub_mul (c d) : c • ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_div_sub (hc : c ≠ 0) (d) : ∫ x in a..b, f (x / c - d) = c • ∫ x in a/c-d..b/c-d, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_mul_sub f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_div_sub (c d) : c⁻¹ • ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_div (hc : c ≠ 0) (d) : ∫ x in a..b, f (d - x / c) = c • ∫ x in d-b/c..d-a/c, f x := by simpa only [div_eq_inv_mul, inv_inv] using integral_comp_sub_mul f (inv_ne_zero hc) d @[simp] lemma inv_smul_integral_comp_sub_div (c d) : c⁻¹ • ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x := by by_cases hc : c = 0; simp [hc] @[simp] lemma integral_comp_sub_right (d) : ∫ x in a..b, f (x - d) = ∫ x in a-d..b-d, f x := by simpa only [sub_eq_add_neg] using integral_comp_add_right f (-d) @[simp] lemma integral_comp_sub_left (d) : ∫ x in a..b, f (d - x) = ∫ x in d-b..d-a, f x := by simpa only [one_mul, one_smul, inv_one] using integral_comp_sub_mul f one_ne_zero d @[simp] lemma integral_comp_neg : ∫ x in a..b, f (-x) = ∫ x in -b..-a, f x := by simpa only [zero_sub] using integral_comp_sub_left f 0 end comp /-! ### Integral is an additive function of the interval In this section we prove that `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` as well as a few other identities trivially equivalent to this one. We also prove that `∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ` provided that `support f ⊆ Ioc a b`. -/ section order_closed_topology variables {a b c d : ℝ} {f g : ℝ → E} {μ : measure ℝ} lemma integrable_on_Icc_iff_integrable_on_Ioc' {E : Type*} [normed_group E] {f : ℝ → E} {a b : ℝ} (ha : μ {a} ≠ ∞) : integrable_on f (Icc a b) μ ↔ integrable_on f (Ioc a b) μ := begin cases le_or_lt a b with hab hab, { have : Icc a b = Icc a a ∪ Ioc a b := (Icc_union_Ioc_eq_Icc le_rfl hab).symm, rw [this, integrable_on_union], simp [ha.lt_top] }, { simp [hab, hab.le] }, end lemma integrable_on_Icc_iff_integrable_on_Ioc {E : Type*}[normed_group E] [has_no_atoms μ] {f : ℝ → E} {a b : ℝ} : integrable_on f (Icc a b) μ ↔ integrable_on f (Ioc a b) μ := integrable_on_Icc_iff_integrable_on_Ioc' (by simp) lemma interval_integrable_iff_integrable_Icc_of_le {E : Type*} [normed_group E] {f : ℝ → E} {a b : ℝ} (hab : a ≤ b) {μ : measure ℝ} [has_no_atoms μ] : interval_integrable f μ a b ↔ integrable_on f (Icc a b) μ := by rw [interval_integrable_iff_integrable_Ioc_of_le hab, integrable_on_Icc_iff_integrable_on_Ioc] /-- If two functions are equal in the relevant interval, their interval integrals are also equal. -/ lemma integral_congr {a b : ℝ} (h : eq_on f g [a, b]) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := by cases le_total a b with hab hab; simpa [hab, integral_of_le, integral_of_ge] using set_integral_congr measurable_set_Ioc (h.mono Ioc_subset_Icc_self) lemma integral_add_adjacent_intervals_cancel (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ + ∫ x in c..a, f x ∂μ = 0 := begin have hac := hab.trans hbc, simp only [interval_integral, sub_add_sub_comm, sub_eq_zero], iterate 4 { rw ← integral_union }, { suffices : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc b a ∪ Ioc c b ∪ Ioc a c, by rw this, rw [Ioc_union_Ioc_union_Ioc_cycle, union_right_comm, Ioc_union_Ioc_union_Ioc_cycle, min_left_comm, max_left_comm] }, all_goals { simp [*, measurable_set.union, measurable_set_Ioc, Ioc_disjoint_Ioc_same, Ioc_disjoint_Ioc_same.symm, hab.1, hab.2, hbc.1, hbc.2, hac.1, hac.2] } end lemma integral_add_adjacent_intervals (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) : ∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ := by rw [← add_neg_eq_zero, ← integral_symm, integral_add_adjacent_intervals_cancel hab hbc] lemma sum_integral_adjacent_intervals_Ico {a : ℕ → ℝ} {m n : ℕ} (hmn : m ≤ n) (hint : ∀ k ∈ Ico m n, interval_integrable f μ (a k) (a $ k+1)) : ∑ (k : ℕ) in finset.Ico m n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a m)..(a n), f x ∂μ := begin revert hint, refine nat.le_induction _ _ n hmn, { simp }, { assume p hmp IH h, rw [finset.sum_Ico_succ_top hmp, IH, integral_add_adjacent_intervals], { apply interval_integrable.trans_iterate_Ico hmp (λ k hk, h k _), exact (Ico_subset_Ico le_rfl (nat.le_succ _)) hk }, { apply h, simp [hmp] }, { assume k hk, exact h _ (Ico_subset_Ico_right p.le_succ hk) } } end lemma sum_integral_adjacent_intervals {a : ℕ → ℝ} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) : ∑ (k : ℕ) in finset.range n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a 0)..(a n), f x ∂μ := begin rw ← nat.Ico_zero_eq_range, exact sum_integral_adjacent_intervals_Ico (zero_le n) (λ k hk, hint k hk.2), end lemma integral_interval_sub_left (hab : interval_integrable f μ a b) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in a..c, f x ∂μ = ∫ x in c..b, f x ∂μ := sub_eq_of_eq_add' $ eq.symm $ integral_add_adjacent_intervals hac (hac.symm.trans hab) lemma integral_interval_add_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ + ∫ x in c..d, f x ∂μ = ∫ x in a..d, f x ∂μ + ∫ x in c..b, f x ∂μ := by rw [← integral_add_adjacent_intervals hac hcd, add_assoc, add_left_comm, integral_add_adjacent_intervals hac (hac.symm.trans hab), add_comm] lemma integral_interval_sub_interval_comm (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in a..c, f x ∂μ - ∫ x in b..d, f x ∂μ := by simp only [sub_eq_add_neg, ← integral_symm, integral_interval_add_interval_comm hab hcd.symm (hac.trans hcd)] lemma integral_interval_sub_interval_comm' (hab : interval_integrable f μ a b) (hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) : ∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in d..b, f x ∂μ - ∫ x in c..a, f x ∂μ := by { rw [integral_interval_sub_interval_comm hab hcd hac, integral_symm b d, integral_symm a c, sub_neg_eq_add, sub_eq_neg_add], } lemma integral_Iic_sub_Iic (ha : integrable_on f (Iic a) μ) (hb : integrable_on f (Iic b) μ) : ∫ x in Iic b, f x ∂μ - ∫ x in Iic a, f x ∂μ = ∫ x in a..b, f x ∂μ := begin wlog hab : a ≤ b using [a b] tactic.skip, { rw [sub_eq_iff_eq_add', integral_of_le hab, ← integral_union (Iic_disjoint_Ioc le_rfl), Iic_union_Ioc_eq_Iic hab], exacts [measurable_set_Ioc, ha, hb.mono_set (λ _, and.right)] }, { intros ha hb, rw [integral_symm, ← this hb ha, neg_sub] } end /-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/ lemma integral_const_of_cdf [is_finite_measure μ] (c : E) : ∫ x in a..b, c ∂μ = ((μ (Iic b)).to_real - (μ (Iic a)).to_real) • c := begin simp only [sub_smul, ← set_integral_const], refine (integral_Iic_sub_Iic _ _).symm; simp only [integrable_on_const, measure_lt_top, or_true] end lemma integral_eq_integral_of_support_subset {a b} (h : support f ⊆ Ioc a b) : ∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ := begin cases le_total a b with hab hab, { rw [integral_of_le hab, ← integral_indicator measurable_set_Ioc, indicator_eq_self.2 h]; apply_instance }, { rw [Ioc_eq_empty hab.not_lt, subset_empty_iff, support_eq_empty_iff] at h, simp [h] } end lemma integral_congr_ae' (h : ∀ᵐ x ∂μ, x ∈ Ioc a b → f x = g x) (h' : ∀ᵐ x ∂μ, x ∈ Ioc b a → f x = g x) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := by simp only [interval_integral, set_integral_congr_ae (measurable_set_Ioc) h, set_integral_congr_ae (measurable_set_Ioc) h'] lemma integral_congr_ae (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = g x) : ∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ := integral_congr_ae' (ae_interval_oc_iff.mp h).1 (ae_interval_oc_iff.mp h).2 lemma integral_zero_ae (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = 0) : ∫ x in a..b, f x ∂μ = 0 := calc ∫ x in a..b, f x ∂μ = ∫ x in a..b, 0 ∂μ : integral_congr_ae h ... = 0 : integral_zero lemma integral_indicator {a₁ a₂ a₃ : ℝ} (h : a₂ ∈ Icc a₁ a₃) : ∫ x in a₁..a₃, indicator {x | x ≤ a₂} f x ∂ μ = ∫ x in a₁..a₂, f x ∂ μ := begin have : {x | x ≤ a₂} ∩ Ioc a₁ a₃ = Ioc a₁ a₂, from Iic_inter_Ioc_of_le h.2, rw [integral_of_le h.1, integral_of_le (h.1.trans h.2), integral_indicator, measure.restrict_restrict, this], exact measurable_set_Iic, all_goals { apply measurable_set_Iic }, 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} (bound : ℝ → ℝ) (hF_meas : ∀ᶠ n in l, ae_strongly_measurable (F n) (μ.restrict (Ι a b))) (h_bound : ∀ᶠ n in l, ∀ᵐ x ∂μ, x ∈ Ι a b → ∥F n x∥ ≤ bound x) (bound_integrable : interval_integrable bound μ a b) (h_lim : ∀ᵐ x ∂μ, x ∈ Ι a b → tendsto (λ n, F n x) l (𝓝 (f x))) : tendsto (λn, ∫ x in a..b, F n x ∂μ) l (𝓝 $ ∫ x in a..b, f x ∂μ) := begin simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc, ← ae_restrict_iff' measurable_set_interval_oc] at *, exact tendsto_const_nhds.smul (tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_lim) end /-- Lebesgue dominated convergence theorem for series. -/ lemma has_sum_integral_of_dominated_convergence {ι} [encodable ι] {F : ι → ℝ → E} (bound : ι → ℝ → ℝ) (hF_meas : ∀ n, ae_strongly_measurable (F n) (μ.restrict (Ι a b))) (h_bound : ∀ n, ∀ᵐ t ∂μ, t ∈ Ι a b → ∥F n t∥ ≤ bound n t) (bound_summable : ∀ᵐ t ∂μ, t ∈ Ι a b → summable (λ n, bound n t)) (bound_integrable : interval_integrable (λ t, ∑' n, bound n t) μ a b) (h_lim : ∀ᵐ t ∂μ, t ∈ Ι a b → has_sum (λ n, F n t) (f t)) : has_sum (λn, ∫ t in a..b, F n t ∂μ) (∫ t in a..b, f t ∂μ) := begin simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc, ← ae_restrict_iff' measurable_set_interval_oc] at *, exact (has_sum_integral_of_dominated_convergence bound hF_meas h_bound bound_summable bound_integrable h_lim).const_smul end open topological_space variables {X : Type*} [topological_space X] [first_countable_topology X] /-- Continuity of interval integral with respect to a parameter, at a point within a set. Given `F : X → ℝ → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀` within `s` and at `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀` within `s`. If `(λ x, F x t)` is continuous at `x₀` within `s` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_within_at_of_dominated_interval {F : X → ℝ → E} {x₀ : X} {bound : ℝ → ℝ} {a b : ℝ} {s : set X} (hF_meas : ∀ᶠ x in 𝓝[s] x₀, ae_strongly_measurable (F x) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝[s] x₀, ∀ᵐ t ∂μ, t ∈ Ι a b → ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous_within_at (λ x, F x t) s x₀) : continuous_within_at (λ x, ∫ t in a..b, F x t ∂μ) s x₀ := tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_cont /-- Continuity of interval integral with respect to a parameter at a point. Given `F : X → ℝ → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a neighborhood of `x₀`, and assume it is bounded by a function integrable on `[a, b]` independent of `x` in a neighborhood of `x₀`. If `(λ x, F x t)` is continuous at `x₀` for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_at_of_dominated_interval {F : X → ℝ → E} {x₀ : X} {bound : ℝ → ℝ} {a b : ℝ} (hF_meas : ∀ᶠ x in 𝓝 x₀, ae_strongly_measurable (F x) (μ.restrict $ Ι a b)) (h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ t ∂μ, t ∈ Ι a b → ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous_at (λ x, F x t) x₀) : continuous_at (λ x, ∫ t in a..b, F x t ∂μ) x₀ := tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_cont /-- Continuity of interval integral with respect to a parameter. Given `F : X → ℝ → E`, assume each `F x` is ae-measurable on `[a, b]`, and assume it is bounded by a function integrable on `[a, b]` independent of `x`. If `(λ x, F x t)` is continuous for almost every `t` in `[a, b]` then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/ lemma continuous_of_dominated_interval {F : X → ℝ → E} {bound : ℝ → ℝ} {a b : ℝ} (hF_meas : ∀ x, ae_strongly_measurable (F x) $ μ.restrict $ Ι a b) (h_bound : ∀ x, ∀ᵐ t ∂μ, t ∈ Ι a b → ∥F x t∥ ≤ bound t) (bound_integrable : interval_integrable bound μ a b) (h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous (λ x, F x t)) : continuous (λ x, ∫ t in a..b, F x t ∂μ) := continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated_interval (eventually_of_forall hF_meas) (eventually_of_forall h_bound) bound_integrable $ h_cont.mono $ λ x himp hx, (himp hx).continuous_at) end order_closed_topology section continuous_primitive open topological_space variables {a b b₀ b₁ b₂ : ℝ} {μ : measure ℝ} {f g : ℝ → E} lemma continuous_within_at_primitive (hb₀ : μ {b₀} = 0) (h_int : interval_integrable f μ (min a b₁) (max a b₂)) : continuous_within_at (λ b, ∫ x in a .. b, f x ∂ μ) (Icc b₁ b₂) b₀ := begin by_cases h₀ : b₀ ∈ Icc b₁ b₂, { have h₁₂ : b₁ ≤ b₂ := h₀.1.trans h₀.2, have min₁₂ : min b₁ b₂ = b₁ := min_eq_left h₁₂, have h_int' : ∀ {x}, x ∈ Icc b₁ b₂ → interval_integrable f μ b₁ x, { rintros x ⟨h₁, h₂⟩, apply h_int.mono_set, apply interval_subset_interval, { exact ⟨min_le_of_left_le (min_le_right a b₁), h₁.trans (h₂.trans $ le_max_of_le_right $ le_max_right _ _)⟩ }, { exact ⟨min_le_of_left_le $ (min_le_right _ _).trans h₁, le_max_of_le_right $ h₂.trans $ le_max_right _ _⟩ } }, have : ∀ b ∈ Icc b₁ b₂, ∫ x in a..b, f x ∂μ = ∫ x in a..b₁, f x ∂μ + ∫ x in b₁..b, f x ∂μ, { rintros b ⟨h₁, h₂⟩, rw ← integral_add_adjacent_intervals _ (h_int' ⟨h₁, h₂⟩), apply h_int.mono_set, apply interval_subset_interval, { exact ⟨min_le_of_left_le (min_le_left a b₁), le_max_of_le_right (le_max_left _ _)⟩ }, { exact ⟨min_le_of_left_le (min_le_right _ _), le_max_of_le_right (h₁.trans $ h₂.trans (le_max_right a b₂))⟩ } }, apply continuous_within_at.congr _ this (this _ h₀), clear this, refine continuous_within_at_const.add _, have : (λ b, ∫ x in b₁..b, f x ∂μ) =ᶠ[𝓝[Icc b₁ b₂] b₀] λ b, ∫ x in b₁..b₂, indicator {x | x ≤ b} f x ∂ μ, { apply eventually_eq_of_mem self_mem_nhds_within, exact λ b b_in, (integral_indicator b_in).symm }, apply continuous_within_at.congr_of_eventually_eq _ this (integral_indicator h₀).symm, have : interval_integrable (λ x, ∥f x∥) μ b₁ b₂, from interval_integrable.norm (h_int' $ right_mem_Icc.mpr h₁₂), refine continuous_within_at_of_dominated_interval _ _ this _ ; clear this, { apply eventually.mono (self_mem_nhds_within), intros x hx, erw [ae_strongly_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le], { rw min₁₂, exact (h_int' hx).1.ae_strongly_measurable }, { exact le_max_of_le_right hx.2 }, exacts [measurable_set_Iic, measurable_set_Iic] }, { refine eventually_of_forall (λ x, eventually_of_forall (λ t, _)), dsimp [indicator], split_ifs ; simp }, { have : ∀ᵐ t ∂μ, t < b₀ ∨ b₀ < t, { apply eventually.mono (compl_mem_ae_iff.mpr hb₀), intros x hx, exact ne.lt_or_lt hx }, apply this.mono, rintros x₀ (hx₀ | hx₀) -, { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : ℝ | t ≤ x}.indicator f x₀ = f x₀, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Ioi_mem_nhds hx₀), intros x hx, simp [hx.le] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀.le] }, { have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : ℝ | t ≤ x}.indicator f x₀ = 0, { apply mem_nhds_within_of_mem_nhds, apply eventually.mono (Iio_mem_nhds hx₀), intros x hx, simp [hx] }, apply continuous_within_at_const.congr_of_eventually_eq this, simp [hx₀] } } }, { apply continuous_within_at_of_not_mem_closure, rwa [closure_Icc] } end lemma continuous_on_primitive [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Ioc a x, f t ∂ μ) (Icc a b) := begin by_cases h : a ≤ b, { have : ∀ x ∈ Icc a b, ∫ t in Ioc a x, f t ∂μ = ∫ t in a..x, f t ∂μ, { intros x x_in, simp_rw [← interval_oc_of_le h, integral_of_le x_in.1] }, rw continuous_on_congr this, intros x₀ hx₀, refine continuous_within_at_primitive (measure_singleton x₀) _, simp only [interval_integrable_iff_integrable_Ioc_of_le, min_eq_left, max_eq_right, h], exact h_int.mono Ioc_subset_Icc_self le_rfl }, { rw Icc_eq_empty h, exact continuous_on_empty _ }, end lemma continuous_on_primitive_Icc [has_no_atoms μ] (h_int : integrable_on f (Icc a b) μ) : continuous_on (λ x, ∫ t in Icc a x, f t ∂ μ) (Icc a b) := begin rw show (λ x, ∫ t in Icc a x, f t ∂μ) = λ x, ∫ t in Ioc a x, f t ∂μ, by { ext x, exact integral_Icc_eq_integral_Ioc }, exact continuous_on_primitive h_int end /-- Note: this assumes that `f` is `interval_integrable`, in contrast to some other lemmas here. -/ lemma continuous_on_primitive_interval' [has_no_atoms μ] (h_int : interval_integrable f μ b₁ b₂) (ha : a ∈ [b₁, b₂]) : continuous_on (λ b, ∫ x in a..b, f x ∂ μ) [b₁, b₂] := begin intros b₀ hb₀, refine continuous_within_at_primitive (measure_singleton _) _, rw [min_eq_right ha.1, max_eq_right ha.2], simpa [interval_integrable_iff, interval_oc] using h_int, end lemma continuous_on_primitive_interval [has_no_atoms μ] (h_int : integrable_on f (interval a b) μ) : continuous_on (λ x, ∫ t in a..x, f t ∂ μ) (interval a b) := continuous_on_primitive_interval' h_int.interval_integrable left_mem_interval lemma continuous_on_primitive_interval_left [has_no_atoms μ] (h_int : integrable_on f (interval a b) μ) : continuous_on (λ x, ∫ t in x..b, f t ∂ μ) (interval a b) := begin rw interval_swap a b at h_int ⊢, simp only [integral_symm b], exact (continuous_on_primitive_interval h_int).neg, end variables [has_no_atoms μ] lemma continuous_primitive (h_int : ∀ a b, interval_integrable f μ a b) (a : ℝ) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := begin rw continuous_iff_continuous_at, intro b₀, cases exists_lt b₀ with b₁ hb₁, cases exists_gt b₀ with b₂ hb₂, apply continuous_within_at.continuous_at _ (Icc_mem_nhds hb₁ hb₂), exact continuous_within_at_primitive (measure_singleton b₀) (h_int _ _) end lemma _root_.measure_theory.integrable.continuous_primitive (h_int : integrable f μ) (a : ℝ) : continuous (λ b, ∫ x in a..b, f x ∂ μ) := continuous_primitive (λ _ _, h_int.interval_integrable) a end continuous_primitive section variables {f g : ℝ → ℝ} {a b : ℝ} {μ : measure ℝ} lemma integral_eq_zero_iff_of_le_of_nonneg_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Ioc a b)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b)] 0 := by rw [integral_of_le hab, integral_eq_zero_iff_of_nonneg_ae hf hfi.1] lemma integral_eq_zero_iff_of_nonneg_ae (hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) : ∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] 0 := begin cases le_total a b with hab hab; simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢, { exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi }, { rw [integral_symm, neg_eq_zero, integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm] } end /-- If `f` is nonnegative and integrable on the unordered interval `set.interval_oc a b`, then its integral over `a..b` is positive if and only if `a < b` and the measure of `function.support f ∩ set.Ioc a b` is positive. -/ lemma integral_pos_iff_support_of_nonneg_ae' (hf : 0 ≤ᵐ[μ.restrict (Ι a b)] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) := begin cases lt_or_le a b with hab hba, { rw interval_oc_of_le hab.le at hf, simp only [hab, true_and, integral_of_le hab.le, set_integral_pos_iff_support_of_nonneg_ae hf hfi.1] }, { suffices : ∫ x in a..b, f x ∂μ ≤ 0, by simp only [this.not_lt, hba.not_lt, false_and], rw [integral_of_ge hba, neg_nonpos], rw [interval_oc_swap, interval_oc_of_le hba] at hf, exact integral_nonneg_of_ae hf } end /-- If `f` is nonnegative a.e.-everywhere and it is integrable on the unordered interval `set.interval_oc a b`, then its integral over `a..b` is positive if and only if `a < b` and the measure of `function.support f ∩ set.Ioc a b` is positive. -/ lemma integral_pos_iff_support_of_nonneg_ae (hf : 0 ≤ᵐ[μ] f) (hfi : interval_integrable f μ a b) : 0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) := integral_pos_iff_support_of_nonneg_ae' (ae_mono measure.restrict_le_self hf) hfi /-- If `f : ℝ → ℝ` is strictly positive and integrable on `(a, b]` for real numbers `a < b`, then its integral over `a..b` is strictly positive. -/ lemma interval_integral_pos_of_pos {f : ℝ → ℝ} {a b : ℝ} (hfi : interval_integrable f measure_space.volume a b) (h : ∀ x, 0 < f x) (hab : a < b) : 0 < ∫ x in a..b, f x := begin have hsupp : support f = univ := eq_univ_iff_forall.mpr (λ t, (h t).ne.symm), replace h₀ : 0 ≤ᵐ[volume] f := eventually_of_forall (λ x, (h x).le), rw integral_pos_iff_support_of_nonneg_ae h₀ hfi, exact ⟨hab, by simp [hsupp, hab]⟩, end /-- If `f` and `g` are two functions that are interval integrable on `a..b`, `a ≤ b`, `f x ≤ g x` for a.e. `x ∈ set.Ioc a b`, and `f x < g x` on a subset of `set.Ioc a b` of nonzero measure, then `∫ x in a..b, f x ∂μ < ∫ x in a..b, g x ∂μ`. -/ lemma integral_lt_integral_of_ae_le_of_measure_set_of_lt_ne_zero (hab : a ≤ b) (hfi : interval_integrable f μ a b) (hgi : interval_integrable g μ a b) (hle : f ≤ᵐ[μ.restrict (Ioc a b)] g) (hlt : μ.restrict (Ioc a b) {x | f x < g x} ≠ 0) : ∫ x in a..b, f x ∂μ < ∫ x in a..b, g x ∂μ := begin rw [← sub_pos, ← integral_sub hgi hfi, integral_of_le hab, measure_theory.integral_pos_iff_support_of_nonneg_ae], { refine pos_iff_ne_zero.2 (mt (measure_mono_null _) hlt), exact λ x hx, (sub_pos.2 hx).ne' }, exacts [hle.mono (λ x, sub_nonneg.2), hgi.1.sub hfi.1] end /-- If `f` and `g` are continuous on `[a, b]`, `a < b`, `f x ≤ g x` on this interval, and `f c < g c` at some point `c ∈ [a, b]`, then `∫ x in a..b, f x < ∫ x in a..b, g x`. -/ lemma integral_lt_integral_of_continuous_on_of_le_of_exists_lt {f g : ℝ → ℝ} {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hgc : continuous_on g (Icc a b)) (hle : ∀ x ∈ Ioc a b, f x ≤ g x) (hlt : ∃ c ∈ Icc a b, f c < g c) : ∫ x in a..b, f x < ∫ x in a..b, g x := begin refine integral_lt_integral_of_ae_le_of_measure_set_of_lt_ne_zero hab.le (hfc.interval_integrable_of_Icc hab.le) (hgc.interval_integrable_of_Icc hab.le) ((ae_restrict_mem measurable_set_Ioc).mono hle) _, contrapose! hlt, have h_eq : f =ᵐ[volume.restrict (Ioc a b)] g, { simp only [← not_le, ← ae_iff] at hlt, exact eventually_le.antisymm ((ae_restrict_iff' measurable_set_Ioc).2 $ eventually_of_forall hle) hlt }, simp only [measure.restrict_congr_set Ioc_ae_eq_Icc] at h_eq, exact λ c hc, (measure.eq_on_Icc_of_ae_eq volume hab.ne h_eq hfc hgc hc).ge end lemma integral_nonneg_of_ae_restrict (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Icc a b)] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := let H := ae_restrict_of_ae_restrict_of_subset Ioc_subset_Icc_self hf in by simpa only [integral_of_le hab] using set_integral_nonneg_of_ae_restrict H lemma integral_nonneg_of_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ] f) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ ae_restrict_of_ae hf lemma integral_nonneg_of_forall (hab : a ≤ b) (hf : ∀ u, 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae hab $ eventually_of_forall hf lemma integral_nonneg (hab : a ≤ b) (hf : ∀ u, u ∈ Icc a b → 0 ≤ f u) : 0 ≤ (∫ u in a..b, f u ∂μ) := integral_nonneg_of_ae_restrict hab $ (ae_restrict_iff' measurable_set_Icc).mpr $ ae_of_all μ hf lemma abs_integral_le_integral_abs (hab : a ≤ b) : |∫ x in a..b, f x ∂μ| ≤ ∫ x in a..b, |f x| ∂μ := by simpa only [← real.norm_eq_abs] using norm_integral_le_integral_norm hab section mono variables (hab : a ≤ b) (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) include hab hf hg lemma integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict (Icc a b)] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := h.filter_mono $ ae_mono $ measure.restrict_mono Ioc_subset_Icc_self $ le_refl μ in by simpa only [integral_of_le hab] using set_integral_mono_ae_restrict hf.1 hg.1 H lemma integral_mono_ae (h : f ≤ᵐ[μ] g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := by simpa only [integral_of_le hab] using set_integral_mono_ae hf.1 hg.1 h lemma integral_mono_on (h : ∀ x ∈ Icc a b, f x ≤ g x) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := let H := λ x hx, h x $ Ioc_subset_Icc_self hx in by simpa only [integral_of_le hab] using set_integral_mono_on hf.1 hg.1 measurable_set_Ioc H lemma integral_mono (h : f ≤ g) : ∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ := integral_mono_ae hab hf hg $ ae_of_all _ h omit hg hab lemma integral_mono_interval {c d} (hca : c ≤ a) (hab : a ≤ b) (hbd : b ≤ d) (hf : 0 ≤ᵐ[μ.restrict (Ioc c d)] f) (hfi : interval_integrable f μ c d): ∫ x in a..b, f x ∂μ ≤ ∫ x in c..d, f x ∂μ := begin rw [integral_of_le hab, integral_of_le (hca.trans (hab.trans hbd))], exact set_integral_mono_set hfi.1 hf (Ioc_subset_Ioc hca hbd).eventually_le end lemma abs_integral_mono_interval {c d } (h : Ι a b ⊆ Ι c d) (hf : 0 ≤ᵐ[μ.restrict (Ι c d)] f) (hfi : interval_integrable f μ c d) : |∫ x in a..b, f x ∂μ| ≤ |∫ x in c..d, f x ∂μ| := have hf' : 0 ≤ᵐ[μ.restrict (Ι a b)] f, from ae_mono (measure.restrict_mono h le_rfl) hf, calc |∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| : abs_integral_eq_abs_integral_interval_oc f ... = ∫ x in Ι a b, f x ∂μ : abs_of_nonneg (measure_theory.integral_nonneg_of_ae hf') ... ≤ ∫ x in Ι c d, f x ∂μ : set_integral_mono_set hfi.def hf h.eventually_le ... ≤ |∫ x in Ι c d, f x ∂μ| : le_abs_self _ ... = |∫ x in c..d, f x ∂μ| : (abs_integral_eq_abs_integral_interval_oc f).symm end mono end /-! ### Fundamental theorem of calculus, part 1, for any measure In this section we prove a few lemmas that can be seen as versions of FTC-1 for interval integrals w.r.t. any measure. Many theorems are formulated for one or two pairs of filters related by `FTC_filter a l l'`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[≥] a, 𝓝[>] a)`, `(a, 𝓝[≤] a, 𝓝[≤] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`. We use this approach to avoid repeating arguments in many very similar cases. Lean can automatically find both `a` and `l'` based on `l`. The most general theorem `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` can be seen as a generalization of lemma `integral_has_strict_fderiv_at` below which states strict differentiability of `∫ x in u..v, f x` in `(u, v)` at `(a, b)` for a measurable function `f` that is integrable on `a..b` and is continuous at `a` and `b`. The lemma is generalized in three directions: first, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` deals with any locally finite measure `μ`; second, it works for one-sided limits/derivatives; third, it assumes only that `f` has finite limits almost surely at `a` and `b`. Namely, let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This theorem is formulated with integral of constants instead of measures in the right hand sides for two reasons: first, this way we avoid `min`/`max` in the statements; second, often it is possible to write better `simp` lemmas for these integrals, see `integral_const` and `integral_const_of_cdf`. In the next subsection we apply this theorem to prove various theorems about differentiability of the integral w.r.t. Lebesgue measure. -/ /-- An auxiliary typeclass for the Fundamental theorem of calculus, part 1. It is used to formulate theorems that work simultaneously for left and right one-sided derivatives of `∫ x in u..v, f x`. -/ class FTC_filter (a : out_param ℝ) (outer : filter ℝ) (inner : out_param $ filter ℝ) extends tendsto_Ixx_class Ioc outer inner : Prop := (pure_le : pure a ≤ outer) (le_nhds : inner ≤ 𝓝 a) [meas_gen : is_measurably_generated inner] /- The `dangerous_instance` linter doesn't take `out_param`s into account, so it thinks that `FTC_filter.to_tendsto_Ixx_class` is dangerous. Disable this linter using `nolint`. -/ attribute [nolint dangerous_instance] FTC_filter.to_tendsto_Ixx_class namespace FTC_filter instance pure (a : ℝ) : FTC_filter a (pure a) ⊥ := { pure_le := le_rfl, le_nhds := bot_le } instance nhds_within_singleton (a : ℝ) : FTC_filter a (𝓝[{a}] a) ⊥ := by { rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)], apply_instance } lemma finite_at_inner {a : ℝ} (l : filter ℝ) {l'} [h : FTC_filter a l l'] {μ : measure ℝ} [is_locally_finite_measure μ] : μ.finite_at_filter l' := (μ.finite_at_nhds a).filter_mono h.le_nhds instance nhds (a : ℝ) : FTC_filter a (𝓝 a) (𝓝 a) := { pure_le := pure_le_nhds a, le_nhds := le_rfl } instance nhds_univ (a : ℝ) : FTC_filter a (𝓝[univ] a) (𝓝 a) := by { rw nhds_within_univ, apply_instance } instance nhds_left (a : ℝ) : FTC_filter a (𝓝[≤] a) (𝓝[≤] a) := { pure_le := pure_le_nhds_within right_mem_Iic, le_nhds := inf_le_left } instance nhds_right (a : ℝ) : FTC_filter a (𝓝[≥] a) (𝓝[>] a) := { pure_le := pure_le_nhds_within left_mem_Ici, le_nhds := inf_le_left } instance nhds_Icc {x a b : ℝ} [h : fact (x ∈ Icc a b)] : FTC_filter x (𝓝[Icc a b] x) (𝓝[Icc a b] x) := { pure_le := pure_le_nhds_within h.out, le_nhds := inf_le_left } instance nhds_interval {x a b : ℝ} [h : fact (x ∈ [a, b])] : FTC_filter x (𝓝[[a, b]] x) (𝓝[[a, b]] x) := by { haveI : fact (x ∈ set.Icc (min a b) (max a b)) := h, exact FTC_filter.nhds_Icc } end FTC_filter open asymptotics section variables {f : ℝ → E} {a b : ℝ} {c ca cb : E} {l l' la la' lb lb' : filter ℝ} {lt : filter ι} {μ : measure ℝ} {u v ua va ub vb : ι → ℝ} /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, where `μ` is a measure finite at `l'`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae` for a version assuming `[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[≥] a`, `𝓝[≤] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : strongly_measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := begin have A := hf.integral_sub_linear_is_o_ae hfm hl (hu.Ioc hv), have B := hf.integral_sub_linear_is_o_ae hfm hl (hv.Ioc hu), simp only [integral_const'], convert (A.trans_le _).sub (B.trans_le _), { ext t, simp_rw [interval_integral, sub_smul], abel }, all_goals { intro t, cases le_total (u t) (v t) with huv huv; simp [huv] } end /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l` so that `u ≤ v`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le` for a version assuming `[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[≥] a`, `𝓝[≤] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : strongly_measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf hl hu hv).congr' (huv.mono $ λ x hx, by simp [integral_const', hx]) (huv.mono $ λ x hx, by simp [integral_const', hx]) /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`. If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure finite at `l`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l` so that `v ≤ u`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge` for a version assuming `[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[≥] a`, `𝓝[≤] a`, `𝓝 a`, then it's easier to apply the non-primed version. The primed version also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' [is_measurably_generated l'] [tendsto_Ixx_class Ioc l l'] (hfm : strongly_measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := (measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf hl hv hu huv).neg_left.congr_left $ λ t, by simp [integral_symm (u t), add_comm] section variables [is_locally_finite_measure μ] [FTC_filter a l l'] include a local attribute [instance] FTC_filter.meas_gen /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae'` for a version that also works, e.g., for `l = l' = at_top`. We use integrals of constants instead of measures because this way it is easier to formulate a statement that works in both cases `u ≤ v` and `v ≤ u`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae (hfm : strongly_measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf (FTC_filter.finite_at_inner l) hu hv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le (hfm : strongly_measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) : is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c) (λ t, (μ $ Ioc (u t) (v t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf (FTC_filter.finite_at_inner l) hu hv huv /-- Fundamental theorem of calculus-1, local version for any measure. Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure. If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l`. See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge'` for a version that also works, e.g., for `l = l' = at_top`. -/ lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge (hfm : strongly_measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) : is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c) (λ t, (μ $ Ioc (v t) (u t)).to_real) lt := measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' hfm hf (FTC_filter.finite_at_inner l) hu hv huv end local attribute [instance] FTC_filter.meas_gen variables [FTC_filter a la la'] [FTC_filter b lb lb'] [is_locally_finite_measure μ] /-- Fundamental theorem of calculus-1, strict derivative in both limits for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ + o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f μ a b) (hmeas_a : strongly_measurable_at_filter f la' μ) (hmeas_b : strongly_measurable_at_filter f lb' μ) (ha_lim : tendsto f (la' ⊓ μ.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ μ.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x ∂μ) - (∫ x in ua t..ub t, f x ∂μ) - (∫ x in ub t..vb t, cb ∂μ - ∫ x in ua t..va t, ca ∂μ)) (λ t, ∥∫ x in ua t..va t, (1:ℝ) ∂μ∥ + ∥∫ x in ub t..vb t, (1:ℝ) ∂μ∥) lt := begin refine ((measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_a ha_lim hua hva).neg_left.add_add (measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_b hb_lim hub hvb)).congr' _ eventually_eq.rfl, have A : ∀ᶠ t in lt, interval_integrable f μ (ua t) (va t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) hua hva, have A' : ∀ᶠ t in lt, interval_integrable f μ a (ua t) := ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) (tendsto_const_pure.mono_right FTC_filter.pure_le) hua, have B : ∀ᶠ t in lt, interval_integrable f μ (ub t) (vb t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) hub hvb, have B' : ∀ᶠ t in lt, interval_integrable f μ b (ub t) := hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) (tendsto_const_pure.mono_right FTC_filter.pure_le) hub, filter_upwards [A, A', B, B'] with _ ua_va a_ua ub_vb b_ub, rw [← integral_interval_sub_interval_comm'], { dsimp only [], abel, }, exacts [ub_vb, ua_va, b_ub.symm.trans $ hab.symm.trans a_ua] end /-- Fundamental theorem of calculus-1, strict derivative in right endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has a finite limit `c` at `lb' ⊓ μ.ae`. Then `∫ x in a..v, f x ∂μ - ∫ x in a..u, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `lb`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f μ a b) (hmeas : strongly_measurable_at_filter f lb' μ) (hf : tendsto f (lb' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, ∫ x in a..v t, f x ∂μ - ∫ x in a..u t, f x ∂μ - ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab strongly_measurable_at_bot hmeas ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hf (tendsto_const_pure : tendsto _ _ (pure a)) tendsto_const_pure hu hv /-- Fundamental theorem of calculus-1, strict derivative in left endpoint for a locally finite measure. Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s around `a`. Suppose that `f` has a finite limit `c` at `la' ⊓ μ.ae`. Then `∫ x in v..b, f x ∂μ - ∫ x in u..b, f x ∂μ = -∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)` as `u` and `v` tend to `la`. -/ lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f μ a b) (hmeas : strongly_measurable_at_filter f la' μ) (hf : tendsto f (la' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, ∫ x in v t..b, f x ∂μ - ∫ x in u t..b, f x ∂μ + ∫ x in u t..v t, c ∂μ) (λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt := by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas strongly_measurable_at_bot hf ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left) hu hv (tendsto_const_pure : tendsto _ _ (pure b)) tendsto_const_pure end /-! ### Fundamental theorem of calculus-1 for Lebesgue measure In this section we restate theorems from the previous section for Lebesgue measure. In particular, we prove that `∫ x in u..v, f x` is strictly differentiable in `(u, v)` at `(a, b)` provided that `f` is integrable on `a..b` and is continuous at `a` and `b`. -/ variables {f : ℝ → E} {c ca cb : E} {l l' la la' lb lb' : filter ℝ} {lt : filter ι} {a b z : ℝ} {u v ua ub va vb : ι → ℝ} [FTC_filter a la la'] [FTC_filter b lb lb'] /-! #### Auxiliary `is_o` statements In this section we prove several lemmas that can be interpreted as strict differentiability of `(u, v) ↦ ∫ x in u..v, f x ∂μ` in `u` and/or `v` at a filter. The statements use `is_o` because we have no definition of `has_strict_(f)deriv_at_filter` in the library. -/ /-- Fundamental theorem of calculus-1, local version. If `f` has a finite limit `c` almost surely at `l'`, where `(l, l')` is an `FTC_filter` pair around `a`, then `∫ x in u..v, f x ∂μ = (v - u) • c + o (v - u)` as both `u` and `v` tend to `l`. -/ lemma integral_sub_linear_is_o_of_tendsto_ae [FTC_filter a l l'] (hfm : strongly_measurable_at_filter f l') (hf : tendsto f (l' ⊓ volume.ae) (𝓝 c)) {u v : ι → ℝ} (hu : tendsto u lt l) (hv : tendsto v lt l) : is_o (λ t, (∫ x in u t..v t, f x) - (v t - u t) • c) (v - u) lt := by simpa [integral_const] using measure_integral_sub_linear_is_o_of_tendsto_ae hfm hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has finite limits `ca` and `cb` almost surely at `la'` and `lb'`, respectively, then `(∫ x in va..vb, f x) - ∫ x in ua..ub, f x = (vb - ub) • cb - (va - ua) • ca + o(∥va - ua∥ + ∥vb - ub∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`. This lemma could've been formulated using `has_strict_fderiv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae (hab : interval_integrable f volume a b) (hmeas_a : strongly_measurable_at_filter f la') (hmeas_b : strongly_measurable_at_filter f lb') (ha_lim : tendsto f (la' ⊓ volume.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ volume.ae) (𝓝 cb)) (hua : tendsto ua lt la) (hva : tendsto va lt la) (hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) : is_o (λ t, (∫ x in va t..vb t, f x) - (∫ x in ua t..ub t, f x) - ((vb t - ub t) • cb - (va t - ua t) • ca)) (λ t, ∥va t - ua t∥ + ∥vb t - ub t∥) lt := by simpa [integral_const] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas_a hmeas_b ha_lim hb_lim hua hva hub hvb /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has a finite limit `c` almost surely at `lb'`, then `(∫ x in a..v, f x) - ∫ x in a..u, f x = (v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `lb`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right (hab : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f lb') (hf : tendsto f (lb' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) : is_o (λ t, (∫ x in a..v t, f x) - (∫ x in a..u t, f x) - (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hab hmeas hf hu hv /-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints. If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around `a`, and `f` has a finite limit `c` almost surely at `la'`, then `(∫ x in v..b, f x) - ∫ x in u..b, f x = -(v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `la`. This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/ lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left (hab : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f la') (hf : tendsto f (la' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) : is_o (λ t, (∫ x in v t..b, f x) - (∫ x in u t..b, f x) + (v t - u t) • c) (v - u) lt := by simpa only [integral_const, smul_eq_mul, mul_one] using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left hab hmeas hf hu hv open continuous_linear_map (fst snd smul_right sub_apply smul_right_apply coe_fst' coe_snd' map_sub) /-! #### Strict differentiability In this section we prove that for a measurable function `f` integrable on `a..b`, * `integral_has_strict_fderiv_at_of_tendsto_ae`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability provided that `f` tends to `ca` and `cb` almost surely as `x` tendsto to `a` and `b`, respectively; * `integral_has_strict_fderiv_at`: the function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` at `(a, b)` in the sense of strict differentiability provided that `f` is continuous at `a` and `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `b`; * `integral_has_strict_deriv_at_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability provided that `f` is continuous at `b`; * `integral_has_strict_deriv_at_of_tendsto_ae_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability provided that `f` tends to `c` almost surely as `x` tends to `a`; * `integral_has_strict_deriv_at_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability provided that `f` is continuous at `a`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : strongly_measurable_at_filter f (𝓝 a)) (hmeas_b : strongly_measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := begin have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb ((continuous_fst.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_fst.comp continuous_fst).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_snd).tendsto ((a, b), (a, b))) ((continuous_snd.comp continuous_fst).tendsto ((a, b), (a, b))), refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability. -/ lemma integral_has_strict_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : strongly_measurable_at_filter f (𝓝 a)) (hmeas_b : strongly_measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- **First Fundamental Theorem of Calculus**: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) c b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb continuous_at_snd continuous_at_fst /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_of_tendsto_ae_right hf.symm hmeas ha).neg /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict differentiability. -/ lemma integral_has_strict_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := by simpa only [← integral_symm] using (integral_has_strict_deriv_at_right hf.symm hmeas ha).neg /-! #### Fréchet differentiability In this subsection we restate results from the previous subsection in terms of `has_fderiv_at`, `has_deriv_at`, `fderiv`, and `deriv`. -/ /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : strongly_measurable_at_filter f (𝓝 a)) (hmeas_b : strongly_measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) := (integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/ lemma integral_has_fderiv_at (hf : interval_integrable f volume a b) (hmeas_a : strongly_measurable_at_filter f (𝓝 a)) (hmeas_b : strongly_measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) := (integral_has_strict_fderiv_at hf hmeas_a hmeas_b ha hb).has_fderiv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : strongly_measurable_at_filter f (𝓝 a)) (hmeas_b : strongly_measurable_at_filter f (𝓝 b)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca := (integral_has_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a` and `b`, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/ lemma fderiv_integral (hf : interval_integrable f volume a b) (hmeas_a : strongly_measurable_at_filter f (𝓝 a)) (hmeas_b : strongly_measurable_at_filter f (𝓝 b)) (ha : continuous_at f a) (hb : continuous_at f b) : fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) = (snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a) := (integral_has_fderiv_at hf hmeas_a hmeas_b ha hb).fderiv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b`. -/ lemma integral_has_deriv_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in a..u, f x) c b := (integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b`. -/ lemma integral_has_deriv_at_right (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : has_deriv_at (λ u, ∫ x in a..u, f x) (f b) b := (integral_has_strict_deriv_at_right hf hmeas hb).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 b)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in a..u, f x) b = c := (integral_has_deriv_at_of_tendsto_ae_right hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_integral_right (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 b)) (hb : continuous_at f b) : deriv (λ u, ∫ x in a..u, f x) b = f b := (integral_has_deriv_at_right hf hmeas hb).deriv /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a`. -/ lemma integral_has_deriv_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 a)) (ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in u..b, f x) (-c) a := (integral_has_strict_deriv_at_of_tendsto_ae_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a`. -/ lemma integral_has_deriv_at_left (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 a)) (ha : continuous_at f a) : has_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a := (integral_has_strict_deriv_at_left hf hmeas ha).has_deriv_at /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite limit `c` almost surely at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 a)) (hb : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in u..b, f x) a = -c := (integral_has_deriv_at_of_tendsto_ae_left hf hmeas hb).deriv /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_integral_left (hf : interval_integrable f volume a b) (hmeas : strongly_measurable_at_filter f (𝓝 a)) (hb : continuous_at f a) : deriv (λ u, ∫ x in u..b, f x) a = -f a := (integral_has_deriv_at_left hf hmeas hb).deriv /-! #### One-sided derivatives -/ /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the following table. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` | | `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at_of_tendsto_ae (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (hmeas_a : strongly_measurable_at_filter f la) (hmeas_b : strongly_measurable_at_filter f lb) (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (s ×ˢ t) (a, b) := begin rw [has_fderiv_within_at, nhds_within_prod_eq], have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[s] a)) tendsto_fst (tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[t] b)) tendsto_snd, refine (this.congr_left _).trans_is_O _, { intro x, simp [sub_smul] }, { exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left } end /-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • f b - u • f a` within `s × t` at `(a, b)`, where `s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `f a` and `f b` at the filters `la` and `lb` from the following table. In most cases this assumption is definitionally equal `continuous_at f _` or `continuous_within_at f _ _`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` | | `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma integral_has_fderiv_within_at (hf : interval_integrable f volume a b) (hmeas_a : strongly_measurable_at_filter f la) (hmeas_b : strongly_measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f la (𝓝 $ f a)) (hb : tendsto f lb (𝓝 $ f b)) : has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) ((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (s ×ˢ t) (a, b) := integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left) (hb.mono_left inf_le_left) /-- An auxiliary tactic closing goals `unique_diff_within_at ℝ s a` where `s ∈ {Iic a, Ici a, univ}`. -/ meta def unique_diff_within_at_Ici_Iic_univ : tactic unit := `[apply_rules [unique_diff_on.unique_diff_within_at, unique_diff_on_Ici, unique_diff_on_Iic, left_mem_Ici, right_mem_Iic, unique_diff_within_at_univ]] /-- Let `f` be a measurable function integrable on `a..b`. Choose `s ∈ {Iic a, Ici a, univ}` and `t ∈ {Iic b, Ici b, univ}`. Suppose that `f` tends to `ca` and `cb` almost surely at the filters `la` and `lb` from the table below. Then `fderiv_within ℝ (λ p, ∫ x in p.1..p.2, f x) (s ×ˢ t)` is equal to `(u, v) ↦ u • cb - v • ca`. | `s` | `la` | `t` | `lb` | | ------- | ---- | --- | ---- | | `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` | | `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` | | `{a}` | `⊥` | `{b}` | `⊥` | | `univ` | `𝓝 a` | `univ` | `𝓝 b` | -/ lemma fderiv_within_integral_of_tendsto_ae (hf : interval_integrable f volume a b) (hmeas_a : strongly_measurable_at_filter f la) (hmeas_b : strongly_measurable_at_filter f lb) {s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb] (ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) (ht : unique_diff_within_at ℝ t b . unique_diff_within_at_Ici_Iic_univ) : fderiv_within ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (s ×ˢ t) (a, b) = ((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) := (integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv_within $ hs.prod ht /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then `u ↦ ∫ x in a..u, f x` has right (resp., left) derivative `c` at `b`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : strongly_measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in a..u, f x) c s b := integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb (tendsto_const_pure.mono_right FTC_filter.pure_le) tendsto_id /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `b`, then `u ↦ ∫ x in a..u, f x` has left (resp., right) derivative `f b` at `b`. -/ lemma integral_has_deriv_within_at_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : strongly_measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) : has_deriv_within_at (λ u, ∫ x in a..u, f x) (f b) s b := integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `b` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/ lemma deriv_within_integral_of_tendsto_ae_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas: strongly_measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = c := (integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `b`, then the right (resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/ lemma deriv_within_integral_right (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)] (hmeas : strongly_measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) (hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in a..u, f x) s b = f b := (integral_has_deriv_within_at_right hf hmeas hb).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then `u ↦ ∫ x in u..b, f x` has right (resp., left) derivative `-c` at `a`. -/ lemma integral_has_deriv_within_at_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : strongly_measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-c) s a := by { simp only [integral_symm b], exact (integral_has_deriv_within_at_of_tendsto_ae_right hf.symm hmeas ha).neg } /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous from the left or from the right at `a`, then `u ↦ ∫ x in u..b, f x` has left (resp., right) derivative `-f a` at `a`. -/ lemma integral_has_deriv_within_at_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : strongly_measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) : has_deriv_within_at (λ u, ∫ x in u..b, f x) (-f a) s a := integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas (ha.mono_left inf_le_left) /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite limit `c` almost surely as `x` tends to `a` from the right or from the left, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/ lemma deriv_within_integral_of_tendsto_ae_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : strongly_measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -c := (integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas ha).deriv_within hs /-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous on the right or on the left at `a`, then the right (resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/ lemma deriv_within_integral_left (hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)] (hmeas : strongly_measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) (hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) : deriv_within (λ u, ∫ x in u..b, f x) s a = -f a := (integral_has_deriv_within_at_left hf hmeas ha).deriv_within hs /-- The integral of a continuous function is differentiable on a real set `s`. -/ theorem differentiable_on_integral_of_continuous {s : set ℝ} (hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) : differentiable_on ℝ (λ u, ∫ x in a..u, f x) s := λ y hy, (integral_has_deriv_at_right (hintg y hy) hcont.ae_strongly_measurable.strongly_measurable_at_filter hcont.continuous_at) .differentiable_at.differentiable_within_at /-! ### Fundamental theorem of calculus, part 2 This section contains theorems pertaining to FTC-2 for interval integrals, i.e., the assertion that `∫ x in a..b, f' x = f b - f a` under suitable assumptions. The most classical version of this theorem assumes that `f'` is continuous. However, this is unnecessarily strong: the result holds if `f'` is just integrable. We prove the strong version, following [Rudin, *Real and Complex Analysis* (Theorem 7.21)][rudin2006real]. The proof is first given for real-valued functions, and then deduced for functions with a general target space. For a real-valued function `g`, it suffices to show that `g b - g a ≤ (∫ x in a..b, g' x) + ε` for all positive `ε`. To prove this, choose a lower-semicontinuous function `G'` with `g' < G'` and with integral close to that of `g'` (its existence is guaranteed by the Vitali-Carathéodory theorem). It satisfies `g t - g a ≤ ∫ x in a..t, G' x` for all `t ∈ [a, b]`: this inequality holds at `a`, and if it holds at `t` then it holds for `u` close to `t` on its right, as the left hand side increases by `g u - g t ∼ (u -t) g' t`, while the right hand side increases by `∫ x in t..u, G' x` which is roughly at least `∫ x in t..u, G' t = (u - t) G' t`, by lower semicontinuity. As `g' t < G' t`, this gives the conclusion. One can therefore push progressively this inequality to the right until the point `b`, where it gives the desired conclusion. -/ variables {g' g : ℝ → ℝ} /-- Hard part of FTC-2 for integrable derivatives, real-valued functions: one has `g b - g a ≤ ∫ y in a..b, g' y`. Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`. -/ lemma sub_le_integral_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : g b - g a ≤ ∫ y in a..b, g' y := begin refine le_of_forall_pos_le_add (λ ε εpos, _), -- Bound from above `g'` by a lower-semicontinuous function `G'`. rcases exists_lt_lower_semicontinuous_integral_lt g' g'int εpos with ⟨G', g'_lt_G', G'cont, G'int, G'lt_top, hG'⟩, -- we will show by "induction" that `g t - g a ≤ ∫ u in a..t, G' u` for all `t ∈ [a, b]`. set s := {t | g t - g a ≤ ∫ u in a..t, (G' u).to_real} ∩ Icc a b, -- the set `s` of points where this property holds is closed. have s_closed : is_closed s, { have : continuous_on (λ t, (g t - g a, ∫ u in a..t, (G' u).to_real)) (Icc a b), { rw ← interval_of_le hab at G'int ⊢ hcont, exact (hcont.sub continuous_on_const).prod (continuous_on_primitive_interval G'int) }, simp only [s, inter_comm], exact this.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' }, have main : Icc a b ⊆ {t | g t - g a ≤ ∫ u in a..t, (G' u).to_real }, { -- to show that the set `s` is all `[a, b]`, it suffices to show that any point `t` in `s` -- with `t < b` admits another point in `s` slightly to its right -- (this is a sort of real induction). apply s_closed.Icc_subset_of_forall_exists_gt (by simp only [integral_same, mem_set_of_eq, sub_self]) (λ t ht v t_lt_v, _), obtain ⟨y, g'_lt_y', y_lt_G'⟩ : ∃ (y : ℝ), (g' t : ereal) < y ∧ (y : ereal) < G' t := ereal.lt_iff_exists_real_btwn.1 (g'_lt_G' t), -- bound from below the increase of `∫ x in a..u, G' x` on the right of `t`, using the lower -- semicontinuity of `G'`. have I1 : ∀ᶠ u in 𝓝[>] t, (u - t) * y ≤ ∫ w in t..u, (G' w).to_real, { have B : ∀ᶠ u in 𝓝 t, (y : ereal) < G' u := G'cont.lower_semicontinuous_at _ _ y_lt_G', rcases mem_nhds_iff_exists_Ioo_subset.1 B with ⟨m, M, ⟨hm, hM⟩, H⟩, have : Ioo t (min M b) ∈ 𝓝[>] t := mem_nhds_within_Ioi_iff_exists_Ioo_subset.2 ⟨min M b, by simp only [hM, ht.right.right, lt_min_iff, mem_Ioi, and_self], subset.refl _⟩, filter_upwards [this] with u hu, have I : Icc t u ⊆ Icc a b := Icc_subset_Icc ht.2.1 (hu.2.le.trans (min_le_right _ _)), calc (u - t) * y = ∫ v in Icc t u, y : by simp only [hu.left.le, measure_theory.integral_const, algebra.id.smul_eq_mul, sub_nonneg, measurable_set.univ, real.volume_Icc, measure.restrict_apply, univ_inter, ennreal.to_real_of_real] ... ≤ ∫ w in t..u, (G' w).to_real : begin rw [interval_integral.integral_of_le hu.1.le, ← integral_Icc_eq_integral_Ioc], apply set_integral_mono_ae_restrict, { simp only [integrable_on_const, real.volume_Icc, ennreal.of_real_lt_top, or_true] }, { exact integrable_on.mono_set G'int I }, { have C1 : ∀ᵐ (x : ℝ) ∂volume.restrict (Icc t u), G' x < ∞ := ae_mono (measure.restrict_mono I le_rfl) G'lt_top, have C2 : ∀ᵐ (x : ℝ) ∂volume.restrict (Icc t u), x ∈ Icc t u := ae_restrict_mem measurable_set_Icc, filter_upwards [C1, C2] with x G'x hx, apply ereal.coe_le_coe_iff.1, have : x ∈ Ioo m M, by simp only [hm.trans_le hx.left, (hx.right.trans_lt hu.right).trans_le (min_le_left M b), mem_Ioo, and_self], convert le_of_lt (H this), exact ereal.coe_to_real G'x.ne (ne_bot_of_gt (g'_lt_G' x)) } end }, -- bound from above the increase of `g u - g a` on the right of `t`, using the derivative at `t` have I2 : ∀ᶠ u in 𝓝[>] t, g u - g t ≤ (u - t) * y, { have g'_lt_y : g' t < y := ereal.coe_lt_coe_iff.1 g'_lt_y', filter_upwards [(hderiv t ⟨ht.2.1, ht.2.2⟩).limsup_slope_le' (not_mem_Ioi.2 le_rfl) g'_lt_y, self_mem_nhds_within] with u hu t_lt_u, have := mul_le_mul_of_nonneg_left hu.le (sub_pos.2 t_lt_u).le, rwa [← smul_eq_mul, sub_smul_slope] at this }, -- combine the previous two bounds to show that `g u - g a` increases less quickly than -- `∫ x in a..u, G' x`. have I3 : ∀ᶠ u in 𝓝[>] t, g u - g t ≤ ∫ w in t..u, (G' w).to_real, { filter_upwards [I1, I2] with u hu1 hu2 using hu2.trans hu1, }, have I4 : ∀ᶠ u in 𝓝[>] t, u ∈ Ioc t (min v b), { refine mem_nhds_within_Ioi_iff_exists_Ioc_subset.2 ⟨min v b, _, subset.refl _⟩, simp only [lt_min_iff, mem_Ioi], exact ⟨t_lt_v, ht.2.2⟩ }, -- choose a point `x` slightly to the right of `t` which satisfies the above bound rcases (I3.and I4).exists with ⟨x, hx, h'x⟩, -- we check that it belongs to `s`, essentially by construction refine ⟨x, _, Ioc_subset_Ioc le_rfl (min_le_left _ _) h'x⟩, calc g x - g a = (g t - g a) + (g x - g t) : by abel ... ≤ (∫ w in a..t, (G' w).to_real) + ∫ w in t..x, (G' w).to_real : add_le_add ht.1 hx ... = ∫ w in a..x, (G' w).to_real : begin apply integral_add_adjacent_intervals, { rw interval_integrable_iff_integrable_Ioc_of_le ht.2.1, exact integrable_on.mono_set G'int (Ioc_subset_Icc_self.trans (Icc_subset_Icc le_rfl ht.2.2.le)) }, { rw interval_integrable_iff_integrable_Ioc_of_le h'x.1.le, apply integrable_on.mono_set G'int, refine Ioc_subset_Icc_self.trans (Icc_subset_Icc ht.2.1 (h'x.2.trans (min_le_right _ _))) } end }, -- now that we know that `s` contains `[a, b]`, we get the desired result by applying this to `b`. calc g b - g a ≤ ∫ y in a..b, (G' y).to_real : main (right_mem_Icc.2 hab) ... ≤ (∫ y in a..b, g' y) + ε : begin convert hG'.le; { rw interval_integral.integral_of_le hab, simp only [integral_Icc_eq_integral_Ioc', real.volume_singleton] }, end end /-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`. -/ lemma integral_le_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : ∫ y in a..b, g' y ≤ g b - g a := begin rw ← neg_le_neg_iff, convert sub_le_integral_of_has_deriv_right_of_le hab hcont.neg (λ x hx, (hderiv x hx).neg) g'int.neg, { abel }, { simp only [integral_neg] } end /-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`: real version -/ lemma integral_eq_sub_of_has_deriv_right_of_le_real (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : ∫ y in a..b, g' y = g b - g a := le_antisymm (integral_le_sub_of_has_deriv_right_of_le hab hcont hderiv g'int) (sub_le_integral_of_has_deriv_right_of_le hab hcont hderiv g'int) /-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`: real version, not requiring differentiability as the left endpoint of the interval. Follows from `integral_eq_sub_of_has_deriv_right_of_le_real` together with a continuity argument. -/ lemma integral_eq_sub_of_has_deriv_right_of_le_real' (hab : a ≤ b) (hcont : continuous_on g (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_within_at g (g' x) (Ioi x) x) (g'int : integrable_on g' (Icc a b)) : ∫ y in a..b, g' y = g b - g a := begin obtain rfl|a_lt_b := hab.eq_or_lt, { simp }, set s := {t | ∫ u in t..b, g' u = g b - g t} ∩ Icc a b, have s_closed : is_closed s, { have : continuous_on (λ t, (∫ u in t..b, g' u, g b - g t)) (Icc a b), { rw ← interval_of_le hab at ⊢ hcont g'int, exact (continuous_on_primitive_interval_left g'int).prod (continuous_on_const.sub hcont) }, simp only [s, inter_comm], exact this.preimage_closed_of_closed is_closed_Icc is_closed_diagonal, }, have A : closure (Ioc a b) ⊆ s, { apply s_closed.closure_subset_iff.2, assume t ht, refine ⟨_, ⟨ht.1.le, ht.2⟩⟩, exact integral_eq_sub_of_has_deriv_right_of_le_real ht.2 (hcont.mono (Icc_subset_Icc ht.1.le le_rfl)) (λ x hx, hderiv x ⟨ht.1.trans_le hx.1, hx.2⟩) (g'int.mono_set (Icc_subset_Icc ht.1.le le_rfl)) }, rw closure_Ioc a_lt_b.ne at A, exact (A (left_mem_Icc.2 hab)).1, end variable {f' : ℝ → E} /-- **Fundamental theorem of calculus-2**: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a right derivative at `f' x` for all `x` in `(a, b)`, and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_within_at f (f' x) (Ioi x) x) (f'int : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := begin refine (normed_space.eq_iff_forall_dual_eq ℝ).2 (λ g, _), rw [← g.interval_integral_comp_comm f'int, g.map_sub], exact integral_eq_sub_of_has_deriv_right_of_le_real' hab (g.continuous.comp_continuous_on hcont) (λ x hx, g.has_fderiv_at.comp_has_deriv_within_at x (hderiv x hx)) (g.integrable_comp ((interval_integrable_iff_integrable_Icc_of_le hab).1 f'int)) end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is integrable on `[a, b]` then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_right (hcont : continuous_on f (interval a b)) (hderiv : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hint : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := begin cases le_total a b with hab hab, { simp only [interval_of_le, min_eq_left, max_eq_right, hab] at hcont hderiv hint, apply integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hint }, { simp only [interval_of_ge, min_eq_right, max_eq_left, hab] at hcont hderiv, rw [integral_symm, integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hint.symm, neg_sub] } end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and has a derivative at `f' x` for all `x` in `(a, b)`, and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_right_of_le hab hcont (λ x hx, (hderiv x hx).has_deriv_within_at) hint /-- Fundamental theorem of calculus-2: If `f : ℝ → E` has a derivative at `f' x` for all `x` in `[a, b]` and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/ theorem integral_eq_sub_of_has_deriv_at (hderiv : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b) : ∫ y in a..b, f' y = f b - f a := integral_eq_sub_of_has_deriv_right (has_deriv_at.continuous_on hderiv) (λ x hx, (hderiv _ (mem_Icc_of_Ioo hx)).has_deriv_within_at) hint theorem integral_eq_sub_of_has_deriv_at_of_tendsto (hab : a < b) {fa fb} (hderiv : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b) (ha : tendsto f (𝓝[>] a) (𝓝 fa)) (hb : tendsto f (𝓝[<] b) (𝓝 fb)) : ∫ y in a..b, f' y = fb - fa := begin set F : ℝ → E := update (update f a fa) b fb, have Fderiv : ∀ x ∈ Ioo a b, has_deriv_at F (f' x) x, { refine λ x hx, (hderiv x hx).congr_of_eventually_eq _, filter_upwards [Ioo_mem_nhds hx.1 hx.2] with _ hy, simp only [F], rw [update_noteq hy.2.ne, update_noteq hy.1.ne'], }, have hcont : continuous_on F (Icc a b), { rw [continuous_on_update_iff, continuous_on_update_iff, Icc_diff_right, Ico_diff_left], refine ⟨⟨λ z hz, (hderiv z hz).continuous_at.continuous_within_at, _⟩, _⟩, { exact λ _, ha.mono_left (nhds_within_mono _ Ioo_subset_Ioi_self) }, { rintro -, refine (hb.congr' _).mono_left (nhds_within_mono _ Ico_subset_Iio_self), filter_upwards [Ioo_mem_nhds_within_Iio (right_mem_Ioc.2 hab)] with _ hz using (update_noteq hz.1.ne' _ _).symm } }, simpa [F, hab.ne, hab.ne'] using integral_eq_sub_of_has_deriv_at_of_le hab.le hcont Fderiv hint end /-- Fundamental theorem of calculus-2: If `f : ℝ → E` is differentiable at every `x` in `[a, b]` and its derivative is integrable on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/ theorem integral_deriv_eq_sub (hderiv : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hint : interval_integrable (deriv f) volume a b) : ∫ y in a..b, deriv f y = f b - f a := integral_eq_sub_of_has_deriv_at (λ x hx, (hderiv x hx).has_deriv_at) hint theorem integral_deriv_eq_sub' (f) (hderiv : deriv f = f') (hdiff : ∀ x ∈ interval a b, differentiable_at ℝ f x) (hcont : continuous_on f' (interval a b)) : ∫ y in a..b, f' y = f b - f a := begin rw [← hderiv, integral_deriv_eq_sub hdiff], rw hderiv, exact hcont.interval_integrable end /-! ### Integration by parts -/ theorem integral_deriv_mul_eq_sub {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hu' : interval_integrable u' volume a b) (hv' : interval_integrable v' volume a b) : ∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a := integral_eq_sub_of_has_deriv_at (λ x hx, (hu x hx).mul (hv x hx)) $ (hu'.mul_continuous_on (has_deriv_at.continuous_on hv)).add (hv'.continuous_on_mul ((has_deriv_at.continuous_on hu))) theorem integral_mul_deriv_eq_deriv_mul {u v u' v' : ℝ → ℝ} (hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x) (hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x) (hu' : interval_integrable u' volume a b) (hv' : interval_integrable v' volume a b) : ∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, v x * u' x := begin rw [← integral_deriv_mul_eq_sub hu hv hu' hv', ← integral_sub], { exact integral_congr (λ x hx, by simp only [mul_comm, add_sub_cancel']) }, { exact ((hu'.mul_continuous_on (has_deriv_at.continuous_on hv)).add (hv'.continuous_on_mul (has_deriv_at.continuous_on hu))) }, { exact hu'.continuous_on_mul (has_deriv_at.continuous_on hv) }, end /-! ### Integration by substitution / Change of variables -/ section smul /-- Change of variables, general form. If `f` is continuous on `[a, b]` and has continuous right-derivative `f'` in `(a, b)`, and `g` is continuous on `f '' [a, b]` then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. We could potentially slightly weaken the conditions, by not requiring that `f'` and `g` are continuous on the endpoints of these intervals, but in that case we need to additionally assume that the functions are integrable on that interval. -/ theorem integral_comp_smul_deriv'' {f f' : ℝ → ℝ} {g : ℝ → E} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, f' x • (g ∘ f) x= ∫ u in f a..f b, g u := begin have h_cont : continuous_on (λ u, ∫ t in f a..f u, g t) [a, b], { rw [hf.image_interval] at hg, refine (continuous_on_primitive_interval' hg.interval_integrable _).comp hf _, { rw ← hf.image_interval, exact mem_image_of_mem f left_mem_interval }, { rw ← hf.image_interval, exact maps_to_image _ _ } }, have h_der : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at (λ u, ∫ t in f a..f u, g t) (f' x • ((g ∘ f) x)) (Ioi x) x, { intros x hx, let I := [Inf (f '' [a, b]), Sup (f '' [a, b])], have hI : f '' [a, b] = I := hf.image_interval, have h2x : f x ∈ I, { rw [← hI], exact mem_image_of_mem f (Ioo_subset_Icc_self hx) }, have h2g : interval_integrable g volume (f a) (f x), { refine (hg.mono $ _).interval_integrable, exact hf.surj_on_interval left_mem_interval (Ioo_subset_Icc_self hx) }, rw [hI] at hg, have h3g : strongly_measurable_at_filter g (𝓝[I] f x) volume := hg.strongly_measurable_at_filter_nhds_within measurable_set_Icc (f x), haveI : fact (f x ∈ I) := ⟨h2x⟩, have : has_deriv_within_at (λ u, ∫ x in f a..u, g x) (g (f x)) I (f x) := integral_has_deriv_within_at_right h2g h3g (hg (f x) h2x), refine (this.scomp x ((hff' x hx).Ioo_of_Ioi hx.2) _).Ioi_of_Ioo hx.2, rw ← hI, exact (maps_to_image _ _).mono (Ioo_subset_Icc_self.trans $ Icc_subset_Icc_left hx.1.le) subset.rfl }, have h_int : interval_integrable (λ (x : ℝ), f' x • (g ∘ f) x) volume a b := (hf'.smul (hg.comp hf $ subset_preimage_image f _)).interval_integrable, simp_rw [integral_eq_sub_of_has_deriv_right h_cont h_der h_int, integral_same, sub_zero], end /-- Change of variables. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous on `f '' [a, b]`, then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. Compared to `interval_integral.integral_comp_smul_deriv` we only require that `g` is continuous on `f '' [a, b]`. -/ theorem integral_comp_smul_deriv' {f f' : ℝ → ℝ} {g : ℝ → E} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, f' x • (g ∘ f) x = ∫ x in f a..f b, g x := integral_comp_smul_deriv'' (λ x hx, (h x hx).continuous_at.continuous_within_at) (λ x hx, (h x $ Ioo_subset_Icc_self hx).has_deriv_within_at) h' hg /-- Change of variables, most common version. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous, then we can substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_smul_deriv {f f' : ℝ → ℝ} {g : ℝ → E} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous g) : ∫ x in a..b, f' x • (g ∘ f) x = ∫ x in f a..f b, g x := integral_comp_smul_deriv' h h' hg.continuous_on theorem integral_deriv_comp_smul_deriv' {f f' : ℝ → ℝ} {g g' : ℝ → E} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g [f a, f b]) (hgg' : ∀ x ∈ Ioo (min (f a) (f b)) (max (f a) (f b)), has_deriv_within_at g (g' x) (Ioi x) x) (hg' : continuous_on g' (f '' [a, b])) : ∫ x in a..b, f' x • (g' ∘ f) x = (g ∘ f) b - (g ∘ f) a := begin rw [integral_comp_smul_deriv'' hf hff' hf' hg', integral_eq_sub_of_has_deriv_right hg hgg' (hg'.mono _).interval_integrable], exact intermediate_value_interval hf end theorem integral_deriv_comp_smul_deriv {f f' : ℝ → ℝ} {g g' : ℝ → E} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hg : ∀ x ∈ interval a b, has_deriv_at g (g' (f x)) (f x)) (hf' : continuous_on f' (interval a b)) (hg' : continuous g') : ∫ x in a..b, f' x • (g' ∘ f) x = (g ∘ f) b - (g ∘ f) a := integral_eq_sub_of_has_deriv_at (λ x hx, (hg x hx).scomp x $ hf x hx) (hf'.smul (hg'.comp_continuous_on $ has_deriv_at.continuous_on hf)).interval_integrable end smul section mul /-- Change of variables, general form for scalar functions. If `f` is continuous on `[a, b]` and has continuous right-derivative `f'` in `(a, b)`, and `g` is continuous on `f '' [a, b]` then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_mul_deriv'' {f f' g : ℝ → ℝ} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u := by simpa [mul_comm] using integral_comp_smul_deriv'' hf hff' hf' hg /-- Change of variables. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous on `f '' [a, b]`, then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. Compared to `interval_integral.integral_comp_mul_deriv` we only require that `g` is continuous on `f '' [a, b]`. -/ theorem integral_comp_mul_deriv' {f f' g : ℝ → ℝ} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous_on g (f '' [a, b])) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x := by simpa [mul_comm] using integral_comp_smul_deriv' h h' hg /-- Change of variables, most common version. If `f` is has continuous derivative `f'` on `[a, b]`, and `g` is continuous, then we can substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`. -/ theorem integral_comp_mul_deriv {f f' g : ℝ → ℝ} (h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (h' : continuous_on f' (interval a b)) (hg : continuous g) : ∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x := integral_comp_mul_deriv' h h' hg.continuous_on theorem integral_deriv_comp_mul_deriv' {f f' g g' : ℝ → ℝ} (hf : continuous_on f [a, b]) (hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x) (hf' : continuous_on f' [a, b]) (hg : continuous_on g [f a, f b]) (hgg' : ∀ x ∈ Ioo (min (f a) (f b)) (max (f a) (f b)), has_deriv_within_at g (g' x) (Ioi x) x) (hg' : continuous_on g' (f '' [a, b])) : ∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a := by simpa [mul_comm] using integral_deriv_comp_smul_deriv' hf hff' hf' hg hgg' hg' theorem integral_deriv_comp_mul_deriv {f f' g g' : ℝ → ℝ} (hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x) (hg : ∀ x ∈ interval a b, has_deriv_at g (g' (f x)) (f x)) (hf' : continuous_on f' (interval a b)) (hg' : continuous g') : ∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a := by simpa [mul_comm] using integral_deriv_comp_smul_deriv hf hg hf' hg' end mul end interval_integral
81fa8d613706f8d62ee3c2ca0ee47f2e04f81a97
2385ce0e3b60d8dbea33dd439902a2070cca7a24
/tests/lean/run/1675.lean
ded29e0040522a83a32f68c2a2713a0b5d85e0bb
[ "Apache-2.0" ]
permissive
TehMillhouse/lean
68d6fdd2fb11a6c65bc28dec308d70f04dad38b4
6bbf2fbd8912617e5a973575bab8c383c9c268a1
refs/heads/master
1,620,830,893,339
1,515,592,479,000
1,515,592,997,000
116,964,828
0
0
null
1,515,592,734,000
1,515,592,734,000
null
UTF-8
Lean
false
false
1,233
lean
def foo (a b : nat) : Prop := a = 0 ∧ b = 0 attribute [simp] foo example (p : nat → Prop) (a b : nat) : foo a b → p (a + b) → p 0 := begin intros h₁ h₂, simp * at *, end example (a b : nat) (p : nat → Prop) (h₁ : a = b + 0) (h₂ : b = 0) (h₃ : p a) : p 0 ∧ a = 0 := by simp * at * constant q : Prop axiom q_lemma : q open tactic example (a b : nat) (p : nat → Prop) (h₁ : a = b + 0) (h₂ : b = 0) (h₃ : p a) : p 0 ∧ a = 0 ∧ q := begin simp * at *, guard_target q, do {e₁ ← get_local `h₁ >>= infer_type, e₂ ← to_expr ```(a = 0), guard (e₁ = e₂)}, do {e₁ ← get_local `h₃ >>= infer_type, e₂ ← to_expr ```(p 0), guard (e₁ = e₂)}, apply q_lemma end example (p : nat → Prop) (a b : nat) : a = 0 ∧ b = 0 → p (a + b) → p 0 := begin intros h₁ h₂, simp [h₁] at *, assumption end example (p : Prop) : p := begin fail_if_success {simp * at *}, -- should fail if nothing was simplified simp * at * {fail_if_unchanged := ff}, -- should work sorry end example (p : Prop) : let h : 0 = 0 := rfl in p := begin intro h, simp * at *, do {e₁ ← get_local `h >>= infer_type, e₂ ← to_expr ```(true), guard (e₁ = e₂)}, sorry end
0cd06f94cc80558a9cb7f63a30ed2ffe9e7fc5fa
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/padics/padic_numbers.lean
78725dc1f1e7c681a7274ef58d464d326c7bb91e
[]
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
22,888
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.padics.padic_norm import Mathlib.analysis.normed_space.basic import Mathlib.PostPort namespace Mathlib /-! # p-adic numbers This file defines the p-adic numbers (rationals) `ℚ_p` as the completion of `ℚ` with respect to the p-adic norm. We show that the p-adic norm on ℚ extends to `ℚ_p`, that `ℚ` is embedded in `ℚ_p`, and that `ℚ_p` is Cauchy complete. ## Important definitions * `padic` : the type of p-adic numbers * `padic_norm_e` : the rational valued p-adic norm on `ℚ_p` ## Notation We introduce the notation `ℚ_[p]` for the p-adic numbers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (prime p)]` as a type class argument. We use the same concrete Cauchy sequence construction that is used to construct ℝ. `ℚ_p` inherits a field structure from this construction. The extension of the norm on ℚ to `ℚ_p` is *not* analogous to extending the absolute value to ℝ, and hence the proof that `ℚ_p` is complete is different from the proof that ℝ is complete. A small special-purpose simplification tactic, `padic_index_simp`, is used to manipulate sequence indices in the proof that the norm extends. `padic_norm_e` is the rational-valued p-adic norm on `ℚ_p`. To instantiate `ℚ_p` as a normed field, we must cast this into a ℝ-valued norm. The `ℝ`-valued norm, using notation `∥ ∥` from normed spaces, is the canonical representation of this norm. `simp` prefers `padic_norm` to `padic_norm_e` when possible. Since `padic_norm_e` and `∥ ∥` have different types, `simp` does not rewrite one to the other. Coercions from `ℚ` to `ℚ_p` are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion -/ /-- The type of Cauchy sequences of rationals with respect to the p-adic norm. -/ def padic_seq (p : ℕ) := cau_seq ℚ (padic_norm p) namespace padic_seq /-- The p-adic norm of the entries of a nonzero Cauchy sequence of rationals is eventually constant. -/ theorem stationary {p : ℕ} [fact (nat.prime p)] {f : cau_seq ℚ (padic_norm p)} (hf : ¬f ≈ 0) : ∃ (N : ℕ), ∀ (m n : ℕ), N ≤ m → N ≤ n → padic_norm p (coe_fn f n) = padic_norm p (coe_fn f m) := sorry /-- For all n ≥ stationary_point f hf, the p-adic norm of f n is the same. -/ def stationary_point {p : ℕ} [fact (nat.prime p)] {f : padic_seq p} (hf : ¬f ≈ 0) : ℕ := classical.some (stationary hf) theorem stationary_point_spec {p : ℕ} [fact (nat.prime p)] {f : padic_seq p} (hf : ¬f ≈ 0) {m : ℕ} {n : ℕ} : stationary_point hf ≤ m → stationary_point hf ≤ n → padic_norm p (coe_fn f n) = padic_norm p (coe_fn f m) := classical.some_spec (stationary hf) /-- Since the norm of the entries of a Cauchy sequence is eventually stationary, we can lift the norm to sequences. -/ def norm {p : ℕ} [fact (nat.prime p)] (f : padic_seq p) : ℚ := dite (f ≈ 0) (fun (hf : f ≈ 0) => 0) fun (hf : ¬f ≈ 0) => padic_norm p (coe_fn f (stationary_point hf)) theorem norm_zero_iff {p : ℕ} [fact (nat.prime p)] (f : padic_seq p) : norm f = 0 ↔ f ≈ 0 := sorry theorem equiv_zero_of_val_eq_of_equiv_zero {p : ℕ} [fact (nat.prime p)] {f : padic_seq p} {g : padic_seq p} (h : ∀ (k : ℕ), padic_norm p (coe_fn f k) = padic_norm p (coe_fn g k)) (hf : f ≈ 0) : g ≈ 0 := sorry theorem norm_nonzero_of_not_equiv_zero {p : ℕ} [fact (nat.prime p)] {f : padic_seq p} (hf : ¬f ≈ 0) : norm f ≠ 0 := hf ∘ iff.mp (norm_zero_iff f) theorem norm_eq_norm_app_of_nonzero {p : ℕ} [fact (nat.prime p)] {f : padic_seq p} (hf : ¬f ≈ 0) : ∃ (k : ℚ), norm f = padic_norm p k ∧ k ≠ 0 := sorry theorem not_lim_zero_const_of_nonzero {p : ℕ} [fact (nat.prime p)] {q : ℚ} (hq : q ≠ 0) : ¬cau_seq.lim_zero (cau_seq.const (padic_norm p) q) := fun (h' : cau_seq.lim_zero (cau_seq.const (padic_norm p) q)) => hq (iff.mp cau_seq.const_lim_zero h') theorem not_equiv_zero_const_of_nonzero {p : ℕ} [fact (nat.prime p)] {q : ℚ} (hq : q ≠ 0) : ¬cau_seq.const (padic_norm p) q ≈ 0 := sorry theorem norm_nonneg {p : ℕ} [fact (nat.prime p)] (f : padic_seq p) : 0 ≤ norm f := sorry /-- An auxiliary lemma for manipulating sequence indices. -/ theorem lift_index_left_left {p : ℕ} [fact (nat.prime p)] {f : padic_seq p} (hf : ¬f ≈ 0) (v2 : ℕ) (v3 : ℕ) : padic_norm p (coe_fn f (stationary_point hf)) = padic_norm p (coe_fn f (max (stationary_point hf) (max v2 v3))) := stationary_point_spec hf (le_max_left (stationary_point hf) (max v2 v3)) (le_refl (stationary_point hf)) /-- An auxiliary lemma for manipulating sequence indices. -/ theorem lift_index_left {p : ℕ} [fact (nat.prime p)] {f : padic_seq p} (hf : ¬f ≈ 0) (v1 : ℕ) (v3 : ℕ) : padic_norm p (coe_fn f (stationary_point hf)) = padic_norm p (coe_fn f (max v1 (max (stationary_point hf) v3))) := stationary_point_spec hf (le_trans (le_max_left (stationary_point hf) v3) (le_max_right v1 (max (stationary_point hf) v3))) (le_refl (stationary_point hf)) /-- An auxiliary lemma for manipulating sequence indices. -/ theorem lift_index_right {p : ℕ} [fact (nat.prime p)] {f : padic_seq p} (hf : ¬f ≈ 0) (v1 : ℕ) (v2 : ℕ) : padic_norm p (coe_fn f (stationary_point hf)) = padic_norm p (coe_fn f (max v1 (max v2 (stationary_point hf)))) := stationary_point_spec hf (le_trans (le_max_right v2 (stationary_point hf)) (le_max_right v1 (max v2 (stationary_point hf)))) (le_refl (stationary_point hf)) /-! ### Valuation on `padic_seq` -/ /-- The `p`-adic valuation on `ℚ` lifts to `padic_seq p`. `valuation f` is defined to be the valuation of the (`ℚ`-valued) stationary point of `f`. -/ def valuation {p : ℕ} [fact (nat.prime p)] (f : padic_seq p) : ℤ := dite (f ≈ 0) (fun (hf : f ≈ 0) => 0) fun (hf : ¬f ≈ 0) => padic_val_rat p (coe_fn f (stationary_point hf)) theorem norm_eq_pow_val {p : ℕ} [fact (nat.prime p)] {f : padic_seq p} (hf : ¬f ≈ 0) : norm f = ↑p ^ (-valuation f) := sorry theorem val_eq_iff_norm_eq {p : ℕ} [fact (nat.prime p)] {f : padic_seq p} {g : padic_seq p} (hf : ¬f ≈ 0) (hg : ¬g ≈ 0) : valuation f = valuation g ↔ norm f = norm g := sorry end padic_seq /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ namespace padic_seq theorem norm_mul {p : ℕ} [hp : fact (nat.prime p)] (f : padic_seq p) (g : padic_seq p) : norm (f * g) = norm f * norm g := sorry theorem eq_zero_iff_equiv_zero {p : ℕ} [hp : fact (nat.prime p)] (f : padic_seq p) : cau_seq.completion.mk f = 0 ↔ f ≈ 0 := cau_seq.completion.mk_eq theorem ne_zero_iff_nequiv_zero {p : ℕ} [hp : fact (nat.prime p)] (f : padic_seq p) : cau_seq.completion.mk f ≠ 0 ↔ ¬f ≈ 0 := iff.mpr not_iff_not (eq_zero_iff_equiv_zero f) theorem norm_const {p : ℕ} [hp : fact (nat.prime p)] (q : ℚ) : norm (cau_seq.const (padic_norm p) q) = padic_norm p q := sorry theorem norm_values_discrete {p : ℕ} [hp : fact (nat.prime p)] (a : padic_seq p) (ha : ¬a ≈ 0) : ∃ (z : ℤ), norm a = ↑p ^ (-z) := sorry theorem norm_one {p : ℕ} [hp : fact (nat.prime p)] : norm 1 = 1 := sorry theorem norm_equiv {p : ℕ} [hp : fact (nat.prime p)] {f : padic_seq p} {g : padic_seq p} (hfg : f ≈ g) : norm f = norm g := sorry theorem norm_nonarchimedean {p : ℕ} [hp : fact (nat.prime p)] (f : padic_seq p) (g : padic_seq p) : norm (f + g) ≤ max (norm f) (norm g) := sorry theorem norm_eq {p : ℕ} [hp : fact (nat.prime p)] {f : padic_seq p} {g : padic_seq p} (h : ∀ (k : ℕ), padic_norm p (coe_fn f k) = padic_norm p (coe_fn g k)) : norm f = norm g := sorry theorem norm_neg {p : ℕ} [hp : fact (nat.prime p)] (a : padic_seq p) : norm (-a) = norm a := sorry theorem norm_eq_of_add_equiv_zero {p : ℕ} [hp : fact (nat.prime p)] {f : padic_seq p} {g : padic_seq p} (h : f + g ≈ 0) : norm f = norm g := sorry theorem add_eq_max_of_ne {p : ℕ} [hp : fact (nat.prime p)] {f : padic_seq p} {g : padic_seq p} (hfgne : norm f ≠ norm g) : norm (f + g) = max (norm f) (norm g) := sorry end padic_seq /-- The p-adic numbers `Q_[p]` are the Cauchy completion of `ℚ` with respect to the p-adic norm. -/ def padic (p : ℕ) [fact (nat.prime p)] := cau_seq.completion.Cauchy namespace padic /-- The discrete field structure on `ℚ_p` is inherited from the Cauchy completion construction. -/ protected instance field {p : ℕ} [fact (nat.prime p)] : field (padic p) := cau_seq.completion.field protected instance inhabited {p : ℕ} [fact (nat.prime p)] : Inhabited (padic p) := { default := 0 } -- short circuits protected instance has_zero {p : ℕ} [fact (nat.prime p)] : HasZero (padic p) := mul_zero_class.to_has_zero (padic p) protected instance has_one {p : ℕ} [fact (nat.prime p)] : HasOne (padic p) := monoid.to_has_one (padic p) protected instance has_add {p : ℕ} [fact (nat.prime p)] : Add (padic p) := distrib.to_has_add (padic p) protected instance has_mul {p : ℕ} [fact (nat.prime p)] : Mul (padic p) := distrib.to_has_mul (padic p) protected instance has_sub {p : ℕ} [fact (nat.prime p)] : Sub (padic p) := sub_neg_monoid.to_has_sub (padic p) protected instance has_neg {p : ℕ} [fact (nat.prime p)] : Neg (padic p) := sub_neg_monoid.to_has_neg (padic p) protected instance has_div {p : ℕ} [fact (nat.prime p)] : Div (padic p) := div_inv_monoid.to_has_div (padic p) protected instance add_comm_group {p : ℕ} [fact (nat.prime p)] : add_comm_group (padic p) := ring.to_add_comm_group (padic p) protected instance comm_ring {p : ℕ} [fact (nat.prime p)] : comm_ring (padic p) := euclidean_domain.to_comm_ring (padic p) /-- Builds the equivalence class of a Cauchy sequence of rationals. -/ def mk {p : ℕ} [fact (nat.prime p)] : padic_seq p → padic p := quotient.mk theorem mk_eq (p : ℕ) [fact (nat.prime p)] {f : padic_seq p} {g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq /-- Embeds the rational numbers in the p-adic numbers. -/ def of_rat (p : ℕ) [fact (nat.prime p)] : ℚ → padic p := cau_seq.completion.of_rat @[simp] theorem of_rat_add (p : ℕ) [fact (nat.prime p)] (x : ℚ) (y : ℚ) : of_rat p (x + y) = of_rat p x + of_rat p y := cau_seq.completion.of_rat_add @[simp] theorem of_rat_neg (p : ℕ) [fact (nat.prime p)] (x : ℚ) : of_rat p (-x) = -of_rat p x := cau_seq.completion.of_rat_neg @[simp] theorem of_rat_mul (p : ℕ) [fact (nat.prime p)] (x : ℚ) (y : ℚ) : of_rat p (x * y) = of_rat p x * of_rat p y := cau_seq.completion.of_rat_mul @[simp] theorem of_rat_sub (p : ℕ) [fact (nat.prime p)] (x : ℚ) (y : ℚ) : of_rat p (x - y) = of_rat p x - of_rat p y := cau_seq.completion.of_rat_sub @[simp] theorem of_rat_div (p : ℕ) [fact (nat.prime p)] (x : ℚ) (y : ℚ) : of_rat p (x / y) = of_rat p x / of_rat p y := cau_seq.completion.of_rat_div @[simp] theorem of_rat_one (p : ℕ) [fact (nat.prime p)] : of_rat p 1 = 1 := rfl @[simp] theorem of_rat_zero (p : ℕ) [fact (nat.prime p)] : of_rat p 0 = 0 := rfl theorem cast_eq_of_rat_of_nat (p : ℕ) [fact (nat.prime p)] (n : ℕ) : ↑n = of_rat p ↑n := sorry theorem cast_eq_of_rat_of_int (p : ℕ) [fact (nat.prime p)] (n : ℤ) : ↑n = of_rat p ↑n := sorry theorem cast_eq_of_rat (p : ℕ) [fact (nat.prime p)] (q : ℚ) : ↑q = of_rat p q := sorry theorem coe_add (p : ℕ) [fact (nat.prime p)] {x : ℚ} {y : ℚ} : ↑(x + y) = ↑x + ↑y := sorry theorem coe_neg (p : ℕ) [fact (nat.prime p)] {x : ℚ} : ↑(-x) = -↑x := sorry theorem coe_mul (p : ℕ) [fact (nat.prime p)] {x : ℚ} {y : ℚ} : ↑(x * y) = ↑x * ↑y := sorry theorem coe_sub (p : ℕ) [fact (nat.prime p)] {x : ℚ} {y : ℚ} : ↑(x - y) = ↑x - ↑y := sorry theorem coe_div (p : ℕ) [fact (nat.prime p)] {x : ℚ} {y : ℚ} : ↑(x / y) = ↑x / ↑y := sorry theorem coe_one (p : ℕ) [fact (nat.prime p)] : ↑1 = 1 := rfl theorem coe_zero (p : ℕ) [fact (nat.prime p)] : ↑0 = 0 := rfl theorem const_equiv (p : ℕ) [fact (nat.prime p)] {q : ℚ} {r : ℚ} : cau_seq.const (padic_norm p) q ≈ cau_seq.const (padic_norm p) r ↔ q = r := sorry theorem of_rat_eq (p : ℕ) [fact (nat.prime p)] {q : ℚ} {r : ℚ} : of_rat p q = of_rat p r ↔ q = r := { mp := iff.mp (const_equiv p) ∘ iff.mp quotient.eq, mpr := fun (h : q = r) => eq.mpr (id (Eq._oldrec (Eq.refl (of_rat p q = of_rat p r)) h)) (Eq.refl (of_rat p r)) } theorem coe_inj (p : ℕ) [fact (nat.prime p)] {q : ℚ} {r : ℚ} : ↑q = ↑r ↔ q = r := sorry protected instance char_zero (p : ℕ) [fact (nat.prime p)] : char_zero (padic p) := char_zero.mk fun (m n : ℕ) => eq.mpr (id (Eq._oldrec (Eq.refl (↑m = ↑n → m = n)) (Eq.symm (rat.cast_coe_nat m)))) (eq.mpr (id (imp_congr_eq (Eq.trans (Eq.trans (congr_arg (Eq ↑↑m) (Eq.symm (rat.cast_coe_nat n))) (propext (coe_inj p))) (propext nat.cast_inj)) (Eq.refl (m = n)))) id) end padic /-- The rational-valued p-adic norm on `ℚ_p` is lifted from the norm on Cauchy sequences. The canonical form of this function is the normed space instance, with notation `∥ ∥`. -/ def padic_norm_e {p : ℕ} [hp : fact (nat.prime p)] : padic p → ℚ := quotient.lift padic_seq.norm padic_seq.norm_equiv namespace padic_norm_e theorem defn {p : ℕ} [fact (nat.prime p)] (f : padic_seq p) {ε : ℚ} (hε : 0 < ε) : ∃ (N : ℕ), ∀ (i : ℕ), i ≥ N → padic_norm_e (quotient.mk f - ↑(coe_fn f i)) < ε := sorry protected theorem nonneg {p : ℕ} [fact (nat.prime p)] (q : padic p) : 0 ≤ padic_norm_e q := quotient.induction_on q padic_seq.norm_nonneg theorem zero_def {p : ℕ} [fact (nat.prime p)] : 0 = quotient.mk 0 := rfl theorem zero_iff {p : ℕ} [fact (nat.prime p)] (q : padic p) : padic_norm_e q = 0 ↔ q = 0 := sorry @[simp] protected theorem zero {p : ℕ} [fact (nat.prime p)] : padic_norm_e 0 = 0 := iff.mpr (zero_iff 0) rfl /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ @[simp] protected theorem one' {p : ℕ} [fact (nat.prime p)] : padic_norm_e 1 = 1 := padic_seq.norm_one @[simp] protected theorem neg {p : ℕ} [fact (nat.prime p)] (q : padic p) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q padic_seq.norm_neg /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem nonarchimedean' {p : ℕ} [fact (nat.prime p)] (q : padic p) (r : padic p) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r padic_seq.norm_nonarchimedean /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem add_eq_max_of_ne' {p : ℕ} [fact (nat.prime p)] {q : padic p} {r : padic p} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r fun (_x _x_1 : cau_seq ℚ (padic_norm p)) => padic_seq.add_eq_max_of_ne theorem triangle_ineq {p : ℕ} [fact (nat.prime p)] (x : padic p) (y : padic p) (z : padic p) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := sorry protected theorem add {p : ℕ} [fact (nat.prime p)] (q : padic p) (r : padic p) : padic_norm_e (q + r) ≤ padic_norm_e q + padic_norm_e r := le_trans (nonarchimedean' q r) (max_le_add_of_nonneg (padic_norm_e.nonneg q) (padic_norm_e.nonneg r)) protected theorem mul' {p : ℕ} [fact (nat.prime p)] (q : padic p) (r : padic p) : padic_norm_e (q * r) = padic_norm_e q * padic_norm_e r := quotient.induction_on₂ q r padic_seq.norm_mul protected instance is_absolute_value {p : ℕ} [fact (nat.prime p)] : is_absolute_value padic_norm_e := is_absolute_value.mk padic_norm_e.nonneg zero_iff padic_norm_e.add padic_norm_e.mul' @[simp] theorem eq_padic_norm' {p : ℕ} [fact (nat.prime p)] (q : ℚ) : padic_norm_e (padic.of_rat p q) = padic_norm p q := padic_seq.norm_const q protected theorem image' {p : ℕ} [fact (nat.prime p)] {q : padic p} : q ≠ 0 → ∃ (n : ℤ), padic_norm_e q = ↑p ^ (-n) := quotient.induction_on q fun (f : cau_seq ℚ (padic_norm p)) (hf : quotient.mk f ≠ 0) => (fun (this : ¬f ≈ 0) => padic_seq.norm_values_discrete f this) (iff.mp (padic_seq.ne_zero_iff_nequiv_zero f) hf) theorem sub_rev {p : ℕ} [fact (nat.prime p)] (q : padic p) (r : padic p) : padic_norm_e (q - r) = padic_norm_e (r - q) := sorry end padic_norm_e namespace padic theorem rat_dense' {p : ℕ} [fact (nat.prime p)] (q : padic p) {ε : ℚ} (hε : 0 < ε) : ∃ (r : ℚ), padic_norm_e (q - ↑r) < ε := sorry /-- `lim_seq f`, for `f` a Cauchy sequence of `p`-adic numbers, is a sequence of rationals with the same limit point as `f`. -/ def lim_seq {p : ℕ} [fact (nat.prime p)] (f : cau_seq (padic p) padic_norm_e) : ℕ → ℚ := fun (n : ℕ) => classical.some sorry theorem exi_rat_seq_conv {p : ℕ} [fact (nat.prime p)] (f : cau_seq (padic p) padic_norm_e) {ε : ℚ} (hε : 0 < ε) : ∃ (N : ℕ), ∀ (i : ℕ), i ≥ N → padic_norm_e (coe_fn f i - ↑(lim_seq f i)) < ε := sorry theorem exi_rat_seq_conv_cauchy {p : ℕ} [fact (nat.prime p)] (f : cau_seq (padic p) padic_norm_e) : is_cau_seq (padic_norm p) (lim_seq f) := sorry theorem complete' {p : ℕ} [fact (nat.prime p)] (f : cau_seq (padic p) padic_norm_e) : ∃ (q : padic p), ∀ (ε : ℚ), ε > 0 → ∃ (N : ℕ), ∀ (i : ℕ), i ≥ N → padic_norm_e (q - coe_fn f i) < ε := sorry protected instance has_dist (p : ℕ) [fact (nat.prime p)] : has_dist (padic p) := has_dist.mk fun (x y : padic p) => ↑(padic_norm_e (x - y)) protected instance metric_space (p : ℕ) [fact (nat.prime p)] : metric_space (padic p) := metric_space.mk sorry sorry sorry sorry (fun (x y : padic p) => ennreal.of_real ((fun (x y : padic p) => ↑(padic_norm_e (x - y))) x y)) (uniform_space_of_dist (fun (x y : padic p) => ↑(padic_norm_e (x - y))) sorry sorry sorry) protected instance has_norm (p : ℕ) [fact (nat.prime p)] : has_norm (padic p) := has_norm.mk fun (x : padic p) => ↑(padic_norm_e x) protected instance normed_field (p : ℕ) [fact (nat.prime p)] : normed_field (padic p) := normed_field.mk sorry sorry protected instance is_absolute_value (p : ℕ) [fact (nat.prime p)] : is_absolute_value fun (a : padic p) => norm a := sorry theorem rat_dense {p : ℕ} {hp : fact (nat.prime p)} (q : padic p) {ε : ℝ} (hε : 0 < ε) : ∃ (r : ℚ), norm (q - ↑r) < ε := sorry end padic namespace padic_norm_e @[simp] protected theorem mul {p : ℕ} [hp : fact (nat.prime p)] (q : padic p) (r : padic p) : norm (q * r) = norm q * norm r := sorry protected theorem is_norm {p : ℕ} [hp : fact (nat.prime p)] (q : padic p) : ↑(padic_norm_e q) = norm q := rfl theorem nonarchimedean {p : ℕ} [hp : fact (nat.prime p)] (q : padic p) (r : padic p) : norm (q + r) ≤ max (norm q) (norm r) := sorry theorem add_eq_max_of_ne {p : ℕ} [hp : fact (nat.prime p)] {q : padic p} {r : padic p} (h : norm q ≠ norm r) : norm (q + r) = max (norm q) (norm r) := sorry @[simp] theorem eq_padic_norm {p : ℕ} [hp : fact (nat.prime p)] (q : ℚ) : norm ↑q = ↑(padic_norm p q) := sorry protected instance padic.nondiscrete_normed_field {p : ℕ} [hp : fact (nat.prime p)] : nondiscrete_normed_field (padic p) := nondiscrete_normed_field.mk sorry @[simp] theorem norm_p {p : ℕ} [hp : fact (nat.prime p)] : norm ↑p = (↑p⁻¹) := sorry theorem norm_p_lt_one {p : ℕ} [hp : fact (nat.prime p)] : norm ↑p < 1 := sorry @[simp] theorem norm_p_pow {p : ℕ} [hp : fact (nat.prime p)] (n : ℤ) : norm (↑p ^ n) = ↑p ^ (-n) := sorry protected theorem image {p : ℕ} [hp : fact (nat.prime p)] {q : padic p} : q ≠ 0 → ∃ (n : ℤ), norm q = ↑(↑p ^ (-n)) := sorry protected theorem is_rat {p : ℕ} [hp : fact (nat.prime p)] (q : padic p) : ∃ (q' : ℚ), norm q = ↑q' := sorry /--`rat_norm q`, for a `p`-adic number `q` is the `p`-adic norm of `q`, as rational number. The lemma `padic_norm_e.eq_rat_norm` asserts `∥q∥ = rat_norm q`. -/ def rat_norm {p : ℕ} [hp : fact (nat.prime p)] (q : padic p) : ℚ := classical.some (padic_norm_e.is_rat q) theorem eq_rat_norm {p : ℕ} [hp : fact (nat.prime p)] (q : padic p) : norm q = ↑(rat_norm q) := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one {p : ℕ} [hp : fact (nat.prime p)] {q : ℚ} (hq : ¬p ∣ rat.denom q) : norm ↑q ≤ 1 := sorry theorem norm_int_le_one {p : ℕ} [hp : fact (nat.prime p)] (z : ℤ) : norm ↑z ≤ 1 := sorry theorem norm_int_lt_one_iff_dvd {p : ℕ} [hp : fact (nat.prime p)] (k : ℤ) : norm ↑k < 1 ↔ ↑p ∣ k := sorry theorem norm_int_le_pow_iff_dvd {p : ℕ} [hp : fact (nat.prime p)] (k : ℤ) (n : ℕ) : norm ↑k ≤ ↑p ^ (-↑n) ↔ ↑(p ^ n) ∣ k := sorry theorem eq_of_norm_add_lt_right {p : ℕ} {hp : fact (nat.prime p)} {z1 : padic p} {z2 : padic p} (h : norm (z1 + z2) < norm z2) : norm z1 = norm z2 := sorry theorem eq_of_norm_add_lt_left {p : ℕ} {hp : fact (nat.prime p)} {z1 : padic p} {z2 : padic p} (h : norm (z1 + z2) < norm z1) : norm z1 = norm z2 := sorry end padic_norm_e namespace padic protected instance complete {p : ℕ} [fact (nat.prime p)] : cau_seq.is_complete (padic p) norm := cau_seq.is_complete.mk sorry theorem padic_norm_e_lim_le {p : ℕ} [fact (nat.prime p)] {f : cau_seq (padic p) norm} {a : ℝ} (ha : 0 < a) (hf : ∀ (i : ℕ), norm (coe_fn f i) ≤ a) : norm (cau_seq.lim f) ≤ a := sorry /-! ### Valuation on `ℚ_[p]` -/ /-- `padic.valuation` lifts the p-adic valuation on rationals to `ℚ_[p]`. -/ def valuation {p : ℕ} [fact (nat.prime p)] : padic p → ℤ := quotient.lift padic_seq.valuation sorry @[simp] theorem valuation_zero {p : ℕ} [fact (nat.prime p)] : valuation 0 = 0 := dif_pos (iff.mpr (const_equiv p) rfl) @[simp] theorem valuation_one {p : ℕ} [fact (nat.prime p)] : valuation 1 = 0 := sorry theorem norm_eq_pow_val {p : ℕ} [fact (nat.prime p)] {x : padic p} : x ≠ 0 → norm x = ↑p ^ (-valuation x) := sorry @[simp] theorem valuation_p {p : ℕ} [fact (nat.prime p)] : valuation ↑p = 1 := sorry
1b72eee0bdb90410999d5335a686e5d48a57c72d
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/dedekind_domain/dvr.lean
62b3fd3e1307b71764ab3d256e471f38b78a3226
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
7,333
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.localization.localization_localization import ring_theory.localization.submodule import ring_theory.discrete_valuation_ring.tfae /-! # Dedekind domains This file defines an equivalent notion of a Dedekind domain (or Dedekind ring), namely a Noetherian integral domain where the localization at all nonzero prime ideals is a DVR (TODO: and shows that implies the main definition). ## Main definitions - `is_dedekind_domain_dvr` alternatively defines a Dedekind domain as an integral domain that is Noetherian, and the localization at every nonzero prime ideal is a DVR. ## Main results - `is_localization.at_prime.discrete_valuation_ring_of_dedekind_domain` shows that `is_dedekind_domain` implies the localization at each nonzero prime ideal is a DVR. - `is_dedekind_domain.is_dedekind_domain_dvr` is one direction of the equivalence of definitions of a Dedekind domain ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. Often, definitions assume that Dedekind domains are not fields. We found it more practical to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [comm_ring A] [is_domain A] [field K] open_locale non_zero_divisors polynomial /-- A Dedekind domain is an integral domain that is Noetherian, and the localization at every nonzero prime is a discrete valuation ring. This is equivalent to `is_dedekind_domain`. TODO: prove the equivalence. -/ structure is_dedekind_domain_dvr : Prop := (is_noetherian_ring : is_noetherian_ring A) (is_dvr_at_nonzero_prime : ∀ P ≠ (⊥ : ideal A), P.is_prime → discrete_valuation_ring (localization.at_prime P)) /-- Localizing a domain of Krull dimension `≤ 1` gives another ring of Krull dimension `≤ 1`. Note that the same proof can/should be generalized to preserving any Krull dimension, once we have a suitable definition. -/ lemma ring.dimension_le_one.localization {R : Type*} (Rₘ : Type*) [comm_ring R] [is_domain R] [comm_ring Rₘ] [algebra R Rₘ] {M : submonoid R} [is_localization M Rₘ] (hM : M ≤ R⁰) (h : ring.dimension_le_one R) : ring.dimension_le_one Rₘ := begin introsI p hp0 hpp, refine ideal.is_maximal_def.mpr ⟨hpp.ne_top, ideal.maximal_of_no_maximal (λ P hpP hPm, _)⟩, have hpP' : (⟨p, hpp⟩ : {p : ideal Rₘ // p.is_prime}) < ⟨P, hPm.is_prime⟩ := hpP, rw ← (is_localization.order_iso_of_prime M Rₘ).lt_iff_lt at hpP', haveI : ideal.is_prime (ideal.comap (algebra_map R Rₘ) p) := ((is_localization.order_iso_of_prime M Rₘ) ⟨p, hpp⟩).2.1, haveI : ideal.is_prime (ideal.comap (algebra_map R Rₘ) P) := ((is_localization.order_iso_of_prime M Rₘ) ⟨P, hPm.is_prime⟩).2.1, have hlt : ideal.comap (algebra_map R Rₘ) p < ideal.comap (algebra_map R Rₘ) P := hpP', refine h.not_lt_lt ⊥ (ideal.comap _ _) (ideal.comap _ _) ⟨_, hpP'⟩, exact is_localization.bot_lt_comap_prime _ _ hM _ hp0 end /-- The localization of a Dedekind domain is a Dedekind domain. -/ lemma is_localization.is_dedekind_domain [is_dedekind_domain A] {M : submonoid A} (hM : M ≤ A⁰) (Aₘ : Type*) [comm_ring Aₘ] [is_domain Aₘ] [algebra A Aₘ] [is_localization M Aₘ] : is_dedekind_domain Aₘ := begin have : ∀ (y : M), is_unit (algebra_map A (fraction_ring A) y), { rintros ⟨y, hy⟩, exact is_unit.mk0 _ (mt is_fraction_ring.to_map_eq_zero_iff.mp (non_zero_divisors.ne_zero (hM hy))) }, letI : algebra Aₘ (fraction_ring A) := ring_hom.to_algebra (is_localization.lift this), haveI : is_scalar_tower A Aₘ (fraction_ring A) := is_scalar_tower.of_algebra_map_eq (λ x, (is_localization.lift_eq this x).symm), haveI : is_fraction_ring Aₘ (fraction_ring A) := is_fraction_ring.is_fraction_ring_of_is_domain_of_is_localization M _ _, refine (is_dedekind_domain_iff _ (fraction_ring A)).mpr ⟨_, _, _⟩, { exact is_localization.is_noetherian_ring M _ (by apply_instance) }, { exact is_dedekind_domain.dimension_le_one.localization Aₘ hM }, { intros x hx, obtain ⟨⟨y, y_mem⟩, hy⟩ := hx.exists_multiple_integral_of_is_localization M _, obtain ⟨z, hz⟩ := (is_integrally_closed_iff _).mp is_dedekind_domain.is_integrally_closed hy, refine ⟨is_localization.mk' Aₘ z ⟨y, y_mem⟩, (is_localization.lift_mk'_spec _ _ _ _).mpr _⟩, rw [hz, set_like.coe_mk, ← algebra.smul_def], refl }, end /-- The localization of a Dedekind domain at every nonzero prime ideal is a Dedekind domain. -/ lemma is_localization.at_prime.is_dedekind_domain [is_dedekind_domain A] (P : ideal A) [P.is_prime] (Aₘ : Type*) [comm_ring Aₘ] [is_domain Aₘ] [algebra A Aₘ] [is_localization.at_prime Aₘ P] : is_dedekind_domain Aₘ := is_localization.is_dedekind_domain A P.prime_compl_le_non_zero_divisors Aₘ lemma is_localization.at_prime.not_is_field {P : ideal A} (hP : P ≠ ⊥) [pP : P.is_prime] (Aₘ : Type*) [comm_ring Aₘ] [algebra A Aₘ] [is_localization.at_prime Aₘ P] : ¬ (is_field Aₘ) := begin intro h, letI := h.to_field, obtain ⟨x, x_mem, x_ne⟩ := P.ne_bot_iff.mp hP, exact (local_ring.maximal_ideal.is_maximal _).ne_top (ideal.eq_top_of_is_unit_mem _ ((is_localization.at_prime.to_map_mem_maximal_iff Aₘ P _).mpr x_mem) (is_unit_iff_ne_zero.mpr ((map_ne_zero_iff (algebra_map A Aₘ) (is_localization.injective Aₘ P.prime_compl_le_non_zero_divisors)).mpr x_ne))), end /-- In a Dedekind domain, the localization at every nonzero prime ideal is a DVR. -/ lemma is_localization.at_prime.discrete_valuation_ring_of_dedekind_domain [is_dedekind_domain A] {P : ideal A} (hP : P ≠ ⊥) [pP : P.is_prime] (Aₘ : Type*) [comm_ring Aₘ] [is_domain Aₘ] [algebra A Aₘ] [is_localization.at_prime Aₘ P] : discrete_valuation_ring Aₘ := begin classical, letI : is_noetherian_ring Aₘ := is_localization.is_noetherian_ring P.prime_compl _ is_dedekind_domain.is_noetherian_ring, letI : local_ring Aₘ := is_localization.at_prime.local_ring Aₘ P, have hnf := is_localization.at_prime.not_is_field A hP Aₘ, exact ((discrete_valuation_ring.tfae Aₘ hnf).out 0 2).mpr (is_localization.at_prime.is_dedekind_domain A P _) end /-- Dedekind domains, in the sense of Noetherian integrally closed domains of Krull dimension ≤ 1, are also Dedekind domains in the sense of Noetherian domains where the localization at every nonzero prime ideal is a DVR. -/ theorem is_dedekind_domain.is_dedekind_domain_dvr [is_dedekind_domain A] : is_dedekind_domain_dvr A := { is_noetherian_ring := is_dedekind_domain.is_noetherian_ring, is_dvr_at_nonzero_prime := λ P hP pP, by exactI is_localization.at_prime.discrete_valuation_ring_of_dedekind_domain A hP _ }
051c65029e57300903f8565a339ca66bf84fe2eb
7cef822f3b952965621309e88eadf618da0c8ae9
/src/computability/turing_machine.lean
46544e741ba5edd7ed4d8ca61b1df44232ed9a30
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
67,542
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Define a sequence of simple machine languages, starting with Turing machines and working up to more complex lanaguages based on Wang B-machines. -/ import data.fintype data.pfun logic.relation open relation namespace turing /-- A direction for the turing machine `move` command, either left or right. -/ @[derive decidable_eq] inductive dir | left | right def tape (Γ) := Γ × list Γ × list Γ def tape.mk {Γ} [inhabited Γ] (l : list Γ) : tape Γ := (l.head, [], l.tail) def tape.mk' {Γ} [inhabited Γ] (L R : list Γ) : tape Γ := (R.head, L, R.tail) def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ | dir.left (a, L, R) := (L.head, L.tail, a :: R) | dir.right (a, L, R) := (R.head, a :: L, R.tail) def tape.nth {Γ} [inhabited Γ] : tape Γ → ℤ → Γ | (a, L, R) 0 := a | (a, L, R) (n+1:ℕ) := R.inth n | (a, L, R) -[1+ n] := L.inth n @[simp] theorem tape.nth_zero {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.nth 0 = T.1 | (a, L, R) := rfl @[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1) | (a, L, R) -[1+ n] := by cases L; refl | (a, L, R) 0 := by cases L; refl | (a, L, R) 1 := rfl | (a, L, R) ((n+1:ℕ)+1) := by rw add_sub_cancel; refl @[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.right).nth i = T.nth (i+1) | (a, L, R) (n+1:ℕ) := by cases R; refl | (a, L, R) 0 := by cases R; refl | (a, L, R) -1 := rfl | (a, L, R) -[1+ n+1] := show _ = tape.nth _ (-[1+ n] - 1 + 1), by rw sub_add_cancel; refl def tape.write {Γ} (b : Γ) : tape Γ → tape Γ | (a, LR) := (b, LR) @[simp] theorem tape.write_self {Γ} : ∀ (T : tape Γ), T.write T.1 = T | (a, LR) := rfl @[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) : ∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i | (a, L, R) 0 := rfl | (a, L, R) (n+1:ℕ) := rfl | (a, L, R) -[1+ n] := rfl def tape.map {Γ Γ'} (f : Γ → Γ') : tape Γ → tape Γ' | (a, L, R) := (f a, L.map f, R.map f) @[simp] theorem tape.map_fst {Γ Γ'} (f : Γ → Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 | (a, L, R) := rfl @[simp] theorem tape.map_write {Γ Γ'} (f : Γ → Γ') (b : Γ) : ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) | (a, L, R) := rfl @[class] def pointed_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') := f (default _) = default _ theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') [pointed_map f] : ∀ (T : tape Γ) d, (T.move d).map f = (T.map f).move d | (a, [], R) dir.left := prod.ext ‹pointed_map f› rfl | (a, b::L, R) dir.left := rfl | (a, L, []) dir.right := prod.ext ‹pointed_map f› rfl | (a, L, b::R) dir.right := rfl theorem tape.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') [f0 : pointed_map f] : ∀ (l : list Γ), (tape.mk l).map f = tape.mk (l.map f) | [] := prod.ext ‹pointed_map f› rfl | (a::l) := rfl def eval {σ} (f : σ → option σ) : σ → roption σ := pfun.fix (λ s, roption.some $ match f s with none := sum.inl s | some s' := sum.inr s' end) def reaches {σ} (f : σ → option σ) : σ → σ → Prop := refl_trans_gen (λ a b, b ∈ f a) def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop := trans_gen (λ a b, b ∈ f a) theorem reaches₁_eq {σ} {f : σ → option σ} {a b c} (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c := trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm theorem reaches_total {σ} {f : σ → option σ} {a b c} : reaches f a b → reaches f a c → reaches f b c ∨ reaches f c b := refl_trans_gen.total_of_right_unique $ λ _ _ _, option.mem_unique theorem reaches₁_fwd {σ} {f : σ → option σ} {a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c := begin rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩, cases option.mem_unique hab h₂, exact hbc end def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop := ∀ c, reaches₁ f b c → reaches₁ f a c theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c | d h₃ := h₁ _ (h₂ _ h₃) @[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a | b h := h theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ} (h : b ∈ f a) : reaches₀ f a b | c h₂ := h₂.head h theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ} (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c := (reaches₀.single h).trans h₂ theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c := h₁.trans (reaches₀.single h) theorem reaches₀_eq {σ} {f : σ → option σ} {a b} (e : f a = f b) : reaches₀ f a b | d h := (reaches₁_eq e).2 h theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches₁ f a b) : reaches₀ f a b | c h₂ := h.trans h₂ theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches f a b) : reaches₀ f a b | c h₂ := h₂.trans_right h theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ} (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c := h _ (trans_gen.single h₂) theorem mem_eval {σ} {f : σ → option σ} {a b} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := ⟨λ h, begin refine pfun.fix_induction h (λ a h IH, _), cases e : f a with a', { rw roption.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $ roption.mem_some_iff.2 $ by rw e; refl), exact ⟨refl_trans_gen.refl, e⟩ }, { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩; rw e at h; cases roption.mem_some_iff.1 h, cases IH a' h' (by rwa e) with h₁ h₂, exact ⟨refl_trans_gen.head e h₁, h₂⟩ } end, λ ⟨h₁, h₂⟩, begin refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _), { refine pfun.mem_fix_iff.2 (or.inl _), rw h₂, apply roption.mem_some }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩), rw show f a = _, from h, apply roption.mem_some } end⟩ theorem eval_maximal₁ {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc := let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in by cases b0.symm.trans h' theorem eval_maximal {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) {c} : reaches f b c ↔ c = b := let ⟨ab, b0⟩ := mem_eval.1 h in refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h' theorem reaches_eval {σ} {f : σ → option σ} {a b} (ab : reaches f a b) : eval f a = eval f b := roption.ext $ λ c, ⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨(or_iff_left_of_imp $ by exact λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1 (reaches_total ab ac), c0⟩, λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩ def respects {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) := ∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with | some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ | none := f₂ a₂ = none end : Prop) theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ := begin induction ab with c₁ ac c₁ d₁ ac cd IH, { have := H aa, rwa (show f₁ a₁ = _, from ac) at this }, { rcases IH with ⟨c₂, cc, ac₂⟩, have := H cc, rw (show f₁ c₁ = _, from cd) at this, rcases this with ⟨d₂, dd, cd₂⟩, exact ⟨_, dd, ac₂.trans cd₂⟩ } end theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ := begin rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab, { exact ⟨_, aa, refl_trans_gen.refl⟩ }, { exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in ⟨b₂, bb, h.to_refl⟩ } end theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) : ∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ := begin induction ab with c₂ d₂ ac cd IH, { exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ }, { rcases IH with ⟨e₁, e₂, ce, ee, ae⟩, rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩, { have := H ee, revert this, cases eg : f₁ e₁ with g₁; simp [respects], { intro c0, cases cd.symm.trans c0 }, { intros g₂ gg cg, rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩, cases option.mem_unique cd cd', exact ⟨_, _, dg, gg, ae.tail eg⟩ } }, { cases option.mem_unique cd cd', exact ⟨_, _, de, ee, ae⟩ } } end theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩, refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩, have := H bb, rwa b0 at this end theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩, cases (refl_trans_gen_iff_eq (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc, refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩, have := H cc, cases f₁ c₁ with d₁, {refl}, rcases this with ⟨d₂, dd, bd⟩, rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩, cases b0.symm.trans h end theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) : (eval f₂ a₂).dom ↔ (eval f₁ a₁).dom := ⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h, λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩ def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop | (some b₁) := reaches₁ f₂ a₂ (tr b₁) | none := f₂ a₂ = none theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ | (some b₁) := reaches₁_eq h | none := by unfold frespects; rw h theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} : respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) := forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq'] theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (H : respects f₁ f₂ (λ a b, tr a = b)) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := roption.ext $ λ b₂, ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in (roption.mem_map_iff _).2 ⟨b₁, hb, bb⟩, λ h, begin rcases (roption.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩, rcases tr_eval H rfl ab with ⟨_, rfl, h⟩, rwa bb at h end⟩ def dwrite {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k') (l : C k') (k) : C k := if h : k = k' then eq.rec_on h.symm l else S k @[simp] theorem dwrite_eq {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k) (l : C k) : dwrite S k l k = l := dif_pos rfl @[simp] theorem dwrite_ne {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k') (l : C k') (k) (h : ¬ k = k') : dwrite S k' l k = S k := dif_neg h @[simp] theorem dwrite_self {K} [decidable_eq K] {C : K → Type*} (S : ∀ k, C k) (k) : dwrite S k (S k) = S := funext $ λ k', by unfold dwrite; split_ifs; [subst h, refl] namespace TM0 section parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states /-- A Turing machine "statement" is just a command to either move left or right, or write a symbol on the tape. -/ inductive stmt | move {} : dir → stmt | write {} : Γ → stmt /-- A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function which, given the current state `q : Λ` and the tape head `a : Γ`, either halts (returns `none`) or returns a new state `q' : Λ` and a `stmt` describing what to do, either a move left or right, or a write command. Both `Λ` and `Γ` are required to be inhabited; the default value for `Γ` is the "blank" tape value, and the default value of `Λ` is the initial state. -/ def machine := Λ → Γ → option (Λ × stmt) /-- The configuration state of a Turing machine during operation consists of a label (machine state), and a tape, represented in the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R` with the machine currently reading the `a`. The lists are automatically extended with blanks as the machine moves around. -/ structure cfg := (q : Λ) (tape : tape Γ) parameters {Γ Λ} /-- Execution semantics of the Turing machine. -/ def step (M : machine) : cfg → option cfg | ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q', match a with | stmt.move d := T.move d | stmt.write a := T.write a end⟩) /-- The statement `reaches M s₁ s₂` means that `s₂` is obtained starting from `s₁` after a finite number of steps from `s₂`. -/ def reaches (M : machine) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- The initial configuration. -/ def init (l : list Γ) : cfg := ⟨default Λ, tape.mk l⟩ /-- Evaluate a Turing machine on initial input to a final state, if it terminates. -/ def eval (M : machine) (l : list Γ) : roption (list Γ) := (eval (step M) (init l)).map (λ c, c.tape.2.2) /-- The raw definition of a Turing machine does not require that `Γ` and `Λ` are finite, and in practice we will be interested in the infinite `Λ` case. We recover instead a notion of "effectively finite" Turing machines, which only make use of a finite subset of their states. We say that a set `S ⊆ Λ` supports a Turing machine `M` if `S` is closed under the transition function and contains the initial state. -/ def supports (M : machine) (S : set Λ) := default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S theorem step_supports (M : machine) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S | ⟨q, T⟩ c' h₁ h₂ := begin rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩, exact ss.2 h h₂, end theorem univ_supports (M : machine) : supports M set.univ := ⟨trivial, λ q a q' s h₁ h₂, trivial⟩ end section variables {Γ : Type*} [inhabited Γ] variables {Γ' : Type*} [inhabited Γ'] variables {Λ : Type*} [inhabited Λ] variables {Λ' : Type*} [inhabited Λ'] def stmt.map (f : Γ → Γ') : stmt Γ → stmt Γ' | (stmt.move d) := stmt.move d | (stmt.write a) := stmt.write (f a) def cfg.map (f : Γ → Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' | ⟨q, T⟩ := ⟨g q, T.map f⟩ variables (M : machine Γ Λ) (f₁ : Γ → Γ') (f₂ : Γ' → Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) def machine.map : machine Γ' Λ' | q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁)) theorem machine.map_step {S} (ss : supports M S) [pointed_map f₁] (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : ∀ c : cfg Γ Λ, c.q ∈ S → (step M c).map (cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) | ⟨q, T⟩ h := begin unfold step machine.map cfg.map, simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _], rcases M q T.1 with _|⟨q', d|a⟩, {refl}, { simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl }, { simp only [step, cfg.map, option.map_some', tape.map_write], refl } end theorem map_init [pointed_map f₁] [g0 : pointed_map g₁] (l : list Γ) : (init l).map f₁ g₁ = init (l.map f₁) := congr (congr_arg cfg.mk g0) (tape.map_mk _ _) theorem machine.map_respects {S} (ss : supports M S) [pointed_map f₁] [pointed_map g₁] (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : respects (step M) (step (M.map f₁ f₂ g₁ g₂)) (λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b) | c _ ⟨cs, rfl⟩ := begin cases e : step M c with c'; unfold respects, { rw [← M.map_step f₁ f₂ g₁ g₂ ss f₂₁ g₂₁ _ cs, e], refl }, { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩, rw [← M.map_step f₁ f₂ g₁ g₂ ss f₂₁ g₂₁ _ cs, e], exact rfl } end end end TM0 namespace TM1 section parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`, which can either be a `move` or `write` command, a `branch` (if statement based on the current tape value), a `load` (set the variable value), a `goto` (call another function), or `halt`. Note that here most statements do not have labels; `goto` commands can only go to a new function. All commands have access to the variable value and current tape value. -/ inductive stmt | move : dir → stmt → stmt | write : (Γ → σ → Γ) → stmt → stmt | load : (Γ → σ → σ) → stmt → stmt | branch : (Γ → σ → bool) → stmt → stmt → stmt | goto {} : (Γ → σ → Λ) → stmt | halt {} : stmt open stmt /-- The configuration of a TM1 machine is given by the currently evaluating statement, the variable store value, and the tape. -/ structure cfg := (l : option Λ) (var : σ) (tape : tape Γ) parameters {Γ Λ σ} /-- The semantics of TM1 evaluation. -/ def step_aux : stmt → σ → tape Γ → cfg | (move d q) v T := step_aux q v (T.move d) | (write a q) v T := step_aux q v (T.write (a T.1 v)) | (load s q) v T := step_aux q (s T.1 v) T | (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T) | (goto l) v T := ⟨some (l T.1 v), v, T⟩ | halt v T := ⟨none, v, T⟩ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, T⟩ := none | ⟨some l, v, T⟩ := some (step_aux (M l) v T) variables [inhabited Λ] [inhabited σ] def init (l : list Γ) : cfg := ⟨some (default _), default _, tape.mk l⟩ def eval (M : Λ → stmt) (l : list Γ) : roption (list Γ) := (eval (step M) (init l)).map (λ c, c.tape.2.2) variables [fintype Γ] def supports_stmt (S : finset Λ) : stmt → Prop | (move d q) := supports_stmt q | (write a q) := supports_stmt q | (load s q) := supports_stmt q | (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ a v, l a v ∈ S | halt := true /-- A set `S` of labels supports machine `M` if all the `goto` statements in the functions in `S` refer only to other functions in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) open_locale classical noncomputable def stmts₁ : stmt → finset stmt | Q@(move d q) := insert Q (stmts₁ q) | Q@(write a q) := insert Q (stmts₁ q) | Q@(load s q) := insert Q (stmts₁ q) | Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply finset.mem_insert_self theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_union, finset.insert_empty_eq_singleton, finset.mem_singleton] at h₁₂, iterate 3 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } }, case TM1.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM1.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.insert_empty_eq_singleton, finset.mem_singleton] at h hs, iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM1.stmt.goto : l { subst h, exact hs }, case TM1.stmt.halt { subst h, trivial } end noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bind (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bind, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bind, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T; intro hs, iterate 3 { exact IH _ _ hs }, case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p T.1 v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) }, case TM1.stmt.halt { apply multiset.mem_cons_self } end end end TM1 namespace TM1to0 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := TM1.stmt Γ Λ σ local notation `cfg₁` := TM1.cfg Γ Λ σ local notation `stmt₀` := TM0.stmt Γ parameters (M : Λ → stmt₁) include M def Λ' := option stmt₁ × σ instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩ open TM0.stmt def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀ | (TM1.stmt.move d q) v := ((some q, v), move d) | (TM1.stmt.write a q) v := ((some q, v), write (a s v)) | (TM1.stmt.load a q) v := tr_aux q (a s v) | (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v) | (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s) | TM1.stmt.halt v := ((none, v), write s) local notation `cfg₀` := TM0.cfg Γ Λ' def tr : TM0.machine Γ Λ' | (none, v) s := none | (some q, v) s := some (tr_aux s q v) def tr_cfg : cfg₁ → cfg₀ | ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩ theorem tr_respects : respects (TM1.step M) (TM0.step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin cases l₁ with l₁, {exact rfl}, unfold tr_cfg TM1.step frespects option.map function.comp option.bind, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T, case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold TM1.step_aux, cases e : p T.1 v, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) }, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } }, iterate 2 { exact trans_gen.single (congr_arg some (congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) } end variables [fintype Γ] [fintype σ] noncomputable def tr_stmts (S : finset Λ) : finset Λ' := (TM1.stmts M S).product finset.univ open_locale classical local attribute [simp] TM1.stmts₁_self theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) : TM0.supports tr (↑(tr_stmts S)) := ⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2 (finset.mem_bind.2 ⟨_, ss.1, TM1.stmts₁_self⟩), finset.mem_univ _⟩, λ q a q' s h₁ h₂, begin rcases q with ⟨_|q, v⟩, {cases h₁}, cases q' with q' v', simp only [tr_stmts, finset.mem_coe, finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢, cases q', {exact multiset.mem_cons_self _ _}, simp only [tr, option.mem_def] at h₁, have := TM1.stmts_supports_stmt ss h₂, revert this, induction q generalizing v; intro hs, case TM1.stmt.move : d q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.write : b q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.load : b q IH { refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { change cond (p a v) _ _ = ((some q', v'), s) at h₁, cases p a v, { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) }, { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } }, case TM1.stmt.goto : l { cases h₁, exact finset.some_mem_insert_none.2 (finset.mem_bind.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) }, case TM1.stmt.halt { cases h₁ } end⟩ theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin rw [roption.map_eq_map, roption.map_map, TM1.eval], congr', exact funext (λ ⟨_, _, _⟩, rfl) end end end TM1to0 /- Reduce an n-symbol Turing machine to a 2-symbol Turing machine -/ namespace TM1to1 open TM1 section parameters {Γ : Type*} [inhabited Γ] theorem exists_enc_dec [fintype Γ] : ∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ), enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a := begin rcases fintype.exists_equiv_fin Γ with ⟨n, ⟨F⟩⟩, let G : fin n ↪ fin n → bool := ⟨λ a b, a = b, λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩, let H := (F.to_embedding.trans G).trans (equiv.vector_equiv_fin _ _).symm.to_embedding, let enc := H.set_value (default _) (vector.repeat ff n), exact ⟨_, enc, function.inv_fun enc, H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩ end parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := stmt Γ Λ σ local notation `cfg₁` := cfg Γ Λ σ inductive Λ' : Type (max u_1 u_2 u_3) | normal : Λ → Λ' | write : Γ → stmt₁ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `stmt'` := stmt bool Λ' σ local notation `cfg'` := cfg bool Λ' σ def read_aux : ∀ n, (vector bool n → stmt') → stmt' | 0 f := f vector.nil | (i+1) f := stmt.branch (λ a s, a) (stmt.move dir.right $ read_aux i (λ v, f (tt :: v))) (stmt.move dir.right $ read_aux i (λ v, f (ff :: v))) parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ) def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q def read (f : Γ → stmt') : stmt' := read_aux n (λ v, move dir.left $ f (dec v)) def write : list bool → stmt' → stmt' | [] q := q | (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q def tr_normal : stmt₁ → stmt' | (stmt.move dir.left q) := move dir.right $ (move dir.left)^[2] $ tr_normal q | (stmt.move dir.right q) := move dir.right $ tr_normal q | (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q | (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q | (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂) | (stmt.goto l) := read $ λ a, stmt.goto (λ _ s, Λ'.normal (l a s)) | stmt.halt := move dir.right $ move dir.left $ stmt.halt def tr_tape' (L R : list Γ) : tape bool := tape.mk' (L.bind (λ x, (enc x).to_list.reverse)) (R.bind (λ x, (enc x).to_list) ++ [default _]) def tr_tape : tape Γ → tape bool | (a, L, R) := tr_tape' L (a :: R) theorem tr_tape_drop_right : ∀ R : list Γ, list.drop n (R.bind (λ x, (enc x).to_list)) = R.tail.bind (λ x, (enc x).to_list) | [] := list.drop_nil _ | (a::R) := list.drop_left' (enc a).2 parameters (enc0 : enc (default _) = vector.repeat ff n) section include enc0 theorem tr_tape_take_right : ∀ R : list Γ, list.take' n (R.bind (λ x, (enc x).to_list)) = (enc R.head).to_list | [] := show list.take' n list.nil = _, by rw [list.take'_nil]; exact (congr_arg vector.to_list enc0).symm | (a::R) := list.take'_left' (enc a).2 end parameters (M : Λ → stmt₁) def tr : Λ' → stmt' | (Λ'.normal l) := tr_normal (M l) | (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q def tr_cfg : cfg₁ → cfg' | ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩ include enc0 theorem tr_tape'_move_left (L R) : (tape.move dir.left)^[n] (tr_tape' L R) = (tr_tape' L.tail (L.head :: R)) := begin cases L with a L, { simp only [enc0, vector.repeat, tr_tape', list.cons_bind, list.head, list.append_assoc], suffices : ∀ i R', default _ ∈ R' → (tape.move dir.left^[i]) (tape.mk' [] R') = tape.mk' [] (list.repeat ff i ++ R'), from this n _ (list.mem_append_right _ (list.mem_singleton_self _)), intros i R' hR, induction i with i IH, {refl}, rw [nat.iterate_succ', IH], refine prod.ext rfl (prod.ext rfl (list.cons_head_tail (list.ne_nil_of_mem $ list.mem_append_right _ hR))) }, { simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ L' R' l₁ l₂ (hR : default _ ∈ R') (e : vector.to_list (enc a) = list.reverse_core l₁ l₂), (tape.move dir.left^[l₁.length]) (tape.mk' (l₁ ++ L') (l₂ ++ R')) = tape.mk' L' (vector.to_list (enc a) ++ R'), { simpa only [list.length_reverse, vector.to_list_length] using this _ _ _ _ _ (list.reverse_reverse _).symm, exact list.mem_append_right _ (list.mem_singleton_self _) }, intros, induction l₁ with b l₁ IH generalizing l₂, { cases e, refl }, simp only [list.length, list.cons_append, nat.iterate_succ], convert IH _ e, exact prod.ext rfl (prod.ext rfl (list.cons_head_tail (list.ne_nil_of_mem $ list.mem_append_right _ hR))) } end theorem tr_tape'_move_right (L R) : (tape.move dir.right)^[n] (tr_tape' L R) = (tr_tape' (R.head :: L) R.tail) := begin cases R with a R, { simp only [enc0, vector.repeat, tr_tape', list.head, list.cons_bind, vector.to_list_mk, list.reverse_repeat], suffices : ∀ i L', (tape.move dir.right^[i]) (ff, L', []) = (ff, list.repeat ff i ++ L', []), from this n _, intros, induction i with i IH, {refl}, rw [nat.iterate_succ', IH], refine prod.ext rfl (prod.ext rfl rfl) }, { simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ L' R' l₁ l₂ : list bool, (tape.move dir.right^[l₂.length]) (tape.mk' (l₁ ++ L') (l₂ ++ R')) = tape.mk' (list.reverse_core l₂ l₁ ++ L') R', { simpa only [vector.to_list_length] using this _ _ [] (enc a).to_list }, intros, induction l₂ with b l₂ IH generalizing l₁, {refl}, exact IH (b::l₁) } end theorem step_aux_move (d q v T) : step_aux (move d q) v T = step_aux q v ((tape.move d)^[n] T) := begin suffices : ∀ i, step_aux (stmt.move d^[i] q) v T = step_aux q v (tape.move d^[i] T), from this n, intro, induction i with i IH generalizing T, {refl}, rw [nat.iterate_succ', step_aux, IH, ← nat.iterate_succ] end parameters (encdec : ∀ a, dec (enc a) = a) include encdec theorem step_aux_read (f v L R) : step_aux (read f) v (tr_tape' L R) = step_aux (f R.head) v (tr_tape' L (R.head :: R.tail)) := begin suffices : ∀ f, step_aux (read_aux n f) v (tr_tape' enc L R) = step_aux (f (enc R.head)) v (tr_tape' enc (R.head :: L) R.tail), { rw [read, this, step_aux_move enc enc0, encdec, tr_tape'_move_left enc enc0], refl }, cases R with a R, { suffices : ∀ i f L', step_aux (read_aux i f) v (ff, L', []) = step_aux (f (vector.repeat ff i)) v (ff, list.repeat ff i ++ L', []), { intro f, convert this n f _, refine prod.ext rfl (prod.ext ((list.cons_bind _ _ _).trans _) rfl), simp only [list.head, enc0, vector.repeat, vector.to_list, list.reverse_repeat] }, clear f L, intros, induction i with i IH generalizing L', {refl}, change step_aux (read_aux i (λ v, f (ff :: v))) v (ff, ff :: L', []) = step_aux (f (vector.repeat ff (nat.succ i))) v (ff, ff :: (list.repeat ff i ++ L'), []), rw [IH], congr', simpa only [list.append_assoc] using congr_arg (++ L') (list.repeat_add ff i 1).symm }, { simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ i f L' R' l₁ l₂ h, step_aux (read_aux i f) v (tape.mk' (l₁ ++ L') (l₂ ++ R')) = step_aux (f ⟨l₂, h⟩) v (tape.mk' (l₂.reverse_core l₁ ++ L') R'), { intro f, convert this n f _ _ _ _ (enc a).2; simp only [subtype.eta]; refl }, clear f L a R, intros, subst i, induction l₂ with a l₂ IH generalizing l₁, {refl}, change (tape.mk' (l₁ ++ L') (a :: (l₂ ++ R'))).1 with a, transitivity step_aux (read_aux l₂.length (λ v, f (a :: v))) v (tape.mk' (a :: l₁ ++ L') (l₂ ++ R')), { cases a; refl }, rw IH, refl } end theorem step_aux_write (q v a b L R) : step_aux (write (enc a).to_list q) v (tr_tape' L (b :: R)) = step_aux q v (tr_tape' (a :: L) R) := begin simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool) (e : l₂'.length = l₂.length), step_aux (write l₂ q) v (tape.mk' (l₁ ++ L') (l₂' ++ R')) = step_aux q v (tape.mk' (list.reverse_core l₂ l₁ ++ L') R'), from this [] _ _ ((enc b).2.trans (enc a).2.symm), clear a b L R, intros, induction l₂ with a l₂ IH generalizing l₁ l₂', { cases list.length_eq_zero.1 e, refl }, cases l₂' with b l₂'; injection e with e, unfold write step_aux, convert IH _ _ e, refl end theorem tr_respects : respects (step M) (step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, (a, L, R)⟩, begin cases l₁ with l₁, {exact rfl}, suffices : ∀ q R, reaches (step (tr enc dec M)) (step_aux (tr_normal dec q) v (tr_tape' enc L R)) (tr_cfg enc (step_aux q v (tape.mk' L R))), { refine trans_gen.head' rfl (this _ (a::R)) }, clear R l₁, intros, induction q with _ q IH _ q IH _ q IH generalizing v L R, case TM1.stmt.move : d q IH { cases d; simp only [tr_normal, nat.iterate, step_aux_move enc enc0, step_aux, tr_tape'_move_left enc enc0, tr_tape'_move_right enc enc0]; apply IH }, case TM1.stmt.write : a q IH { simp only [tr_normal, step_aux_read enc dec enc0 encdec, step_aux], refine refl_trans_gen.head rfl _, simp only [tr, tr_normal, step_aux, step_aux_write enc dec enc0 encdec, step_aux_move enc enc0, tr_tape'_move_left enc enc0], apply IH }, case TM1.stmt.load : a q IH { simp only [tr_normal, step_aux_read enc dec enc0 encdec], apply IH }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp only [tr_normal, step_aux_read enc dec enc0 encdec, step_aux], change (tape.mk' L R).1 with R.head, cases p R.head v; [apply IH₂, apply IH₁] }, case TM1.stmt.goto : l { simp only [tr_normal, step_aux_read enc dec enc0 encdec, step_aux], apply refl_trans_gen.refl }, case TM1.stmt.halt { simp only [tr_normal, step_aux, tr_cfg, step_aux_move enc enc0, tr_tape'_move_left enc enc0, tr_tape'_move_right enc enc0], apply refl_trans_gen.refl } end omit enc0 encdec open_locale classical parameters [fintype Γ] noncomputable def writes : stmt₁ → finset Λ' | (stmt.move d q) := writes q | (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q | (stmt.load f q) := writes q | (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂ | (stmt.goto l) := ∅ | stmt.halt := ∅ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bind (λ l, insert (Λ'.normal l) (writes (M l))) theorem supports_stmt_move {S d q} : supports_stmt S (move d q) = supports_stmt S q := suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this, by intro; induction i generalizing q; simp only [*, nat.iterate]; refl theorem supports_stmt_write {S l q} : supports_stmt S (write l q) = supports_stmt S q := by induction l with a l IH; simp only [write, supports_stmt, *] local attribute [simp] supports_stmt_move supports_stmt_write theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'}, (∀ a, supports_stmt S (f a)) → supports_stmt S (read f) := suffices ∀ i (f : vector bool i → stmt'), (∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f), from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]), λ i f hf, begin induction i with i IH, {exact hf _}, split; apply IH; intro; apply hf, end theorem tr_supports {S} (ss : supports M S) : supports tr (tr_supp S) := ⟨finset.mem_bind.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩, λ q h, begin suffices : ∀ q, supports_stmt S q → (∀ q' ∈ writes q, q' ∈ tr_supp M S) → supports_stmt (tr_supp M S) (tr_normal dec q) ∧ ∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'), { rcases finset.mem_bind.1 h with ⟨l, hl, h⟩, have := this _ (ss.2 _ hl) (λ q' hq, finset.mem_bind.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩), rcases finset.mem_insert.1 h with rfl | h, exacts [this.1, this.2 _ h] }, intros q hs hw, induction q, case TM1.stmt.move : d q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨_, IH.2⟩, cases d; simp only [tr_normal, nat.iterate, supports_stmt_move, IH] }, case TM1.stmt.write : f q IH { unfold writes at hw ⊢, simp only [finset.mem_image, finset.mem_union, finset.mem_univ, exists_prop, true_and] at hw ⊢, replace IH := IH hs (λ q hq, hw q (or.inr hq)), refine ⟨supports_stmt_read _ $ λ a _ s, hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩, rcases hq with ⟨a, q₂, rfl⟩ | hq, { simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] }, { exact IH.2 _ hq } }, case TM1.stmt.load : a q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold writes at hw ⊢, simp only [finset.mem_union] at hw ⊢, replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)), replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)), exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩), λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ }, case TM1.stmt.goto : l { refine ⟨_, λ _, false.elim⟩, refine supports_stmt_read _ (λ a _ s, _), exact finset.mem_bind.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ }, case TM1.stmt.halt { refine ⟨_, λ _, false.elim⟩, simp only [supports_stmt, supports_stmt_move, tr_normal] } end⟩ end end TM1to1 namespace TM0to1 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] inductive Λ' | normal : Λ → Λ' | act : TM0.stmt Γ → Λ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `cfg₀` := TM0.cfg Γ Λ local notation `stmt₁` := TM1.stmt Γ Λ' unit local notation `cfg₁` := TM1.cfg Γ Λ' unit parameters (M : TM0.machine Γ Λ) open TM1.stmt def tr : Λ' → stmt₁ | (Λ'.normal q) := branch (λ a _, (M q a).is_none) halt $ goto (λ a _, match M q a with | none := default _ | some (q', s) := Λ'.act s q' end) | (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q) | (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q) def tr_cfg : cfg₀ → cfg₁ | ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩ theorem tr_respects : respects (TM0.step M) (TM1.step tr) (λ a b, tr_cfg a = b) := fun_respects.2 $ λ ⟨q, T⟩, begin cases e : M q T.1, { simp only [TM0.step, tr_cfg, e]; exact eq.refl none }, cases val with q' s, simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'], have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩, { cases s with d a; refl }, refine trans_gen.head _ (trans_gen.head' this _), { unfold TM1.step TM1.step_aux tr has_mem.mem, rw e, refl }, cases e' : M q' _, { apply refl_trans_gen.single, unfold TM1.step TM1.step_aux tr has_mem.mem, rw e', refl }, { refl } end end end TM0to1 namespace TM2 section parameters {K : Type*} [decidable_eq K] -- Index type of stacks parameters (Γ : K → Type*) -- Type of stack elements parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks. The operation `push` puts an element on one of the stacks, and `pop` removes an element from a stack (and modifying the internal state based on the result). `peek` modifies the internal state but does not remove an element. -/ inductive stmt | push {} : ∀ k, (σ → Γ k) → stmt → stmt | peek {} : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | pop {} : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | load : (σ → σ) → stmt → stmt | branch : (σ → bool) → stmt → stmt → stmt | goto {} : (σ → Λ) → stmt | halt {} : stmt open stmt structure cfg := (l : option Λ) (var : σ) (stk : ∀ k, list (Γ k)) parameters {Γ Λ σ K} def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg | (push k f q) v S := step_aux q v (dwrite S k (f v :: S k)) | (peek k f q) v S := step_aux q (f v (S k).head') S | (pop k f q) v S := step_aux q (f v (S k).head') (dwrite S k (S k).tail) | (load a q) v S := step_aux q (a v) S | (branch f q₁ q₂) v S := cond (f v) (step_aux q₁ v S) (step_aux q₂ v S) | (goto f) v S := ⟨some (f v), v, S⟩ | halt v S := ⟨none, v, S⟩ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, S⟩ := none | ⟨some l, v, S⟩ := some (step_aux (M l) v S) def reaches (M : Λ → stmt) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) variables [inhabited Λ] [inhabited σ] def init (k) (L : list (Γ k)) : cfg := ⟨some (default _), default _, dwrite (λ _, []) k L⟩ def eval (M : Λ → stmt) (k) (L : list (Γ k)) : roption (list (Γ k)) := (eval (step M) (init k L)).map $ λ c, c.stk k variables [fintype K] [∀ k, fintype (Γ k)] [fintype σ] def supports_stmt (S : finset Λ) : stmt → Prop | (push k f q) := supports_stmt q | (peek k f q) := supports_stmt q | (pop k f q) := supports_stmt q | (load a q) := supports_stmt q | (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ v, l v ∈ S | halt := true def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) open_locale classical noncomputable def stmts₁ : stmt → finset stmt | Q@(push k f q) := insert Q (stmts₁ q) | Q@(peek k f q) := insert Q (stmts₁ q) | Q@(pop k f q) := insert Q (stmts₁ q) | Q@(load a q) := insert Q (stmts₁ q) | Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q@(goto l) := {Q} | Q@halt := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply finset.mem_insert_self theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.insert_empty_eq_singleton, finset.mem_singleton, finset.mem_union] at h₁₂, iterate 4 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } }, case TM2.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM2.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.insert_empty_eq_singleton, finset.mem_singleton] at h hs, iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM2.stmt.goto : l { subst h, exact hs }, case TM2.stmt.halt { subst h, trivial } end noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bind (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bind, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bind, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T; intro hs, iterate 4 { exact IH _ _ hs }, case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) }, case TM2.stmt.halt { apply multiset.mem_cons_self } end end end TM2 namespace TM2to1 section parameters {K : Type*} [decidable_eq K] parameters {Γ : K → Type*} parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₂` := TM2.stmt Γ Λ σ local notation `cfg₂` := TM2.cfg Γ Λ σ inductive stackel (k : K) | val : Γ k → stackel | bottom : stackel | top : stackel instance stackel.inhabited (k) : inhabited (stackel k) := ⟨stackel.top _⟩ def stackel.is_bottom {k} : stackel k → bool | (stackel.bottom _) := tt | _ := ff def stackel.is_top {k} : stackel k → bool | (stackel.top _) := tt | _ := ff def stackel.get {k} : stackel k → option (Γ k) | (stackel.val a) := some a | _ := none section open stackel def stackel_equiv {k} : stackel k ≃ option (option (Γ k)) := begin refine ⟨λ s, _, λ s, _, _, _⟩, { cases s, exacts [some (some s), none, some none] }, { rcases s with _|_|s, exacts [bottom _, top _, val s] }, { intro s, cases s; refl }, { intro s, rcases s with _|_|s; refl }, end end def Γ' := ∀ k, stackel k instance Γ'.inhabited : inhabited Γ' := ⟨λ _, default _⟩ instance stackel.fintype {k} [fintype (Γ k)] : fintype (stackel k) := fintype.of_equiv _ stackel_equiv.symm instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' := pi.fintype inductive st_act (k : K) | push {} : (σ → Γ k) → st_act | pop {} : bool → (σ → option (Γ k) → σ) → st_act section open st_act def st_run {k : K} : st_act k → stmt₂ → stmt₂ | (push f) := TM2.stmt.push k f | (pop ff f) := TM2.stmt.peek k f | (pop tt f) := TM2.stmt.pop k f def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ | (push f) := v | (pop b f) := f v l.head' def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k) | (push f) := f v :: l | (pop ff f) := l | (pop tt f) := l.tail @[elab_as_eliminator] def {l} stmt_st_rec {C : stmt₂ → Sort l} (H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q)) (H₂ : Π a q (IH : C q), C (TM2.stmt.load a q)) (H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂)) (H₄ : Π l, C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) : ∀ n, C n | (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q) | (TM2.stmt.peek k f q) := H₁ _ (pop ff f) _ (stmt_st_rec q) | (TM2.stmt.pop k f q) := H₁ _ (pop tt f) _ (stmt_st_rec q) | (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q) | (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂) | (TM2.stmt.goto l) := H₄ _ | TM2.stmt.halt := H₅ theorem supports_run [fintype K] [∀ k, fintype (Γ k)] [fintype σ] (S : finset Λ) {k} (s : st_act k) (q) : TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q := by rcases s with _|_|_; refl end inductive Λ' : Type (max u_1 u_2 u_3 u_4) | normal {} : Λ → Λ' | go (k) : st_act k → stmt₂ → Λ' | ret {} : K → stmt₂ → Λ' open Λ' instance : inhabited Λ' := ⟨normal (default _)⟩ local notation `stmt₁` := TM1.stmt Γ' Λ' σ local notation `cfg₁` := TM1.cfg Γ' Λ' σ open TM1.stmt def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁ | (st_act.push f) := write (λ a s, dwrite a k $ stackel.val $ f s) $ move dir.right $ write (λ a s, dwrite a k $ stackel.top k) q | (st_act.pop b f) := move dir.left $ load (λ a s, f s (a k).get) $ cond b ( branch (λ a s, (a k).is_bottom) ( move dir.right q ) ( move dir.right $ write (λ a s, dwrite a k $ default _) $ move dir.left $ write (λ a s, dwrite a k $ stackel.top k) q ) ) ( move dir.right q ) def tr_init (k) (L : list (Γ k)) : list Γ' := stackel.bottom :: match L.reverse with | [] := [stackel.top] | (a::L') := dwrite stackel.top k (stackel.val a) :: (L'.map stackel.val ++ [stackel.top k]).map (dwrite (default _) k) end theorem step_run {k : K} (q v S) : ∀ s : st_act k, TM2.step_aux (st_run s q) v S = TM2.step_aux q (st_var v (S k) s) (dwrite S k (st_write v (S k) s)) | (st_act.push f) := rfl | (st_act.pop ff f) := by unfold st_write; rw dwrite_self; refl | (st_act.pop tt f) := rfl def tr_normal : stmt₂ → stmt₁ | (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q) | (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.pop ff f) q) | (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop tt f) q) | (TM2.stmt.load a q) := load (λ _, a) (tr_normal q) | (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂) | (TM2.stmt.goto l) := goto (λ a s, normal (l s)) | TM2.stmt.halt := halt theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) := by rcases s with _|_|_; refl parameters (M : Λ → stmt₂) include M def tr : Λ' → stmt₁ | (normal q) := tr_normal (M q) | (go k s q) := branch (λ a s, (a k).is_top) (tr_st_act (goto (λ _ _, ret k q)) s) (move dir.right $ goto (λ _ _, go k s q)) | (ret k q) := branch (λ a s, (a k).is_bottom) (tr_normal q) (move dir.left $ goto (λ _ _, ret k q)) def tr_stk {k} (S : list (Γ k)) (L : list (stackel k)) : Prop := ∃ n, L = (S.map stackel.val).reverse_core (stackel.top k :: list.repeat (default _) n) local attribute [pp_using_anonymous_constructor] turing.TM1.cfg inductive tr_cfg : cfg₂ → cfg₁ → Prop | mk {q v} {S : ∀ k, list (Γ k)} {L : list Γ'} : (∀ k, tr_stk (S k) (L.map (λ a, a k))) → tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, (stackel.bottom, [], L)⟩ theorem tr_respects_aux₁ {k} (o q v) : ∀ S₁ {s S₂} {T : list Γ'}, T.map (λ (a : Γ'), a k) = (list.map stackel.val S₁).reverse_core (s :: S₂) → ∃ a T₁ T₂, T = list.reverse_core T₁ (a :: T₂) ∧ a k = s ∧ T₁.map (λ (a : Γ'), a k) = S₁.map stackel.val ∧ T₂.map (λ (a : Γ'), a k) = S₂ ∧ reaches₀ (TM1.step tr) ⟨some (go k o q), v, (stackel.bottom, [], T)⟩ ⟨some (go k o q), v, (a, T₁ ++ [stackel.bottom], T₂)⟩ | [] s S₂ (a :: T) hT := by injection hT with es e₂; exact ⟨a, [], _, rfl, es, rfl, e₂, reaches₀.single rfl⟩ | (s' :: S₁) s S₂ T hT := let ⟨a, T₁, b'::T₂, e, es', e₁, e₂, H⟩ := tr_respects_aux₁ S₁ hT in by injection e₂ with es e₂; exact ⟨b', a::T₁, T₂, e, es, congr (congr_arg list.cons es') e₁, e₂, H.tail (by unfold TM1.step; change some (cond (TM2to1.stackel.is_top (a k)) _ _) = _; rw es'; refl)⟩ local attribute [simp] TM1.step TM1.step_aux tr tr_st_act st_var st_write tape.move tape.write list.reverse_core stackel.get stackel.is_bottom theorem tr_respects_aux₂ {k q v} {S : Π k, list (Γ k)} {T₁ T₂ : list Γ'} {a : Γ'} (hT : ∀ k, tr_stk (S k) ((T₁.reverse_core (a :: T₂)).map (λ (a : Γ'), a k))) (e₁ : T₁.map (λ (a : Γ'), a k) = list.map stackel.val (S k)) (ea : a k = stackel.top k) (o) : let v' := st_var v (S k) o, Sk' := st_write v (S k) o, S' : ∀ k, list (Γ k) := dwrite S k Sk' in ∃ b (T₁' T₂' : list Γ'), (∀ (k' : K), tr_stk (S' k') ((T₁'.reverse_core (b :: T₂')).map (λ (a : Γ'), a k'))) ∧ T₁'.map (λ a, a k) = Sk'.map stackel.val ∧ b k = stackel.top k ∧ TM1.step_aux (tr_st_act q o) v (a, T₁ ++ [stackel.bottom], T₂) = TM1.step_aux q v' (b, T₁' ++ [stackel.bottom], T₂') := begin dsimp only, cases o with f b f, case TM2to1.st_act.push : { refine ⟨_, dwrite a k (stackel.val (f v)) :: T₁, _, _, by simp only [list.map, dwrite_eq, e₁]; refl, by simp only [tape.write, tape.move, dwrite_eq], rfl⟩, intro k', cases hT k' with n e, by_cases h : k' = k, { subst k', existsi n.pred, simp only [list.reverse_core_eq, list.map_append, list.map_reverse, e₁, list.map_cons, list.append_left_inj] at e, simp only [list.reverse_core_eq, e.1, e.2, list.map_append, prod.fst, list.map_reverse, list.reverse_cons, list.map, dwrite_eq, e₁, list.map_tail, list.tail_repeat, TM2to1.st_write] }, { cases T₂ with t T₂, { existsi n+1, simpa only [dwrite_ne _ _ _ _ h, list.reverse_core_eq, e₁, list.repeat_add, tape.write, tape.move, list.reverse_cons, list.map_reverse, list.map_append, list.map, list.head, list.tail, list.append_assoc] using congr_arg (++ [default Γ' k']) e }, { existsi n, simpa only [dwrite_ne _ _ _ _ h, list.reverse_core_eq, e₁, list.repeat_add, tape.write, tape.move, list.reverse_cons, list.map_reverse, list.map_append, list.map, list.head, list.tail, list.append_assoc] using e } } }, have dw := dwrite_self S k, cases T₁ with t T₁; cases eS : S k with s Sk; rw eS at e₁ dw; injection e₁ with tk e₁'; cases b, { -- peek nil simp only [dw, st_write], exact ⟨_, [], _, hT, rfl, ea, rfl⟩ }, { -- pop nil simp only [dw, st_write, list.tail], exact ⟨_, [], _, hT, rfl, ea, rfl⟩ }, { -- peek cons change t k = stackel.val s at tk, simp only [eS, tk, dw, st_write, TM1.step_aux, tr_st_act, cond, tape.move, list.head, list.tail, list.cons_append], exact ⟨_, t::T₁, _, hT, e₁, ea, rfl⟩ }, { -- pop cons change t k = stackel.val s at tk, simp only [tk, st_write, list.tail, TM1.step_aux, tr_st_act, cond, tape.move, list.cons_append, list.head], refine ⟨_, _, _, _, e₁', dwrite_eq _ _ _, rfl⟩, intro k', cases hT k' with n e, by_cases h : k' = k, { subst k', existsi n+1, simp only [list.reverse_core_eq, eS, e₁', list.append_left_inj, list.map_append, list.map_reverse, list.map, list.reverse_cons, list.append_assoc, list.cons_append] at e ⊢, simp only [tape.move, tape.write, list.head, list.tail, dwrite_eq], rw [e.2.2]; refl }, { existsi n, simpa only [dwrite_ne _ _ _ _ h, list.map, list.head, list.tail, list.reverse_core, list.map_reverse_core, tape.move, tape.write] using e } }, end theorem tr_respects_aux₃ {k q v} {S : Π k, list (Γ k)} {T : list Γ'} (hT : ∀ k, tr_stk (S k) (T.map (λ (a : Γ'), a k))) : ∀ (T₁ : list Γ') {T₂ : list Γ'} {a : Γ'} {S₁} (e : T = T₁.reverse_core (a :: T₂)) (ha : (a k).is_bottom = ff) (e₁ : T₁.map (λ (a : Γ'), a k) = list.map stackel.val S₁), reaches₀ (TM1.step tr) ⟨some (ret k q), v, (a, T₁ ++ [stackel.bottom], T₂)⟩ ⟨some (ret k q), v, (stackel.bottom, [], T)⟩ | [] T₂ a S₁ e ha e₁ := reaches₀.single (by simp only [ha, e, TM1.step, option.mem_def, tr, TM1.step_aux] {constructor_eq:=ff}; refl) | (b :: T₁) T₂ a (s :: S₁) e ha e₁ := begin unfold list.map at e₁, injection e₁ with es e₁, refine reaches₀.head _ (tr_respects_aux₃ T₁ e (by rw es; refl) e₁), simp only [ha, option.mem_def, TM1.step, tr, TM1.step_aux], refl end theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)} (hT : ∀ (k : K), tr_stk (S k) (list.map (λ (a : Γ'), a k) T)) (o : st_act k) (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list Γ'}, (∀ (k : K), tr_stk (S k) (list.map (λ (a : Γ'), a k) T)) → (∃ b, tr_cfg (TM2.step_aux q v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (stackel.bottom, [], T)) b)) : ∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q)) v (stackel.bottom, [], T)) b := begin rcases hT k with ⟨n, hTk⟩, simp only [tr_normal_run], rcases tr_respects_aux₁ M o q v _ hTk with ⟨a, T₁, T₂, rfl, ea, e₁, e₂, hgo⟩, rcases tr_respects_aux₂ M hT e₁ ea _ with ⟨b, T₁', T₂', hT', e₁', eb, hrun⟩, have hret := tr_respects_aux₃ M hT' _ rfl (by rw eb; refl) e₁', have := hgo.tail' rfl, simp only [ea, tr, TM1.step_aux] at this, rw [hrun, TM1.step_aux] at this, rcases IH hT' with ⟨c, gc, rc⟩, simp only [step_run], refine ⟨c, gc, (this.to₀.trans hret _ (trans_gen.head' rfl rc)).to_refl⟩ end local attribute [simp] respects TM2.step TM2.step_aux tr_normal theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg := λ c₁ c₂ h, begin cases h with l v S L hT, clear h, cases l, {constructor}, simp only [TM2.step, respects, option.map_some'], suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _, from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩, rw [tr], revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros, { exact tr_respects_aux M hT s @IH }, { exact IH hT }, { unfold TM2.step_aux tr_normal TM1.step_aux, cases p v; [exact IH₂ hT, exact IH₁ hT] }, { exact ⟨_, ⟨hT⟩, refl_trans_gen.refl⟩ }, { exact ⟨_, ⟨hT⟩, refl_trans_gen.refl⟩ } end theorem tr_cfg_init (k) (L : list (Γ k)) : tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) := ⟨λ k', begin unfold tr_init, cases e : L.reverse with a L', { cases list.reverse_eq_nil.1 e, rw dwrite_self, exact ⟨0, rfl⟩ }, by_cases k' = k, { subst k', existsi 0, simp only [list.tail, dwrite_eq, list.reverse_core_eq, list.repeat, tr_init, list.map, list.map_map, (∘), list.map_id' (λ _, rfl)], rw [← list.map_reverse, e], refl }, { existsi L'.length + 1, simp only [dwrite_ne _ _ _ _ h, list.tail, tr_init, list.map_map, list.map, list.map_append, list.repeat_add, (∘), list.map_const] {constructor_eq:=ff}, refl } end⟩ theorem tr_eval_dom (k) (L : list (Γ k)) : (TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom := tr_eval_dom tr_respects (tr_cfg_init _ _) theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval tr (tr_init k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ S : ∀ k, list (Γ k), (∀ k', tr_stk (S k') (L₁.map (λ a, a k'))) ∧ S k = L₂ := begin rcases (roption.mem_map_iff _).1 H₁ with ⟨c₁, h₁, rfl⟩, rcases (roption.mem_map_iff _).1 H₂ with ⟨c₂, h₂, rfl⟩, rcases tr_eval (tr_respects M) (tr_cfg_init M k L) h₂ with ⟨_, ⟨q, v, S, L₁', hT⟩, h₃⟩, cases roption.mem_unique h₁ h₃, exact ⟨S, hT, rfl⟩ end variables [fintype K] [∀ k, fintype (Γ k)] [fintype σ] open_locale classical local attribute [simp] TM2.stmts₁_self noncomputable def tr_stmts₁ : stmt₂ → finset Λ' | Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret k q} ∪ tr_stmts₁ q | Q@(TM2.stmt.peek k f q) := {go k (st_act.pop ff f) q, ret k q} ∪ tr_stmts₁ q | Q@(TM2.stmt.pop k f q) := {go k (st_act.pop tt f) q, ret k q} ∪ tr_stmts₁ q | Q@(TM2.stmt.load a q) := tr_stmts₁ q | Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂ | _ := ∅ theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret k q} ∪ tr_stmts₁ q := by rcases s with _|_|_; unfold tr_stmts₁ st_run noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bind (λ l, insert (normal l) (tr_stmts₁ (M l))) local attribute [simp] tr_stmts₁ tr_stmts₁_run supports_run tr_normal_run TM1.supports_stmt TM2.supports_stmt theorem tr_supports {S} (ss : TM2.supports M S) : TM1.supports tr (tr_supp S) := ⟨finset.mem_bind.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩, λ l' h, begin suffices : ∀ q (ss' : TM2.supports_stmt S q) (sub : ∀ x ∈ tr_stmts₁ M q, x ∈ tr_supp M S), TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧ (∀ l' ∈ tr_stmts₁ M q, TM1.supports_stmt (tr_supp M S) (tr M l')), { rcases finset.mem_bind.1 h with ⟨l, lS, h⟩, have := this _ (ss.2 l lS) (λ x hx, finset.mem_bind.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩), rcases finset.mem_insert.1 h with rfl | h; [exact this.1, exact this.2 _ h] }, clear h l', refine stmt_st_rec _ _ _ _ _; intros, { -- stack op rw TM2to1.supports_run at ss', simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.has_insert_eq_insert, finset.insert_empty_eq_singleton, finset.mem_insert, finset.mem_singleton] at sub, have hgo := sub _ (or.inl $ or.inr rfl), have hret := sub _ (or.inl $ or.inl rfl), cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂, refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩, rw [tr_stmts₁_run] at h, simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.has_insert_eq_insert, finset.insert_empty_eq_singleton, finset.mem_insert, finset.mem_singleton] at h, rcases h with ⟨rfl | rfl⟩ | h, { unfold TM1.supports_stmt TM2to1.tr, exact ⟨IH₁, λ _ _, hret⟩ }, { unfold TM1.supports_stmt TM2to1.tr, rcases s with _|_|_, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } }, { exact IH₂ _ h } }, { -- load unfold TM2to1.tr_stmts₁ at ss' sub ⊢, exact IH ss' sub }, { -- branch unfold TM2to1.tr_stmts₁ at sub, cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂, cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂, refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩, rw [tr_stmts₁] at h, rcases finset.mem_union.1 h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] }, { -- goto rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt, unfold TM2.supports_stmt at ss', exact ⟨λ _ v, finset.mem_bind.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ }, { exact ⟨trivial, λ _, false.elim⟩ } -- halt end⟩ end end TM2to1 end turing
81c1c9efcd56b270e3bd1945c65de690106c61e2
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/metric_space/gromov_hausdorff.lean
d6b068acf48f90133088b1dbc3a9dd271ac05ab9
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
55,821
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import set_theory.cardinal.basic import topology.metric_space.closeds import topology.metric_space.completion import topology.metric_space.gromov_hausdorff_realized import topology.metric_space.kuratowski /-! # Gromov-Hausdorff distance This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry. We introduce the space of all nonempty compact metric spaces, up to isometry, called `GH_space`, and endow it with a metric space structure. The distance, known as the Gromov-Hausdorff distance, is defined as follows: given two nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance between all possible isometric embeddings of `X` and `Y` in all metric spaces. To define properly the Gromov-Hausdorff space, we consider the non-empty compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type, and define the distance as the infimum of the Hausdorff distance over all embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description, as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an embedding called the Kuratowski embedding. To prove that we have a distance, we should show that if spaces can be coupled to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff distance is realized, i.e., there is a coupling for which the Hausdorff distance is exactly the Gromov-Hausdorff distance. This follows from a compactness argument, essentially following from Arzela-Ascoli. ## Main results We prove the most important properties of the Gromov-Hausdorff space: it is a polish space, i.e., it is complete and second countable. We also prove the Gromov compactness criterion. -/ noncomputable theory open_locale classical topology ennreal local notation `ℓ_infty_ℝ`:= lp (λ n : ℕ, ℝ) ∞ universes u v w open classical set function topological_space filter metric quotient open bounded_continuous_function nat int Kuratowski_embedding open sum (inl inr) local attribute [instance] metric_space_sum namespace Gromov_Hausdorff section GH_space /- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets. Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty compact type to `GH_space`. -/ /-- Equivalence relation identifying two nonempty compact sets which are isometric -/ private def isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop := λ x y, nonempty (x ≃ᵢ y) /-- This is indeed an equivalence relation -/ private lemma is_equivalence_isometry_rel : equivalence isometry_rel := ⟨λ x, ⟨isometry_equiv.refl _⟩, λ x y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩ /-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/ instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) := setoid.mk isometry_rel is_equivalence_isometry_rel /-- The Gromov-Hausdorff space -/ definition GH_space : Type := quotient (isometry_rel.setoid) /-- Map any nonempty compact type to `GH_space` -/ definition to_GH_space (X : Type u) [metric_space X] [compact_space X] [nonempty X] : GH_space := ⟦nonempty_compacts.Kuratowski_embedding X⟧ instance : inhabited GH_space := ⟨quot.mk _ ⟨⟨{0}, is_compact_singleton⟩, singleton_nonempty _⟩⟩ /-- A metric space representative of any abstract point in `GH_space` -/ @[nolint has_nonempty_instance] def GH_space.rep (p : GH_space) : Type := (quotient.out p : nonempty_compacts ℓ_infty_ℝ) lemma eq_to_GH_space_iff {X : Type u} [metric_space X] [compact_space X] [nonempty X] {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space X ↔ ∃ Ψ : X → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p := begin simp only [to_GH_space, quotient.eq], refine ⟨λ h, _, _⟩, { rcases setoid.symm h with ⟨e⟩, have f := (Kuratowski_embedding.isometry X).isometry_equiv_on_range.trans e, use [λ x, f x, isometry_subtype_coe.comp f.isometry], rw [range_comp, f.range_eq_univ, set.image_univ, subtype.range_coe], refl }, { rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩, have f := ((Kuratowski_embedding.isometry X).isometry_equiv_on_range.symm.trans isomΨ.isometry_equiv_on_range).symm, have E : (range Ψ ≃ᵢ nonempty_compacts.Kuratowski_embedding X) = (p ≃ᵢ range (Kuratowski_embedding X)), by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl }, exact ⟨cast E f⟩ } end lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p := eq_to_GH_space_iff.2 ⟨λ x, x, isometry_subtype_coe, subtype.range_coe⟩ section local attribute [reducible] GH_space.rep instance rep_GH_space_metric_space {p : GH_space} : metric_space p.rep := by apply_instance instance rep_GH_space_compact_space {p : GH_space} : compact_space p.rep := by apply_instance instance rep_GH_space_nonempty {p : GH_space} : nonempty p.rep := by apply_instance end lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space p.rep = p := begin change to_GH_space (quot.out p : nonempty_compacts ℓ_infty_ℝ) = p, rw ← eq_to_GH_space, exact quot.out_eq p end /-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are isometric. -/ lemma to_GH_space_eq_to_GH_space_iff_isometry_equiv {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] : to_GH_space X = to_GH_space Y ↔ nonempty (X ≃ᵢ Y) := ⟨begin simp only [to_GH_space, quotient.eq], rintro ⟨e⟩, have I : ((nonempty_compacts.Kuratowski_embedding X) ≃ᵢ (nonempty_compacts.Kuratowski_embedding Y)) = ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have f := (Kuratowski_embedding.isometry X).isometry_equiv_on_range, have g := (Kuratowski_embedding.isometry Y).isometry_equiv_on_range.symm, exact ⟨f.trans $ (cast I e).trans g⟩ end, begin rintro ⟨e⟩, simp only [to_GH_space, quotient.eq], have f := (Kuratowski_embedding.isometry X).isometry_equiv_on_range.symm, have g := (Kuratowski_embedding.isometry Y).isometry_equiv_on_range, have I : ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))) = ((nonempty_compacts.Kuratowski_embedding X) ≃ᵢ (nonempty_compacts.Kuratowski_embedding Y)), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, exact ⟨cast I ((f.trans e).trans g)⟩ end⟩ /-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition, we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/ instance : has_dist (GH_space) := { dist := λ x y, Inf $ (λ p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) '' ({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}) } /-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/ def GH_dist (X : Type u) (Y : Type v) [metric_space X] [nonempty X] [compact_space X] [metric_space Y] [nonempty Y] [compact_space Y] : ℝ := dist (to_GH_space X) (to_GH_space Y) lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist p.rep (q.rep) := by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep] /-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance of isometric copies of the spaces, in any metric space. -/ theorem GH_dist_le_Hausdorff_dist {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] {γ : Type w} [metric_space γ] {Φ : X → γ} {Ψ : Y → γ} (ha : isometry Φ) (hb : isometry Ψ) : GH_dist X Y ≤ Hausdorff_dist (range Φ) (range Ψ) := begin /- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not separable in general. We restrict to the union of the images of `X` and `Y` in `γ`, which is separable and therefore embeddable in `ℓ^∞(ℝ)`. -/ rcases exists_mem_of_nonempty X with ⟨xX, _⟩, let s : set γ := (range Φ) ∪ (range Ψ), let Φ' : X → subtype s := λ y, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩, let Ψ' : Y → subtype s := λ y, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩, have IΦ' : isometry Φ' := λ x y, ha x y, have IΨ' : isometry Ψ' := λ x y, hb x y, have : is_compact s, from (is_compact_range ha.continuous).union (is_compact_range hb.continuous), letI : metric_space (subtype s) := by apply_instance, haveI : compact_space (subtype s) := ⟨is_compact_iff_is_compact_univ.1 ‹is_compact s›⟩, haveI : nonempty (subtype s) := ⟨Φ' xX⟩, have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl }, have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl }, have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'), { rw [ΦΦ', ΨΨ', range_comp, range_comp], exact Hausdorff_dist_image (isometry_subtype_coe) }, rw this, -- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding let F := Kuratowski_embedding (subtype s), have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _), rw ← this, -- Let `A` and `B` be the images of `X` and `Y` under this embedding. They are in `ℓ^∞(ℝ)`, and -- their Hausdorff distance is the same as in the original space. let A : nonempty_compacts ℓ_infty_ℝ := ⟨⟨F '' (range Φ'), (is_compact_range IΦ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩, (range_nonempty _).image _⟩, let B : nonempty_compacts ℓ_infty_ℝ := ⟨⟨F '' (range Ψ'), (is_compact_range IΨ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩, (range_nonempty _).image _⟩, have AX : ⟦A⟧ = to_GH_space X, { rw eq_to_GH_space_iff, exact ⟨λ x, F (Φ' x), (Kuratowski_embedding.isometry _).comp IΦ', range_comp _ _⟩ }, have BY : ⟦B⟧ = to_GH_space Y, { rw eq_to_GH_space_iff, exact ⟨λ x, F (Ψ' x), (Kuratowski_embedding.isometry _).comp IΨ', range_comp _ _⟩ }, refine cInf_le ⟨0, _⟩ _, { simp only [lower_bounds, mem_image, mem_prod, mem_set_of_eq, prod.exists, and_imp, forall_exists_index], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg }, apply (mem_image _ _ _).2, existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), simp [AX, BY], end /-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance, essentially by design. -/ lemma Hausdorff_dist_optimal {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) = GH_dist X Y := begin inhabit X, inhabit Y, /- we only need to check the inequality `≤`, as the other one follows from the previous lemma. As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance in the optimal coupling is smaller than the Hausdorff distance of any coupling. First, we check this for couplings which already have small Hausdorff distance: in this case, the induced "distance" on `X ⊕ Y` belongs to the candidates family introduced in the definition of the optimal coupling, and the conclusion follows from the optimality of the optimal coupling within this family. -/ have A : ∀ p q : nonempty_compacts ℓ_infty_ℝ, ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y → Hausdorff_dist (p : set ℓ_infty_ℝ) q < diam (univ : set X) + 1 + diam (univ : set Y) → Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ Hausdorff_dist (p : set ℓ_infty_ℝ) q, { assume p q hp hq bound, rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩, rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩, have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y), { rcases exists_mem_of_nonempty X with ⟨xX, _⟩, have : ∃ y ∈ range Ψ, dist (Φ xX) y < diam (univ : set X) + 1 + diam (univ : set Y), { rw Ψrange, have : Φ xX ∈ ↑p := Φrange.subst (mem_range_self _), exact exists_dist_lt_of_Hausdorff_dist_lt this bound (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty p.is_compact.bounded q.is_compact.bounded) }, rcases this with ⟨y, hy, dy⟩, rcases mem_range.1 hy with ⟨z, hzy⟩, rw ← hzy at dy, have DΦ : diam (range Φ) = diam (univ : set X) := Φisom.diam_range, have DΨ : diam (range Ψ) = diam (univ : set Y) := Ψisom.diam_range, calc diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xX) (Ψ z) + diam (range Ψ) : diam_union (mem_range_self _) (mem_range_self _) ... ≤ diam (univ : set X) + (diam (univ : set X) + 1 + diam (univ : set Y)) + diam (univ : set Y) : by { rw [DΦ, DΨ], apply add_le_add (add_le_add le_rfl (le_of_lt dy)) le_rfl } ... = 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by ring }, let f : X ⊕ Y → ℓ_infty_ℝ := λ x, match x with | inl y := Φ y | inr z := Ψ z end, let F : (X ⊕ Y) × (X ⊕ Y) → ℝ := λ p, dist (f p.1) (f p.2), -- check that the induced "distance" is a candidate have Fgood : F ∈ candidates X Y, { simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero, and_self, set.mem_set_of_eq], repeat {split}, { exact λ x y, calc F (inl x, inl y) = dist (Φ x) (Φ y) : rfl ... = dist x y : Φisom.dist_eq x y }, { exact λ x y, calc F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl ... = dist x y : Ψisom.dist_eq x y }, { exact λ x y, dist_comm _ _ }, { exact λ x y z, dist_triangle _ _ _ }, { exact λ x y, calc F (x, y) ≤ diam (range Φ ∪ range Ψ) : begin have A : ∀ z : X ⊕ Y, f z ∈ range Φ ∪ range Ψ, { assume z, cases z, { apply mem_union_left, apply mem_range_self }, { apply mem_union_right, apply mem_range_self } }, refine dist_le_diam_of_mem _ (A _) (A _), rw [Φrange, Ψrange], exact (p ⊔ q).is_compact.bounded, end ... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : I } }, let Fb := candidates_b_of_candidates F Fgood, have : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD Fb := Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood), refine le_trans this (le_of_forall_le_of_dense (λ r hr, _)), have I1 : ∀ x : X, (⨅ y, Fb (inl x, inr y)) ≤ r, { assume x, have : f (inl x) ∈ ↑p := Φrange.subst (mem_range_self _), rcases exists_dist_lt_of_Hausdorff_dist_lt this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty p.is_compact.bounded q.is_compact.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Ψ, by rwa [← Ψrange] at zq, rcases mem_range.1 this with ⟨y, hy⟩, calc (⨅ y, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa only [add_zero] using HD_below_aux1 0) y ... = dist (Φ x) (Ψ y) : rfl ... = dist (f (inl x)) z : by rw hy ... ≤ r : le_of_lt hz }, have I2 : ∀ y : Y, (⨅ x, Fb (inl x, inr y)) ≤ r, { assume y, have : f (inr y) ∈ ↑q := Ψrange.subst (mem_range_self _), rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr (Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty p.is_compact.bounded q.is_compact.bounded) with ⟨z, zq, hz⟩, have : z ∈ range Φ, by rwa [← Φrange] at zq, rcases mem_range.1 this with ⟨x, hx⟩, calc (⨅ x, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa only [add_zero] using HD_below_aux2 0) x ... = dist (Φ x) (Ψ y) : rfl ... = dist z (f (inr y)) : by rw hx ... ≤ r : le_of_lt hz }, simp only [HD, csupr_le I1, csupr_le I2, max_le_iff, and_self] }, /- Get the same inequality for any coupling. If the coupling is quite good, the desired inequality has been proved above. If it is bad, then the inequality is obvious. -/ have B : ∀ p q : nonempty_compacts ℓ_infty_ℝ, ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y → Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ Hausdorff_dist (p : set ℓ_infty_ℝ) q, { assume p q hp hq, by_cases h : Hausdorff_dist (p : set ℓ_infty_ℝ) q < diam (univ : set X) + 1 + diam (univ : set Y), { exact A p q hp hq h }, { calc Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD (candidates_b_dist X Y) : Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b) ... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : HD_candidates_b_dist_le ... ≤ Hausdorff_dist (p : set ℓ_infty_ℝ) q : not_lt.1 h } }, refine le_antisymm _ _, { apply le_cInf, { refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ }, { rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩, exact B p q hp hq } }, { exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl X Y) (isometry_optimal_GH_injr X Y) } end /-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding the optimal coupling through its Kuratowski embedding. -/ theorem GH_dist_eq_Hausdorff_dist (X : Type u) [metric_space X] [compact_space X] [nonempty X] (Y : Type v) [metric_space Y] [compact_space Y] [nonempty Y] : ∃ Φ : X → ℓ_infty_ℝ, ∃ Ψ : Y → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧ GH_dist X Y = Hausdorff_dist (range Φ) (range Ψ) := begin let F := Kuratowski_embedding (optimal_GH_coupling X Y), let Φ := F ∘ optimal_GH_injl X Y, let Ψ := F ∘ optimal_GH_injr X Y, refine ⟨Φ, Ψ, _, _, _⟩, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl X Y) }, { exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr X Y) }, { rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr X Y), image_univ, ← Hausdorff_dist_optimal], exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm }, end /-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/ instance : metric_space GH_space := { dist := dist, dist_self := λ x, begin rcases exists_rep x with ⟨y, hy⟩, refine le_antisymm _ _, { apply cInf_le, { exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩}, { simp only [mem_image, mem_prod, mem_set_of_eq, prod.exists], existsi [y, y], simpa only [and_self, Hausdorff_dist_self_zero, eq_self_iff_true, and_true]} }, { apply le_cInf, { exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ }, { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } }, end, dist_comm := λ x y, begin have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) '' ({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}) = ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) ∘ prod.swap) '' ({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}), { congr, funext, simp only [comp_app, prod.fst_swap, prod.snd_swap], rw Hausdorff_dist_comm }, simp only [dist, A, image_comp, image_swap_prod], end, eq_of_dist_eq_zero := λ x y hxy, begin /- To show that two spaces at zero distance are isometric, we argue that the distance is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance, i.e., they coincide. Therefore, the original spaces are isometric. -/ rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩, rw [← dist_GH_dist, hxy] at DΦΨ, have : range Φ = range Ψ, { have hΦ : is_compact (range Φ) := is_compact_range Φisom.continuous, have hΨ : is_compact (range Ψ) := is_compact_range Ψisom.continuous, apply (is_closed.Hausdorff_dist_zero_iff_eq _ _ _).1 (DΦΨ.symm), { exact hΦ.is_closed }, { exact hΨ.is_closed }, { exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) hΦ.bounded hΨ.bounded } }, have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this, have eΨ := cast T Ψisom.isometry_equiv_on_range.symm, have e := Φisom.isometry_equiv_on_range.trans eΨ, rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometry_equiv], exact ⟨e⟩ end, dist_triangle := λ x y z, begin /- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y` and `Z` in a space `γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff distance in `γ` to conclude. -/ let X := x.rep, let Y := y.rep, let Z := z.rep, let γ1 := optimal_GH_coupling X Y, let γ2 := optimal_GH_coupling Y Z, let Φ : Y → γ1 := optimal_GH_injr X Y, have hΦ : isometry Φ := isometry_optimal_GH_injr X Y, let Ψ : Y → γ2 := optimal_GH_injl Y Z, have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z, let γ := glue_space hΦ hΨ, have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ, calc dist x z = dist (to_GH_space X) (to_GH_space Z) : by rw [x.to_GH_space_rep, z.to_GH_space_rep] ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : GH_dist_le_Hausdorff_dist ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)) ((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z)) ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) + Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : begin refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (range_nonempty _) _ _), { exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y)))).bounded }, { exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injr X Y)))).bounded } end ... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y))) ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y))) + Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z))) ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) : by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj] ... = Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) + Hausdorff_dist (range (optimal_GH_injl Y Z)) (range (optimal_GH_injr Y Z)) : by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ), Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)] ... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) : by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist] ... = dist x y + dist y z: by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep] end } end GH_space --section end Gromov_Hausdorff /-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/ definition topological_space.nonempty_compacts.to_GH_space {X : Type u} [metric_space X] (p : nonempty_compacts X) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p open topological_space namespace Gromov_Hausdorff section nonempty_compacts variables {X : Type u} [metric_space X] theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts X) : dist p.to_GH_space q.to_GH_space ≤ dist p q := begin have ha : isometry (coe : p → X) := isometry_subtype_coe, have hb : isometry (coe : q → X) := isometry_subtype_coe, have A : dist p q = Hausdorff_dist (p : set X) q := rfl, have I : ↑p = range (coe : p → X) := subtype.range_coe_subtype.symm, have J : ↑q = range (coe : q → X) := subtype.range_coe_subtype.symm, rw [A, I, J], exact GH_dist_le_Hausdorff_dist ha hb end lemma to_GH_space_lipschitz : lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) := lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist lemma to_GH_space_continuous : continuous (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) := to_GH_space_lipschitz.continuous end nonempty_compacts section /- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/ variables {X : Type u} [metric_space X] [compact_space X] [nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] -- we want to ignore these instances in the following theorem local attribute [instance, priority 10] sum.topological_space sum.uniform_space /-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. -/ theorem GH_dist_le_of_approx_subsets {s : set X} (Φ : s → Y) {ε₁ ε₂ ε₃ : ℝ} (hs : ∀ x : X, ∃ y ∈ s, dist x y ≤ ε₁) (hs' : ∀ x : Y, ∃ y : s, dist x (Φ y) ≤ ε₃) (H : ∀ x y : s, |dist x y - dist (Φ x) (Φ y)| ≤ ε₂) : GH_dist X Y ≤ ε₁ + ε₂ / 2 + ε₃ := begin refine le_of_forall_pos_le_add (λ δ δ0, _), rcases exists_mem_of_nonempty X with ⟨xX, _⟩, rcases hs xX with ⟨xs, hxs, Dxs⟩, have sne : s.nonempty := ⟨xs, hxs⟩, letI : nonempty s := sne.to_subtype, have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩), have : ∀ p q : s, |dist p q - dist (Φ p) (Φ q)| ≤ 2 * (ε₂/2 + δ) := λ p q, calc |dist p q - dist (Φ p) (Φ q)| ≤ ε₂ : H p q ... ≤ 2 * (ε₂/2 + δ) : by linarith, -- glue `X` and `Y` along the almost matching subsets letI : metric_space (X ⊕ Y) := glue_metric_approx (λ x:s, (x:X)) (λ x, Φ x) (ε₂/2 + δ) (by linarith) this, let Fl := @sum.inl X Y, let Fr := @sum.inr X Y, have Il : isometry Fl := isometry.of_dist_eq (λ x y, rfl), have Ir : isometry Fr := isometry.of_dist_eq (λ x y, rfl), /- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances of `X` and `s` (in the coupling or, equivalently in the original space), of `s` and `Φ s`, and of `Φ s` and `Y` (in the coupling or, equivalently, in the original space). The first term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive constant where positivity is used to ensure that the coupling is really a metric space and not a premetric space on `X ⊕ Y`). -/ have : GH_dist X Y ≤ Hausdorff_dist (range Fl) (range Fr) := GH_dist_le_Hausdorff_dist Il Ir, have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s) + Hausdorff_dist (Fl '' s) (range Fr), { have B : bounded (range Fl) := (is_compact_range Il.continuous).bounded, exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _) (sne.image _) B (B.mono (image_subset_range _ _))) }, have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) + Hausdorff_dist (Fr '' (range Φ)) (range Fr), { have B : bounded (range Fr) := (is_compact_range Ir.continuous).bounded, exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded ((range_nonempty _).image _) (range_nonempty _) (bounded.mono (image_subset_range _ _) B) B) }, have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁, { rw [← image_univ, Hausdorff_dist_image Il], have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs, refine Hausdorff_dist_le_of_mem_dist this (λ x hx, hs x) (λ x hx, ⟨x, mem_univ _, by simpa only [dist_self]⟩) }, have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ, { refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩, rw ← xx', use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)], exact le_of_eq (glue_dist_glued_points (λ x:s, (x:X)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) }, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩, rcases mem_range.1 y_in_s' with ⟨x, xy⟩, use [Fl x, mem_image_of_mem _ x.2], rw [← yx', ← xy, dist_comm], exact le_of_eq (glue_dist_glued_points (@subtype.val X s) Φ (ε₂/2 + δ) x) } }, have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃, { rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir], rcases exists_mem_of_nonempty Y with ⟨xY, _⟩, rcases hs' xY with ⟨xs', Dxs'⟩, have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs', refine Hausdorff_dist_le_of_mem_dist this (λ x hx, ⟨x, mem_univ _, by simpa only [dist_self]⟩) (λ x _, _), rcases hs' x with ⟨y, Dy⟩, exact ⟨Φ y, mem_range_self _, Dy⟩ }, linarith end end --section /-- The Gromov-Hausdorff space is second countable. -/ instance : second_countable_topology GH_space := begin refine second_countable_of_countable_discretization (λ δ δpos, _), let ε := (2/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, have : ∀ p:GH_space, ∃ s : set p.rep, s.finite ∧ (univ ⊆ (⋃x∈s, ball x ε)) := λ p, by simpa only [subset_univ, exists_true_left] using finite_cover_balls_of_compact is_compact_univ εpos, -- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space -- `p.rep` representing `p`) choose s hs using this, have : ∀ p:GH_space, ∀ t:set p.rep, t.finite → ∃ n:ℕ, ∃ e:equiv t (fin n), true, { assume p t ht, letI : fintype t := finite.fintype ht, exact ⟨fintype.card t, fintype.equiv_fin t, trivial⟩ }, choose N e hne using this, -- cardinality of the nice finite subset `s p` of `p.rep`, called `N p` let N := λ p:GH_space, N p (s p) (hs p).1, -- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p` let E := λ p:GH_space, e p (s p) (hs p).1, -- A function `F` associating to `p : GH_space` the data of all distances between points -- in the `ε`-dense set `s p`. let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) := λp, ⟨N p, λa b, ⌊ε⁻¹ * dist ((E p).symm a) ((E p).symm b)⌋⟩, refine ⟨Σ n, fin n → fin n → ℤ, by apply_instance, F, λp q hpq, _⟩, /- As the target space of F is countable, it suffices to show that two points `p` and `q` with `F p = F q` are at distance `≤ δ`. For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`) to `q.rep` (representing `q`) which is almost an isometry on `s p`, and with image `s q`. For this, we compose the identification of `s p` with `fin (N p)` and the inverse of the identification of `s q` with `fin (N q)`. Together with the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then composing with the canonical inclusion we get `Φ`. -/ have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λ x, Ψ x, -- Use the almost isometry `Φ` to show that `p.rep` and `q.rep` -- are within controlled Gromov-Hausdorff distance. have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε, { refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _), rcases mem_Union₂.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_of_lt hy⟩ }, show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _), rcases mem_Union₂.1 this with ⟨y, ys, hy⟩, let i : ℕ := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).is_lt, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y, { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_of_lt hy }, show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i : ℕ := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j : ℕ := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)).1, { simp only [equiv.apply_symm_apply, fin.val_eq_coe, fin.coe_cast] }, -- Express `dist x y` in terms of `F p` have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y), by simp only [F, (E p).symm_apply_apply], have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y), by { rw ← this, congr; apply fin.ext_iff.2; refl }, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by simp only [F, (E q).symm_apply_apply], have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by { rw ← this, congr; apply fin.ext_iff.2; [exact i', exact j'] }, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, rw [Ap, Aq] at this, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc |ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| = |ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm ... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc |dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist p.rep (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ : by { simp only [ε], ring } end /-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the interesting direction that these conditions imply compactness. -/ lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ} (ulim : tendsto u at_top (𝓝 0)) (hdiam : ∀ p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C) (hcov : ∀ p ∈ t, ∀ n:ℕ, ∃ s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) : totally_bounded t := begin /- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`, up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/ refine metric.totally_bounded_of_finite_discretization (λ δ δpos, _), let ε := (1/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, -- choose `n` for which `u n < ε` rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩, have u_le_ε : u n ≤ ε, { have := hn n le_rfl, simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this, exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) }, -- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n` have : ∀ p:GH_space, ∃ s : set p.rep, ∃ N ≤ K n, ∃ E : equiv s (fin N), p ∈ t → univ ⊆ ⋃x∈s, ball x (u n), { assume p, by_cases hp : p ∉ t, { have : nonempty (equiv (∅ : set p.rep) (fin 0)), { rw ← fintype.card_eq, simp only [empty_card', fintype.card_fin] }, use [∅, 0, bot_le, choice (this)] }, { rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩, rcases cardinal.lt_aleph_0.1 (lt_of_le_of_lt scard (cardinal.nat_lt_aleph_0 _)) with ⟨N, hN⟩, rw [hN, cardinal.nat_cast_le] at scard, have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin], cases quotient.exact this with E, use [s, N, scard, E], simp only [scover, implies_true_iff] } }, choose s N hN E hs using this, -- Define a function `F` taking values in a finite type and associating to `p` enough data -- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`. let M := ⌊ε⁻¹ * max C 0⌋₊, let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) := λ p, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩, λ a b, ⟨min M ⌊ε⁻¹ * dist ((E p).symm a) ((E p).symm b)⌋₊, ( min_le_left _ _).trans_lt (nat.lt_succ_self _) ⟩ ⟩, refine ⟨_, _, (λ p, F p), _⟩, apply_instance, -- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq, have Npq : N p = N q := fin.ext_iff.1 (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)), let Φ : s p → q.rep := λ x, Ψ x, have main : GH_dist p.rep (q.rep) ≤ ε + ε/2 + ε, { -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense -- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows -- from `GH_dist_le_of_approx_subsets` refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, `s p` is `ε`-dense assume x, have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _), rcases mem_Union₂.1 this with ⟨y, ys, hy⟩, exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ }, show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, `s q` is `ε`-dense, and it is the range of `Φ` assume x, have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _), rcases mem_Union₂.1 this with ⟨y, ys, hy⟩, let i : ℕ := E q ⟨y, ys⟩, let hi := ((E q) ⟨y, ys⟩).2, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk], have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).symm ⟨i, hip⟩, use z, have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_trans (le_of_lt hy) u_le_ε }, show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε, { /- the distance between `x` and `y` is encoded in `F p`, and the distance between `Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`. As `F p = F q`, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)` let i : ℕ := E p x, have hip : i < N p := ((E p) x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q) (Ψ x)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] }, -- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)` let j : ℕ := E p y, have hjp : j < N p := ((E p) y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q) (Ψ y)), by { simp only [equiv.apply_symm_apply, fin.coe_cast] }, -- Express `dist x y` in terms of `F p` have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ⌊ε⁻¹ * dist x y⌋₊ := calc ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 : by { congr; apply fin.ext_iff.2; refl } ... = min M ⌊ε⁻¹ * dist x y⌋₊ : by simp only [F, (E p).symm_apply_apply] ... = ⌊ε⁻¹ * dist x y⌋₊ : begin refine min_eq_right (nat.floor_mono _), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le), change dist (x : p.rep) y ≤ C, refine le_trans (dist_le_diam_of_mem is_compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam p pt end, -- Express `dist (Φ x) (Φ y)` in terms of `F q` have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ := calc ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 : by { congr; apply fin.ext_iff.2; [exact i', exact j'] } ... = min M ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ : by simp only [F, (E q).symm_apply_apply] ... = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ : begin refine min_eq_right (nat.floor_mono _), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le), change dist (Ψ x : q.rep) (Ψ y) ≤ C, refine le_trans (dist_le_diam_of_mem is_compact_univ.bounded (mem_univ _) (mem_univ _)) _, exact hdiam q qt end, -- use the equality between `F p` and `F q` to deduce that the distances have equal -- integer parts have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant `f` -- then `subst` revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, have : ⌊ε⁻¹ * dist x y⌋ = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋, { rw [Ap, Aq] at this, have D : 0 ≤ ⌊ε⁻¹ * dist x y⌋ := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), have D' : 0 ≤ ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋ := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg), rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', int.floor_to_nat,int.floor_to_nat, this] }, -- deduce that the distances coincide up to `ε`, by a straightforward computation -- that should be automated have I := calc |ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| = |ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm ... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc |dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) : by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist p.rep (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ/2 : by { simp only [ε, one_div], ring } ... < δ : half_lt_self δpos end section complete /- We will show that a sequence `u n` of compact metric spaces satisfying `dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space. We need to exhibit the limiting compact metric space. For this, start from a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)` for all `n`, in a common metric space. Formally, this is done as follows. Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space `Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive limit of the `Y n`, and finally let `Z` be the completion of `Z0`. The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty compact metric space we are looking for. -/ variables (X : ℕ → Type) [∀ n, metric_space (X n)] [∀ n, compact_space (X n)] [∀ n, nonempty (X n)] /-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding of a type `A` in another metric space. -/ structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 := (space : Type) (metric : metric_space space) (embed : A → space) (isom : isometry embed) local attribute [instance] aux_gluing_struct.metric instance (A : Type) [metric_space A] : inhabited (aux_gluing_struct A) := ⟨{ space := A, metric := by apply_instance, embed := id, isom := λ x y, rfl }⟩ /-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each `X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/ def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n default $ λ n Y, { space := glue_space Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))), metric := by apply_instance, embed := (to_glue_r Y.isom (isometry_optimal_GH_injl (X n) (X (n+1)))) ∘ (optimal_GH_injr (X n) (X (n+1))), isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X (n+1))) } /-- The Gromov-Hausdorff space is complete. -/ instance : complete_space GH_space := begin have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num }, -- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) this (λ u hu, _), -- `X n` is a representative of `u n` let X := λ n, (u n).rep, -- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n` let Y := aux_gluing X, -- this equality is true by definition but Lean unfolds some defs in the wrong order have E : ∀ n : ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X (n + 1))) = (Y (n + 1)).space := λ n, by { dsimp only [Y, aux_gluing], refl }, let c := λ n, cast (E n), have ic : ∀ n, isometry (c n) := λ n x y, by { dsimp only [Y, aux_gluing], exact rfl }, -- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction let f : Π n, (Y n).space → (Y (n + 1)).space := λ n, c n ∘ to_glue_l (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)), have I : ∀ n, isometry (f n) := λ n, (ic n).comp (to_glue_l_isometry _ _), -- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z` let Z0 := metric.inductive_limit I, let Z := uniform_space.completion Z0, let Φ := to_inductive_limit I, let coeZ := (coe : Z0 → Z), -- let `X2 n` be the image of `X n` in the space `Z` let X2 := λ n, range (coeZ ∘ (Φ n) ∘ (Y n).embed), have isom : ∀ n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed), { assume n, refine uniform_space.completion.coe_isometry.comp _, exact (to_inductive_limit_isometry _ _).comp (Y n).isom }, -- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between -- `u n` and `u (n+1)`, therefore bounded by `1/2^n` have D2 : ∀ n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n, { assume n, have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injl (X n) (X n.succ))), { change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injl (X n) (X n.succ))), simp only [X2, Φ], rw [← to_inductive_limit_commute I], simp only [f], rw ← to_glue_commute }, rw range_comp at X2n, have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injr (X n) (X n.succ))), by refl, rw range_comp at X2nsucc, rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist], { exact hu n n n.succ (le_refl n) (le_succ n) }, { apply uniform_space.completion.coe_isometry.comp _, exact (to_inductive_limit_isometry _ _).comp ((ic n).comp (to_glue_r_isometry _ _)) } }, -- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which -- is a metric space let X3 : ℕ → nonempty_compacts Z := λ n, ⟨⟨X2 n, is_compact_range (isom n).continuous⟩, range_nonempty _⟩, -- `X3 n` is a Cauchy sequence by construction, as the successive distances are -- bounded by `(1/2)^n` have : cauchy_seq X3, { refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λ n, _), rw one_mul, exact le_of_lt (D2 n) }, -- therefore, it converges to a limit `L` rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩, -- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L` have M : tendsto (λ n, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) := tendsto.comp (to_GH_space_continuous.tendsto _) hL, -- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`. have : ∀ n, (X3 n).to_GH_space = u n, { assume n, rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometry_equiv], constructor, convert (isom n).isometry_equiv_on_range.symm, }, -- Finally, we have proved the convergence of `u n` exact ⟨L.to_GH_space, by simpa only [this] using M⟩ end end complete--section end Gromov_Hausdorff --namespace
113ce0a148ed82c2952c7305e14a379457e3b371
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/derived.lean
993ad9472f831a1490c026f9695ea7dc6cbcc67d
[ "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
7,638
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.preadditive.projective_resolution /-! # Left-derived functors We define the left-derived functors `F.left_derived n : C ⥤ D` for any additive functor `F` out of a category with projective resolutions. The definition is ``` projective_resolutions C ⋙ F.map_homotopy_category _ ⋙ homotopy_category.homology_functor D _ n ``` that is, we pick a projective resolution (thought of as an object of the homotopy category), we apply `F` objectwise, and compute `n`-th homology. We show that these left-derived functors can be calculated on objects using any choice of projective resolution, and on morphisms by any choice of lift to a chain map between chosen projective resolutions. Similarly we define natural transformations between left-derived functors coming from natural transformations between the original additive functors, and show how to compute the components. ## Implementation We don't assume the categories involved are abelian (just preadditive, and have equalizers, cokernels, and image maps), or that the functors are right exact. None of these assumptions are needed yet. It is often convenient, of course, to work with `[abelian C] [enough_projectives C] [abelian D]` which (assuming the results from `category_theory.abelian.projective`) are enough to provide all the typeclass hypotheses assumed here. -/ noncomputable theory open category_theory open category_theory.limits universes v u namespace category_theory variables {C : Type u} [category.{v} C] {D : Type*} [category D] -- Importing `category_theory.abelian.projective` and assuming -- `[abelian C] [enough_projectives C] [abelian D]` suffices to acquire all the following: variables [preadditive C] [has_zero_object C] [has_equalizers C] [has_images C] [has_projective_resolutions C] variables [preadditive D] [has_zero_object D] [has_equalizers D] [has_cokernels D] [has_images D] [has_image_maps D] /-- The left derived functors of an additive functor. -/ def functor.left_derived (F : C ⥤ D) [F.additive] (n : ℕ) : C ⥤ D := projective_resolutions C ⋙ F.map_homotopy_category _ ⋙ homotopy_category.homology_functor D _ n -- TODO the left derived functors are additive (and linear when `F` is linear) /-- We can compute a left derived functor using a chosen projective resolution. -/ @[simps] def functor.left_derived_obj_iso (F : C ⥤ D) [F.additive] (n : ℕ) {X : C} (P : ProjectiveResolution X) : (F.left_derived n).obj X ≅ (homology_functor D _ n).obj ((F.map_homological_complex _).obj P.complex) := (homotopy_category.homology_functor D _ n).map_iso (homotopy_category.iso_of_homotopy_equiv (F.map_homotopy_equiv (ProjectiveResolution.homotopy_equiv _ P))) ≪≫ (homotopy_category.homology_factors D _ n).app _ /-- The 0-th derived functor of `F` on a projective object `X` is just `F.obj X`. -/ @[simps] def functor.left_derived_obj_projective_zero (F : C ⥤ D) [F.additive] (X : C) [projective X] : (F.left_derived 0).obj X ≅ F.obj X := F.left_derived_obj_iso 0 (ProjectiveResolution.self X) ≪≫ (homology_functor _ _ _).map_iso ((chain_complex.single₀_map_homological_complex F).app X) ≪≫ (chain_complex.homology_functor_0_single₀ D).app (F.obj X) open_locale zero_object /-- The higher derived functors vanish on projective objects. -/ @[simps] def functor.left_derived_obj_projective_succ (F : C ⥤ D) [F.additive] (n : ℕ) (X : C) [projective X] : (F.left_derived (n+1)).obj X ≅ 0 := F.left_derived_obj_iso (n+1) (ProjectiveResolution.self X) ≪≫ (homology_functor _ _ _).map_iso ((chain_complex.single₀_map_homological_complex F).app X) ≪≫ (chain_complex.homology_functor_succ_single₀ D n).app (F.obj X) /-- We can compute a left derived functor on a morphism using a lift of that morphism to a chain map between chosen projective resolutions. -/ lemma functor.left_derived_map_eq (F : C ⥤ D) [F.additive] (n : ℕ) {X Y : C} (f : X ⟶ Y) {P : ProjectiveResolution X} {Q : ProjectiveResolution Y} (g : P.complex ⟶ Q.complex) (w : g ≫ Q.π = P.π ≫ (chain_complex.single₀ C).map f) : (F.left_derived n).map f = (F.left_derived_obj_iso n P).hom ≫ (homology_functor D _ n).map ((F.map_homological_complex _).map g) ≫ (F.left_derived_obj_iso n Q).inv := begin dsimp only [functor.left_derived, functor.left_derived_obj_iso], dsimp, simp only [category.comp_id, category.id_comp], rw [←homology_functor_map, homotopy_category.homology_functor_map_factors], simp only [←functor.map_comp], congr' 1, apply homotopy_category.eq_of_homotopy, apply functor.map_homotopy, apply homotopy.trans, exact homotopy_category.homotopy_out_map _, apply ProjectiveResolution.lift_homotopy f, { simp, }, { simp [w], }, end /-- The natural transformation between left-derived functors induced by a natural transformation. -/ @[simps] def nat_trans.left_derived {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) (n : ℕ) : F.left_derived n ⟶ G.left_derived n := whisker_left (projective_resolutions C) (whisker_right (nat_trans.map_homotopy_category α _) (homotopy_category.homology_functor D _ n)) @[simp] lemma nat_trans.left_derived_id (F : C ⥤ D) [F.additive] (n : ℕ) : nat_trans.left_derived (𝟙 F) n = 𝟙 (F.left_derived n) := by { simp [nat_trans.left_derived], refl, } -- The `simp_nf` linter times out here, so we disable it. @[simp, nolint simp_nf] lemma nat_trans.left_derived_comp {F G H : C ⥤ D} [F.additive] [G.additive] [H.additive] (α : F ⟶ G) (β : G ⟶ H) (n : ℕ) : nat_trans.left_derived (α ≫ β) n = nat_trans.left_derived α n ≫ nat_trans.left_derived β n := by simp [nat_trans.left_derived] /-- A component of the natural transformation between left-derived functors can be computed using a chosen projective resolution. -/ lemma nat_trans.left_derived_eq {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) (n : ℕ) {X : C} (P : ProjectiveResolution X) : (nat_trans.left_derived α n).app X = (F.left_derived_obj_iso n P).hom ≫ (homology_functor D _ n).map ((nat_trans.map_homological_complex α _).app P.complex) ≫ (G.left_derived_obj_iso n P).inv := begin symmetry, dsimp [nat_trans.left_derived, functor.left_derived_obj_iso], simp only [category.comp_id, category.id_comp], rw [←homology_functor_map, homotopy_category.homology_functor_map_factors], simp only [←functor.map_comp], congr' 1, apply homotopy_category.eq_of_homotopy, simp only [nat_trans.map_homological_complex_naturality_assoc, ←functor.map_comp], apply homotopy.comp_left_id, rw [←functor.map_id], apply functor.map_homotopy, apply homotopy_equiv.homotopy_hom_inv_id, end -- TODO: -- lemma nat_trans.left_derived_projective_zero {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) -- (X : C) [projective X] : -- (nat_trans.left_derived α 0).app X = -- (F.left_derived_obj_projective_zero X).hom ≫ -- α.app X ≫ -- (G.left_derived_obj_projective_zero X).inv := sorry -- TODO: -- lemma nat_trans.left_derived_projective_succ {F G : C ⥤ D} [F.additive] [G.additive] (α : F ⟶ G) -- (n : ℕ) (X : C) [projective X] : -- (nat_trans.left_derived α (n+1)).app X = 0 := sorry -- TODO left-derived functors of the identity functor are the identity -- (requires we assume `abelian`?) -- PROJECT left-derived functors of a composition (Grothendieck sequence) end category_theory
56897e568778326d3b1b497d0f92ea73eac88946
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/quotient.lean
94b63d2b1c21ddd49c8ad8b0667c5ec4c8238694
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,666
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import category_theory.natural_isomorphism import category_theory.equivalence import category_theory.eq_to_hom /-! # Quotient category Constructs the quotient of a category by an arbitrary family of relations on its hom-sets, by introducing a type synonym for the objects, and identifying homs as necessary. This is analogous to 'the quotient of a group by the normal closure of a subset', rather than 'the quotient of a group by a normal subgroup'. When taking the quotient by a congruence relation, `functor_map_eq_iff` says that no unnecessary identifications have been made. -/ /-- A `hom_rel` on `C` consists of a relation on every hom-set. -/ @[derive inhabited] def hom_rel (C) [quiver C] := Π ⦃X Y : C⦄, (X ⟶ Y) → (X ⟶ Y) → Prop namespace category_theory variables {C : Type*} [category C] (r : hom_rel C) include r /-- A `hom_rel` is a congruence when it's an equivalence on every hom-set, and it can be composed from left and right. -/ class congruence : Prop := (is_equiv : ∀ {X Y}, is_equiv _ (@r X Y)) (comp_left : ∀ {X Y Z} (f : X ⟶ Y) {g g' : Y ⟶ Z}, r g g' → r (f ≫ g) (f ≫ g')) (comp_right : ∀ {X Y Z} {f f' : X ⟶ Y} (g : Y ⟶ Z), r f f' → r (f ≫ g) (f' ≫ g)) attribute [instance] congruence.is_equiv /-- A type synonym for `C`, thought of as the objects of the quotient category. -/ @[ext] structure quotient := (as : C) instance [inhabited C] : inhabited (quotient r) := ⟨ { as := default } ⟩ namespace quotient /-- Generates the closure of a family of relations w.r.t. composition from left and right. -/ inductive comp_closure ⦃s t : C⦄ : (s ⟶ t) → (s ⟶ t) → Prop | intro {a b} (f : s ⟶ a) (m₁ m₂ : a ⟶ b) (g : b ⟶ t) (h : r m₁ m₂) : comp_closure (f ≫ m₁ ≫ g) (f ≫ m₂ ≫ g) lemma comp_closure.of {a b} (m₁ m₂ : a ⟶ b) (h : r m₁ m₂) : comp_closure r m₁ m₂ := by simpa using comp_closure.intro (𝟙 _) m₁ m₂ (𝟙 _) h lemma comp_left {a b c : C} (f : a ⟶ b) : Π (g₁ g₂ : b ⟶ c) (h : comp_closure r g₁ g₂), comp_closure r (f ≫ g₁) (f ≫ g₂) | _ _ ⟨x, m₁, m₂, y, h⟩ := by simpa using comp_closure.intro (f ≫ x) m₁ m₂ y h lemma comp_right {a b c : C} (g : b ⟶ c) : Π (f₁ f₂ : a ⟶ b) (h : comp_closure r f₁ f₂), comp_closure r (f₁ ≫ g) (f₂ ≫ g) | _ _ ⟨x, m₁, m₂, y, h⟩ := by simpa using comp_closure.intro x m₁ m₂ (y ≫ g) h /-- Hom-sets of the quotient category. -/ def hom (s t : quotient r) := quot $ @comp_closure C _ r s.as t.as instance (a : quotient r) : inhabited (hom r a a) := ⟨quot.mk _ (𝟙 a.as)⟩ /-- Composition in the quotient category. -/ def comp ⦃a b c : quotient r⦄ : hom r a b → hom r b c → hom r a c := λ hf hg, quot.lift_on hf ( λ f, quot.lift_on hg (λ g, quot.mk _ (f ≫ g)) (λ g₁ g₂ h, quot.sound $ comp_left r f g₁ g₂ h) ) (λ f₁ f₂ h, quot.induction_on hg $ λ g, quot.sound $ comp_right r g f₁ f₂ h) @[simp] lemma comp_mk {a b c : quotient r} (f : a.as ⟶ b.as) (g : b.as ⟶ c.as) : comp r (quot.mk _ f) (quot.mk _ g) = quot.mk _ (f ≫ g) := rfl instance category : category (quotient r) := { hom := hom r, id := λ a, quot.mk _ (𝟙 a.as), comp := comp r } /-- The functor from a category to its quotient. -/ @[simps] def functor : C ⥤ quotient r := { obj := λ a, { as := a }, map := λ _ _ f, quot.mk _ f } noncomputable instance : full (functor r) := { preimage := λ X Y f, quot.out f, } instance : ess_surj (functor r) := { mem_ess_image := λ Y, ⟨Y.as, ⟨eq_to_iso (by { ext, refl, })⟩⟩ } protected lemma induction {P : Π {a b : quotient r}, (a ⟶ b) → Prop} (h : ∀ {x y : C} (f : x ⟶ y), P ((functor r).map f)) : ∀ {a b : quotient r} (f : a ⟶ b), P f := by { rintros ⟨x⟩ ⟨y⟩ ⟨f⟩, exact h f, } protected lemma sound {a b : C} {f₁ f₂ : a ⟶ b} (h : r f₁ f₂) : (functor r).map f₁ = (functor r).map f₂ := by simpa using quot.sound (comp_closure.intro (𝟙 a) f₁ f₂ (𝟙 b) h) lemma functor_map_eq_iff [congruence r] {X Y : C} (f f' : X ⟶ Y) : (functor r).map f = (functor r).map f' ↔ r f f' := begin split, { erw quot.eq, intro h, induction h with m m' hm, { cases hm, apply congruence.comp_left, apply congruence.comp_right, assumption, }, { apply refl }, { apply symm, assumption }, { apply trans; assumption }, }, { apply quotient.sound }, end variables {D : Type*} [category D] (F : C ⥤ D) (H : ∀ (x y : C) (f₁ f₂ : x ⟶ y), r f₁ f₂ → F.map f₁ = F.map f₂) include H /-- The induced functor on the quotient category. -/ @[simps] def lift : quotient r ⥤ D := { obj := λ a, F.obj a.as, map := λ a b hf, quot.lift_on hf (λ f, F.map f) (by { rintros _ _ ⟨_, _, _, _, _, _, h⟩, simp [H _ _ _ _ h], }), map_id' := λ a, F.map_id a.as, map_comp' := by { rintros a b c ⟨f⟩ ⟨g⟩, exact F.map_comp f g, } } /-- The original functor factors through the induced functor. -/ def lift.is_lift : (functor r) ⋙ lift r F H ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) @[simp] lemma lift.is_lift_hom (X : C) : (lift.is_lift r F H).hom.app X = 𝟙 (F.obj X) := rfl @[simp] lemma lift.is_lift_inv (X : C) : (lift.is_lift r F H).inv.app X = 𝟙 (F.obj X) := rfl lemma lift_map_functor_map {X Y : C} (f : X ⟶ Y) : (lift r F H).map ((functor r).map f) = F.map f := by { rw ←(nat_iso.naturality_1 (lift.is_lift r F H)), dsimp, simp, } end quotient end category_theory
8db48e98572862b8dabc1f1d3454a8b36abd5f3e
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/counterexamples/canonically_ordered_comm_semiring_two_mul.lean
9279565dfbcfa0a067fe692ddfcf8e4033b7a138
[ "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
9,495
lean
/- Copyright (c) 2021 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.zmod.basic import ring_theory.subsemiring import algebra.order.monoid /-! A `canonically_ordered_comm_semiring` with two different elements `a` and `b` such that `a ≠ b` and `2 * a = 2 * b`. Thus, multiplication by a fixed non-zero element of a canonically ordered semiring need not be injective. In particular, multiplying by a strictly positive element need not be strictly monotone. Recall that a `canonically_ordered_comm_semiring` is a commutative semiring with a partial ordering that is "canonical" in the sense that the inequality `a ≤ b` holds if and only if there is a `c` such that `a + c = b`. There are several compatibility conditions among addition/multiplication and the order relation. The point of the counterexample is to show that monotonicity of multiplication cannot be strengthened to **strict** monotonicity. Reference: https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/canonically_ordered.20pathology -/ namespace from_Bhavik /-- Bhavik Mehta's example. There are only the initial definitions, but no proofs. The Type `K` is a canonically ordered commutative semiring with the property that `2 * (1/2) ≤ 2 * 1`, even though it is not true that `1/2 ≤ 1`, since `1/2` and `1` are not comparable. -/ @[derive [comm_semiring]] def K : Type := subsemiring.closure ({1.5} : set ℚ) instance : has_coe K ℚ := ⟨λ x, x.1⟩ instance inhabited_K : inhabited K := ⟨0⟩ instance : preorder K := { le := λ x y, x = y ∨ (x : ℚ) + 1 ≤ (y : ℚ), le_refl := λ x, or.inl rfl, le_trans := λ x y z xy yz, begin rcases xy with (rfl | _), { apply yz }, rcases yz with (rfl | _), { right, apply xy }, right, exact xy.trans (le_trans ((le_add_iff_nonneg_right _).mpr zero_le_one) yz) end } end from_Bhavik lemma mem_zmod_2 (a : zmod 2) : a = 0 ∨ a = 1 := begin rcases a with ⟨_ | _ | _ | _ | a_val, _ | ⟨_, _ | ⟨_, ⟨⟩⟩⟩⟩, { exact or.inl rfl }, { exact or.inr rfl }, end lemma add_self_zmod_2 (a : zmod 2) : a + a = 0 := begin rcases mem_zmod_2 a with rfl | rfl; refl, end namespace Nxzmod_2 variables {a b : ℕ × zmod 2} /-- The preorder relation on `ℕ × ℤ/2ℤ` where we only compare the first coordinate, except that we leave incomparable each pair of elements with the same first component. For instance, `∀ α, β ∈ ℤ/2ℤ`, the inequality `(1,α) ≤ (2,β)` holds, whereas, `∀ n ∈ ℤ`, the elements `(n,0)` and `(n,1)` are incomparable. -/ instance preN2 : partial_order (ℕ × zmod 2) := { le := λ x y, x = y ∨ x.1 < y.1, le_refl := λ a, or.inl rfl, le_trans := λ x y z xy yz, begin rcases xy with (rfl | _), { exact yz }, { rcases yz with (rfl | _), { exact or.inr xy}, { exact or.inr (xy.trans yz) } } end, le_antisymm := begin intros a b ab ba, cases ab with ab ab, { exact ab }, { cases ba with ba ba, { exact ba.symm }, { exact (nat.lt_asymm ab ba).elim } } end } instance csrN2 : comm_semiring (ℕ × zmod 2) := by apply_instance instance csrN2_1 : add_cancel_comm_monoid (ℕ × zmod 2) := { add_left_cancel := λ a b c h, (add_right_inj a).mp h, ..Nxzmod_2.csrN2 } /-- A strict inequality forces the first components to be different. -/ @[simp] lemma lt_def : a < b ↔ a.1 < b.1 := begin refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨(rfl | a1), h1⟩, { exact ((not_or_distrib.mp h1).1).elim rfl }, { exact a1 } }, refine ⟨or.inr h, not_or_distrib.mpr ⟨λ k, _, not_lt.mpr h.le⟩⟩, rw k at h, exact nat.lt_asymm h h end lemma add_left_cancel : ∀ (a b c : ℕ × zmod 2), a + b = a + c → b = c := λ a b c h, (add_right_inj a).mp h lemma add_le_add_left : ∀ (a b : ℕ × zmod 2), a ≤ b → ∀ (c : ℕ × zmod 2), c + a ≤ c + b := begin rintros a b (rfl | ab) c, { refl }, { exact or.inr (by simpa) } end lemma le_of_add_le_add_left : ∀ (a b c : ℕ × zmod 2), a + b ≤ a + c → b ≤ c := begin rintros a b c (bc | bc), { exact le_of_eq ((add_right_inj a).mp bc) }, { exact or.inr (by simpa using bc) } end lemma zero_le_one : (0 : ℕ × zmod 2) ≤ 1 := dec_trivial lemma mul_lt_mul_of_pos_left : ∀ (a b c : ℕ × zmod 2), a < b → 0 < c → c * a < c * b := λ a b c ab c0, lt_def.mpr ((mul_lt_mul_left (lt_def.mp c0)).mpr (lt_def.mp ab)) lemma mul_lt_mul_of_pos_right : ∀ (a b c : ℕ × zmod 2), a < b → 0 < c → a * c < b * c := λ a b c ab c0, lt_def.mpr ((mul_lt_mul_right (lt_def.mp c0)).mpr (lt_def.mp ab)) instance ocsN2 : ordered_comm_semiring (ℕ × zmod 2) := { add_le_add_left := add_le_add_left, le_of_add_le_add_left := le_of_add_le_add_left, zero_le_one := zero_le_one, mul_lt_mul_of_pos_left := mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := mul_lt_mul_of_pos_right, ..Nxzmod_2.csrN2_1, ..(infer_instance : partial_order (ℕ × zmod 2)), ..(infer_instance : comm_semiring (ℕ × zmod 2)) } end Nxzmod_2 namespace ex_L open Nxzmod_2 subtype /-- Initially, `L` was defined as the subsemiring closure of `(1,0)`. -/ def L : Type := { l : (ℕ × zmod 2) // l ≠ (0, 1) } instance zero : has_zero L := ⟨⟨(0, 0), dec_trivial⟩⟩ instance one : has_one L := ⟨⟨(1, 1), dec_trivial⟩⟩ instance inhabited : inhabited L := ⟨1⟩ lemma add_L {a b : ℕ × zmod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) : a + b ≠ (0, 1) := begin rcases a with ⟨a, a2⟩, rcases b with ⟨b, b2⟩, cases b, { rcases mem_zmod_2 b2 with rfl | rfl, { simp [ha] }, { simpa only } }, { simp [(a + b).succ_ne_zero] } end lemma mul_L {a b : ℕ × zmod 2} (ha : a ≠ (0, 1)) (hb : b ≠ (0, 1)) : a * b ≠ (0, 1) := begin rcases a with ⟨a, a2⟩, rcases b with ⟨b, b2⟩, cases b, { rcases mem_zmod_2 b2 with rfl | rfl; rcases mem_zmod_2 a2 with rfl | rfl; -- while this looks like a non-terminal `simp`, it (almost) isn't: there is only one goal where -- it does not finish the proof and on that goal it asks to prove `false` simp, exact hb rfl }, cases a, { rcases mem_zmod_2 b2 with rfl | rfl; rcases mem_zmod_2 a2 with rfl | rfl; -- while this looks like a non-terminal `simp`, it (almost) isn't: there is only one goal where -- it does not finish the proof and on that goal it asks to prove `false` simp, exact ha rfl }, { simp [mul_ne_zero _ _, nat.succ_ne_zero _] } end instance has_add_L : has_add L := { add := λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨a + b, add_L ha hb⟩ } instance : has_mul L := { mul := λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨a * b, mul_L ha hb⟩ } instance : ordered_comm_semiring L := begin refine function.injective.ordered_comm_semiring _ subtype.coe_injective rfl rfl _ _; { refine λ x y, _, cases x, cases y, refl } end lemma bot_le : ∀ (a : L), 0 ≤ a := begin rintros ⟨⟨an, a2⟩, ha⟩, cases an, { rcases mem_zmod_2 a2 with (rfl | rfl), { refl, }, { exact (ha rfl).elim } }, { refine or.inr _, exact nat.succ_pos _ } end instance order_bot : order_bot L := { bot := 0, bot_le := bot_le, ..(infer_instance : partial_order L) } lemma le_iff_exists_add : ∀ (a b : L), a ≤ b ↔ ∃ (c : L), b = a + c := begin rintros ⟨⟨an, a2⟩, ha⟩ ⟨⟨bn, b2⟩, hb⟩, rw subtype.mk_le_mk, refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨rfl, rfl⟩ | h, { exact ⟨(0 : L), (add_zero _).symm⟩ }, { refine ⟨⟨⟨bn - an, b2 + a2⟩, _⟩, _⟩, { rw [ne.def, prod.mk.inj_iff, not_and_distrib], exact or.inl (ne_of_gt (nat.sub_pos_of_lt h)) }, { congr, { exact (add_sub_cancel_of_le h.le).symm }, { change b2 = a2 + (b2 + a2), rw [add_comm b2, ← add_assoc, add_self_zmod_2, zero_add] } } } }, { rcases h with ⟨⟨⟨c, c2⟩, hc⟩, abc⟩, injection abc with abc, rw [prod.mk_add_mk, prod.mk.inj_iff] at abc, rcases abc with ⟨rfl, rfl⟩, cases c, { refine or.inl _, rw [ne.def, prod.mk.inj_iff, eq_self_iff_true, true_and] at hc, rcases mem_zmod_2 c2 with rfl | rfl, { rw [add_zero, add_zero] }, { exact (hc rfl).elim } }, { refine or.inr _, exact (lt_add_iff_pos_right _).mpr c.succ_pos } } end lemma eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : L), a * b = 0 → a = 0 ∨ b = 0 := begin rintros ⟨⟨a, a2⟩, ha⟩ ⟨⟨b, b2⟩, hb⟩ ab1, injection ab1 with ab, injection ab with abn ab2, rw mul_eq_zero at abn, rcases abn with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { refine or.inl _, rcases mem_zmod_2 a2 with rfl | rfl, { refl }, { exact (ha rfl).elim } }, { refine or.inr _, rcases mem_zmod_2 b2 with rfl | rfl, { refl }, { exact (hb rfl).elim } } end instance can : canonically_ordered_comm_semiring L := { le_iff_exists_add := le_iff_exists_add, eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, ..(infer_instance : order_bot L), ..(infer_instance : ordered_comm_semiring L) } /-- The elements `(1,0)` and `(1,1)` of `L` are different, but their doubles coincide. -/ example : ∃ a b : L, a ≠ b ∧ 2 * a = 2 * b := begin refine ⟨⟨(1,0), by simp⟩, 1, λ (h : (⟨(1, 0), _⟩ : L) = ⟨⟨1, 1⟩, _⟩), _, rfl⟩, obtain (F : (0 : zmod 2) = 1) := congr_arg (λ j : L, j.1.2) h, cases F, end end ex_L
02b1a6de9e536af14c3e1e593be4152b3219ea1c
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/any_goals.lean
3e91b7691129b2d50ba70a2bb662dffc52b88447
[ "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
190
lean
constant f : nat → nat axiom fax : ∀ x, f x = x example (a b c : nat) : b = c → f a = a ∧ c = b := begin intros, constructor, any_goals {rw fax}, {symmetry, assumption} end
a0aa8ec89fb1c0dce95aa83f46f98a8e065b6c3c
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/vector_bundle.lean
9a62e373990ca23c3f868557f0e73ab3141b1889
[ "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
47,214
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri, Sebastien Gouezel, Heather Macbeth, Patrick Massot -/ import analysis.normed_space.bounded_linear_maps import topology.fiber_bundle /-! # Topological vector bundles In this file we define topological vector bundles. Let `B` be the base space. In our formalism, a topological vector bundle is by definition the type `bundle.total_space E` where `E : B → Type*` is a function associating to `x : B` the fiber over `x`. This type `bundle.total_space E` is just a type synonym for `Σ (x : B), E x`, with the interest that one can put another topology than on `Σ (x : B), E x` which has the disjoint union topology. To have a topological vector bundle structure on `bundle.total_space E`, one should additionally have the following data: * `F` should be a normed space over a normed field `R`; * There should be a topology on `bundle.total_space E`, for which the projection to `B` is a topological fiber bundle with fiber `F` (in particular, each fiber `E x` is homeomorphic to `F`); * For each `x`, the fiber `E x` should be a topological vector space over `R`, and the injection from `E x` to `bundle.total_space F E` should be an embedding; * There should be a distinguished set of bundle trivializations (which are continuous linear equivs in the fibres), the "trivialization atlas" * There should be a choice of bundle trivialization at each point, which belongs to this atlas. If all these conditions are satisfied, and if moreover for any two trivializations `e`, `e'` in the atlas the transition function considered as a map from `B` into `F →L[R] F` is continuous on `e.base_set ∩ e'.base_set` with respect to the operator norm topology on `F →L[R] F`, we register the typeclass `topological_vector_bundle R F E`. If `E₁ : B → Type*` and `E₂ : B → Type*` define two topological vector bundles over `R` with fiber models `F₁` and `F₂`, denote by `E₁ ×ᵇ E₂` the sigma type of direct sums, with fiber `E x := (E₁ x × E₂ x)`. We can endow `bundle.total_space (E₁ ×ᵇ E₂)` with a topological vector bundle structure, `bundle.prod.topological_vector_bundle`. A similar construction (which is yet to be formalized) can be done for the vector bundle of continuous linear maps from `E₁ x` to `E₂ x` with fiber a type synonym `vector_bundle_continuous_linear_map R F₁ E₁ F₂ E₂ x := (E₁ x →L[R] E₂ x)` (and with the topology inherited from the norm-topology on `F₁ →L[R] F₂`, without the need to define the strong topology on continuous linear maps between general topological vector spaces). Likewise for tensor products of topological vector bundles, exterior algebras, and so on, where the topology can be defined using a norm on the fiber model if this helps. ## Tags Vector bundle -/ noncomputable theory open bundle set variables (R : Type*) {B : Type*} (F : Type*) (E : B → Type*) section topological_vector_space variables [semiring R] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] [topological_space F] [add_comm_monoid F] [module R F] [topological_space B] /-- Local pretrivialization for vector prebundles. -/ @[nolint has_inhabited_instance] structure topological_vector_bundle.pretrivialization extends to_fiber_bundle_pretrivialization : topological_fiber_bundle.pretrivialization F (proj E) := (linear : ∀ x ∈ base_set, is_linear_map R (λ y : (E x), (to_fun y).2)) instance : has_coe_to_fun (topological_vector_bundle.pretrivialization R F E) _ := ⟨λ e, e.to_fun⟩ instance : has_coe (topological_vector_bundle.pretrivialization R F E) (topological_fiber_bundle.pretrivialization F (proj E)) := ⟨topological_vector_bundle.pretrivialization.to_fiber_bundle_pretrivialization⟩ variable [topological_space (total_space E)] /-- Local trivialization for vector bundles. -/ @[nolint has_inhabited_instance] structure topological_vector_bundle.trivialization extends to_fiber_bundle_trivialization : topological_fiber_bundle.trivialization F (proj E) := (linear : ∀ x ∈ base_set, is_linear_map R (λ y : (E x), (to_fun y).2)) open topological_vector_bundle instance : has_coe_to_fun (trivialization R F E) (λ _, total_space E → B × F) := ⟨λ e, e.to_fun⟩ instance : has_coe (trivialization R F E) (topological_fiber_bundle.trivialization F (proj E)) := ⟨topological_vector_bundle.trivialization.to_fiber_bundle_trivialization⟩ namespace topological_vector_bundle variables {R F E} /-- Natural identification as `topological_vector_bundle.pretrivialization`. -/ def trivialization.to_pretrivialization (e : trivialization R F E) : topological_vector_bundle.pretrivialization R F E := { ..e } lemma trivialization.mem_source (e : trivialization R F E) {x : total_space E} : x ∈ e.source ↔ proj E x ∈ e.base_set := topological_fiber_bundle.trivialization.mem_source e @[simp, mfld_simps] lemma trivialization.coe_coe (e : trivialization R F E) : ⇑e.to_local_homeomorph = e := rfl @[simp, mfld_simps] lemma trivialization.coe_fst (e : trivialization R F E) {x : total_space E} (ex : x ∈ e.source) : (e x).1 = (proj E) x := e.proj_to_fun x ex end topological_vector_bundle end topological_vector_space section open topological_vector_bundle variables (B) variables [nondiscrete_normed_field R] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] [normed_group F] [normed_space R F] [topological_space B] [topological_space (total_space E)] [∀ x, topological_space (E x)] /-- The valid transition functions for a topological vector bundle over `B` modelled on a normed space `F`: a transition function must be a local homeomorphism of `B × F` with source and target both `s ×ˢ univ`, which on this set is of the form `λ (b, v), (b, ε b v)` for some continuous map `ε` from `s` to `F ≃L[R] F`. Here continuity is with respect to the operator norm on `F →L[R] F`. -/ def continuous_transitions (e : local_equiv (B × F) (B × F)) : Prop := ∃ s : set B, e.source = s ×ˢ (univ : set F) ∧ e.target = s ×ˢ (univ : set F) ∧ ∃ ε : B → (F ≃L[R] F), continuous_on (λ b, (ε b : F →L[R] F)) s ∧ ∀ b ∈ s, ∀ v : F, e (b, v) = (b, ε b v) variables {B} /-- The space `total_space E` (for `E : B → Type*` such that each `E x` is a topological vector space) has a topological vector space structure with fiber `F` (denoted with `topological_vector_bundle R F E`) if around every point there is a fiber bundle trivialization which is linear in the fibers. -/ class topological_vector_bundle := (total_space_mk_inducing [] : ∀ (b : B), inducing (total_space_mk E b)) (trivialization_atlas [] : set (trivialization R F E)) (trivialization_at [] : B → trivialization R F E) (mem_base_set_trivialization_at [] : ∀ b : B, b ∈ (trivialization_at b).base_set) (trivialization_mem_atlas [] : ∀ b : B, trivialization_at b ∈ trivialization_atlas) (continuous_coord_change : ∀ e e' ∈ trivialization_atlas, continuous_transitions R B F (e.to_local_equiv.symm.trans e'.to_local_equiv : _)) export topological_vector_bundle (trivialization_atlas trivialization_at mem_base_set_trivialization_at trivialization_mem_atlas) variable [topological_vector_bundle R F E] namespace topological_vector_bundle @[simp, mfld_simps] lemma mem_source_trivialization_at (z : total_space E) : z ∈ (trivialization_at R F E z.1).source := by { rw topological_fiber_bundle.trivialization.mem_source, apply mem_base_set_trivialization_at } variables {R F E} /-- The co-ordinate change (transition function) between two trivializations of a vector bundle over `B` modelled on `F`: this is a function from `B` to `F ≃L[R] F` (of course, only meaningful on the intersection of the domains of definition of the two trivializations). -/ def coord_change {e e' : trivialization R F E} (he : e ∈ trivialization_atlas R F E) (he' : e' ∈ trivialization_atlas R F E) : B → F ≃L[R] F := (topological_vector_bundle.continuous_coord_change e he e' he').some_spec.2.2.some lemma continuous_on_coord_change {e e' : trivialization R F E} (he : e ∈ trivialization_atlas R F E) (he' : e' ∈ trivialization_atlas R F E) : continuous_on (λ b, (coord_change he he' b : F →L[R] F)) (e.base_set ∩ e'.base_set) := begin let s := (continuous_coord_change e he e' he').some, let hs := (continuous_coord_change e he e' he').some_spec.1, have hs : s = e.base_set ∩ e'.base_set, { have : s ×ˢ (univ : set F) = (e.base_set ∩ e'.base_set) ×ˢ (univ : set F) := hs.symm.trans (topological_fiber_bundle.trivialization.symm_trans_source_eq e e'), have hF : (univ : set F).nonempty := univ_nonempty, rwa prod_eq_iff_eq hF at this }, rw ← hs, exact (continuous_coord_change e he e' he').some_spec.2.2.some_spec.1 end lemma trans_eq_coord_change {e e' : trivialization R F E} (he : e ∈ trivialization_atlas R F E) (he' : e' ∈ trivialization_atlas R F E) {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) (v : F) : e' (e.to_local_homeomorph.symm (b, v)) = (b, coord_change he he' b v) := begin let s := (continuous_coord_change e he e' he').some, let hs := (continuous_coord_change e he e' he').some_spec.1, have hs : s = e.base_set ∩ e'.base_set, { have : s ×ˢ (univ : set F) = (e.base_set ∩ e'.base_set) ×ˢ (univ : set F) := hs.symm.trans (topological_fiber_bundle.trivialization.symm_trans_source_eq e e'), have hF : (univ : set F).nonempty := univ_nonempty, rwa prod_eq_iff_eq hF at this }, rw ← hs at hb, exact (continuous_coord_change e he e' he').some_spec.2.2.some_spec.2 b hb v end attribute [irreducible] coord_change namespace trivialization /-- In a topological vector bundle, a trivialization in the fiber (which is a priori only linear) is in fact a continuous linear equiv between the fibers and the model fiber. -/ def continuous_linear_equiv_at (e : trivialization R F E) (b : B) (hb : b ∈ e.base_set) : E b ≃L[R] F := { to_fun := λ y, (e ⟨b, y⟩).2, inv_fun := λ z, begin have : ((e.to_local_homeomorph.symm) (b, z)).fst = b := topological_fiber_bundle.trivialization.proj_symm_apply' _ hb, have C : E ((e.to_local_homeomorph.symm) (b, z)).fst = E b, by rw this, exact cast C (e.to_local_homeomorph.symm (b, z)).2 end, left_inv := begin assume v, rw [← heq_iff_eq], apply (cast_heq _ _).trans, have A : (b, (e ⟨b, v⟩).snd) = e ⟨b, v⟩, { refine prod.ext _ rfl, symmetry, exact topological_fiber_bundle.trivialization.coe_fst' _ hb }, have B : e.to_local_homeomorph.symm (e ⟨b, v⟩) = ⟨b, v⟩, { apply local_homeomorph.left_inv_on, rw topological_fiber_bundle.trivialization.mem_source, exact hb }, rw [A, B], end, right_inv := begin assume v, have B : e (e.to_local_homeomorph.symm (b, v)) = (b, v), { apply local_homeomorph.right_inv_on, rw topological_fiber_bundle.trivialization.mem_target, exact hb }, have C : (e (e.to_local_homeomorph.symm (b, v))).2 = v, by rw [B], conv_rhs { rw ← C }, dsimp, congr, ext, { exact (topological_fiber_bundle.trivialization.proj_symm_apply' _ hb).symm }, { exact (cast_heq _ _).trans (by refl) }, end, map_add' := λ v w, (e.linear _ hb).map_add v w, map_smul' := λ c v, (e.linear _ hb).map_smul c v, continuous_to_fun := begin refine continuous_snd.comp _, apply continuous_on.comp_continuous e.to_local_homeomorph.continuous_on (topological_vector_bundle.total_space_mk_inducing R F E b).continuous (λ x, _), rw topological_fiber_bundle.trivialization.mem_source, exact hb, end, continuous_inv_fun := begin rw (topological_vector_bundle.total_space_mk_inducing R F E b).continuous_iff, dsimp, have : continuous (λ (z : F), e.to_fiber_bundle_trivialization.to_local_homeomorph.symm (b, z)), { apply e.to_local_homeomorph.symm.continuous_on.comp_continuous (continuous_const.prod_mk continuous_id') (λ z, _), simp only [topological_fiber_bundle.trivialization.mem_target, hb, local_equiv.symm_source, local_homeomorph.symm_to_local_equiv] }, convert this, ext z, { exact (topological_fiber_bundle.trivialization.proj_symm_apply' _ hb).symm }, { exact cast_heq _ _ }, end } @[simp] lemma continuous_linear_equiv_at_apply (e : trivialization R F E) (b : B) (hb : b ∈ e.base_set) (y : E b) : e.continuous_linear_equiv_at b hb y = (e ⟨b, y⟩).2 := rfl @[simp] lemma continuous_linear_equiv_at_apply' (e : trivialization R F E) (x : total_space E) (hx : x ∈ e.source) : e.continuous_linear_equiv_at (proj E x) (e.mem_source.1 hx) x.2 = (e x).2 := by { cases x, refl } lemma apply_eq_prod_continuous_linear_equiv_at (e : trivialization R F E) (b : B) (hb : b ∈ e.base_set) (z : E b) : e.to_local_homeomorph ⟨b, z⟩ = (b, e.continuous_linear_equiv_at b hb z) := begin ext, { convert e.coe_fst _, rw e.source_eq, exact hb }, { simp } end lemma symm_apply_eq_mk_continuous_linear_equiv_at_symm (e : trivialization R F E) (b : B) (hb : b ∈ e.base_set) (z : F) : e.to_local_homeomorph.symm ⟨b, z⟩ = total_space_mk E b ((e.continuous_linear_equiv_at b hb).symm z) := begin have h : (b, z) ∈ e.to_local_homeomorph.target, { rw e.target_eq, exact ⟨hb, mem_univ _⟩ }, apply e.to_local_homeomorph.inj_on (e.to_local_homeomorph.map_target h), { simp [e.source_eq, hb] }, simp [-continuous_linear_equiv_at_apply, e.apply_eq_prod_continuous_linear_equiv_at b hb, e.to_local_homeomorph.right_inv h], end lemma comp_continuous_linear_equiv_at_eq_coord_change {e e' : trivialization R F E} (he : e ∈ trivialization_atlas R F E) (he' : e' ∈ trivialization_atlas R F E) {b : B} (hb : b ∈ e.base_set ∩ e'.base_set) : (e.continuous_linear_equiv_at b hb.1).symm.trans (e'.continuous_linear_equiv_at b hb.2) = coord_change he he' b := begin ext v, suffices : (b, e'.continuous_linear_equiv_at b hb.2 ((e.continuous_linear_equiv_at b hb.1).symm v)) = (b, coord_change he he' b v), { simpa using this }, rw [← trans_eq_coord_change he he' hb, ← apply_eq_prod_continuous_linear_equiv_at, symm_apply_eq_mk_continuous_linear_equiv_at_symm], refl, end end trivialization section local attribute [reducible] bundle.trivial instance {B : Type*} {F : Type*} [add_comm_monoid F] (b : B) : add_comm_monoid (bundle.trivial B F b) := ‹add_comm_monoid F› instance {B : Type*} {F : Type*} [add_comm_group F] (b : B) : add_comm_group (bundle.trivial B F b) := ‹add_comm_group F› instance {B : Type*} {F : Type*} [add_comm_monoid F] [module R F] (b : B) : module R (bundle.trivial B F b) := ‹module R F› end variables (R B F) /-- Local trivialization for trivial bundle. -/ def trivial_topological_vector_bundle.trivialization : trivialization R F (bundle.trivial B F) := { to_fun := λ x, (x.fst, x.snd), inv_fun := λ y, ⟨y.fst, y.snd⟩, source := univ, target := univ, map_source' := λ x h, mem_univ (x.fst, x.snd), map_target' :=λ y h, mem_univ ⟨y.fst, y.snd⟩, left_inv' := λ x h, sigma.eq rfl rfl, right_inv' := λ x h, prod.ext rfl rfl, open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { rw [←continuous_iff_continuous_on_univ, continuous_iff_le_induced], simp only [prod.topological_space, induced_inf, induced_compose], exact le_rfl, }, continuous_inv_fun := by { rw [←continuous_iff_continuous_on_univ, continuous_iff_le_induced], simp only [bundle.total_space.topological_space, induced_inf, induced_compose], exact le_rfl, }, base_set := univ, open_base_set := is_open_univ, source_eq := rfl, target_eq := by simp only [univ_prod_univ], proj_to_fun := λ y hy, rfl, linear := λ x hx, ⟨λ y z, rfl, λ c y, rfl⟩ } @[simp] lemma trivial_topological_vector_bundle.trivialization_source : (trivial_topological_vector_bundle.trivialization R B F).source = univ := rfl @[simp] lemma trivial_topological_vector_bundle.trivialization_target : (trivial_topological_vector_bundle.trivialization R B F).target = univ := rfl instance trivial_bundle.topological_vector_bundle : topological_vector_bundle R F (bundle.trivial B F) := { trivialization_atlas := {trivial_topological_vector_bundle.trivialization R B F}, trivialization_at := λ x, trivial_topological_vector_bundle.trivialization R B F, mem_base_set_trivialization_at := mem_univ, trivialization_mem_atlas := λ x, mem_singleton _, total_space_mk_inducing := λ b, ⟨begin have : (λ (x : trivial B F b), x) = @id F, by { ext x, refl }, simp only [total_space.topological_space, induced_inf, induced_compose, function.comp, proj, induced_const, top_inf_eq, trivial.proj_snd, id.def, trivial.topological_space, this, induced_id], end⟩, continuous_coord_change := begin intros e he e' he', rw [mem_singleton_iff.mp he, mem_singleton_iff.mp he'], exact ⟨univ, by simp, by simp, λb, continuous_linear_equiv.refl R F, continuous_const.continuous_on, λ b hb v, rfl⟩ end } variables {R B F} /- Not registered as an instance because of a metavariable. -/ lemma is_topological_vector_bundle_is_topological_fiber_bundle : is_topological_fiber_bundle F (proj E) := λ x, ⟨(trivialization_at R F E x).to_fiber_bundle_trivialization, mem_base_set_trivialization_at R F E x⟩ variables (R B F) include R F @[continuity] lemma continuous_proj : continuous (proj E) := begin apply @is_topological_fiber_bundle.continuous_proj B F, apply @is_topological_vector_bundle_is_topological_fiber_bundle R, end end topological_vector_bundle /-! ### Constructing topological vector bundles -/ variables (B) /-- Analogous construction of `topological_fiber_bundle_core` for vector bundles. This construction gives a way to construct vector bundles from a structure registering how trivialization changes act on fibers. -/ structure topological_vector_bundle_core (ι : Type*) := (base_set : ι → set B) (is_open_base_set : ∀ i, is_open (base_set i)) (index_at : B → ι) (mem_base_set_at : ∀ x, x ∈ base_set (index_at x)) (coord_change : ι → ι → B → (F →L[R] F)) (coord_change_self : ∀ i, ∀ x ∈ base_set i, ∀ v, coord_change i i x v = v) (coord_change_continuous : ∀ i j, continuous_on (coord_change i j) (base_set i ∩ base_set j)) (coord_change_comp : ∀ i j k, ∀ x ∈ (base_set i) ∩ (base_set j) ∩ (base_set k), ∀ v, (coord_change j k x) (coord_change i j x v) = coord_change i k x v) /-- The trivial topological vector bundle core, in which all the changes of coordinates are the identity. -/ def trivial_topological_vector_bundle_core (ι : Type*) [inhabited ι] : topological_vector_bundle_core R B F ι := { base_set := λ ι, univ, is_open_base_set := λ i, is_open_univ, index_at := λ x, default, mem_base_set_at := λ x, mem_univ x, coord_change := λ i j x, continuous_linear_map.id R F, coord_change_self := λ i x hx v, rfl, coord_change_comp := λ i j k x hx v, rfl, coord_change_continuous := λ i j, continuous_on_const, } instance (ι : Type*) [inhabited ι] : inhabited (topological_vector_bundle_core R B F ι) := ⟨trivial_topological_vector_bundle_core R B F ι⟩ namespace topological_vector_bundle_core variables {R B F} {ι : Type*} (Z : topological_vector_bundle_core R B F ι) /-- Natural identification to a `topological_fiber_bundle_core`. -/ def to_topological_vector_bundle_core : topological_fiber_bundle_core ι B F := { coord_change := λ i j b, Z.coord_change i j b, coord_change_continuous := λ i j, is_bounded_bilinear_map_apply.continuous.comp_continuous_on ((Z.coord_change_continuous i j).prod_map continuous_on_id), ..Z } instance to_topological_vector_bundle_core_coe : has_coe (topological_vector_bundle_core R B F ι) (topological_fiber_bundle_core ι B F) := ⟨to_topological_vector_bundle_core⟩ include Z lemma coord_change_linear_comp (i j k : ι): ∀ x ∈ (Z.base_set i) ∩ (Z.base_set j) ∩ (Z.base_set k), (Z.coord_change j k x).comp (Z.coord_change i j x) = Z.coord_change i k x := λ x hx, by { ext v, exact Z.coord_change_comp i j k x hx v } /-- The index set of a topological vector bundle core, as a convenience function for dot notation -/ @[nolint unused_arguments has_inhabited_instance] def index := ι /-- The base space of a topological vector bundle core, as a convenience function for dot notation-/ @[nolint unused_arguments, reducible] def base := B /-- The fiber of a topological vector bundle core, as a convenience function for dot notation and typeclass inference -/ @[nolint unused_arguments has_inhabited_instance] def fiber (x : B) := F section fiber_instances local attribute [reducible] fiber --just to record instances instance topological_space_fiber (x : B) : topological_space (Z.fiber x) := by apply_instance instance add_comm_monoid_fiber : ∀ (x : B), add_comm_monoid (Z.fiber x) := λ x, by apply_instance instance module_fiber : ∀ (x : B), module R (Z.fiber x) := λ x, by apply_instance variable [add_comm_group F] instance add_comm_group_fiber : ∀ (x : B), add_comm_group (Z.fiber x) := λ x, by apply_instance end fiber_instances /-- The projection from the total space of a topological fiber bundle core, on its base. -/ @[reducible, simp, mfld_simps] def proj : total_space Z.fiber → B := bundle.proj Z.fiber /-- The total space of the topological vector bundle, as a convenience function for dot notation. It is by definition equal to `bundle.total_space Z.fiber`, a.k.a. `Σ x, Z.fiber x` but with a different name for typeclass inference. -/ @[nolint unused_arguments, reducible] def total_space := bundle.total_space Z.fiber /-- Local homeomorphism version of the trivialization change. -/ def triv_change (i j : ι) : local_homeomorph (B × F) (B × F) := topological_fiber_bundle_core.triv_change ↑Z i j @[simp, mfld_simps] lemma mem_triv_change_source (i j : ι) (p : B × F) : p ∈ (Z.triv_change i j).source ↔ p.1 ∈ Z.base_set i ∩ Z.base_set j := topological_fiber_bundle_core.mem_triv_change_source ↑Z i j p variable (ι) /-- Topological structure on the total space of a topological bundle created from core, designed so that all the local trivialization are continuous. -/ instance to_topological_space : topological_space (Z.total_space) := topological_fiber_bundle_core.to_topological_space ι ↑Z variables {ι} (b : B) (a : F) @[simp, mfld_simps] lemma coe_coord_change (i j : ι) : topological_fiber_bundle_core.coord_change ↑Z i j b = Z.coord_change i j b := rfl /-- Extended version of the local trivialization of a fiber bundle constructed from core, registering additionally in its type that it is a local bundle trivialization. -/ def local_triv (i : ι) : topological_vector_bundle.trivialization R F Z.fiber := { linear := λ x hx, { map_add := λ v w, by simp only [continuous_linear_map.map_add] with mfld_simps, map_smul := λ r v, by simp only [continuous_linear_map.map_smul] with mfld_simps}, ..topological_fiber_bundle_core.local_triv ↑Z i } variable (i : ι) @[simp, mfld_simps] lemma mem_local_triv_source (p : Z.total_space) : p ∈ (Z.local_triv i).source ↔ p.1 ∈ Z.base_set i := iff.rfl @[simp, mfld_simps] lemma base_set_at : Z.base_set i = (Z.local_triv i).base_set := rfl @[simp, mfld_simps] lemma local_triv_apply (p : Z.total_space) : (Z.local_triv i) p = ⟨p.1, Z.coord_change (Z.index_at p.1) i p.1 p.2⟩ := rfl @[simp, mfld_simps] lemma mem_local_triv_target (p : B × F) : p ∈ (Z.local_triv i).target ↔ p.1 ∈ (Z.local_triv i).base_set := topological_fiber_bundle_core.mem_local_triv_target Z i p @[simp, mfld_simps] lemma local_triv_symm_fst (p : B × F) : (Z.local_triv i).to_local_homeomorph.symm p = ⟨p.1, Z.coord_change i (Z.index_at p.1) p.1 p.2⟩ := rfl /-- Preferred local trivialization of a vector bundle constructed from core, at a given point, as a bundle trivialization -/ def local_triv_at (b : B) : topological_vector_bundle.trivialization R F Z.fiber := Z.local_triv (Z.index_at b) @[simp, mfld_simps] lemma local_triv_at_def : Z.local_triv (Z.index_at b) = Z.local_triv_at b := rfl @[simp, mfld_simps] lemma mem_source_at : (⟨b, a⟩ : Z.total_space) ∈ (Z.local_triv_at b).source := by { rw [local_triv_at, mem_local_triv_source], exact Z.mem_base_set_at b } @[simp, mfld_simps] lemma local_triv_at_apply : ((Z.local_triv_at b) ⟨b, a⟩) = ⟨b, a⟩ := topological_fiber_bundle_core.local_triv_at_apply Z b a @[simp, mfld_simps] lemma mem_local_triv_at_base_set : b ∈ (Z.local_triv_at b).base_set := topological_fiber_bundle_core.mem_local_triv_at_base_set Z b instance : topological_vector_bundle R F Z.fiber := { total_space_mk_inducing := λ b, ⟨ begin refine le_antisymm _ (λ s h, _), { rw ←continuous_iff_le_induced, exact topological_fiber_bundle_core.continuous_total_space_mk ↑Z b, }, { refine is_open_induced_iff.mpr ⟨(Z.local_triv_at b).source ∩ (Z.local_triv_at b) ⁻¹' ((Z.local_triv_at b).base_set ×ˢ s), (continuous_on_open_iff (Z.local_triv_at b).open_source).mp (Z.local_triv_at b).continuous_to_fun _ ((Z.local_triv_at b).open_base_set.prod h), _⟩, rw [preimage_inter, ←preimage_comp, function.comp], simp only [total_space_mk], refine ext_iff.mpr (λ a, ⟨λ ha, _, λ ha, ⟨Z.mem_base_set_at b, _⟩⟩), { simp only [mem_prod, mem_preimage, mem_inter_eq, local_triv_at_apply] at ha, exact ha.2.2, }, { simp only [mem_prod, mem_preimage, mem_inter_eq, local_triv_at_apply], exact ⟨Z.mem_base_set_at b, ha⟩, } } end⟩, trivialization_atlas := set.range Z.local_triv, trivialization_at := Z.local_triv_at, mem_base_set_trivialization_at := Z.mem_base_set_at, trivialization_mem_atlas := λ b, ⟨Z.index_at b, rfl⟩, continuous_coord_change := begin classical, rintros _ ⟨i, rfl⟩ _ ⟨i', rfl⟩, refine ⟨Z.base_set i ∩ Z.base_set i', _, _, λ b, if h : b ∈ Z.base_set i ∩ Z.base_set i' then continuous_linear_equiv.equiv_of_inverse (Z.coord_change i i' b) (Z.coord_change i' i b) _ _ else continuous_linear_equiv.refl R F, _, _⟩, { ext ⟨b, f⟩, simp }, { ext ⟨b, f⟩, simp [and_comm] }, { intro f, rw [Z.coord_change_comp _ _ _ _ ⟨h, h.1⟩, Z.coord_change_self _ _ h.1] }, { intro f, rw [Z.coord_change_comp _ _ _ _ ⟨⟨h.2, h.1⟩, h.2⟩, Z.coord_change_self _ _ h.2] }, { apply continuous_on.congr (Z.coord_change_continuous i i'), intros b hb, simp [hb], ext v, refl }, { intros b hb v, have : b ∈ Z.base_set i ∩ Z.base_set (Z.index_at b) ∩ Z.base_set i', { simp only [base_set_at, local_triv_at_def, mem_inter_eq, mem_local_triv_at_base_set] at *, tauto }, simp [hb, Z.coord_change_comp _ _ _ _ this] } end } /-- The projection on the base of a topological vector bundle created from core is continuous -/ @[continuity] lemma continuous_proj : continuous Z.proj := topological_fiber_bundle_core.continuous_proj Z /-- The projection on the base of a topological vector bundle created from core is an open map -/ lemma is_open_map_proj : is_open_map Z.proj := topological_fiber_bundle_core.is_open_map_proj Z end topological_vector_bundle_core end /-! ### Topological vector prebundle -/ section variables [nondiscrete_normed_field R] [∀ x, add_comm_monoid (E x)] [∀ x, module R (E x)] [normed_group F] [normed_space R F] [topological_space B] [∀ x, topological_space (E x)] open topological_space /-- This structure permits to define a vector bundle when trivializations are given as local equivalences but there is not yet a topology on the total space. The total space is hence given a topology in such a way that there is a fiber bundle structure for which the local equivalences are also local homeomorphisms and hence vector bundle trivializations. -/ @[nolint has_inhabited_instance] structure topological_vector_prebundle := (pretrivialization_atlas : set (topological_vector_bundle.pretrivialization R F E)) (pretrivialization_at : B → topological_vector_bundle.pretrivialization R F E) (mem_base_pretrivialization_at : ∀ x : B, x ∈ (pretrivialization_at x).base_set) (pretrivialization_mem_atlas : ∀ x : B, pretrivialization_at x ∈ pretrivialization_atlas) (continuous_coord_change : ∀ e e' ∈ pretrivialization_atlas, continuous_transitions R B F (e'.to_local_equiv.symm.trans e.to_local_equiv : _)) (total_space_mk_inducing : ∀ (b : B), inducing ((pretrivialization_at b) ∘ (total_space_mk E b))) namespace topological_vector_prebundle variables {R E F} /-- Natural identification of `topological_vector_prebundle` as a `topological_fiber_prebundle`. -/ def to_topological_fiber_prebundle (a : topological_vector_prebundle R F E) : topological_fiber_prebundle F (proj E) := { pretrivialization_atlas := pretrivialization.to_fiber_bundle_pretrivialization '' a.pretrivialization_atlas, pretrivialization_at := λ x, (a.pretrivialization_at x).to_fiber_bundle_pretrivialization, pretrivialization_mem_atlas := λ x, ⟨_, a.pretrivialization_mem_atlas x, rfl⟩, continuous_triv_change := begin rintros _ ⟨e, he, rfl⟩ _ ⟨e', he', rfl⟩, obtain ⟨s, hs, hs', ε, hε, heε⟩ := a.continuous_coord_change e he e' he', have H : e'.to_fiber_bundle_pretrivialization.to_local_equiv.target ∩ (e'.to_fiber_bundle_pretrivialization.to_local_equiv.symm) ⁻¹' e.to_fiber_bundle_pretrivialization.to_local_equiv.source = s ×ˢ (univ : set F), { simpa using hs }, rw H, have : continuous_on (λ p : B × F, (p.1, (ε p.1) p.2)) (s ×ˢ (univ : set F)), { apply continuous_on_fst.prod, exact is_bounded_bilinear_map_apply.continuous.comp_continuous_on (hε.prod_map continuous_on_id) }, apply this.congr, rintros ⟨b, f⟩ ⟨hb : b ∈ s, -⟩, exact heε _ hb _, end, .. a } /-- Topology on the total space that will make the prebundle into a bundle. -/ def total_space_topology (a : topological_vector_prebundle R F E) : topological_space (total_space E) := a.to_topological_fiber_prebundle.total_space_topology /-- Promotion from a `topologial_vector_prebundle.trivialization` to a `topological_vector_bundle.trivialization`. -/ def trivialization_of_mem_pretrivialization_atlas (a : topological_vector_prebundle R F E) {e : topological_vector_bundle.pretrivialization R F E} (he : e ∈ a.pretrivialization_atlas) : @topological_vector_bundle.trivialization R _ F E _ _ _ _ _ _ _ a.total_space_topology := begin letI := a.total_space_topology, exact { linear := e.linear, ..a.to_topological_fiber_prebundle.trivialization_of_mem_pretrivialization_atlas ⟨e, he, rfl⟩ } end variable (a : topological_vector_prebundle R F E) lemma mem_trivialization_at_source (b : B) (x : E b) : total_space_mk E b x ∈ (a.pretrivialization_at b).source := begin simp only [(a.pretrivialization_at b).source_eq, mem_preimage, proj], exact a.mem_base_pretrivialization_at b, end @[simp] lemma total_space_mk_preimage_source (b : B) : (total_space_mk E b) ⁻¹' (a.pretrivialization_at b).source = univ := begin apply eq_univ_of_univ_subset, rw [(a.pretrivialization_at b).source_eq, ←preimage_comp, function.comp], simp only [proj], rw preimage_const_of_mem _, exact a.mem_base_pretrivialization_at b, end @[continuity] lemma continuous_total_space_mk (b : B) : @continuous _ _ _ a.total_space_topology (total_space_mk E b) := begin letI := a.total_space_topology, let e := a.trivialization_of_mem_pretrivialization_atlas (a.pretrivialization_mem_atlas b), rw e.to_local_homeomorph.continuous_iff_continuous_comp_left (a.total_space_mk_preimage_source b), exact continuous_iff_le_induced.mpr (le_antisymm_iff.mp (a.total_space_mk_inducing b).induced).1, end lemma inducing_total_space_mk_of_inducing_comp (b : B) (h : inducing ((a.pretrivialization_at b) ∘ (total_space_mk E b))) : @inducing _ _ _ a.total_space_topology (total_space_mk E b) := begin letI := a.total_space_topology, rw ←restrict_comp_cod_restrict (a.mem_trivialization_at_source b) at h, apply inducing.of_cod_restrict (a.mem_trivialization_at_source b), refine inducing_of_inducing_compose _ (continuous_on_iff_continuous_restrict.mp (a.trivialization_of_mem_pretrivialization_atlas (a.pretrivialization_mem_atlas b)).continuous_to_fun) h, exact (a.continuous_total_space_mk b).cod_restrict (a.mem_trivialization_at_source b), end /-- Make a `topological_vector_bundle` from a `topological_vector_prebundle`. Concretely this means that, given a `topological_vector_prebundle` structure for a sigma-type `E` -- which consists of a number of "pretrivializations" identifying parts of `E` with product spaces `U × F` -- one establishes that for the topology constructed on the sigma-type using `topological_vector_prebundle.total_space_topology`, these "pretrivializations" are actually "trivializations" (i.e., homeomorphisms with respect to the constructed topology). -/ def to_topological_vector_bundle : @topological_vector_bundle R _ F E _ _ _ _ _ _ a.total_space_topology _ := { total_space_mk_inducing := λ b, a.inducing_total_space_mk_of_inducing_comp b (a.total_space_mk_inducing b), trivialization_atlas := {e | ∃ e₀ (he₀ : e₀ ∈ a.pretrivialization_atlas), e = a.trivialization_of_mem_pretrivialization_atlas he₀}, trivialization_at := λ x, a.trivialization_of_mem_pretrivialization_atlas (a.pretrivialization_mem_atlas x), mem_base_set_trivialization_at := a.mem_base_pretrivialization_at, trivialization_mem_atlas := λ x, ⟨_, a.pretrivialization_mem_atlas x, rfl⟩, continuous_coord_change := begin rintros _ ⟨e, he, rfl⟩ _ ⟨e', he', rfl⟩, exact a.continuous_coord_change e' he' e he, end } end topological_vector_prebundle end /-! ### Direct sum of two vector bundles over the same base -/ namespace topological_vector_bundle section defs variables (E₁ : B → Type*) (E₂ : B → Type*) variables [topological_space (total_space E₁)] [topological_space (total_space E₂)] /-- Equip the total space of the fibrewise product of two topological vector bundles `E₁`, `E₂` with the induced topology from the diagonal embedding into `(total_space E₁) × (total_space E₂)`. -/ instance prod.topological_space : topological_space (total_space (E₁ ×ᵇ E₂)) := topological_space.induced (λ p, ((⟨p.1, p.2.1⟩ : total_space E₁), (⟨p.1, p.2.2⟩ : total_space E₂))) (by apply_instance : topological_space ((total_space E₁) × (total_space E₂))) /-- The diagonal map from the total space of the fibrewise product of two topological vector bundles `E₁`, `E₂` into `(total_space E₁) × (total_space E₂)` is `inducing`. -/ lemma prod.inducing_diag : inducing (λ p, (⟨p.1, p.2.1⟩, ⟨p.1, p.2.2⟩) : total_space (E₁ ×ᵇ E₂) → (total_space E₁) × (total_space E₂)) := ⟨rfl⟩ end defs variables [nondiscrete_normed_field R] [topological_space B] variables (F₁ : Type*) [normed_group F₁] [normed_space R F₁] (E₁ : B → Type*) [topological_space (total_space E₁)] [Π x, add_comm_monoid (E₁ x)] [Π x, module R (E₁ x)] variables (F₂ : Type*) [normed_group F₂] [normed_space R F₂] (E₂ : B → Type*) [topological_space (total_space E₂)] [Π x, add_comm_monoid (E₂ x)] [Π x, module R (E₂ x)] namespace trivialization variables (e₁ : trivialization R F₁ E₁) (e₂ : trivialization R F₂ E₂) include e₁ e₂ variables {R F₁ E₁ F₂ E₂} /-- Given trivializations `e₁`, `e₂` for vector bundles `E₁`, `E₂` over a base `B`, the forward function for the construction `topological_vector_bundle.trivialization.prod`, the induced trivialization for the direct sum of `E₁` and `E₂`. -/ def prod.to_fun' : total_space (E₁ ×ᵇ E₂) → B × (F₁ × F₂) := λ ⟨x, v₁, v₂⟩, ⟨x, (e₁ ⟨x, v₁⟩).2, (e₂ ⟨x, v₂⟩).2⟩ variables {e₁ e₂} lemma prod.continuous_to_fun : continuous_on (prod.to_fun' e₁ e₂) (proj (E₁ ×ᵇ E₂) ⁻¹' (e₁.base_set ∩ e₂.base_set)) := begin let f₁ : total_space (E₁ ×ᵇ E₂) → total_space E₁ × total_space E₂ := λ p, ((⟨p.1, p.2.1⟩ : total_space E₁), (⟨p.1, p.2.2⟩ : total_space E₂)), let f₂ : total_space E₁ × total_space E₂ → (B × F₁) × (B × F₂) := λ p, ⟨e₁ p.1, e₂ p.2⟩, let f₃ : (B × F₁) × (B × F₂) → B × F₁ × F₂ := λ p, ⟨p.1.1, p.1.2, p.2.2⟩, have hf₁ : continuous f₁ := (prod.inducing_diag E₁ E₂).continuous, have hf₂ : continuous_on f₂ (e₁.source ×ˢ e₂.source) := e₁.to_local_homeomorph.continuous_on.prod_map e₂.to_local_homeomorph.continuous_on, have hf₃ : continuous f₃ := (continuous_fst.comp continuous_fst).prod_mk (continuous_snd.prod_map continuous_snd), refine ((hf₃.comp_continuous_on hf₂).comp hf₁.continuous_on _).congr _, { rw [e₁.source_eq, e₂.source_eq], exact maps_to_preimage _ _ }, rintros ⟨b, v₁, v₂⟩ ⟨hb₁, hb₂⟩, simp only [prod.to_fun', prod.mk.inj_iff, eq_self_iff_true, and_true], rw e₁.coe_fst, rw [e₁.source_eq, mem_preimage], exact hb₁, end variables (e₁ e₂) variables [Π x : B, topological_space (E₁ x)] [Π x : B, topological_space (E₂ x)] [topological_vector_bundle R F₁ E₁] [topological_vector_bundle R F₂ E₂] /-- Given trivializations `e₁`, `e₂` for vector bundles `E₁`, `E₂` over a base `B`, the inverse function for the construction `topological_vector_bundle.trivialization.prod`, the induced trivialization for the direct sum of `E₁` and `E₂`. -/ def prod.inv_fun' (p : B × (F₁ × F₂)) : total_space (E₁ ×ᵇ E₂) := begin obtain ⟨x, w₁, w₂⟩ := p, refine ⟨x, _, _⟩, { by_cases h : x ∈ e₁.base_set, { exact (e₁.continuous_linear_equiv_at x h).symm w₁ }, { exact 0 } }, { by_cases h : x ∈ e₂.base_set, { exact (e₂.continuous_linear_equiv_at x h).symm w₂ }, { exact 0 } }, end variables {e₁ e₂} lemma prod.inv_fun'_apply {x : B} (hx₁ : x ∈ e₁.base_set) (hx₂ : x ∈ e₂.base_set) (w₁ : F₁) (w₂ : F₂) : prod.inv_fun' e₁ e₂ ⟨x, w₁, w₂⟩ = ⟨x, ((e₁.continuous_linear_equiv_at x hx₁).symm w₁, (e₂.continuous_linear_equiv_at x hx₂).symm w₂)⟩ := begin dsimp [prod.inv_fun'], rw [dif_pos, dif_pos], end lemma prod.left_inv {x : total_space (E₁ ×ᵇ E₂)} (h : x ∈ proj (E₁ ×ᵇ E₂) ⁻¹' (e₁.base_set ∩ e₂.base_set)) : prod.inv_fun' e₁ e₂ (prod.to_fun' e₁ e₂ x) = x := begin obtain ⟨x, v₁, v₂⟩ := x, simp only [prod.to_fun', prod.inv_fun', sigma.mk.inj_iff, true_and, eq_self_iff_true, prod.mk.inj_iff, heq_iff_eq], split, { rw [dif_pos, ← e₁.continuous_linear_equiv_at_apply x h.1, continuous_linear_equiv.symm_apply_apply] }, { rw [dif_pos, ← e₂.continuous_linear_equiv_at_apply x h.2, continuous_linear_equiv.symm_apply_apply] }, end lemma prod.right_inv {x : B × F₁ × F₂} (h : x ∈ (e₁.base_set ∩ e₂.base_set) ×ˢ (univ : set (F₁ × F₂))) : prod.to_fun' e₁ e₂ (prod.inv_fun' e₁ e₂ x) = x := begin obtain ⟨x, w₁, w₂⟩ := x, obtain ⟨h, -⟩ := h, dsimp only [prod.to_fun', prod.inv_fun'], simp only [prod.mk.inj_iff, eq_self_iff_true, true_and], split, { rw [dif_pos, ← e₁.continuous_linear_equiv_at_apply x h.1, continuous_linear_equiv.apply_symm_apply] }, { rw [dif_pos, ← e₂.continuous_linear_equiv_at_apply x h.2, continuous_linear_equiv.apply_symm_apply] }, end lemma prod.continuous_inv_fun : continuous_on (prod.inv_fun' e₁ e₂) ((e₁.base_set ∩ e₂.base_set) ×ˢ (univ : set (F₁ × F₂))) := begin rw (prod.inducing_diag E₁ E₂).continuous_on_iff, suffices : continuous_on (λ p : B × F₁ × F₂, (e₁.to_local_homeomorph.symm ⟨p.1, p.2.1⟩, e₂.to_local_homeomorph.symm ⟨p.1, p.2.2⟩)) ((e₁.base_set ∩ e₂.base_set) ×ˢ (univ : set (F₁ × F₂))), { refine this.congr _, rintros ⟨b, v₁, v₂⟩ ⟨⟨h₁, h₂⟩, _⟩, dsimp at ⊢ h₁ h₂, rw [prod.inv_fun'_apply h₁ h₂, e₁.symm_apply_eq_mk_continuous_linear_equiv_at_symm b h₁, e₂.symm_apply_eq_mk_continuous_linear_equiv_at_symm b h₂] }, have H₁ : continuous (λ p : B × F₁ × F₂, ((p.1, p.2.1), (p.1, p.2.2))) := (continuous_id.prod_map continuous_fst).prod_mk (continuous_id.prod_map continuous_snd), have H₂ := e₁.to_local_homeomorph.symm.continuous_on.prod_map e₂.to_local_homeomorph.symm.continuous_on, refine H₂.comp H₁.continuous_on (λ x h, ⟨_, _⟩), { dsimp, rw e₁.target_eq, exact ⟨h.1.1, mem_univ _⟩ }, { dsimp, rw e₂.target_eq, exact ⟨h.1.2, mem_univ _⟩ } end variables (e₁ e₂) /-- Given trivializations `e₁`, `e₂` for vector bundles `E₁`, `E₂` over a base `B`, the induced trivialization for the direct sum of `E₁` and `E₂`, whose base set is `e₁.base_set ∩ e₂.base_set`. -/ def prod : trivialization R (F₁ × F₂) (E₁ ×ᵇ E₂) := { to_fun := prod.to_fun' e₁ e₂, inv_fun := prod.inv_fun' e₁ e₂, source := (proj (λ x, E₁ x × E₂ x)) ⁻¹' (e₁.base_set ∩ e₂.base_set), target := (e₁.base_set ∩ e₂.base_set) ×ˢ (set.univ : set (F₁ × F₂)), map_source' := λ ⟨x, v₁, v₂⟩ h, ⟨h, set.mem_univ _⟩, map_target' := λ ⟨x, w₁, w₂⟩ h, h.1, left_inv' := λ x, prod.left_inv, right_inv' := λ x, prod.right_inv, open_source := begin refine (e₁.open_base_set.inter e₂.open_base_set).preimage _, have : continuous (proj E₁) := continuous_proj R B F₁, exact this.comp (continuous_fst.comp (prod.inducing_diag E₁ E₂).continuous), end, open_target := (e₁.open_base_set.inter e₂.open_base_set).prod is_open_univ, continuous_to_fun := prod.continuous_to_fun, continuous_inv_fun := prod.continuous_inv_fun, base_set := e₁.base_set ∩ e₂.base_set, open_base_set := e₁.open_base_set.inter e₂.open_base_set, source_eq := rfl, target_eq := rfl, proj_to_fun := λ ⟨x, v₁, v₂⟩ h, rfl, linear := λ x ⟨h₁, h₂⟩, { map_add := λ ⟨v₁, v₂⟩ ⟨v₁', v₂'⟩, congr_arg2 prod.mk ((e₁.linear x h₁).map_add v₁ v₁') ((e₂.linear x h₂).map_add v₂ v₂'), map_smul := λ c ⟨v₁, v₂⟩, congr_arg2 prod.mk ((e₁.linear x h₁).map_smul c v₁) ((e₂.linear x h₂).map_smul c v₂), } } @[simp] lemma base_set_prod : (prod e₁ e₂).base_set = e₁.base_set ∩ e₂.base_set := rfl variables {e₁ e₂} lemma prod_apply {x : B} (hx₁ : x ∈ e₁.base_set) (hx₂ : x ∈ e₂.base_set) (v₁ : E₁ x) (v₂ : E₂ x) : prod e₁ e₂ ⟨x, (v₁, v₂)⟩ = ⟨x, e₁.continuous_linear_equiv_at x hx₁ v₁, e₂.continuous_linear_equiv_at x hx₂ v₂⟩ := rfl lemma prod_symm_apply {x : B} (hx₁ : x ∈ e₁.base_set) (hx₂ : x ∈ e₂.base_set) (w₁ : F₁) (w₂ : F₂) : (prod e₁ e₂).to_local_equiv.symm (x, (w₁, w₂)) = ⟨x, ((e₁.continuous_linear_equiv_at x hx₁).symm w₁, (e₂.continuous_linear_equiv_at x hx₂).symm w₂)⟩ := prod.inv_fun'_apply hx₁ hx₂ w₁ w₂ end trivialization open trivialization variables [Π x : B, topological_space (E₁ x)] [Π x : B, topological_space (E₂ x)] [topological_vector_bundle R F₁ E₁] [topological_vector_bundle R F₂ E₂] /-- The product of two vector bundles is a vector bundle. -/ instance _root_.bundle.prod.topological_vector_bundle : topological_vector_bundle R (F₁ × F₂) (E₁ ×ᵇ E₂) := { total_space_mk_inducing := λ b, begin rw (prod.inducing_diag E₁ E₂).inducing_iff, exact (total_space_mk_inducing R F₁ E₁ b).prod_mk (total_space_mk_inducing R F₂ E₂ b), end, trivialization_atlas := (λ (p : trivialization R F₁ E₁ × trivialization R F₂ E₂), p.1.prod p.2) '' (trivialization_atlas R F₁ E₁ ×ˢ trivialization_atlas R F₂ E₂), trivialization_at := λ b, (trivialization_at R F₁ E₁ b).prod (trivialization_at R F₂ E₂ b), mem_base_set_trivialization_at := λ b, ⟨mem_base_set_trivialization_at R F₁ E₁ b, mem_base_set_trivialization_at R F₂ E₂ b⟩, trivialization_mem_atlas := λ b, ⟨(_, _), ⟨trivialization_mem_atlas R F₁ E₁ b, trivialization_mem_atlas R F₂ E₂ b⟩, rfl⟩, continuous_coord_change := begin rintros _ ⟨⟨e₁, e₂⟩, ⟨he₁, he₂⟩, rfl⟩ _ ⟨⟨e'₁, e'₂⟩, ⟨he'₁, he'₂⟩, rfl⟩, let s := e₁.base_set ∩ e'₁.base_set, let t := e₂.base_set ∩ e'₂.base_set, let ε := coord_change he₁ he'₁, let η := coord_change he₂ he'₂, have fact : (s ∩ t) ×ˢ (univ : set $ F₁ × F₂) = (e₁.base_set ∩ e₂.base_set ∩ (e'₁.base_set ∩ e'₂.base_set)) ×ˢ (univ : set $ F₁ × F₂), by mfld_set_tac, refine ⟨s ∩ t, _, _, λ b, (ε b).prod (η b), _, _⟩, { rw fact, apply topological_fiber_bundle.trivialization.symm_trans_source_eq }, { rw fact, apply topological_fiber_bundle.trivialization.symm_trans_target_eq }, { have hε := (continuous_on_coord_change he₁ he'₁).mono (inter_subset_left s t), have hη := (continuous_on_coord_change he₂ he'₂).mono (inter_subset_right s t), exact hε.prod_map_equivL R hη }, { rintros b ⟨hbs, hbt⟩ ⟨u, v⟩, have h : (e₁.prod e₂).to_local_homeomorph.symm _ = _ := prod_symm_apply hbs.1 hbt.1 u v, simp only [ε, η, h, prod_apply hbs.2 hbt.2, ← comp_continuous_linear_equiv_at_eq_coord_change he₁ he'₁ hbs, ← comp_continuous_linear_equiv_at_eq_coord_change he₂ he'₂ hbt, eq_self_iff_true, function.comp_app, local_equiv.coe_trans, local_homeomorph.coe_coe, local_homeomorph.coe_coe_symm, prod.mk.inj_iff, topological_vector_bundle.trivialization.coe_coe, true_and, continuous_linear_equiv.prod_apply, continuous_linear_equiv.trans_apply] }, end } variables {R F₁ E₁ F₂ E₂} @[simp] lemma trivialization.continuous_linear_equiv_at_prod {e₁ : trivialization R F₁ E₁} {e₂ : trivialization R F₂ E₂} {x : B} (hx₁ : x ∈ e₁.base_set) (hx₂ : x ∈ e₂.base_set) : (e₁.prod e₂).continuous_linear_equiv_at x ⟨hx₁, hx₂⟩ = (e₁.continuous_linear_equiv_at x hx₁).prod (e₂.continuous_linear_equiv_at x hx₂) := begin ext1, funext v, obtain ⟨v₁, v₂⟩ := v, rw [(e₁.prod e₂).continuous_linear_equiv_at_apply, trivialization.prod], exact congr_arg prod.snd (prod_apply hx₁ hx₂ v₁ v₂), end end topological_vector_bundle
3dcb7ed9c282d5dede4524d14193e1edf263d6ee
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/category_theory/limits/functor_category.lean
cf2cda5f48d7c112999974a02dec421bcc5f5761
[ "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
10,547
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.preserves.limits open category_theory category_theory.category namespace category_theory.limits universes v v₂ u -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u} [category.{v} C] variables {J K : Type v} [small_category J] [category.{v₂} K] @[simp, reassoc] lemma limit.lift_π_app (H : J ⥤ K ⥤ C) [has_limit H] (c : cone H) (j : J) (k : K) : (limit.lift H c).app k ≫ (limit.π H j).app k = (c.π.app j).app k := congr_app (limit.lift_π c j) k @[simp, reassoc] lemma colimit.ι_desc_app (H : J ⥤ K ⥤ C) [has_colimit H] (c : cocone H) (j : J) (k : K) : (colimit.ι H j).app k ≫ (colimit.desc H c).app k = (c.ι.app j).app k := congr_app (colimit.ι_desc c j) k /-- The evaluation functors jointly reflect limits: that is, to show a cone is a limit of `F` it suffices to show that each evaluation cone is a limit. In other words, to prove a cone is limiting you can show it's pointwise limiting. -/ def evaluation_jointly_reflects_limits {F : J ⥤ K ⥤ C} (c : cone F) (t : Π (k : K), is_limit (((evaluation K C).obj k).map_cone c)) : is_limit c := { lift := λ s, { app := λ k, (t k).lift ⟨s.X.obj k, whisker_right s.π ((evaluation K C).obj k)⟩, naturality' := λ X Y f, (t Y).hom_ext $ λ j, begin rw [assoc, (t Y).fac _ j], simpa using ((t X).fac_assoc ⟨s.X.obj X, whisker_right s.π ((evaluation K C).obj X)⟩ j _).symm, end }, fac' := λ s j, nat_trans.ext _ _ $ funext $ λ k, (t k).fac _ j, uniq' := λ s m w, nat_trans.ext _ _ $ funext $ λ x, (t x).hom_ext $ λ j, (congr_app (w j) x).trans ((t x).fac ⟨s.X.obj _, whisker_right s.π ((evaluation K C).obj _)⟩ j).symm } /-- Given a functor `F` and a collection of limit cones for each diagram `X ↦ F X k`, we can stitch them together to give a cone for the diagram `F`. `combined_is_limit` shows that the new cone is limiting, and `eval_combined` shows it is (essentially) made up of the original cones. -/ @[simps] def combine_cones (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) : cone F := { X := { obj := λ k, (c k).cone.X, map := λ k₁ k₂ f, (c k₂).is_limit.lift ⟨_, (c k₁).cone.π ≫ F.flip.map f⟩, map_id' := λ k, (c k).is_limit.hom_ext (λ j, by { dsimp, simp }), map_comp' := λ k₁ k₂ k₃ f₁ f₂, (c k₃).is_limit.hom_ext (λ j, by simp) }, π := { app := λ j, { app := λ k, (c k).cone.π.app j }, naturality' := λ j₁ j₂ g, nat_trans.ext _ _ $ funext $ λ k, (c k).cone.π.naturality g } } /-- The stitched together cones each project down to the original given cones (up to iso). -/ def evaluate_combined_cones (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) (k : K) : ((evaluation K C).obj k).map_cone (combine_cones F c) ≅ (c k).cone := cones.ext (iso.refl _) (by tidy) /-- Stitching together limiting cones gives a limiting cone. -/ def combined_is_limit (F : J ⥤ K ⥤ C) (c : Π (k : K), limit_cone (F.flip.obj k)) : is_limit (combine_cones F c) := evaluation_jointly_reflects_limits _ (λ k, (c k).is_limit.of_iso_limit (evaluate_combined_cones F c k).symm) /-- The evaluation functors jointly reflect colimits: that is, to show a cocone is a colimit of `F` it suffices to show that each evaluation cocone is a colimit. In other words, to prove a cocone is colimiting you can show it's pointwise colimiting. -/ def evaluation_jointly_reflects_colimits {F : J ⥤ K ⥤ C} (c : cocone F) (t : Π (k : K), is_colimit (((evaluation K C).obj k).map_cocone c)) : is_colimit c := { desc := λ s, { app := λ k, (t k).desc ⟨s.X.obj k, whisker_right s.ι ((evaluation K C).obj k)⟩, naturality' := λ X Y f, (t X).hom_ext $ λ j, begin rw [(t X).fac_assoc _ j], erw ← (c.ι.app j).naturality_assoc f, erw (t Y).fac ⟨s.X.obj _, whisker_right s.ι _⟩ j, dsimp, simp, end }, fac' := λ s j, nat_trans.ext _ _ $ funext $ λ k, (t k).fac _ j, uniq' := λ s m w, nat_trans.ext _ _ $ funext $ λ x, (t x).hom_ext $ λ j, (congr_app (w j) x).trans ((t x).fac ⟨s.X.obj _, whisker_right s.ι ((evaluation K C).obj _)⟩ j).symm } /-- Given a functor `F` and a collection of colimit cocones for each diagram `X ↦ F X k`, we can stitch them together to give a cocone for the diagram `F`. `combined_is_colimit` shows that the new cocone is colimiting, and `eval_combined` shows it is (essentially) made up of the original cocones. -/ @[simps] def combine_cocones (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) : cocone F := { X := { obj := λ k, (c k).cocone.X, map := λ k₁ k₂ f, (c k₁).is_colimit.desc ⟨_, F.flip.map f ≫ (c k₂).cocone.ι⟩, map_id' := λ k, (c k).is_colimit.hom_ext (λ j, by { dsimp, simp }), map_comp' := λ k₁ k₂ k₃ f₁ f₂, (c k₁).is_colimit.hom_ext (λ j, by simp) }, ι := { app := λ j, { app := λ k, (c k).cocone.ι.app j }, naturality' := λ j₁ j₂ g, nat_trans.ext _ _ $ funext $ λ k, (c k).cocone.ι.naturality g } } /-- The stitched together cocones each project down to the original given cocones (up to iso). -/ def evaluate_combined_cocones (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) (k : K) : ((evaluation K C).obj k).map_cocone (combine_cocones F c) ≅ (c k).cocone := cocones.ext (iso.refl _) (by tidy) /-- Stitching together colimiting cocones gives a colimiting cocone. -/ def combined_is_colimit (F : J ⥤ K ⥤ C) (c : Π (k : K), colimit_cocone (F.flip.obj k)) : is_colimit (combine_cocones F c) := evaluation_jointly_reflects_colimits _ (λ k, (c k).is_colimit.of_iso_colimit (evaluate_combined_cocones F c k).symm) noncomputable theory instance functor_category_has_limits_of_shape [has_limits_of_shape J C] : has_limits_of_shape J (K ⥤ C) := { has_limit := λ F, has_limit.mk { cone := combine_cones F (λ k, get_limit_cone _), is_limit := combined_is_limit _ _ } } instance functor_category_has_colimits_of_shape [has_colimits_of_shape J C] : has_colimits_of_shape J (K ⥤ C) := { has_colimit := λ F, has_colimit.mk { cocone := combine_cocones _ (λ k, get_colimit_cocone _), is_colimit := combined_is_colimit _ _ } } instance functor_category_has_limits [has_limits C] : has_limits (K ⥤ C) := {} instance functor_category_has_colimits [has_colimits C] : has_colimits (K ⥤ C) := {} instance evaluation_preserves_limits_of_shape [has_limits_of_shape J C] (k : K) : preserves_limits_of_shape J ((evaluation K C).obj k) := { preserves_limit := λ F, preserves_limit_of_preserves_limit_cone (combined_is_limit _ _) $ is_limit.of_iso_limit (limit.is_limit _) (evaluate_combined_cones F _ k).symm } /-- If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a limit, then the evaluation of that limit at `k` is the limit of the evaluations of `F.obj j` at `k`. -/ def limit_obj_iso_limit_comp_evaluation [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : (limit F).obj k ≅ limit (F ⋙ ((evaluation K C).obj k)) := preserves_limit_iso ((evaluation K C).obj k) F @[simp, reassoc] lemma limit_obj_iso_limit_comp_evaluation_hom_π [has_limits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) : (limit_obj_iso_limit_comp_evaluation F k).hom ≫ limit.π (F ⋙ ((evaluation K C).obj k)) j = (limit.π F j).app k := begin dsimp [limit_obj_iso_limit_comp_evaluation], simp, end @[simp, reassoc] lemma limit_obj_iso_limit_comp_evaluation_inv_π_app [has_limits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K): (limit_obj_iso_limit_comp_evaluation F k).inv ≫ (limit.π F j).app k = limit.π (F ⋙ ((evaluation K C).obj k)) j := begin dsimp [limit_obj_iso_limit_comp_evaluation], rw iso.inv_comp_eq, simp, end @[ext] lemma limit_obj_ext {H : J ⥤ K ⥤ C} [has_limits_of_shape J C] {k : K} {W : C} {f g : W ⟶ (limit H).obj k} (w : ∀ j, f ≫ (limits.limit.π H j).app k = g ≫ (limits.limit.π H j).app k) : f = g := begin apply (cancel_mono (limit_obj_iso_limit_comp_evaluation H k).hom).1, ext, simpa using w j, end instance evaluation_preserves_colimits_of_shape [has_colimits_of_shape J C] (k : K) : preserves_colimits_of_shape J ((evaluation K C).obj k) := { preserves_colimit := λ F, preserves_colimit_of_preserves_colimit_cocone (combined_is_colimit _ _) $ is_colimit.of_iso_colimit (colimit.is_colimit _) (evaluate_combined_cocones F _ k).symm } /-- If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a colimit, then the evaluation of that colimit at `k` is the colimit of the evaluations of `F.obj j` at `k`. -/ def colimit_obj_iso_colimit_comp_evaluation [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : (colimit F).obj k ≅ colimit (F ⋙ ((evaluation K C).obj k)) := preserves_colimit_iso ((evaluation K C).obj k) F @[simp, reassoc] lemma colimit_obj_iso_colimit_comp_evaluation_ι_inv [has_colimits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) : colimit.ι (F ⋙ ((evaluation K C).obj k)) j ≫ (colimit_obj_iso_colimit_comp_evaluation F k).inv = (colimit.ι F j).app k := begin dsimp [colimit_obj_iso_colimit_comp_evaluation], simp, end @[simp, reassoc] lemma colimit_obj_iso_colimit_comp_evaluation_ι_app_hom [has_colimits_of_shape J C] (F : J ⥤ (K ⥤ C)) (j : J) (k : K) : (colimit.ι F j).app k ≫ (colimit_obj_iso_colimit_comp_evaluation F k).hom = colimit.ι (F ⋙ ((evaluation K C).obj k)) j := begin dsimp [colimit_obj_iso_colimit_comp_evaluation], rw ←iso.eq_comp_inv, simp, end @[ext] lemma colimit_obj_ext {H : J ⥤ K ⥤ C} [has_colimits_of_shape J C] {k : K} {W : C} {f g : (colimit H).obj k ⟶ W} (w : ∀ j, (colimit.ι H j).app k ≫ f = (colimit.ι H j).app k ≫ g) : f = g := begin apply (cancel_epi (colimit_obj_iso_colimit_comp_evaluation H k).inv).1, ext, simpa using w j, end instance evaluation_preserves_limits [has_limits C] (k : K) : preserves_limits ((evaluation K C).obj k) := { preserves_limits_of_shape := λ J 𝒥, by resetI; apply_instance } instance evaluation_preserves_colimits [has_colimits C] (k : K) : preserves_colimits ((evaluation K C).obj k) := { preserves_colimits_of_shape := λ J 𝒥, by resetI; apply_instance } end category_theory.limits
ae7e789ae6bfc1f9f3e349f0b56c0fe747501ae3
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/eq3.lean
d37d59b1c15393b200a37b907d933d0e4aad5ccc
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
188
lean
variable Vector : Nat -> Type variable n : Nat variable v1 : Vector n variable v2 : Vector (n + 0) variable v3 : Vector (0 + n) axiom H1 : v1 == v2 axiom H2 : v2 == v3 check htrans H1 H2
da5ed8e2c96f7edbe162dd19fd4c6d0cb0abcaf5
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/ematch1.lean
165488d59f9c08f45c712adc6382418f0733f7a0
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
781
lean
constant f : nat → nat constant g : nat → nat axiom Ax : ∀ x, (: f (g x) :) = x open tactic meta def add_insts : list (expr × expr) → tactic unit | [] := skip | ((inst, pr)::r) := do assertv `_einst inst pr, add_insts r meta def ematch_test (h : name) (e : expr) : tactic unit := do cc ← cc_state.mk_using_hs, ems ← return $ ematch_state.mk default_ematch_config, hlemma ← hinst_lemma.mk_from_decl h, (r, cc, ems) ← ematch cc ems hlemma e, add_insts r example (a b c : nat) : f a = b → a = g c → f a ≠ c → false := by do intros, e ← to_expr `(f a), ematch_test `Ax e, trace_state, cc example (a b c : nat) : f a = b → a = g c → f a = c := by do intros, e ← to_expr `(f a), ematch_test `Ax e, cc
163e750b8ea87e0522f293d61c300ed19f917e71
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/ring_theory/polynomial.lean
9488d0411fbde5807199ef96f81fc5755a21961b
[ "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
17,215
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Ring-theoretic supplement of data.polynomial. Main result: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring. -/ import data.equiv.fin data.polynomial data.mv_polynomial import ring_theory.subring import ring_theory.ideals ring_theory.noetherian noncomputable theory local attribute [instance, priority 100] classical.prop_decidable universes u v w namespace polynomial variables (R : Type u) [comm_ring R] /-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker variable {R} theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} : f ∈ degree_le R n ↔ degree f ≤ n := by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) : degree_le R m ≤ degree_le R n := λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H) theorem degree_le_eq_span_X_pow {n : ℕ} : degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← finsupp.sum_single p, finsupp.sum, submodule.mem_coe], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [single_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_le.2, apply le_trans (degree_X_pow_le _) (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end /-- Given a polynomial, return the polynomial whose coefficients are in the ring closure of the original coefficients. -/ def restriction (p : polynomial R) : polynomial (ring.closure (↑p.frange : set R)) := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem else ring.subset_closure $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ @[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := rfl @[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := rfl @[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := rfl @[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := rfl @[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ @[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := rfl @[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl variables {S : Type v} [comm_ring S] {f : R → S} {x : S} theorem eval₂_restriction {p : polynomial R} : eval₂ f x p = eval₂ (f ∘ subtype.val) x p.restriction := rfl section to_subring variables (p : polynomial R) (T : set R) [is_subring T] /-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`, return the corresponding polynomial whose coefficients are in `T. -/ def to_subring (hp : ↑p.frange ⊆ T) : polynomial T := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem else hp $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ variables (hp : ↑p.frange ⊆ T) include hp @[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := rfl @[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := rfl @[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := rfl @[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := rfl @[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ omit hp @[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (set.empty_subset _) = 0 := rfl @[simp] theorem to_subring_one : to_subring (1 : polynomial R) T (set.subset.trans (finset.coe_subset.2 finsupp.frange_single) (set.singleton_subset_iff.2 is_submonoid.one_mem)) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl end to_subring variables (T : set R) [is_subring T] /-- Given a polynomial whose coefficients are in some subring, return the corresponding polynomial whose coefificents are in the ambient ring. -/ def of_subring (p : polynomial T) : polynomial R := ⟨p.support, subtype.val ∘ p.to_fun, λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ h, congr_arg subtype.val h, λ h, subtype.eq h⟩)⟩ @[simp] theorem frange_of_subring {p : polynomial T} : ↑(p.of_subring T).frange ⊆ T := λ y H, let ⟨hy, x, hx⟩ := finsupp.mem_frange.1 H in hx ▸ (p.to_fun x).2 end polynomial variables {R : Type u} {σ : Type v} [comm_ring R] namespace ideal open polynomial /-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/ def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) := { carrier := I.carrier, zero := I.zero_mem, add := λ _ _, I.add_mem, smul := λ c x H, by rw [← C_mul']; exact submodule.smul_mem _ _ H } variables {I : ideal (polynomial R)} theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl variables (I) /-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := degree_le R n ⊓ I.of_polynomial /-- Given an ideal `I` of `R[X]`, make the ideal in `R` of leading coefficients of polynomials in `I` with degree ≤ `n`. -/ def leading_coeff_nth (n : ℕ) : ideal R := (I.degree_le n).map $ lcoeff R n theorem mem_leading_coeff_nth (n : ℕ) (x) : x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x := begin simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le], split, { rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩, cases lt_or_eq_of_le hpdeg with hpdeg hpdeg, { refine ⟨0, I.zero_mem, bot_le, _⟩, rw [leading_coeff_zero, eq_comm], exact coeff_eq_zero_of_degree_lt hpdeg }, { refine ⟨p, hpI, le_of_eq hpdeg, _⟩, rw [leading_coeff, nat_degree, hpdeg], refl } }, { rintro ⟨p, hpI, hpdeg, rfl⟩, have : nat_degree p + (n - nat_degree p) = n, { exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) }, refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right hpI⟩, _⟩, { apply le_trans (degree_mul_le _ _) _, apply le_trans (add_le_add' (degree_le_nat_degree) (degree_X_pow_le _)) _, rw [← with_bot.coe_add, this], exact le_refl _ }, { rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } } end theorem mem_leading_coeff_nth_zero (x) : x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I := (mem_leading_coeff_nth _ _ _).trans ⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff, nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg), ← eq_C_of_degree_le_zero hpdeg], λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩ theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := begin intros r hr, simp only [submodule.mem_coe, mem_leading_coeff_nth] at hr ⊢, rcases hr with ⟨p, hpI, hpdeg, rfl⟩, refine ⟨p * X ^ (n - m), I.mul_mem_right hpI, _, leading_coeff_mul_X_pow⟩, refine le_trans (degree_mul_le _ _) _, refine le_trans (add_le_add' hpdeg (degree_X_pow_le _)) _, rw [← with_bot.coe_add, nat.add_sub_cancel' H], exact le_refl _ end /-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the leading coefficients in `I`. -/ def leading_coeff : ideal R := ⨆ n : ℕ, I.leading_coeff_nth n theorem mem_leading_coeff (x) : x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x := begin rw [leading_coeff, submodule.mem_supr_of_directed], simp only [mem_leading_coeff_nth], { split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ }, rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ }, intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _), I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩ end theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal /-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/ protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] : is_noetherian_ring (polynomial R) := ⟨assume I : ideal (polynomial R), let L := I.leading_coeff in let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance)) (set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _, let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N) (λ h, HN ▸ I.leading_coeff_nth_mono h) (λ h x hx, classical.by_contradiction $ λ hxm, have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min (well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩, this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩), have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)), from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _) (λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ hf), ⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin change I ≤ ideal.span ↑s, intros p hp, generalize hn : p.nat_degree = k, induction k using nat.strong_induction_on with k ih generalizing p, cases le_or_lt k N, { subst k, refine hs2 ⟨polynomial.mem_degree_le.2 (le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ }, { have hp0 : p ≠ 0, { rintro rfl, cases hn, exact nat.not_lt_zero _ h }, have : (0 : R) ≠ 1, { intro h, apply hp0, ext i, refine (mul_one _).symm.trans _, rw [← h, mul_zero], refl }, letI : nonzero_comm_ring R := { zero_ne_one := this, ..(infer_instance : comm_ring R) }, have : p.leading_coeff ∈ I.leading_coeff_nth N, { rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2 ⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) }, rw I.mem_leading_coeff_nth at this, rcases this with ⟨q, hq, hdq, hlqp⟩, have hq0 : q ≠ 0, { intro H, rw [← polynomial.leading_coeff_eq_zero] at H, rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H }, have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree, { rw [polynomial.degree_mul_eq', polynomial.degree_X_pow], rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0], rw [← with_bot.coe_add, nat.add_sub_cancel', hn], { refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) }, rw [polynomial.leading_coeff_X_pow, mul_one], exact mt polynomial.leading_coeff_eq_zero.1 hq0 }, have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff, { rw [← hlqp, polynomial.leading_coeff_mul_X_pow] }, have := polynomial.degree_sub_lt h1 hp0 h2, rw [polynomial.degree_eq_nat_degree hp0] at this, rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)), refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _), { by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0, { rw hpq, exact ideal.zero_mem _ }, refine ih _ _ (I.sub_mem hp (I.mul_mem_right hq)) rfl, rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this }, exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ } end⟩⟩ attribute [instance] polynomial.is_noetherian_ring namespace mv_polynomial lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial (fin 0) R) := is_noetherian_ring_of_ring_equiv R ((mv_polynomial.pempty_ring_equiv R).symm.trans (mv_polynomial.ring_equiv_of_equiv _ fin_zero_equiv'.symm)) theorem is_noetherian_ring_fin [is_noetherian_ring R] : ∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R) | 0 := is_noetherian_ring_fin_0 | (n+1) := @is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _ (mv_polynomial.fin_succ_equiv _ n).symm (@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin)) /-- The multivariate polynomial ring in finitely many variables over a noetherian ring is itself a noetherian ring. -/ instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _ (mv_polynomial.ring_equiv_of_equiv _ e.symm) is_noetherian_ring_fin lemma is_integral_domain_fin_zero (R : Type u) [comm_ring R] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial (fin 0) R) := ring_equiv.is_integral_domain R hR ((ring_equiv_of_equiv R fin_zero_equiv').trans (mv_polynomial.pempty_ring_equiv R)) /-- Auxilliary lemma: Multivariate polynomials over an integral domain with variables indexed by `fin n` form an integral domain. This fact is proven inductively, and then used to prove the general case without any finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ lemma is_integral_domain_fin (R : Type u) [comm_ring R] (hR : is_integral_domain R) : ∀ (n : ℕ), is_integral_domain (mv_polynomial (fin n) R) | 0 := is_integral_domain_fin_zero R hR | (n+1) := ring_equiv.is_integral_domain (polynomial (mv_polynomial (fin n) R)) (is_integral_domain_fin n).polynomial (mv_polynomial.fin_succ_equiv _ n) lemma is_integral_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ] (hR : is_integral_domain R) : is_integral_domain (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _ (mv_polynomial.is_integral_domain_fin _ hR _) (ring_equiv_of_equiv R e) /-- Auxilliary definition: Multivariate polynomials in finitely many variables over an integral domain form an integral domain. This fact is proven by transport of structure from the `mv_polynomial.integral_domain_fin`, and then used to prove the general case without finiteness hypotheses. See `mv_polynomial.integral_domain` for the general case. -/ def integral_domain_fintype (R : Type u) (σ : Type v) [integral_domain R] [fintype σ] : integral_domain (mv_polynomial σ R) := @is_integral_domain.to_integral_domain _ _ $ mv_polynomial.is_integral_domain_fintype R σ $ integral_domain.to_is_integral_domain R protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [integral_domain R] {σ : Type v} (p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 := begin obtain ⟨s, p, rfl⟩ := exists_finset_rename p, obtain ⟨t, q, rfl⟩ := exists_finset_rename q, have : p.rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) * q.rename (subtype.map id (finset.subset_union_right s t)) = 0, { apply injective_rename _ subtype.val_injective, simpa using h }, letI := mv_polynomial.integral_domain_fintype R {x // x ∈ (s ∪ t)}, rw mul_eq_zero at this, cases this; [left, right], all_goals { simpa using congr_arg (rename subtype.val) this } end /-- The multivariate polynomial ring over an integral domain is an integral domain. -/ instance {R : Type u} {σ : Type v} [integral_domain R] : integral_domain (mv_polynomial σ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero, zero_ne_one := begin intro H, have : eval₂ id (λ s, (0:R)) (0 : mv_polynomial σ R) = eval₂ id (λ s, (0:R)) (1 : mv_polynomial σ R), { congr, exact H }, simpa, end, .. (by apply_instance : comm_ring (mv_polynomial σ R)) } end mv_polynomial
a2ae6eca97c2b310482f2773a7d7abd1661f3798
3446e92e64a5de7ed1f2109cfb024f83cd904c34
/src/game/world5/level6.lean
91b1be4c90cf29870db52ee61c2a3699ad9bbdeb
[]
no_license
kckennylau/natural_number_game
019f4a5f419c9681e65234ecd124c564f9a0a246
ad8c0adaa725975be8a9f978c8494a39311029be
refs/heads/master
1,598,784,137,722
1,571,905,156,000
1,571,905,156,000
218,354,686
0
0
null
1,572,373,319,000
1,572,373,318,000
null
UTF-8
Lean
false
false
1,998
lean
import game.world5.level5 -- hide namespace mynat -- hide /- # World 5 : Inequality world ## Level 6 : `le_antisymm` In this level, it would be helpful if you knew about how to create extra hypotheses in the middle of a proof. Say you have a hypothesis `h : a + b = a` and you remember back from world 2 level 12 that you proved `eq_zero_of_add_right_eq_self {a b : mynat} : a + b = a → b = 0`. You can think of `eq_zero_of_add_right_eq_self` as a function which turns proofs of `a + b = a` into proofs of `b = 0`. So you can use the `have` tactic, and type `have h2 := eq_zero_of_add_right_eq_self h,` and now `h2` will be a proof that `b = 0`. Also don't forget that you can use the `rw` tactic on hypotheses -- `rw h1 at h2` will replace occurrences of the left hand side of `h1` in `h2`, with the right hand side. -/ /- Lemma ≤ is antisymmetric. In other words, if a ≤ b and b ≤ a then a = b. -/ theorem le_antisymm {{a b : mynat}} (hab : a ≤ b) (hba : b ≤ a) : a = b := begin [less_leaky] cases hab with c hc, cases hba with d hd, rw hd at hc, rw add_assoc at hc, have h := eq_zero_of_add_right_eq_self hc.symm, have h2 := add_right_eq_zero h, rw h2 at hd, rw add_zero at hd, assumption, end /- Congratulations -- you just proved that the natural numbers are a partial order! To come: about 25 more ≤ levels. But that will have to wait for v1.1. If you got this far, and did the world 2 and 3 extra levels, then you have beaten the game. Now think of a simple mathematical theorem, and see if you can formulate and prove it yourself using the Lean Theorem Prover. Download Lean and its maths library <a href="https://github.com/leanprover-community/mathlib" target=blank">here</a> (please follow the installation instructions to the letter) and if and when you get stuck, come and ask at <a href="https://leanprover.zulipchat.com" target=blank">the Lean chat</a>. -/ instance : partial_order mynat := by structure_helper -- hide end mynat
ad30bba21f6c814a1f35eb16d09d208638b1ff22
137c667471a40116a7afd7261f030b30180468c2
/src/measure_theory/decomposition.lean
ac03092ff1229b6eef722eaa812ef1565c70f94a
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,492
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Hahn decomposition theorem TODO: * show general for signed measures (into ℝ) -/ import measure_theory.measure_space open set filter open_locale classical topological_space ennreal namespace measure_theory variables {α : Type*} [measurable_space α] {μ ν : measure α} -- suddenly this is necessary?! private lemma aux {m : ℕ} {γ d : ℝ} (h : γ - (1 / 2) ^ m < d) : γ - 2 * (1 / 2) ^ m + (1 / 2) ^ m ≤ d := by linarith /-- **Hahn decomposition theorem** -/ lemma hahn_decomposition [finite_measure μ] [finite_measure ν] : ∃s, measurable_set s ∧ (∀t, measurable_set t → t ⊆ s → ν t ≤ μ t) ∧ (∀t, measurable_set t → t ⊆ sᶜ → μ t ≤ ν t) := begin let d : set α → ℝ := λs, ((μ s).to_nnreal : ℝ) - (ν s).to_nnreal, let c : set ℝ := d '' {s | measurable_set s }, let γ : ℝ := Sup c, have hμ : ∀s, μ s < ∞ := measure_lt_top μ, have hν : ∀s, ν s < ∞ := measure_lt_top ν, have to_nnreal_μ : ∀s, ((μ s).to_nnreal : ℝ≥0∞) = μ s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hμ _), have to_nnreal_ν : ∀s, ((ν s).to_nnreal : ℝ≥0∞) = ν s := (assume s, ennreal.coe_to_nnreal $ ne_top_of_lt $ hν _), have d_empty : d ∅ = 0, { simp [d], rw [measure_empty, measure_empty], simp }, have d_split : ∀s t, measurable_set s → measurable_set t → d s = d (s \ t) + d (s ∩ t), { assume s t hs ht, simp only [d], rw [measure_eq_inter_diff hs ht, measure_eq_inter_diff hs ht, ennreal.to_nnreal_add (hμ _) (hμ _), ennreal.to_nnreal_add (hν _) (hν _), nnreal.coe_add, nnreal.coe_add], simp only [sub_eq_add_neg, neg_add], ac_refl }, have d_Union : ∀(s : ℕ → set α), (∀n, measurable_set (s n)) → monotone s → tendsto (λn, d (s n)) at_top (𝓝 (d (⋃n, s n))), { assume s hs hm, refine tendsto.sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ∞ _).comp $ tendsto_measure_Union hs hm), exact hμ _, exact hν _ }, have d_Inter : ∀(s : ℕ → set α), (∀n, measurable_set (s n)) → (∀n m, n ≤ m → s m ⊆ s n) → tendsto (λn, d (s n)) at_top (𝓝 (d (⋂n, s n))), { assume s hs hm, refine tendsto.sub _ _; refine (nnreal.tendsto_coe.2 $ (ennreal.tendsto_to_nnreal $ @ne_top_of_lt _ _ _ ∞ _).comp $ tendsto_measure_Inter hs hm _), exact hμ _, exact ⟨0, hμ _⟩, exact hν _, exact ⟨0, hν _⟩ }, have bdd_c : bdd_above c, { use (μ univ).to_nnreal, rintros r ⟨s, hs, rfl⟩, refine le_trans (sub_le_self _ $ nnreal.coe_nonneg _) _, rw [nnreal.coe_le_coe, ← ennreal.coe_le_coe, to_nnreal_μ, to_nnreal_μ], exact measure_mono (subset_univ _) }, have c_nonempty : c.nonempty := nonempty.image _ ⟨_, measurable_set.empty⟩, have d_le_γ : ∀s, measurable_set s → d s ≤ γ := assume s hs, le_cSup bdd_c ⟨s, hs, rfl⟩, have : ∀n:ℕ, ∃s : set α, measurable_set s ∧ γ - (1/2)^n < d s, { assume n, have : γ - (1/2)^n < γ := sub_lt_self γ (pow_pos (half_pos zero_lt_one) n), rcases exists_lt_of_lt_cSup c_nonempty this with ⟨r, ⟨s, hs, rfl⟩, hlt⟩, exact ⟨s, hs, hlt⟩ }, rcases classical.axiom_of_choice this with ⟨e, he⟩, change ℕ → set α at e, have he₁ : ∀n, measurable_set (e n) := assume n, (he n).1, have he₂ : ∀n, γ - (1/2)^n < d (e n) := assume n, (he n).2, let f : ℕ → ℕ → set α := λn m, (finset.Ico n (m + 1)).inf e, have hf : ∀n m, measurable_set (f n m), { assume n m, simp only [f, finset.inf_eq_infi], exact measurable_set.bInter (countable_encodable _) (assume i _, he₁ _) }, have f_subset_f : ∀{a b c d}, a ≤ b → c ≤ d → f a d ⊆ f b c, { assume a b c d hab hcd, dsimp only [f], rw [finset.inf_eq_infi, finset.inf_eq_infi], refine bInter_subset_bInter_left _, simp, rintros j ⟨hbj, hjc⟩, exact ⟨le_trans hab hbj, lt_of_lt_of_le hjc $ add_le_add_right hcd 1⟩ }, have f_succ : ∀n m, n ≤ m → f n (m + 1) = f n m ∩ e (m + 1), { assume n m hnm, have : n ≤ m + 1 := le_of_lt (nat.succ_le_succ hnm), simp only [f], rw [finset.Ico.succ_top this, finset.inf_insert, set.inter_comm], refl }, have le_d_f : ∀n m, m ≤ n → γ - 2 * ((1 / 2) ^ m) + (1 / 2) ^ n ≤ d (f m n), { assume n m h, refine nat.le_induction _ _ n h, { have := he₂ m, simp only [f], rw [finset.Ico.succ_singleton, finset.inf_singleton], exact aux this }, { assume n (hmn : m ≤ n) ih, have : γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n + 1)) ≤ γ + d (f m (n + 1)), { calc γ + (γ - 2 * (1 / 2)^m + (1 / 2) ^ (n+1)) ≤ γ + (γ - 2 * (1 / 2)^m + ((1 / 2) ^ n - (1/2)^(n+1))) : begin refine add_le_add_left (add_le_add_left _ _) γ, simp only [pow_add, pow_one, le_sub_iff_add_le], linarith end ... = (γ - (1 / 2)^(n+1)) + (γ - 2 * (1 / 2)^m + (1 / 2)^n) : by simp only [sub_eq_add_neg]; ac_refl ... ≤ d (e (n + 1)) + d (f m n) : add_le_add (le_of_lt $ he₂ _) ih ... ≤ d (e (n + 1)) + d (f m n \ e (n + 1)) + d (f m (n + 1)) : by rw [f_succ _ _ hmn, d_split (f m n) (e (n + 1)) (hf _ _) (he₁ _), add_assoc] ... = d (e (n + 1) ∪ f m n) + d (f m (n + 1)) : begin rw [d_split (e (n + 1) ∪ f m n) (e (n + 1)), union_diff_left, union_inter_cancel_left], ac_refl, exact (he₁ _).union (hf _ _), exact (he₁ _) end ... ≤ γ + d (f m (n + 1)) : add_le_add_right (d_le_γ _ $ (he₁ _).union (hf _ _)) _ }, exact (add_le_add_iff_left γ).1 this } }, let s := ⋃ m, ⋂n, f m n, have γ_le_d_s : γ ≤ d s, { have hγ : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 γ), { suffices : tendsto (λm:ℕ, γ - 2 * (1/2)^m) at_top (𝓝 (γ - 2 * 0)), { simpa }, exact (tendsto_const_nhds.sub $ tendsto_const_nhds.mul $ tendsto_pow_at_top_nhds_0_of_lt_1 (le_of_lt $ half_pos $ zero_lt_one) (half_lt_self zero_lt_one)) }, have hd : tendsto (λm, d (⋂n, f m n)) at_top (𝓝 (d (⋃ m, ⋂ n, f m n))), { refine d_Union _ _ _, { assume n, exact measurable_set.Inter (assume m, hf _ _) }, { exact assume n m hnm, subset_Inter (assume i, subset.trans (Inter_subset (f n) i) $ f_subset_f hnm $ le_refl _) } }, refine le_of_tendsto_of_tendsto' hγ hd (assume m, _), have : tendsto (λn, d (f m n)) at_top (𝓝 (d (⋂ n, f m n))), { refine d_Inter _ _ _, { assume n, exact hf _ _ }, { assume n m hnm, exact f_subset_f (le_refl _) hnm } }, refine ge_of_tendsto this (eventually_at_top.2 ⟨m, assume n hmn, _⟩), change γ - 2 * (1 / 2) ^ m ≤ d (f m n), refine le_trans _ (le_d_f _ _ hmn), exact le_add_of_le_of_nonneg (le_refl _) (pow_nonneg (le_of_lt $ half_pos $ zero_lt_one) _) }, have hs : measurable_set s := measurable_set.Union (assume n, measurable_set.Inter (assume m, hf _ _)), refine ⟨s, hs, _, _⟩, { assume t ht hts, have : 0 ≤ d t := ((add_le_add_iff_left γ).1 $ calc γ + 0 ≤ d s : by rw [add_zero]; exact γ_le_d_s ... = d (s \ t) + d t : by rw [d_split _ _ hs ht, inter_eq_self_of_subset_right hts] ... ≤ γ + d t : add_le_add (d_le_γ _ (hs.diff ht)) (le_refl _)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le_coe], simpa only [d, le_sub_iff_add_le, zero_add] using this }, { assume t ht hts, have : d t ≤ 0, exact ((add_le_add_iff_left γ).1 $ calc γ + d t ≤ d s + d t : add_le_add γ_le_d_s (le_refl _) ... = d (s ∪ t) : begin rw [d_split _ _ (hs.union ht) ht, union_diff_right, union_inter_cancel_right, diff_eq_self.2], exact assume a ⟨hat, has⟩, hts hat has end ... ≤ γ + 0 : by rw [add_zero]; exact d_le_γ _ (hs.union ht)), rw [← to_nnreal_μ, ← to_nnreal_ν, ennreal.coe_le_coe, ← nnreal.coe_le_coe], simpa only [d, sub_le_iff_le_add, zero_add] using this } end end measure_theory
9f33727b71aa1312ef3881ecad9295bd6c3a3042
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/lie/skew_adjoint.lean
4242eeeb37ec86cdd353fb4f015fc3ff227c333e
[ "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,201
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.matrix import linear_algebra.matrix.bilinear_form /-! # Lie algebras of skew-adjoint endomorphisms of a bilinear form When a module carries a bilinear form, the Lie algebra of endomorphisms of the module contains a distinguished Lie subalgebra: the skew-adjoint endomorphisms. Such subalgebras are important because they provide a simple, explicit construction of the so-called classical Lie algebras. This file defines the Lie subalgebra of skew-adjoint endomorphims cut out by a bilinear form on a module and proves some basic related results. It also provides the corresponding definitions and results for the Lie algebra of square matrices. ## Main definitions * `skew_adjoint_lie_subalgebra` * `skew_adjoint_lie_subalgebra_equiv` * `skew_adjoint_matrices_lie_subalgebra` * `skew_adjoint_matrices_lie_subalgebra_equiv` ## Tags lie algebra, skew-adjoint, bilinear form -/ universes u v w w₁ section skew_adjoint_endomorphisms open bilin_form variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variables (B : bilin_form R M) lemma bilin_form.is_skew_adjoint_bracket (f g : module.End R M) (hf : f ∈ B.skew_adjoint_submodule) (hg : g ∈ B.skew_adjoint_submodule) : ⁅f, g⁆ ∈ B.skew_adjoint_submodule := begin rw mem_skew_adjoint_submodule at *, have hfg : is_adjoint_pair B B (f * g) (g * f), { rw ←neg_mul_neg g f, exact hf.mul hg, }, have hgf : is_adjoint_pair B B (g * f) (f * g), { rw ←neg_mul_neg f g, exact hg.mul hf, }, change bilin_form.is_adjoint_pair B B (f * g - g * f) (-(f * g - g * f)), rw neg_sub, exact hfg.sub hgf, end /-- Given an `R`-module `M`, equipped with a bilinear form, the skew-adjoint endomorphisms form a Lie subalgebra of the Lie algebra of endomorphisms. -/ def skew_adjoint_lie_subalgebra : lie_subalgebra R (module.End R M) := { lie_mem' := B.is_skew_adjoint_bracket, ..B.skew_adjoint_submodule } variables {N : Type w} [add_comm_group N] [module R N] (e : N ≃ₗ[R] M) /-- An equivalence of modules with bilinear forms gives equivalence of Lie algebras of skew-adjoint endomorphisms. -/ def skew_adjoint_lie_subalgebra_equiv : skew_adjoint_lie_subalgebra (B.comp (↑e : N →ₗ[R] M) ↑e) ≃ₗ⁅R⁆ skew_adjoint_lie_subalgebra B := begin apply lie_equiv.of_subalgebras _ _ e.lie_conj, ext f, simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact (bilin_form.is_pair_self_adjoint_equiv (-B) B e f).symm, end @[simp] lemma skew_adjoint_lie_subalgebra_equiv_apply (f : skew_adjoint_lie_subalgebra (B.comp ↑e ↑e)) : ↑(skew_adjoint_lie_subalgebra_equiv B e f) = e.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] @[simp] lemma skew_adjoint_lie_subalgebra_equiv_symm_apply (f : skew_adjoint_lie_subalgebra B) : ↑((skew_adjoint_lie_subalgebra_equiv B e).symm f) = e.symm.lie_conj f := by simp [skew_adjoint_lie_subalgebra_equiv] end skew_adjoint_endomorphisms section skew_adjoint_matrices open_locale matrix variables {R : Type u} {n : Type w} [comm_ring R] [decidable_eq n] [fintype n] variables (J : matrix n n R) lemma matrix.lie_transpose (A B : matrix n n R) : ⁅A, B⁆ᵀ = ⁅Bᵀ, Aᵀ⁆ := show (A * B - B * A)ᵀ = (Bᵀ * Aᵀ - Aᵀ * Bᵀ), by simp lemma matrix.is_skew_adjoint_bracket (A B : matrix n n R) (hA : A ∈ skew_adjoint_matrices_submodule J) (hB : B ∈ skew_adjoint_matrices_submodule J) : ⁅A, B⁆ ∈ skew_adjoint_matrices_submodule J := begin simp only [mem_skew_adjoint_matrices_submodule] at *, change ⁅A, B⁆ᵀ ⬝ J = J ⬝ -⁅A, B⁆, change Aᵀ ⬝ J = J ⬝ -A at hA, change Bᵀ ⬝ J = J ⬝ -B at hB, simp only [←matrix.mul_eq_mul] at *, rw [matrix.lie_transpose, lie_ring.of_associative_ring_bracket, lie_ring.of_associative_ring_bracket, sub_mul, mul_assoc, mul_assoc, hA, hB, ←mul_assoc, ←mul_assoc, hA, hB], noncomm_ring, end /-- The Lie subalgebra of skew-adjoint square matrices corresponding to a square matrix `J`. -/ def skew_adjoint_matrices_lie_subalgebra : lie_subalgebra R (matrix n n R) := { lie_mem' := J.is_skew_adjoint_bracket, ..(skew_adjoint_matrices_submodule J) } @[simp] lemma mem_skew_adjoint_matrices_lie_subalgebra (A : matrix n n R) : A ∈ skew_adjoint_matrices_lie_subalgebra J ↔ A ∈ skew_adjoint_matrices_submodule J := iff.rfl /-- An invertible matrix `P` gives a Lie algebra equivalence between those endomorphisms that are skew-adjoint with respect to a square matrix `J` and those with respect to `PᵀJP`. -/ def skew_adjoint_matrices_lie_subalgebra_equiv (P : matrix n n R) (h : invertible P) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (Pᵀ ⬝ J ⬝ P) := lie_equiv.of_subalgebras _ _ (P.lie_conj h).symm begin ext A, suffices : P.lie_conj h A ∈ skew_adjoint_matrices_submodule J ↔ A ∈ skew_adjoint_matrices_submodule (Pᵀ ⬝ J ⬝ P), { simp only [lie_subalgebra.mem_coe, submodule.mem_map_equiv, lie_subalgebra.mem_map_submodule, coe_coe], exact this, }, simp [matrix.is_skew_adjoint, J.is_adjoint_pair_equiv' _ _ P (is_unit_of_invertible P)], end lemma skew_adjoint_matrices_lie_subalgebra_equiv_apply (P : matrix n n R) (h : invertible P) (A : skew_adjoint_matrices_lie_subalgebra J) : ↑(skew_adjoint_matrices_lie_subalgebra_equiv J P h A) = P⁻¹ ⬝ ↑A ⬝ P := by simp [skew_adjoint_matrices_lie_subalgebra_equiv] /-- An equivalence of matrix algebras commuting with the transpose endomorphisms restricts to an equivalence of Lie algebras of skew-adjoint matrices. -/ def skew_adjoint_matrices_lie_subalgebra_equiv_transpose {m : Type w} [decidable_eq m] [fintype m] (e : matrix n n R ≃ₐ[R] matrix m m R) (h : ∀ A, (e A)ᵀ = e (Aᵀ)) : skew_adjoint_matrices_lie_subalgebra J ≃ₗ⁅R⁆ skew_adjoint_matrices_lie_subalgebra (e J) := lie_equiv.of_subalgebras _ _ e.to_lie_equiv begin ext A, suffices : J.is_skew_adjoint (e.symm A) ↔ (e J).is_skew_adjoint A, by simpa [this], simp [matrix.is_skew_adjoint, matrix.is_adjoint_pair, ← matrix.mul_eq_mul, ← h, ← function.injective.eq_iff e.injective], end @[simp] lemma skew_adjoint_matrices_lie_subalgebra_equiv_transpose_apply {m : Type w} [decidable_eq m] [fintype m] (e : matrix n n R ≃ₐ[R] matrix m m R) (h : ∀ A, (e A)ᵀ = e (Aᵀ)) (A : skew_adjoint_matrices_lie_subalgebra J) : (skew_adjoint_matrices_lie_subalgebra_equiv_transpose J e h A : matrix m m R) = e A := rfl lemma mem_skew_adjoint_matrices_lie_subalgebra_unit_smul (u : Rˣ) (J A : matrix n n R) : A ∈ skew_adjoint_matrices_lie_subalgebra (u • J) ↔ A ∈ skew_adjoint_matrices_lie_subalgebra J := begin change A ∈ skew_adjoint_matrices_submodule (u • J) ↔ A ∈ skew_adjoint_matrices_submodule J, simp only [mem_skew_adjoint_matrices_submodule, matrix.is_skew_adjoint, matrix.is_adjoint_pair], split; intros h, { simpa using congr_arg (λ B, u⁻¹ • B) h, }, { simp [h], }, end end skew_adjoint_matrices
e91c05f979cec1061880bde983bba3f9b538c477
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/974.lean
0be5d5203b6649a7e2e4fc99e6fd160d8eaf0660
[ "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
705
lean
inductive Formula : Nat → Type u | bot : Formula n | imp (f₁ f₂ : Formula n ) : Formula n | all (f : Formula (n+1)) : Formula n def Formula.count_quantifiers : {n:Nat} → Formula n → Nat | _, imp f₁ f₂ => f₁.count_quantifiers + f₂.count_quantifiers | _, all f => f.count_quantifiers + 1 | _, _ => 0 attribute [simp] Formula.count_quantifiers #check Formula.count_quantifiers._eq_1 #check Formula.count_quantifiers._eq_2 #check Formula.count_quantifiers._eq_3 @[simp] def Formula.count_quantifiers2 : Formula n → Nat | imp f₁ f₂ => f₁.count_quantifiers2 + f₂.count_quantifiers2 | all f => f.count_quantifiers2 + 1 | _ => 0
f9f8e80013bccc25ba74fb804bf7fc153482c8ff
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/nat_bug5.lean
5b76a52e4dcc9a5a90755f3b0538ea9e32eb58aa
[ "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,313
lean
import logic open eq.ops eq namespace foo inductive nat : Type := | zero : nat | succ : nat → nat namespace nat definition add (x y : nat) : nat := nat.rec x (λn r, succ r) y infixl `+` := add definition mul (n m : nat) := nat.rec zero (fun m x, x + n) m infixl `*` := mul axiom add_one (n:nat) : n + (succ zero) = succ n axiom mul_zero_right (n : nat) : n * zero = zero axiom add_zero (n : nat) : n + zero = n axiom mul_succ_right (n m : nat) : n * succ m = n * m + n axiom add_assoc (n m k : nat) : (n + m) + k = n + (m + k) axiom add_right_comm (n m k : nat) : n + m + k = n + k + m set_option unifier.max_steps 50000 theorem mul_add_distr_left (n m k : nat) : (n + m) * k = n * k + m * k := nat.induction_on k (calc (n + m) * zero = zero : eq.refl _ ... = n * zero + m * zero : eq.refl _) (take l IH, calc (n + m) * succ l = (n + m) * l + (n + m) : mul_succ_right _ _ ... = n * l + m * l + (n + m) : {IH} ... = n * l + m * l + n + m : symm (add_assoc _ _ _) ... = n * l + n + m * l + m : {add_right_comm _ _ _} ... = n * l + n + (m * l + m) : add_assoc _ _ _ ... = n * succ l + (m * l + m) : {symm (mul_succ_right _ _)} ... = n * succ l + m * succ l : {symm (mul_succ_right _ _)}) end nat end foo
18368fca8f27506a960f57de8b7567062242c9e9
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/analysis/complex/polynomial.lean
47adeb2a143834a94da63620bf45415aac44d460
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
6,027
lean
/- Copyright (c) 2019 Chris Hughes All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.polynomial topology.instances.polynomial analysis.complex.exponential open complex polynomial metric filter is_absolute_value set lattice namespace complex lemma exists_forall_abs_polynomial_eval_le (p : polynomial ℂ) : ∃ x, ∀ y, (p.eval x).abs ≤ (p.eval y).abs := if hp0 : 0 < degree p then let ⟨r, hr0, hr⟩ := polynomial.tendsto_infinity complex.abs hp0 ((p.eval 0).abs) in let ⟨x, hx₁, hx₂⟩ := exists_forall_le_of_compact_of_continuous (λ y, (p.eval y).abs) (continuous_abs.comp p.continuous_eval) (closed_ball 0 r) (proper_space.compact_ball _ _) (set.ne_empty_iff_exists_mem.2 ⟨0, by simp [le_of_lt hr0]⟩) in ⟨x, λ y, if hy : y.abs ≤ r then hx₂ y $ by simpa [complex.dist_eq] using hy else le_trans (hx₂ _ (by simp [le_of_lt hr0])) (le_of_lt (hr y (lt_of_not_ge hy)))⟩ else ⟨p.coeff 0, by rw [eq_C_of_degree_le_zero (le_of_not_gt hp0)]; simp⟩ /- The following proof uses the method given at https://ncatlab.org/nlab/show/fundamental+theorem+of+algebra#classical_fta_via_advanced_calculus -/ /-- The fundamental theorem of algebra. Every non constant complex polynomial has a root -/ lemma exists_root {f : polynomial ℂ} (hf : 0 < degree f) : ∃ z : ℂ, is_root f z := let ⟨z₀, hz₀⟩ := exists_forall_abs_polynomial_eval_le f in exists.intro z₀ $ by_contradiction $ λ hf0, have hfX : f - C (f.eval z₀) ≠ 0, from mt sub_eq_zero.1 (λ h, not_le_of_gt hf (h.symm ▸ degree_C_le)), let n := root_multiplicity z₀ (f - C (f.eval z₀)) in let g := (f - C (f.eval z₀)) /ₘ ((X - C z₀) ^ n) in have hg0 : g.eval z₀ ≠ 0, from eval_div_by_monic_pow_root_multiplicity_ne_zero _ hfX, have hg : g * (X - C z₀) ^ n = f - C (f.eval z₀), from div_by_monic_mul_pow_root_multiplicity_eq _ _, have hn0 : 0 < n, from nat.pos_of_ne_zero $ λ hn0, by simpa [g, hn0] using hg0, let ⟨δ', hδ'₁, hδ'₂⟩ := continuous_iff.1 (polynomial.continuous_eval g) z₀ ((g.eval z₀).abs) (complex.abs_pos.2 hg0) in let δ := min (min (δ' / 2) 1) (((f.eval z₀).abs / (g.eval z₀).abs) / 2) in have hf0' : 0 < (f.eval z₀).abs, from complex.abs_pos.2 hf0, have hfg0 : 0 < abs (eval z₀ f) * (abs (eval z₀ g))⁻¹, from div_pos hf0' (complex.abs_pos.2 hg0), have hδ0 : 0 < δ, from lt_min (lt_min (half_pos hδ'₁) (by norm_num)) (half_pos hfg0), have hδ : ∀ z : ℂ, abs (z - z₀) = δ → abs (g.eval z - g.eval z₀) < (g.eval z₀).abs, from λ z hz, hδ'₂ z (by rw [complex.dist_eq, hz]; exact lt_of_le_of_lt (le_trans (min_le_left _ _) (min_le_left _ _)) (half_lt_self hδ'₁)), have hδ1 : δ ≤ 1, from le_trans (min_le_left _ _) (min_le_right _ _), let F : polynomial ℂ := C (f.eval z₀) + C (g.eval z₀) * (X - C z₀) ^ n in let z' := (-f.eval z₀ * (g.eval z₀).abs * δ ^ n / ((f.eval z₀).abs * g.eval z₀)) ^ (n⁻¹ : ℂ) + z₀ in have hF₁ : F.eval z' = f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs, by simp only [F, cpow_nat_inv_pow _ hn0, div_eq_mul_inv, eval_pow, mul_assoc, mul_comm (g.eval z₀), mul_left_comm (g.eval z₀), mul_left_comm (g.eval z₀)⁻¹, mul_inv', inv_mul_cancel hg0, eval_C, eval_add, eval_neg, sub_eq_add_neg, eval_mul, eval_X, add_neg_cancel_right, neg_mul_eq_neg_mul_symm, mul_one, div_eq_mul_inv]; simp only [mul_comm, mul_left_comm, mul_assoc], have hδs : (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs < 1, by rw [div_eq_mul_inv, mul_right_comm, mul_comm, ← @inv_inv' _ _ (complex.abs _ * _), mul_inv', inv_inv', ← div_eq_mul_inv, div_lt_iff hfg0, one_mul]; calc δ ^ n ≤ δ ^ 1 : pow_le_pow_of_le_one (le_of_lt hδ0) hδ1 hn0 ... = δ : pow_one _ ... ≤ ((f.eval z₀).abs / (g.eval z₀).abs) / 2 : min_le_right _ _ ... < _ : half_lt_self hfg0, have hF₂ : (F.eval z').abs = (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n, from calc (F.eval z').abs = (f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs).abs : congr_arg abs hF₁ ... = abs (f.eval z₀) * complex.abs (1 - (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs : ℝ) : by rw [← complex.abs_mul]; exact congr_arg complex.abs (by simp [mul_add, add_mul, mul_assoc, div_eq_mul_inv]) ... = _ : by rw [complex.abs_of_nonneg (sub_nonneg.2 (le_of_lt hδs)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt hf0')), mul_one], have hef0 : abs (eval z₀ g) * (eval z₀ f).abs ≠ 0, from mul_ne_zero (mt complex.abs_eq_zero.1 hg0) (mt complex.abs_eq_zero.1 hf0), have hz'z₀ : abs (z' - z₀) = δ, by simp [z', mul_assoc, mul_left_comm _ (_ ^ n), mul_comm _ (_ ^ n), mul_comm (eval z₀ f).abs, _root_.mul_div_cancel _ hef0, of_real_mul, neg_mul_eq_neg_mul_symm, neg_div, is_absolute_value.abv_pow complex.abs, complex.abs_of_nonneg (le_of_lt hδ0), real.pow_nat_rpow_nat_inv (le_of_lt hδ0) hn0], have hF₃ : (f.eval z' - F.eval z').abs < (g.eval z₀).abs * δ ^ n, from calc (f.eval z' - F.eval z').abs = (g.eval z' - g.eval z₀).abs * (z' - z₀).abs ^ n : by rw [← eq_sub_iff_add_eq.1 hg, ← is_absolute_value.abv_pow complex.abs, ← complex.abs_mul, sub_mul]; simp [F, eval_pow, eval_add, eval_mul, eval_sub, eval_C, eval_X, eval_neg, add_sub_cancel] ... = (g.eval z' - g.eval z₀).abs * δ ^ n : by rw hz'z₀ ... < _ : (mul_lt_mul_right (pow_pos hδ0 _)).2 (hδ _ hz'z₀), lt_irrefl (f.eval z₀).abs $ calc (f.eval z₀).abs ≤ (f.eval z').abs : hz₀ _ ... = (F.eval z' + (f.eval z' - F.eval z')).abs : by simp ... ≤ (F.eval z').abs + (f.eval z' - F.eval z').abs : complex.abs_add _ _ ... < (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n + (g.eval z₀).abs * δ ^ n : add_lt_add_of_le_of_lt (by rw hF₂) hF₃ ... = (f.eval z₀).abs : sub_add_cancel _ _ end complex
cf338ebdce9c6afe4155c6aba6c08e84529789cd
ce89339993655da64b6ccb555c837ce6c10f9ef4
/bluejam/chap7/mybool.lean
3e8a8bfa2c32c001a4e9cd748567a37cc421a044
[]
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
722
lean
namespace hidden inductive bool : Type | ff : bool | tt : bool open hidden.bool def band (b1 b2 : bool) : bool := bool.cases_on b1 ff b2 def bnot (b1 : bool) : bool := bool.cases_on b1 tt ff def bor (b1 b2 : bool) : bool := bool.cases_on b1 b2 tt theorem band_comm (b1 b2 : bool) : band b1 b2 = band b2 b1 := begin cases b1; cases b2; apply rfl end theorem bor_comm (b1 b2 : bool) : bor b1 b2 = bor b2 b1 := begin cases b1; cases b2; apply rfl end theorem band_assoc (a b c : bool) : band (band a b) c = band a (band b c) := begin cases a; cases b; cases c; apply rfl end theorem de_morgan (a b : bool) : bnot (band a b) = bor (bnot a) (bnot b) := begin cases a; cases b; apply rfl end end hidden
ac93f52b89b9fa8306aed9c22b31ef1b6b97bc0f
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/data/tuple.lean
eb144f47de327ae1c676d1beb54088ab6a312023
[ "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
11,058
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Tuples are lists of a fixed size. It is implemented as a subtype. -/ import logic data.list data.fin open nat list subtype function definition tuple [reducible] (A : Type) (n : nat) := {l : list A | length l = n} namespace tuple variables {A B C : Type} theorem induction_on [recursor 4] {P : ∀ {n}, tuple A n → Prop} : ∀ {n} (v : tuple A n), (∀ (l : list A) {n : nat} (h : length l = n), P (tag l h)) → P v | n (tag l h) H := @H l n h definition nil : tuple A 0 := tag [] rfl lemma length_succ {n : nat} {l : list A} (a : A) : length l = n → length (a::l) = succ n := λ h, congr_arg succ h definition cons {n : nat} : A → tuple A n → tuple A (succ n) | a (tag v h) := tag (a::v) (length_succ a h) notation a :: b := cons a b protected definition is_inhabited [instance] [h : inhabited A] : ∀ (n : nat), inhabited (tuple A n) | 0 := inhabited.mk nil | (succ n) := inhabited.mk (inhabited.value h :: inhabited.value (is_inhabited n)) protected definition has_decidable_eq [instance] [h : decidable_eq A] : ∀ (n : nat), decidable_eq (tuple A n) := _ definition head {n : nat} : tuple A (succ n) → A | (tag [] h) := by contradiction | (tag (a::v) h) := a definition tail {n : nat} : tuple A (succ n) → tuple A n | (tag [] h) := by contradiction | (tag (a::v) h) := tag v (succ.inj h) theorem head_cons {n : nat} (a : A) (v : tuple A n) : head (a :: v) = a := by induction v; reflexivity theorem tail_cons {n : nat} (a : A) (v : tuple A n) : tail (a :: v) = v := by induction v; reflexivity theorem head_lcons {n : nat} (a : A) (l : list A) (h : length (a::l) = succ n) : head (tag (a::l) h) = a := rfl theorem tail_lcons {n : nat} (a : A) (l : list A) (h : length (a::l) = succ n) : tail (tag (a::l) h) = tag l (succ.inj h) := rfl definition last {n : nat} : tuple A (succ n) → A | (tag l h) := list.last l (ne_nil_of_length_eq_succ h) theorem eta : ∀ {n : nat} (v : tuple A (succ n)), head v :: tail v = v | 0 (tag [] h) := by contradiction | 0 (tag (a::l) h) := rfl | (n+1) (tag [] h) := by contradiction | (n+1) (tag (a::l) h) := rfl definition of_list (l : list A) : tuple A (list.length l) := tag l rfl definition to_list {n : nat} : tuple A n → list A | (tag l h) := l theorem to_list_of_list (l : list A) : to_list (of_list l) = l := rfl theorem to_list_nil : to_list nil = ([] : list A) := rfl theorem length_to_list {n : nat} : ∀ (v : tuple A n), list.length (to_list v) = n | (tag l h) := h theorem heq_of_list_eq {n m} : ∀ {v₁ : tuple A n} {v₂ : tuple A m}, to_list v₁ = to_list v₂ → n = m → v₁ == v₂ | (tag l₁ h₁) (tag l₂ h₂) e₁ e₂ := begin clear heq_of_list_eq, subst e₂, subst h₁, unfold to_list at e₁, subst l₁ end theorem list_eq_of_heq {n m} {v₁ : tuple A n} {v₂ : tuple A m} : v₁ == v₂ → n = m → to_list v₁ = to_list v₂ := begin intro h₁ h₂, revert v₁ v₂ h₁, subst n, intro v₁ v₂ h₁, rewrite [heq.to_eq h₁] end theorem of_list_to_list {n : nat} (v : tuple A n) : of_list (to_list v) == v := begin apply heq_of_list_eq, rewrite to_list_of_list, rewrite length_to_list end /- append -/ definition append {n m : nat} : tuple A n → tuple A m → tuple A (n + m) | (tag l₁ h₁) (tag l₂ h₂) := tag (list.append l₁ l₂) (by rewrite [length_append, h₁, h₂]) infix ++ := append open eq.ops lemma push_eq_rec : ∀ {n m : nat} {l : list A} (h₁ : n = m) (h₂ : length l = n), h₁ ▹ (tag l h₂) = tag l (h₁ ▹ h₂) | n n l (eq.refl n) h₂ := rfl theorem append_nil_right {n : nat} (v : tuple A n) : v ++ nil = v := induction_on v (λ l n h, by unfold [tuple.append, tuple.nil]; congruence; apply list.append_nil_right) theorem append_nil_left {n : nat} (v : tuple A n) : !zero_add ▹ (nil ++ v) = v := induction_on v (λ l n h, begin unfold [tuple.append, tuple.nil], rewrite [push_eq_rec] end) theorem append_nil_left_heq {n : nat} (v : tuple A n) : nil ++ v == v := heq_of_eq_rec_left !zero_add (append_nil_left v) theorem append.assoc {n₁ n₂ n₃} : ∀ (v₁ : tuple A n₁) (v₂ : tuple A n₂) (v₃ : tuple A n₃), !add.assoc ▹ ((v₁ ++ v₂) ++ v₃) = v₁ ++ (v₂ ++ v₃) | (tag l₁ h₁) (tag l₂ h₂) (tag l₃ h₃) := begin unfold tuple.append, rewrite push_eq_rec, congruence, apply list.append.assoc end theorem append.assoc_heq {n₁ n₂ n₃} (v₁ : tuple A n₁) (v₂ : tuple A n₂) (v₃ : tuple A n₃) : (v₁ ++ v₂) ++ v₃ == v₁ ++ (v₂ ++ v₃) := heq_of_eq_rec_left !add.assoc (append.assoc v₁ v₂ v₃) /- reverse -/ definition reverse {n : nat} : tuple A n → tuple A n | (tag l h) := tag (list.reverse l) (by rewrite [length_reverse, h]) theorem reverse_reverse {n : nat} (v : tuple A n) : reverse (reverse v) = v := induction_on v (λ l n h, begin unfold reverse, congruence, apply list.reverse_reverse end) theorem tuple0_eq_nil : ∀ (v : tuple A 0), v = nil | (tag [] h) := rfl | (tag (a::l) h) := by contradiction /- mem -/ definition mem {n : nat} (a : A) (v : tuple A n) : Prop := a ∈ elt_of v notation e ∈ s := mem e s notation e ∉ s := ¬ e ∈ s theorem not_mem_nil (a : A) : a ∉ nil := list.not_mem_nil a theorem mem_cons [simp] {n : nat} (a : A) (v : tuple A n) : a ∈ a :: v := induction_on v (λ l n h, !list.mem_cons) theorem mem_cons_of_mem {n : nat} (y : A) {x : A} {v : tuple A n} : x ∈ v → x ∈ y :: v := induction_on v (λ l n h₁ h₂, list.mem_cons_of_mem y h₂) theorem eq_or_mem_of_mem_cons {n : nat} {x y : A} {v : tuple A n} : x ∈ y::v → x = y ∨ x ∈ v := induction_on v (λ l n h₁ h₂, eq_or_mem_of_mem_cons h₂) theorem mem_singleton {n : nat} {x a : A} : x ∈ (a::nil : tuple A 1) → x = a := assume h, list.mem_singleton h /- map -/ definition map {n : nat} (f : A → B) : tuple A n → tuple B n | (tag l h) := tag (list.map f l) (by clear map; substvars; rewrite length_map) theorem map_nil (f : A → B) : map f nil = nil := rfl theorem map_cons {n : nat} (f : A → B) (a : A) (v : tuple A n) : map f (a::v) = f a :: map f v := by induction v; reflexivity theorem map_tag {n : nat} (f : A → B) (l : list A) (h : length l = n) : map f (tag l h) = tag (list.map f l) (by substvars; rewrite length_map) := by reflexivity theorem map_map {n : nat} (g : B → C) (f : A → B) (v : tuple A n) : map g (map f v) = map (g ∘ f) v := begin cases v, rewrite *map_tag, apply subtype.eq, apply list.map_map end theorem map_id {n : nat} (v : tuple A n) : map id v = v := begin induction v, unfold map, congruence, apply list.map_id end theorem mem_map {n : nat} {a : A} {v : tuple A n} (f : A → B) : a ∈ v → f a ∈ map f v := begin induction v, unfold map, apply list.mem_map end theorem exists_of_mem_map {n : nat} {f : A → B} {b : B} {v : tuple A n} : b ∈ map f v → ∃a, a ∈ v ∧ f a = b := begin induction v, unfold map, apply list.exists_of_mem_map end theorem eq_of_map_const {n : nat} {b₁ b₂ : B} {v : tuple A n} : b₁ ∈ map (const A b₂) v → b₁ = b₂ := begin induction v, unfold map, apply list.eq_of_map_const end /- product -/ definition product {n m : nat} : tuple A n → tuple B m → tuple (A × B) (n * m) | (tag l₁ h₁) (tag l₂ h₂) := tag (list.product l₁ l₂) (by rewrite [length_product, h₁, h₂]) theorem nil_product {m : nat} (v : tuple B m) : !zero_mul ▹ product (@nil A) v = nil := begin induction v, unfold [nil, product], rewrite push_eq_rec end theorem nil_product_heq {m : nat} (v : tuple B m) : product (@nil A) v == (@nil (A × B)) := heq_of_eq_rec_left _ (nil_product v) theorem product_nil {n : nat} (v : tuple A n) : product v (@nil B) = nil := begin induction v, unfold [nil, product], congruence, apply list.product_nil end theorem mem_product {n m : nat} {a : A} {b : B} {v₁ : tuple A n} {v₂ : tuple B m} : a ∈ v₁ → b ∈ v₂ → (a, b) ∈ product v₁ v₂ := begin cases v₁, cases v₂, unfold product, apply list.mem_product end theorem mem_of_mem_product_left {n m : nat} {a : A} {b : B} {v₁ : tuple A n} {v₂ : tuple B m} : (a, b) ∈ product v₁ v₂ → a ∈ v₁ := begin cases v₁, cases v₂, unfold product, apply list.mem_of_mem_product_left end theorem mem_of_mem_product_right {n m : nat} {a : A} {b : B} {v₁ : tuple A n} {v₂ : tuple B m} : (a, b) ∈ product v₁ v₂ → b ∈ v₂ := begin cases v₁, cases v₂, unfold product, apply list.mem_of_mem_product_right end /- ith -/ open fin definition ith {n : nat} : tuple A n → fin n → A | (tag l h₁) (mk i h₂) := list.ith l i (by rewrite h₁; exact h₂) lemma ith_zero {n : nat} (a : A) (v : tuple A n) (h : 0 < succ n) : ith (a::v) (mk 0 h) = a := by induction v; reflexivity lemma ith_fin_zero {n : nat} (a : A) (v : tuple A n) : ith (a::v) (zero n) = a := by unfold zero; apply ith_zero lemma ith_succ {n : nat} (a : A) (v : tuple A n) (i : nat) (h : succ i < succ n) : ith (a::v) (mk (succ i) h) = ith v (mk_pred i h) := by induction v; reflexivity lemma ith_fin_succ {n : nat} (a : A) (v : tuple A n) (i : fin n) : ith (a::v) (succ i) = ith v i := begin cases i, unfold fin.succ, rewrite ith_succ end lemma ith_zero_eq_head {n : nat} (v : tuple A (nat.succ n)) : ith v (zero n) = head v := by rewrite [-eta v, ith_fin_zero, head_cons] lemma ith_succ_eq_ith_tail {n : nat} (v : tuple A (nat.succ n)) (i : fin n) : ith v (succ i) = ith (tail v) i := by rewrite [-eta v, ith_fin_succ, tail_cons] protected lemma ext {n : nat} (v₁ v₂ : tuple A n) (h : ∀ i : fin n, ith v₁ i = ith v₂ i) : v₁ = v₂ := begin induction n with n ih, rewrite [tuple0_eq_nil v₁, tuple0_eq_nil v₂], rewrite [-eta v₁, -eta v₂], congruence, show head v₁ = head v₂, by rewrite [-ith_zero_eq_head, -ith_zero_eq_head]; apply h, have ∀ i : fin n, ith (tail v₁) i = ith (tail v₂) i, from take i, by rewrite [-ith_succ_eq_ith_tail, -ith_succ_eq_ith_tail]; apply h, show tail v₁ = tail v₂, from ih _ _ this end /- tabulate -/ definition tabulate : Π {n : nat}, (fin n → A) → tuple A n | 0 f := nil | (n+1) f := f (@zero n) :: tabulate (λ i : fin n, f (succ i)) theorem ith_tabulate {n : nat} (f : fin n → A) (i : fin n) : ith (tabulate f) i = f i := begin induction n with n ih, apply elim0 i, cases i with v hlt, cases v, {unfold tabulate, rewrite ith_zero}, {unfold tabulate, rewrite [ith_succ, ih]} end end tuple
1fec4cdea915f77772239e94cb69a7f570723b68
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Data/Options.lean
cc3ad10181934373df9f20c42f1855fb46a4023f
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,854
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich and Leonardo de Moura -/ import Lean.Data.KVMap namespace Lean def Options := KVMap def Options.empty : Options := {} instance : Inhabited Options := ⟨Options.empty⟩ instance : ToString Options := inferInstanceAs (ToString KVMap) structure OptionDecl := (defValue : DataValue) (group : String := "") (descr : String := "") def OptionDecls := NameMap OptionDecl instance : Inhabited OptionDecls := ⟨({} : NameMap OptionDecl)⟩ private def initOptionDeclsRef : IO (IO.Ref OptionDecls) := IO.mkRef (mkNameMap OptionDecl) @[builtinInit initOptionDeclsRef] private constant optionDeclsRef : IO.Ref OptionDecls @[export lean_register_option] def registerOption (name : Name) (decl : OptionDecl) : IO Unit := do let decls ← optionDeclsRef.get if decls.contains name then throw $ IO.userError s!"invalid option declaration '{name}', option already exists" optionDeclsRef.set $ decls.insert name decl def getOptionDecls : IO OptionDecls := optionDeclsRef.get @[export lean_get_option_decls_array] def getOptionDeclsArray : IO (Array (Name × OptionDecl)) := do let decls ← getOptionDecls pure $ decls.fold (fun (r : Array (Name × OptionDecl)) k v => r.push (k, v)) #[] def getOptionDecl (name : Name) : IO OptionDecl := do let decls ← getOptionDecls let (some decl) ← pure (decls.find? name) | throw $ IO.userError s!"unknown option '{name}'" pure decl def getOptionDefaulValue (name : Name) : IO DataValue := do let decl ← getOptionDecl name pure decl.defValue def getOptionDescr (name : Name) : IO String := do let decl ← getOptionDecl name pure decl.descr def setOptionFromString (opts : Options) (entry : String) : IO Options := do let ps := (entry.splitOn "=").map String.trim let [key, val] ← pure ps | throw $ IO.userError "invalid configuration option entry, it must be of the form '<key> = <value>'" let key := Name.mkSimple key let defValue ← getOptionDefaulValue key match defValue with | DataValue.ofString v => pure $ opts.setString key val | DataValue.ofBool v => if key == `true then pure $ opts.setBool key true else if key == `false then pure $ opts.setBool key false else throw $ IO.userError s!"invalid Bool option value '{val}'" | DataValue.ofName v => pure $ opts.setName key val.toName | DataValue.ofNat v => match val.toNat? with | none => throw (IO.userError s!"invalid Nat option value '{val}'") | some v => pure $ opts.setNat key v | DataValue.ofInt v => match val.toInt? with | none => throw (IO.userError s!"invalid Int option value '{val}'") | some v => pure $ opts.setInt key v builtin_initialize registerOption `verbose { defValue := true, group := "", descr := "disable/enable verbose messages" } registerOption `timeout { defValue := DataValue.ofNat 0, group := "", descr := "the (deterministic) timeout is measured as the maximum of memory allocations (in thousands) per task, the default is unbounded" } registerOption `maxMemory { defValue := DataValue.ofNat 2048, group := "", descr := "maximum amount of memory available for Lean in megabytes" } class MonadOptions (m : Type → Type) := (getOptions : m Options) export MonadOptions (getOptions) instance (m n) [MonadOptions m] [MonadLift m n] : MonadOptions n := { getOptions := liftM (getOptions : m _) } variables {m} [Monad m] [MonadOptions m] def getBoolOption (k : Name) (defValue := false) : m Bool := do let opts ← getOptions pure $ opts.getBool k defValue def getNatOption (k : Name) (defValue := 0) : m Nat := do let opts ← getOptions pure $ opts.getNat k defValue end Lean
4b0a8ec50243590247ba296bf9e76a89fc74010c
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/hidingInaccessibleNames.lean
c4ebdae1945eaec3ba97792201fd0852c20cff91
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
618
lean
def f : (xs : List Nat) → Nat → xs ≠ [] → Nat | [], _, _ => _ | [a,b], _, _ => _ | _, _, _ => _ set_option pp.inaccessibleNames true in def f : (xs : List Nat) → Nat → xs ≠ [] → Nat | [], _, _ => _ | [a,b], _, _ => _ | _, _, _ => _ theorem ex1 : p ∨ q → q ∨ p := by intro h cases h traceState apply Or.inr assumption apply Or.inl assumption done theorem ex2 : {p : Prop} → [Decidable p] → p → decide p = true | _, isTrue _, _ => _ | _, isFalse h₁, h₂ => absurd h₂ h₁ theorem ex3 : ∀ {c d : Char}, c = d → c.val = d.val | _, _, rfl => _
635defbcc42033e160728264828d06cdb24c6bd4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/limits/preserves/shapes/products.lean
751bb9de6af24b4bf6eb299a45b37799819ad27a
[ "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
6,649
lean
/- Copyright (c) 2020 Scott Morrison, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.shapes.products import category_theory.limits.preserves.basic /-! # Preserving products > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Constructions to relate the notions of preserving products and reflecting products to concrete fans. In particular, we show that `pi_comparison G f` is an isomorphism iff `G` preserves the limit of `f`. -/ noncomputable theory universes w v₁ v₂ u₁ u₂ open category_theory category_theory.category category_theory.limits variables {C : Type u₁} [category.{v₁} C] variables {D : Type u₂} [category.{v₂} D] variables (G : C ⥤ D) namespace category_theory.limits variables {J : Type w} (f : J → C) /-- The map of a fan is a limit iff the fan consisting of the mapped morphisms is a limit. This essentially lets us commute `fan.mk` with `functor.map_cone`. -/ def is_limit_map_cone_fan_mk_equiv {P : C} (g : Π j, P ⟶ f j) : is_limit (G.map_cone (fan.mk P g)) ≃ is_limit (fan.mk _ (λ j, G.map (g j)) : fan (λ j, G.obj (f j))) := begin refine (is_limit.postcompose_hom_equiv _ _).symm.trans (is_limit.equiv_iso_limit _), refine discrete.nat_iso (λ j, iso.refl (G.obj (f j.as))), refine cones.ext (iso.refl _) (λ j, by { discrete_cases, dsimp, simp }), end /-- The property of preserving products expressed in terms of fans. -/ def is_limit_fan_mk_obj_of_is_limit [preserves_limit (discrete.functor f) G] {P : C} (g : Π j, P ⟶ f j) (t : is_limit (fan.mk _ g)) : is_limit (fan.mk (G.obj P) (λ j, G.map (g j)) : fan (λ j, G.obj (f j))) := is_limit_map_cone_fan_mk_equiv _ _ _ (preserves_limit.preserves t) /-- The property of reflecting products expressed in terms of fans. -/ def is_limit_of_is_limit_fan_mk_obj [reflects_limit (discrete.functor f) G] {P : C} (g : Π j, P ⟶ f j) (t : is_limit (fan.mk _ (λ j, G.map (g j)) : fan (λ j, G.obj (f j)))) : is_limit (fan.mk P g) := reflects_limit.reflects ((is_limit_map_cone_fan_mk_equiv _ _ _).symm t) section variables [has_product f] /-- If `G` preserves products and `C` has them, then the fan constructed of the mapped projection of a product is a limit. -/ def is_limit_of_has_product_of_preserves_limit [preserves_limit (discrete.functor f) G] : is_limit (fan.mk _ (λ (j : J), G.map (pi.π f j)) : fan (λ j, G.obj (f j))) := is_limit_fan_mk_obj_of_is_limit G f _ (product_is_product _) variables [has_product (λ (j : J), G.obj (f j))] /-- If `pi_comparison G f` is an isomorphism, then `G` preserves the limit of `f`. -/ def preserves_product.of_iso_comparison [i : is_iso (pi_comparison G f)] : preserves_limit (discrete.functor f) G := begin apply preserves_limit_of_preserves_limit_cone (product_is_product f), apply (is_limit_map_cone_fan_mk_equiv _ _ _).symm _, apply is_limit.of_point_iso (limit.is_limit (discrete.functor (λ (j : J), G.obj (f j)))), apply i, end variable [preserves_limit (discrete.functor f) G] /-- If `G` preserves limits, we have an isomorphism from the image of a product to the product of the images. -/ def preserves_product.iso : G.obj (∏ f) ≅ ∏ (λ j, G.obj (f j)) := is_limit.cone_point_unique_up_to_iso (is_limit_of_has_product_of_preserves_limit G f) (limit.is_limit _) @[simp] lemma preserves_product.iso_hom : (preserves_product.iso G f).hom = pi_comparison G f := rfl instance : is_iso (pi_comparison G f) := begin rw ← preserves_product.iso_hom, apply_instance, end end /-- The map of a cofan is a colimit iff the cofan consisting of the mapped morphisms is a colimit. This essentially lets us commute `cofan.mk` with `functor.map_cocone`. -/ def is_colimit_map_cocone_cofan_mk_equiv {P : C} (g : Π j, f j ⟶ P) : is_colimit (G.map_cocone (cofan.mk P g)) ≃ is_colimit (cofan.mk _ (λ j, G.map (g j)) : cofan (λ j, G.obj (f j))) := begin refine (is_colimit.precompose_hom_equiv _ _).symm.trans (is_colimit.equiv_iso_colimit _), refine discrete.nat_iso (λ j, iso.refl (G.obj (f j.as))), refine cocones.ext (iso.refl _) (λ j, by { discrete_cases, dsimp, simp }), end /-- The property of preserving coproducts expressed in terms of cofans. -/ def is_colimit_cofan_mk_obj_of_is_colimit [preserves_colimit (discrete.functor f) G] {P : C} (g : Π j, f j ⟶ P) (t : is_colimit (cofan.mk _ g)) : is_colimit (cofan.mk (G.obj P) (λ j, G.map (g j)) : cofan (λ j, G.obj (f j))) := is_colimit_map_cocone_cofan_mk_equiv _ _ _ (preserves_colimit.preserves t) /-- The property of reflecting coproducts expressed in terms of cofans. -/ def is_colimit_of_is_colimit_cofan_mk_obj [reflects_colimit (discrete.functor f) G] {P : C} (g : Π j, f j ⟶ P) (t : is_colimit (cofan.mk _ (λ j, G.map (g j)) : cofan (λ j, G.obj (f j)))) : is_colimit (cofan.mk P g) := reflects_colimit.reflects ((is_colimit_map_cocone_cofan_mk_equiv _ _ _).symm t) section variables [has_coproduct f] /-- If `G` preserves coproducts and `C` has them, then the cofan constructed of the mapped inclusion of a coproduct is a colimit. -/ def is_colimit_of_has_coproduct_of_preserves_colimit [preserves_colimit (discrete.functor f) G] : is_colimit (cofan.mk _ (λ (j : J), G.map (sigma.ι f j)) : cofan (λ j, G.obj (f j))) := is_colimit_cofan_mk_obj_of_is_colimit G f _ (coproduct_is_coproduct _) variables [has_coproduct (λ (j : J), G.obj (f j))] /-- If `sigma_comparison G f` is an isomorphism, then `G` preserves the colimit of `f`. -/ def preserves_coproduct.of_iso_comparison [i : is_iso (sigma_comparison G f)] : preserves_colimit (discrete.functor f) G := begin apply preserves_colimit_of_preserves_colimit_cocone (coproduct_is_coproduct f), apply (is_colimit_map_cocone_cofan_mk_equiv _ _ _).symm _, apply is_colimit.of_point_iso (colimit.is_colimit (discrete.functor (λ (j : J), G.obj (f j)))), apply i, end variable [preserves_colimit (discrete.functor f) G] /-- If `G` preserves colimits, we have an isomorphism from the image of a coproduct to the coproduct of the images. -/ def preserves_coproduct.iso : G.obj (∐ f) ≅ ∐ (λ j, G.obj (f j)) := is_colimit.cocone_point_unique_up_to_iso (is_colimit_of_has_coproduct_of_preserves_colimit G f) (colimit.is_colimit _) @[simp] lemma preserves_coproduct.inv_hom : (preserves_coproduct.iso G f).inv = sigma_comparison G f := rfl instance : is_iso (sigma_comparison G f) := begin rw ← preserves_coproduct.inv_hom, apply_instance, end end end category_theory.limits
e1938e8153c0f44cb86b7c7883cd6503b11957b4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1371.lean
8de3b393af3126430146e80c3a2584a1a4cecf3a
[ "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
128
lean
def f (stx : Lean.Syntax) := match stx with | `($f $a) => 1 | `($_) => 2 | `($f $b) => 3 | _ => "hello"
7b9fbd73beeab5242d331ea7cc9264d555b1c186
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/704.lean
1e4a305e7e3d5366b37e5eda029b2934fe569569
[ "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
130
lean
open classical eval if true then 1 else (0:num) attribute prop_decidable [instance] [priority 0] eval if true then 1 else (0:num)
9154146aaee0185c1dfa07fb1ca2ab2ba70e1a6e
798dd332c1ad790518589a09bc82459fb12e5156
/analysis/topology/uniform_space.lean
8f9ba23dba083495158ffa1de131880770e33df4
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
83,313
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * completion (on Cauchy filters instead of Cauchy sequences) * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact One reason to directly formalize uniform spaces is foundational: we define ℝ as a completion of ℚ. The central concept of uniform spaces is its uniformity: a filter relating two elements of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter data.quot analysis.topology.topological_space analysis.topology.continuity open set lattice filter classical local attribute [instance] prop_decidable set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) := by ext p; cases p; simp only [mem_comp_rel]; tauto /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U.sets) x, (x, x) ∈ r) (symm : ∀ r ∈ U.sets, {p | prod.swap p ∈ r} ∈ U.sets) (comp : ∀ r ∈ U.sets, ∃ t ∈ U.sets, comp_rel t t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity.sets, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity.sets)) @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity.sets)) : uniform_space α := ⟨c, is_open_uniformity⟩ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.refl _ } def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.refl _ } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity : filter (α × α) := (@uniform_space.to_core α _).uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ (@uniformity α _).sets) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ @uniformity α _ := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ (@uniformity α _).sets) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) uniformity ≤ uniformity := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : uniformity.lift' (λs:set (α×α), comp_rel s s) ≤ uniformity := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto prod.swap (@uniformity α _) uniformity := symm_le_uniformity lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ_, (a, a)) f uniformity := assume s hs, show {x | (a, a) ∈ s} ∈ f.sets, from univ_mem_sets' $ assume b, refl_mem_uniformity hs lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, comp_rel t t ⊆ s := have s ∈ (uniformity.lift' (λt:set (α×α), comp_rel t t)).sets, from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : uniformity ≤ (@prod.swap α α) <$> uniformity := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : uniformity = (@prod.swap α α) <$> uniformity := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : uniformity.lift (λs, g (preimage prod.swap s)) ≤ f) : uniformity.lift g ≤ f := calc uniformity.lift g ≤ (filter.map prod.swap (@uniformity α _)).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f): uniformity.lift (λs, f (comp_rel s s)) ≤ uniformity.lift f := calc uniformity.lift (λs, f (comp_rel s s)) = (uniformity.lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ uniformity.lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ uniformity := calc uniformity.lift' (λd, comp_rel d (comp_rel d d)) = uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ uniformity.lift (λs, uniformity.lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal ... = uniformity.lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ uniformity : comp_le_uniformity lemma mem_nhds_uniformity_iff {x : α} {s : set α} : (s ∈ (nhds x).sets) ↔ ({p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets) := ⟨ begin simp [mem_nhds_sets_iff, is_open_uniformity], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ (@uniformity α _).sets}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_comap_uniformity {x : α} : nhds x = uniformity.comap (prod.mk x) := by ext s; rw [mem_nhds_uniformity_iff, mem_comap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, uniformity.sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_uniformity {x : α} : nhds x = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) := begin ext s, rw [mem_lift'_sets], tactic.swap, apply monotone_preimage, simp [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, uniformity.sets_of_superset h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {y : α | (x, y) ∈ s} ∈ (nhds x).sets := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ (uniformity.sets : set (set (α×α)))) : {x : α | (x, y) ∈ s} ∈ (nhds y).sets := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (nhds a) uniformity := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (nhds a) uniformity := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_comp monotone_preimage $ monotone_comp monotone_preimage monotone_principal) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x).lift g = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> uniformity).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = uniformity.lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ monotone_comp monotone_preimage hg ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (nhds a).lift (λs:set α, (nhds b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = uniformity.lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ (@uniformity α _).sets) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ (nhds (x, y)).sets, begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d∈(@uniformity α _).sets, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) uniformity).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ (uniformity.lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s∈(@uniformity α _).sets, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀s∈(@uniformity α _).sets, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : (@uniformity α _) = uniformity.lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc uniformity.lift' closure ≤ uniformity.lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ uniformity : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : (@uniformity α _) = uniformity.lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ (@uniformity α _).sets, by filter_upwards [hs] this, by simp [this]) (assume s hs, (uniformity.lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ (@uniformity α _).sets) : interior s ∈ (@uniformity α _).sets := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed [uniform_space α] {s : set (α×α)} (h : s ∈ (@uniformity α _).sets) : ∃t∈(@uniformity α _).sets, is_closed t ∧ t ⊆ s := have s ∈ ((@uniformity α _).lift' closure).sets, by rwa [uniformity_eq_uniformity_closure] at h, have ∃t∈(@uniformity α _).sets, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, uniformity.sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /- uniform continuity -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) uniformity uniformity theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ (@uniformity β _).sets, {x : α × α | (f x.1, f x.2) ∈ r} ∈ (@uniformity α _).sets := iff.rfl lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := @tendsto_const_uniformity _ _ _ b uniformity lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (g ∘ f) := hf.comp hg def uniform_embedding [uniform_space β] (f : α → β) := function.injective f ∧ comap (λx:α×α, (f x.1, f x.2)) uniformity = uniformity theorem uniform_embedding_def [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ ∀ s, s ∈ (@uniformity α _).sets ↔ ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by rw [uniform_embedding, eq_comm, filter.ext_iff]; simp [subset_def] theorem uniform_embedding_def' [uniform_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ s, s ∈ (@uniformity α _).sets → ∃ t ∈ (@uniformity β _).sets, ∀ x y : α, (f x, f y) ∈ t → (x, y) ∈ s := by simp [uniform_embedding_def, uniform_continuous_def]; exact ⟨λ ⟨I, H⟩, ⟨I, λ s su, (H _).2 ⟨s, su, λ x y, id⟩, λ s, (H s).1⟩, λ ⟨I, H₁, H₂⟩, ⟨I, λ s, ⟨H₂ s, λ ⟨t, tu, h⟩, sets_of_superset _ (H₁ t tu) (λ ⟨a, b⟩, h a b)⟩⟩⟩ lemma uniform_embedding.uniform_continuous [uniform_space β] {f : α → β} (hf : uniform_embedding f) : uniform_continuous f := (uniform_embedding_def'.1 hf).2.1 lemma uniform_embedding.uniform_continuous_iff [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hg : uniform_embedding g) : uniform_continuous f ↔ uniform_continuous (g ∘ f) := by simp [uniform_continuous, tendsto]; rw [← hg.2, ← map_le_iff_le_comap, filter.map_map] lemma uniform_embedding.dense_embedding [uniform_space β] {f : α → β} (h : uniform_embedding f) (hd : ∀x, x ∈ closure (range f)) : dense_embedding f := { dense := hd, inj := h.left, induced := begin intro a, simp [h.right.symm, nhds_eq_uniformity], rw [comap_lift'_eq, comap_lift'_eq2], refl, exact monotone_preimage, exact monotone_preimage end } lemma uniform_continuous.continuous [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_tendsto.mpr $ assume a, calc map f (nhds a) ≤ (map (λp:α×α, (f p.1, f p.2)) uniformity).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) : begin rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2], exact (lift'_mono' $ assume s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩, ⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩), exact monotone_preimage, exact monotone_preimage end ... ≤ nhds (f a) : by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _) lemma closure_image_mem_nhds_of_uniform_embedding [uniform_space α] [uniform_space β] {s : set (α×α)} {e : α → β} (b : β) (he₁ : uniform_embedding e) (he₂ : dense_embedding e) (hs : s ∈ (@uniformity α _).sets) : ∃a, closure (e '' {a' | (a, a') ∈ s}) ∈ (nhds b).sets := have s ∈ (comap (λp:α×α, (e p.1, e p.2)) $ uniformity).sets, from he₁.right.symm ▸ hs, let ⟨t₁, ht₁u, ht₁⟩ := this in have ht₁ : ∀p:α×α, (e p.1, e p.2) ∈ t₁ → p ∈ s, from ht₁, let ⟨t₂, ht₂u, ht₂s, ht₂c⟩ := comp_symm_of_uniformity ht₁u in let ⟨t, htu, hts, htc⟩ := comp_symm_of_uniformity ht₂u in have preimage e {b' | (b, b') ∈ t₂} ∈ (comap e $ nhds b).sets, from preimage_mem_comap $ mem_nhds_left b ht₂u, let ⟨a, (ha : (b, e a) ∈ t₂)⟩ := inhabited_of_mem_sets (he₂.comap_nhds_neq_bot) this in have ∀b' (s' : set (β × β)), (b, b') ∈ t → s' ∈ (@uniformity β _).sets → {y : β | (b', y) ∈ s'} ∩ e '' {a' : α | (a, a') ∈ s} ≠ ∅, from assume b' s' hb' hs', have preimage e {b'' | (b', b'') ∈ s' ∩ t} ∈ (comap e $ nhds b').sets, from preimage_mem_comap $ mem_nhds_left b' $ inter_mem_sets hs' htu, let ⟨a₂, ha₂s', ha₂t⟩ := inhabited_of_mem_sets (he₂.comap_nhds_neq_bot) this in have (e a, e a₂) ∈ t₁, from ht₂c $ prod_mk_mem_comp_rel (ht₂s ha) $ htc $ prod_mk_mem_comp_rel hb' ha₂t, have e a₂ ∈ {b'':β | (b', b'') ∈ s'} ∩ e '' {a' | (a, a') ∈ s}, from ⟨ha₂s', mem_image_of_mem _ $ ht₁ (a, a₂) this⟩, ne_empty_of_mem this, have ∀b', (b, b') ∈ t → nhds b' ⊓ principal (e '' {a' | (a, a') ∈ s}) ≠ ⊥, begin intros b' hb', rw [nhds_eq_uniformity, lift'_inf_principal_eq, lift'_neq_bot_iff], exact assume s, this b' s hb', exact monotone_inter monotone_preimage monotone_const end, have ∀b', (b, b') ∈ t → b' ∈ closure (e '' {a' | (a, a') ∈ s}), from assume b' hb', by rw [closure_eq_nhds]; exact this b' hb', ⟨a, (nhds b).sets_of_superset (mem_nhds_left b htu) this⟩ /-- A filter `f` is Cauchy if for every entourage `r`, there exists an `s ∈ f` such that `s × s ⊆ r`. This is a generalization of Cauchy sequences, because if `a : ℕ → α` then the filter of sets containing cofinitely many of the `a n` is Cauchy iff `a` is a Cauchy sequence. -/ def cauchy (f : filter α) := f ≠ ⊥ ∧ filter.prod f f ≤ uniformity lemma cauchy_iff [uniform_space α] {f : filter α} : cauchy f ↔ (f ≠ ⊥ ∧ (∀s∈(@uniformity α _).sets, ∃t∈f.sets, set.prod t t ⊆ s)) := and_congr (iff.refl _) $ forall_congr $ assume s, forall_congr $ assume hs, mem_prod_same_iff lemma cauchy_downwards {f g : filter α} (h_c : cauchy f) (hg : g ≠ ⊥) (h_le : g ≤ f) : cauchy g := ⟨hg, le_trans (filter.prod_mono h_le h_le) h_c.right⟩ lemma cauchy_nhds {a : α} : cauchy (nhds a) := ⟨nhds_neq_bot, calc filter.prod (nhds a) (nhds a) = uniformity.lift (λs:set (α×α), uniformity.lift' (λt:set(α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (a, y) ∈ t})) : nhds_nhds_eq_uniformity_uniformity_prod ... ≤ uniformity.lift' (λs:set (α×α), comp_rel s s) : le_infi $ assume s, le_infi $ assume hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le_of_le hs $ principal_mono.mpr $ assume ⟨x, y⟩ ⟨(hx : (x, a) ∈ s), (hy : (a, y) ∈ s)⟩, ⟨a, hx, hy⟩ ... ≤ uniformity : comp_le_uniformity⟩ lemma cauchy_pure {a : α} : cauchy (pure a) := cauchy_downwards cauchy_nhds (show principal {a} ≠ ⊥, by simp) (pure_le_nhds a) lemma le_nhds_of_cauchy_adhp {f : filter α} {x : α} (hf : cauchy f) (adhs : f ⊓ nhds x ≠ ⊥) : f ≤ nhds x := have ∀s∈f.sets, x ∈ closure s, begin intros s hs, simp [closure_eq_nhds, inf_comm], exact assume h', adhs $ bot_unique $ h' ▸ inf_le_inf (by simp; exact hs) (le_refl _) end, calc f ≤ f.lift' (λs:set α, {y | x ∈ closure s ∧ y ∈ closure s}) : le_infi $ assume s, le_infi $ assume hs, begin rw [←forall_sets_neq_empty_iff_neq_bot] at adhs, simp [this s hs], exact mem_sets_of_superset hs subset_closure end ... ≤ f.lift' (λs:set α, {y | (x, y) ∈ closure (set.prod s s)}) : by simp [closure_prod_eq]; exact le_refl _ ... = (filter.prod f f).lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : begin rw [prod_same_eq], rw [lift'_lift'_assoc], exact monotone_prod monotone_id monotone_id, exact monotone_comp (assume s t h x h', closure_mono h h') monotone_preimage end ... ≤ uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ closure s}) : lift'_mono hf.right (le_refl _) ... = (uniformity.lift' closure).lift' (λs:set (α×α), {y | (x, y) ∈ s}) : begin rw [lift'_lift'_assoc], exact assume s t h, closure_mono h, exact monotone_preimage end ... = uniformity.lift' (λs:set (α×α), {y | (x, y) ∈ s}) : by rw [←uniformity_eq_uniformity_closure] ... = nhds x : by rw [nhds_eq_uniformity] lemma le_nhds_iff_adhp_of_cauchy {f : filter α} {x : α} (hf : cauchy f) : f ≤ nhds x ↔ f ⊓ nhds x ≠ ⊥ := ⟨assume h, (inf_of_le_left h).symm ▸ hf.left, le_nhds_of_cauchy_adhp hf⟩ lemma cauchy_map [uniform_space β] {f : filter α} {m : α → β} (hm : uniform_continuous m) (hf : cauchy f) : cauchy (map m f) := ⟨have f ≠ ⊥, from hf.left, by simp; assumption, calc filter.prod (map m f) (map m f) = map (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_map_map_eq ... ≤ map (λp:α×α, (m p.1, m p.2)) uniformity : map_mono hf.right ... ≤ uniformity : hm⟩ lemma cauchy_comap [uniform_space β] {f : filter β} {m : α → β} (hm : comap (λp:α×α, (m p.1, m p.2)) uniformity ≤ uniformity) (hf : cauchy f) (hb : comap m f ≠ ⊥) : cauchy (comap m f) := ⟨hb, calc filter.prod (comap m f) (comap m f) = comap (λp:α×α, (m p.1, m p.2)) (filter.prod f f) : filter.prod_comap_comap_eq ... ≤ comap (λp:α×α, (m p.1, m p.2)) uniformity : comap_mono hf.right ... ≤ uniformity : hm⟩ /- separated uniformity -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (@uniformity α _).sets lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ (@uniformity α _).sets, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ (@uniformity α _).sets), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ protected def separation_setoid (α : Type u) [u : uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ @[class] def separated (α : Type u) [uniform_space α] := separation_rel α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, (∀ r ∈ (@uniformity α _).sets, (x, y) ∈ r) → x = y := by simp [separated, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, x ≠ y → ∃ r ∈ (@uniformity α _).sets, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [classical.not_forall] instance separated_t2 [s : separated α] : t2_space α := ⟨assume x y, assume h : x ≠ y, let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := separated_def'.1 s x y h in let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in have {y | (x, y) ∈ d'} ∈ (nhds x).sets, from mem_nhds_left x hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ (nhds y).sets, from mem_nhds_right y hd', let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in have u ∩ v = ∅, from eq_empty_of_subset_empty $ assume z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩, have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩, hxy $ hd'd' this, ⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩ instance separated_regular [separated α] : regular_space α := { regular := λs a hs ha, have -s ∈ (nhds a).sets, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ -s} ∈ uniformity.sets, from mem_nhds_uniformity_iff.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ uniformity.sets, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ -s, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ (nhds a).sets, from (nhds a).sets_of_superset (mem_nhds_left a hd) subset_closure, have nhds a ⊓ principal (-closure e) = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (principal (- closure e)) (principal (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨- closure e, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..separated_t2 } /-- A set `s` is totally bounded if for every entourage `d` there is a finite set of points `t` such that every element of `s` is `d`-near to some element of `t`. -/ def totally_bounded (s : set α) : Prop := ∀d ∈ (@uniformity α _).sets, ∃t : set α, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) theorem totally_bounded_iff_subset {s : set α} : totally_bounded s ↔ ∀d ∈ (@uniformity α _).sets, ∃t ⊆ s, finite t ∧ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}) := ⟨λ H d hd, begin rcases comp_symm_of_uniformity hd with ⟨r, hr, rs, rd⟩, rcases H r hr with ⟨k, fk, ks⟩, let u := {y ∈ k | ∃ x, x ∈ s ∧ (x, y) ∈ r}, let f : u → α := λ x, classical.some x.2.2, have : ∀ x : u, f x ∈ s ∧ (f x, x.1) ∈ r := λ x, classical.some_spec x.2.2, refine ⟨range f, _, _, _⟩, { exact range_subset_iff.2 (λ x, (this x).1) }, { have : finite u := finite_subset fk (λ x h, h.1), exact ⟨@set.fintype_range _ _ _ _ this.fintype⟩ }, { intros x xs, have := ks xs, simp at this, rcases this with ⟨y, hy, xy⟩, let z : coe_sort u := ⟨y, hy, x, xs, xy⟩, simp, exact ⟨_, ⟨_, z.2, rfl⟩, rd $ mem_comp_rel.2 ⟨_, xy, rs (this z).2⟩⟩ } end, λ H d hd, let ⟨t, _, ht⟩ := H d hd in ⟨t, ht⟩⟩ lemma totally_bounded_subset [uniform_space α] {s₁ s₂ : set α} (hs : s₁ ⊆ s₂) (h : totally_bounded s₂) : totally_bounded s₁ := assume d hd, let ⟨t, ht₁, ht₂⟩ := h d hd in ⟨t, ht₁, subset.trans hs ht₂⟩ lemma totally_bounded_closure [uniform_space α] {s : set α} (h : totally_bounded s) : totally_bounded (closure s) := assume t ht, let ⟨t', ht', hct', htt'⟩ := mem_uniformity_is_closed ht, ⟨c, hcf, hc⟩ := h t' ht' in ⟨c, hcf, calc closure s ⊆ closure (⋃ (y : α) (H : y ∈ c), {x : α | (x, y) ∈ t'}) : closure_mono hc ... = _ : closure_eq_of_is_closed $ is_closed_Union hcf $ assume i hi, continuous_iff_is_closed.mp (continuous_id.prod_mk continuous_const) _ hct' ... ⊆ _ : bUnion_subset $ assume i hi, subset.trans (assume x, @htt' (x, i)) (subset_bUnion_of_mem hi)⟩ lemma totally_bounded_image [uniform_space α] [uniform_space β] {f : α → β} {s : set α} (hf : uniform_continuous f) (hs : totally_bounded s) : totally_bounded (f '' s) := assume t ht, have {p:α×α | (f p.1, f p.2) ∈ t} ∈ (@uniformity α _).sets, from hf ht, let ⟨c, hfc, hct⟩ := hs _ this in ⟨f '' c, finite_image f hfc, begin simp [image_subset_iff], simp [subset_def] at hct, intros x hx, simp [-mem_image], exact let ⟨i, hi, ht⟩ := hct x hx in ⟨f i, mem_image_of_mem f hi, ht⟩ end⟩ lemma totally_bounded_preimage [uniform_space α] [uniform_space β] {f : α → β} {s : set β} (hf : uniform_embedding f) (hs : totally_bounded s) : totally_bounded (f ⁻¹' s) := λ t ht, begin rw ← hf.2 at ht, rcases mem_comap_sets.2 ht with ⟨t', ht', ts⟩, rcases totally_bounded_iff_subset.1 (totally_bounded_subset (image_preimage_subset f s) hs) _ ht' with ⟨c, cs, hfc, hct⟩, refine ⟨f ⁻¹' c, finite_preimage hf.1 hfc, λ x h, _⟩, have := hct (mem_image_of_mem f h), simp at this ⊢, rcases this with ⟨z, zc, zt⟩, rcases cs zc with ⟨y, yc, rfl⟩, exact ⟨y, zc, ts (by exact zt)⟩ end lemma cauchy_of_totally_bounded_of_ultrafilter {s : set α} {f : filter α} (hs : totally_bounded s) (hf : ultrafilter f) (h : f ≤ principal s) : cauchy f := ⟨hf.left, assume t ht, let ⟨t', ht'₁, ht'_symm, ht'_t⟩ := comp_symm_of_uniformity ht in let ⟨i, hi, hs_union⟩ := hs t' ht'₁ in have (⋃y∈i, {x | (x,y) ∈ t'}) ∈ f.sets, from mem_sets_of_superset (le_principal_iff.mp h) hs_union, have ∃y∈i, {x | (x,y) ∈ t'} ∈ f.sets, from mem_of_finite_Union_ultrafilter hf hi this, let ⟨y, hy, hif⟩ := this in have set.prod {x | (x,y) ∈ t'} {x | (x,y) ∈ t'} ⊆ comp_rel t' t', from assume ⟨x₁, x₂⟩ ⟨(h₁ : (x₁, y) ∈ t'), (h₂ : (x₂, y) ∈ t')⟩, ⟨y, h₁, ht'_symm h₂⟩, (filter.prod f f).sets_of_superset (prod_mem_prod hif hif) (subset.trans this ht'_t)⟩ lemma totally_bounded_iff_filter {s : set α} : totally_bounded s ↔ (∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c) := ⟨assume : totally_bounded s, assume f hf hs, ⟨ultrafilter_of f, ultrafilter_of_le, cauchy_of_totally_bounded_of_ultrafilter this (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hs)⟩, assume h : ∀f, f ≠ ⊥ → f ≤ principal s → ∃c ≤ f, cauchy c, assume d hd, classical.by_contradiction $ assume hs, have hd_cover : ∀{t:set α}, finite t → ¬ s ⊆ (⋃y∈t, {x | (x,y) ∈ d}), by simpa using hs, let f := ⨅t:{t : set α // finite t}, principal (s \ (⋃y∈t.val, {x | (x,y) ∈ d})), ⟨a, ha⟩ := @exists_mem_of_ne_empty α s (assume h, hd_cover finite_empty $ h.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_neq_bot_of_directed ⟨a⟩ (assume ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨⟨t₁ ∪ t₂, finite_union ht₁ ht₂⟩, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inl, principal_mono.mpr $ diff_subset_diff_right $ Union_subset_Union $ assume t, Union_subset_Union_const or.inr⟩) (assume ⟨t, ht⟩, by simp [diff_eq_empty]; exact hd_cover ht), have f ≤ principal s, from infi_le_of_le ⟨∅, finite_empty⟩ $ by simp; exact subset.refl s, let ⟨c, (hc₁ : c ≤ f), (hc₂ : cauchy c)⟩ := h f ‹f ≠ ⊥› this, ⟨m, hm, (hmd : set.prod m m ⊆ d)⟩ := (@mem_prod_same_iff α c d).mp $ hc₂.right hd in have c ≤ principal s, from le_trans ‹c ≤ f› this, have m ∩ s ∈ c.sets, from inter_mem_sets hm $ le_principal_iff.mp this, let ⟨y, hym, hys⟩ := inhabited_of_mem_sets hc₂.left this in let ys := (⋃y'∈({y}:set α), {x | (x, y') ∈ d}) in have m ⊆ ys, from assume y' hy', show y' ∈ (⋃y'∈({y}:set α), {x | (x, y') ∈ d}), by simp; exact @hmd (y', y) ⟨hy', hym⟩, have c ≤ principal (s - ys), from le_trans hc₁ $ infi_le_of_le ⟨{y}, finite_singleton _⟩ $ le_refl _, have (s - ys) ∩ (m ∩ s) ∈ c.sets, from inter_mem_sets (le_principal_iff.mp this) ‹m ∩ s ∈ c.sets›, have ∅ ∈ c.sets, from c.sets_of_superset this $ assume x ⟨⟨hxs, hxys⟩, hxm, _⟩, hxys $ ‹m ⊆ ys› hxm, hc₂.left $ empty_in_sets_eq_bot.mp this⟩ lemma totally_bounded_iff_ultrafilter {s : set α} : totally_bounded s ↔ (∀f, ultrafilter f → f ≤ principal s → cauchy f) := ⟨assume hs f, cauchy_of_totally_bounded_of_ultrafilter hs, assume h, totally_bounded_iff_filter.mpr $ assume f hf hfs, have cauchy (ultrafilter_of f), from h (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs), ⟨ultrafilter_of f, ultrafilter_of_le, this⟩⟩ lemma compact_of_totally_bounded_complete {s : set α} (ht : totally_bounded s) (hc : ∀{f:filter α}, cauchy f → f ≤ principal s → ∃x∈s, f ≤ nhds x) : compact s := begin rw [compact_iff_ultrafilter_le_nhds], rw [totally_bounded_iff_ultrafilter] at ht, exact assume f hf hfs, hc (ht _ hf hfs) hfs end /-- A complete space is defined here using uniformities. A uniform space is complete if every Cauchy filter converges. -/ class complete_space (α : Type u) [uniform_space α] : Prop := (complete : ∀{f:filter α}, cauchy f → ∃x, f ≤ nhds x) theorem le_nhds_lim_of_cauchy {α} [uniform_space α] [complete_space α] [inhabited α] {f : filter α} (hf : cauchy f) : f ≤ nhds (lim f) := lim_spec (complete_space.complete hf) lemma complete_of_is_closed [complete_space α] {s : set α} {f : filter α} (h : is_closed s) (hf : cauchy f) (hfs : f ≤ principal s) : ∃x∈s, f ≤ nhds x := let ⟨x, hx⟩ := complete_space.complete hf in have x ∈ s, from is_closed_iff_nhds.mp h x $ neq_bot_of_le_neq_bot hf.left $ le_inf hx hfs, ⟨x, this, hx⟩ lemma compact_of_totally_bounded_is_closed [complete_space α] {s : set α} (ht : totally_bounded s) (hc : is_closed s) : compact s := @compact_of_totally_bounded_complete α _ s ht $ assume f, complete_of_is_closed hc lemma complete_space_extension [uniform_space β] {m : β → α} (hm : uniform_embedding m) (dense : ∀x, x ∈ closure (range m)) (h : ∀f:filter β, cauchy f → ∃x:α, map m f ≤ nhds x) : complete_space α := ⟨assume (f : filter α), assume hf : cauchy f, let p : set (α × α) → set α → set α := λs t, {y : α| ∃x:α, x ∈ t ∧ (x, y) ∈ s}, g := uniformity.lift (λs, f.lift' (p s)) in have mp₀ : monotone p, from assume a b h t s ⟨x, xs, xa⟩, ⟨x, xs, h xa⟩, have mp₁ : ∀{s}, monotone (p s), from assume s a b h x ⟨y, ya, yxs⟩, ⟨y, h ya, yxs⟩, have f ≤ g, from le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, le_principal_iff.mpr $ mem_sets_of_superset ht $ assume x hx, ⟨x, hx, refl_mem_uniformity hs⟩, have g ≠ ⊥, from neq_bot_of_le_neq_bot hf.left this, have comap m g ≠ ⊥, from comap_neq_bot $ assume t ht, let ⟨t', ht', ht_mem⟩ := (mem_lift_sets $ monotone_lift' monotone_const mp₀).mp ht in let ⟨t'', ht'', ht'_sub⟩ := (mem_lift'_sets mp₁).mp ht_mem in let ⟨x, (hx : x ∈ t'')⟩ := inhabited_of_mem_sets hf.left ht'' in have h₀ : nhds x ⊓ principal (range m) ≠ ⊥, by simp [closure_eq_nhds] at dense; exact dense x, have h₁ : {y | (x, y) ∈ t'} ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_left α (nhds x) (principal (range m)) _ $ mem_nhds_left x ht', have h₂ : range m ∈ (nhds x ⊓ principal (range m)).sets, from @mem_inf_sets_of_right α (nhds x) (principal (range m)) _ $ subset.refl _, have {y | (x, y) ∈ t'} ∩ range m ∈ (nhds x ⊓ principal (range m)).sets, from @inter_mem_sets α (nhds x ⊓ principal (range m)) _ _ h₁ h₂, let ⟨y, xyt', b, b_eq⟩ := inhabited_of_mem_sets h₀ this in ⟨b, b_eq.symm ▸ ht'_sub ⟨x, hx, xyt'⟩⟩, have cauchy g, from ⟨‹g ≠ ⊥›, assume s hs, let ⟨s₁, hs₁, (comp_s₁ : comp_rel s₁ s₁ ⊆ s)⟩ := comp_mem_uniformity_sets hs, ⟨s₂, hs₂, (comp_s₂ : comp_rel s₂ s₂ ⊆ s₁)⟩ := comp_mem_uniformity_sets hs₁, ⟨t, ht, (prod_t : set.prod t t ⊆ s₂)⟩ := mem_prod_same_iff.mp (hf.right hs₂) in have hg₁ : p (preimage prod.swap s₁) t ∈ g.sets, from mem_lift (symm_le_uniformity hs₁) $ @mem_lift' α α f _ t ht, have hg₂ : p s₂ t ∈ g.sets, from mem_lift hs₂ $ @mem_lift' α α f _ t ht, have hg : set.prod (p (preimage prod.swap s₁) t) (p s₂ t) ∈ (filter.prod g g).sets, from @prod_mem_prod α α _ _ g g hg₁ hg₂, (filter.prod g g).sets_of_superset hg (assume ⟨a, b⟩ ⟨⟨c₁, c₁t, hc₁⟩, ⟨c₂, c₂t, hc₂⟩⟩, have (c₁, c₂) ∈ set.prod t t, from ⟨c₁t, c₂t⟩, comp_s₁ $ prod_mk_mem_comp_rel hc₁ $ comp_s₂ $ prod_mk_mem_comp_rel (prod_t this) hc₂)⟩, have cauchy (filter.comap m g), from cauchy_comap (le_of_eq hm.right) ‹cauchy g› (by assumption), let ⟨x, (hx : map m (filter.comap m g) ≤ nhds x)⟩ := h _ this in have map m (filter.comap m g) ⊓ nhds x ≠ ⊥, from (le_nhds_iff_adhp_of_cauchy (cauchy_map hm.uniform_continuous this)).mp hx, have g ⊓ nhds x ≠ ⊥, from neq_bot_of_le_neq_bot this (inf_le_inf (assume s hs, ⟨s, hs, subset.refl _⟩) (le_refl _)), ⟨x, calc f ≤ g : by assumption ... ≤ nhds x : le_nhds_of_cauchy_adhp ‹cauchy g› this⟩⟩ /- separation space -/ section separation_space local attribute [instance] separation_setoid instance {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity, refl := assume s hs ⟨a, b⟩ (h : a = b), have ∀a:α, (a, a) ∈ preimage (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) s, from assume a, refl_mem_uniformity hs, h ▸ quotient.induction_on a this, symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_map, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity).lift' (λs, comp_rel s s) = uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ separation_rel α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ (@uniformity α _).sets), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma comap_quotient_le_uniformity : comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity ≤ uniformity := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (@uniformity α _).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) uniformity = uniformity := le_antisymm comap_quotient_le_uniformity le_comap_map lemma complete_space_separation [h : complete_space α] : complete_space (quotient (separation_setoid α)) := ⟨assume f, assume hf : cauchy f, have cauchy (comap (λx, ⟦x⟧) f), from cauchy_comap comap_quotient_le_uniformity hf $ comap_neq_bot_of_surj hf.left $ assume b, quotient.exists_rep _, let ⟨x, (hx : comap (λx, ⟦x⟧) f ≤ nhds x)⟩ := complete_space.complete this in ⟨⟦x⟧, calc f ≤ map (λx, ⟦x⟧) (comap (λx, ⟦x⟧) f) : le_map_comap $ assume b, quotient.exists_rep _ ... ≤ map (λx, ⟦x⟧) (nhds x) : map_mono hx ... ≤ _ : continuous_iff_tendsto.mp uniform_continuous_quotient_mk.continuous _⟩⟩ lemma separated_separation [h : complete_space α] : separated (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) uniformity).sets, from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp, exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ variables [uniform_space β] [uniform_space γ] lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ separation_rel α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniformity_quotient : @uniformity (quotient (separation_setoid α)) _ = uniformity.map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma separated_of_uniform_continuous {f : α → β} (H : uniform_continuous f) {x y : α} (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated β] {f : α → β} (H : uniform_continuous f) {x y : α} (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h end separation_space section uniform_extension variables [uniform_space β] [uniform_space γ] {e : β → α} (h_e : uniform_embedding e) (h_dense : ∀x, x ∈ closure (range e)) {f : β → γ} (h_f : uniform_continuous f) local notation `ψ` := (h_e.dense_embedding h_dense).extend f lemma uniformly_extend_of_emb [cγ : complete_space γ] [sγ : separated γ] {b : β} : ψ (e b) = f b := dense_embedding.extend_e_eq _ $ continuous_iff_tendsto.mp h_f.continuous b lemma uniformly_extend_exists [complete_space γ] [sγ : separated γ] {a : α} : ∃c, tendsto f (comap e (nhds a)) (nhds c) := let de := (h_e.dense_embedding h_dense) in have cauchy (nhds a), from cauchy_nhds, have cauchy (comap e (nhds a)), from cauchy_comap (le_of_eq h_e.right) this de.comap_nhds_neq_bot, have cauchy (map f (comap e (nhds a))), from cauchy_map h_f this, complete_space.complete this lemma uniformly_extend_spec [complete_space γ] [sγ : separated γ] {a : α} : tendsto f (comap e (nhds a)) (nhds (ψ a)) := @lim_spec _ (id _) _ _ $ uniformly_extend_exists h_e h_dense h_f lemma uniform_continuous_uniformly_extend [cγ : complete_space γ] [sγ : separated γ] : uniform_continuous ψ := assume d hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in have h_pnt : ∀{a m}, m ∈ (nhds a).sets → ∃c, c ∈ f '' preimage e m ∧ (c, ψ a) ∈ s ∧ (ψ a, c) ∈ s, from assume a m hm, have nb : map f (comap e (nhds a)) ≠ ⊥, from map_ne_bot (h_e.dense_embedding h_dense).comap_nhds_neq_bot, have (f '' preimage e m) ∩ ({c | (c, ψ a) ∈ s } ∩ {c | (ψ a, c) ∈ s }) ∈ (map f (comap e (nhds a))).sets, from inter_mem_sets (image_mem_map $ preimage_mem_comap $ hm) (uniformly_extend_spec h_e h_dense h_f $ inter_mem_sets (mem_nhds_right _ hs) (mem_nhds_left _ hs)), inhabited_of_mem_sets nb this, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (@uniformity β _).sets, from h_f hs, have preimage (λp:β×β, (f p.1, f p.2)) s ∈ (comap (λx:β×β, (e x.1, e x.2)) uniformity).sets, by rwa [h_e.right.symm] at this, let ⟨t, ht, ts⟩ := this in show preimage (λp:(α×α), (ψ p.1, ψ p.2)) d ∈ uniformity.sets, from (@uniformity α _).sets_of_superset (interior_mem_uniformity ht) $ assume ⟨x₁, x₂⟩ hx_t, have nhds (x₁, x₂) ≤ principal (interior t), from is_open_iff_nhds.mp is_open_interior (x₁, x₂) hx_t, have interior t ∈ (filter.prod (nhds x₁) (nhds x₂)).sets, by rwa [nhds_prod_eq, le_principal_iff] at this, let ⟨m₁, hm₁, m₂, hm₂, (hm : set.prod m₁ m₂ ⊆ interior t)⟩ := mem_prod_iff.mp this in let ⟨a, ha₁, _, ha₂⟩ := h_pnt hm₁ in let ⟨b, hb₁, hb₂, _⟩ := h_pnt hm₂ in have set.prod (preimage e m₁) (preimage e m₂) ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s, from calc _ ⊆ preimage (λp:(β×β), (e p.1, e p.2)) (interior t) : preimage_mono hm ... ⊆ preimage (λp:(β×β), (e p.1, e p.2)) t : preimage_mono interior_subset ... ⊆ preimage (λp:(β×β), (f p.1, f p.2)) s : ts, have set.prod (f '' preimage e m₁) (f '' preimage e m₂) ⊆ s, from calc set.prod (f '' preimage e m₁) (f '' preimage e m₂) = (λp:(β×β), (f p.1, f p.2)) '' (set.prod (preimage e m₁) (preimage e m₂)) : prod_image_image_eq ... ⊆ (λp:(β×β), (f p.1, f p.2)) '' preimage (λp:(β×β), (f p.1, f p.2)) s : mono_image this ... ⊆ s : image_subset_iff.mpr $ subset.refl _, have (a, b) ∈ s, from @this (a, b) ⟨ha₁, hb₁⟩, hs_comp $ show (ψ x₁, ψ x₂) ∈ comp_rel s (comp_rel s s), from ⟨a, ha₂, ⟨b, this, hb₂⟩⟩ end uniform_extension end uniform_space end /-- Space of Cauchy filters This is essentially the completion of a uniform space. The embeddings are the neighbourhood filters. This space is not minimal, the separated uniform space (i.e. quotiented on the intersection of all entourages) is necessary for this. -/ def Cauchy (α : Type u) [uniform_space α] : Type u := { f : filter α // cauchy f } namespace Cauchy section parameters {α : Type u} [uniform_space α] def gen (s : set (α × α)) : set (Cauchy α × Cauchy α) := {p | s ∈ (filter.prod (p.1.val) (p.2.val)).sets } lemma monotone_gen : monotone gen := monotone_set_of $ assume p, @monotone_mem_sets (α×α) (filter.prod (p.1.val) (p.2.val)) private lemma symm_gen : map prod.swap (uniformity.lift' gen) ≤ uniformity.lift' gen := calc map prod.swap (uniformity.lift' gen) = uniformity.lift' (λs:set (α×α), {p | s ∈ (filter.prod (p.2.val) (p.1.val)).sets }) : begin delta gen, simp [map_lift'_eq, monotone_set_of, monotone_mem_sets, function.comp, image_swap_eq_preimage_swap] end ... ≤ uniformity.lift' gen : uniformity_lift_le_swap (monotone_comp (monotone_set_of $ assume p, @monotone_mem_sets (α×α) ((filter.prod ((p.2).val) ((p.1).val)))) monotone_principal) begin have h := λ(p:Cauchy α×Cauchy α), @filter.prod_comm _ _ (p.2.val) (p.1.val), simp [function.comp, h], exact le_refl _ end private lemma comp_rel_gen_gen_subset_gen_comp_rel {s t : set (α×α)} : comp_rel (gen s) (gen t) ⊆ (gen (comp_rel s t) : set (Cauchy α × Cauchy α)) := assume ⟨f, g⟩ ⟨h, h₁, h₂⟩, let ⟨t₁, (ht₁ : t₁ ∈ f.val.sets), t₂, (ht₂ : t₂ ∈ h.val.sets), (h₁ : set.prod t₁ t₂ ⊆ s)⟩ := mem_prod_iff.mp h₁ in let ⟨t₃, (ht₃ : t₃ ∈ h.val.sets), t₄, (ht₄ : t₄ ∈ g.val.sets), (h₂ : set.prod t₃ t₄ ⊆ t)⟩ := mem_prod_iff.mp h₂ in have t₂ ∩ t₃ ∈ h.val.sets, from inter_mem_sets ht₂ ht₃, let ⟨x, xt₂, xt₃⟩ := inhabited_of_mem_sets (h.property.left) this in (filter.prod f.val g.val).sets_of_superset (prod_mem_prod ht₁ ht₄) (assume ⟨a, b⟩ ⟨(ha : a ∈ t₁), (hb : b ∈ t₄)⟩, ⟨x, h₁ (show (a, x) ∈ set.prod t₁ t₂, from ⟨ha, xt₂⟩), h₂ (show (x, b) ∈ set.prod t₃ t₄, from ⟨xt₃, hb⟩)⟩) private lemma comp_gen : (uniformity.lift' gen).lift' (λs, comp_rel s s) ≤ uniformity.lift' gen := calc (uniformity.lift' gen).lift' (λs, comp_rel s s) = uniformity.lift' (λs, comp_rel (gen s) (gen s)) : begin rw [lift'_lift'_assoc], exact monotone_gen, exact (monotone_comp_rel monotone_id monotone_id) end ... ≤ uniformity.lift' (λs, gen $ comp_rel s s) : lift'_mono' $ assume s hs, comp_rel_gen_gen_subset_gen_comp_rel ... = (uniformity.lift' $ λs:set(α×α), comp_rel s s).lift' gen : begin rw [lift'_lift'_assoc], exact (monotone_comp_rel monotone_id monotone_id), exact monotone_gen end ... ≤ uniformity.lift' gen : lift'_mono comp_le_uniformity (le_refl _) instance completion_space : uniform_space (Cauchy α) := uniform_space.of_core { uniformity := uniformity.lift' gen, refl := principal_le_lift' $ assume s hs ⟨a, b⟩ (a_eq_b : a = b), a_eq_b ▸ a.property.right hs, symm := symm_gen, comp := comp_gen } theorem mem_uniformity {s : set (Cauchy α × Cauchy α)} : s ∈ (@uniformity (Cauchy α) _).sets ↔ ∃ t ∈ (@uniformity α _).sets, gen t ⊆ s := mem_lift'_sets monotone_gen theorem mem_uniformity' {s : set (Cauchy α × Cauchy α)} : s ∈ (@uniformity (Cauchy α) _).sets ↔ ∃ t ∈ (@uniformity α _).sets, ∀ f g : Cauchy α, t ∈ (filter.prod f.1 g.1).sets → (f, g) ∈ s := mem_uniformity.trans $ bex_congr $ λ t h, prod.forall /-- Embedding of `α` into its completion -/ def pure_cauchy (a : α) : Cauchy α := ⟨pure a, cauchy_pure⟩ lemma uniform_embedding_pure_cauchy : uniform_embedding (pure_cauchy : α → Cauchy α) := ⟨assume a₁ a₂ h, have (pure_cauchy a₁).val = (pure_cauchy a₂).val, from congr_arg _ h, have {a₁} = ({a₂} : set α), from principal_eq_iff_eq.mp this, by simp at this; assumption, have (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) = id, from funext $ assume s, set.ext $ assume ⟨a₁, a₂⟩, by simp [preimage, gen, pure_cauchy, prod_principal_principal], calc comap (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) (uniformity.lift' gen) = uniformity.lift' (preimage (λ (x : α × α), (pure_cauchy (x.fst), pure_cauchy (x.snd))) ∘ gen) : comap_lift'_eq monotone_gen ... = uniformity : by simp [this]⟩ lemma pure_cauchy_dense : ∀x, x ∈ closure (range pure_cauchy) := assume f, have h_ex : ∀s∈(@uniformity (Cauchy α) _).sets, ∃y:α, (f, pure_cauchy y) ∈ s, from assume s hs, let ⟨t'', ht''₁, (ht''₂ : gen t'' ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht'₁, ht'₂⟩ := comp_mem_uniformity_sets ht''₁ in have t' ∈ (filter.prod (f.val) (f.val)).sets, from f.property.right ht'₁, let ⟨t, ht, (h : set.prod t t ⊆ t')⟩ := mem_prod_same_iff.mp this in let ⟨x, (hx : x ∈ t)⟩ := inhabited_of_mem_sets f.property.left ht in have t'' ∈ (filter.prod f.val (pure x)).sets, from mem_prod_iff.mpr ⟨t, ht, {y:α | (x, y) ∈ t'}, assume y, begin simp, intro h, simp [h], exact refl_mem_uniformity ht'₁ end, assume ⟨a, b⟩ ⟨(h₁ : a ∈ t), (h₂ : (x, b) ∈ t')⟩, ht'₂ $ prod_mk_mem_comp_rel (@h (a, x) ⟨h₁, hx⟩) h₂⟩, ⟨x, ht''₂ $ by dsimp [gen]; exact this⟩, begin simp [closure_eq_nhds, nhds_eq_uniformity, lift'_inf_principal_eq, set.inter_comm], exact (lift'_neq_bot_iff $ monotone_inter monotone_const monotone_preimage).mpr (assume s hs, let ⟨y, hy⟩ := h_ex s hs in have pure_cauchy y ∈ range pure_cauchy ∩ {y : Cauchy α | (f, y) ∈ s}, from ⟨mem_range_self y, hy⟩, ne_empty_of_mem this) end instance : complete_space (Cauchy α) := complete_space_extension uniform_embedding_pure_cauchy pure_cauchy_dense $ assume f hf, let f' : Cauchy α := ⟨f, hf⟩ in have map pure_cauchy f ≤ uniformity.lift' (preimage (prod.mk f')), from le_lift' $ assume s hs, let ⟨t, ht₁, (ht₂ : gen t ⊆ s)⟩ := (mem_lift'_sets monotone_gen).mp hs in let ⟨t', ht', (h : set.prod t' t' ⊆ t)⟩ := mem_prod_same_iff.mp (hf.right ht₁) in have t' ⊆ { y : α | (f', pure_cauchy y) ∈ gen t }, from assume x hx, (filter.prod f (pure x)).sets_of_superset (prod_mem_prod ht' $ mem_pure hx) h, f.sets_of_superset ht' $ subset.trans this (preimage_mono ht₂), ⟨f', by simp [nhds_eq_uniformity]; assumption⟩ end end Cauchy instance nonempty_Cauchy {α : Type u} [h : nonempty α] [uniform_space α] : nonempty (Cauchy α) := h.rec_on $ assume a, nonempty.intro $ Cauchy.pure_cauchy a instance inhabited_Cauchy {α : Type u} [inhabited α] [uniform_space α] : inhabited (Cauchy α) := ⟨Cauchy.pure_cauchy $ default α⟩ section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, s.uniformity ≤ t.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, @le_trans _ _ c.uniformity b.uniformity a.uniformity h₂ h₁ } instance : has_Sup (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma le_Sup {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : t ≤ Sup tt := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma Sup_le {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t' ≤ t) : Sup tt ≤ t := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_bot (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_top (uniform_space α) := ⟨{ to_topological_space := ⊤, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c h₁ h₂, Sup_le $ assume t', begin simp, intro h, cases h with h h, repeat { subst h; assumption } end, inf := λa b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := assume a b c h₁ h₂, le_Sup ⟨h₁, h₂⟩, inf_le_left := assume a b, Sup_le $ assume x ⟨ha, hb⟩, ha, inf_le_right := assume a b, Sup_le $ assume x ⟨ha, hb⟩, hb, top := ⊤, le_top := assume u, u.refl, bot := ⊥, bot_le := assume a, show a.uniformity ≤ ⊤, from le_top, Sup := Sup, le_Sup := assume s u, le_Sup, Sup_le := assume s u, Sup_le, Inf := λtt, Sup {t | ∀t'∈tt, t ≤ t'}, le_Inf := assume s a hs, le_Sup hs, Inf_le := assume s a ha, Sup_le $ assume u hs, hs _ ha, ..uniform_space.partial_order } lemma supr_uniformity {ι : Sort*} {u : ι → uniform_space α} : (supr u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, a = u i), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : a = u i)⟩, ha.symm ▸ infi_le _ _) lemma sup_uniformity {u v : uniform_space α} : (u ⊔ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊔ v) = (⨆i (h : i = u ∨ i = v), i), by simp [supr_or, supr_sup_eq], calc (u ⊔ v).uniformity = ((⨆i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [supr_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊤⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_comap.comp tendsto_swap_uniformity, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced_eq_comap, mem_nhds_uniformity_iff, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff.1 $ mem_nhds_left _ ht⟩ } end } lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := eq_of_nhds_eq_nhds $ assume a, begin simp [nhds_induced_eq_comap, nhds_eq_uniformity, nhds_eq_uniformity], change comap f (uniformity.lift' (preimage (λb, (f a, b)))) = (u.uniformity.comap (λp:α×α, (f p.1, f p.2))).lift' (preimage (λa', (a, a'))), rw [comap_lift'_eq monotone_preimage, comap_lift'_eq2 monotone_preimage], exact rfl end lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := rfl lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := bot_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊥) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊥) lemma to_topological_space_supr {ι : Sort*} {u : ι → uniform_space α} : @uniform_space.to_topological_space α (supr u) = (⨆i, @uniform_space.to_topological_space α (u i)) := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_supr, nhds_eq_uniformity], change _ = (supr u).uniformity.lift' (preimage $ prod.mk a), begin rw [supr_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, @nhds_eq_uniformity α (u i) a), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (have supr u = ⊥, from bot_unique $ supr_le $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (supr u) = ⊥, from this.symm ▸ to_topological_space_bot, this.symm ▸ bot_le) (supr_le $ assume i, to_topological_space_mono $ le_supr _ _)) lemma to_topological_space_Sup {s : set (uniform_space α)} : @uniform_space.to_topological_space α (Sup s) = (⨆i∈s, @uniform_space.to_topological_space α i) := begin rw [Sup_eq_supr, to_topological_space_supr], apply congr rfl, funext x, exact to_topological_space_supr end lemma to_topological_space_sup {u v : uniform_space α} : @uniform_space.to_topological_space α (u ⊔ v) = @uniform_space.to_topological_space α u ⊔ @uniform_space.to_topological_space α v := ord_continuous_sup $ assume s, to_topological_space_Sup instance : uniform_space empty := ⊤ instance : uniform_space unit := ⊤ instance : uniform_space bool := ⊤ instance : uniform_space ℕ := ⊤ instance : uniform_space ℤ := ⊤ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : (@uniformity (subtype p) _) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) uniformity := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ (nhds a).sets) : tendsto f (nhds a) (nhds (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_tendsto.mp hf.continuous _) instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊔ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊔ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_sup, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : @uniformity (α × β) _ = uniformity.comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ uniformity.comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := sup_uniformity lemma uniform_embedding_subtype_emb {α : Type*} {β : Type*} [uniform_space α] [uniform_space β] (p : α → Prop) {e : α → β} (ue : uniform_embedding e) (de : dense_embedding e) : uniform_embedding (de.subtype_emb p) := ⟨(de.subtype p).inj, by simp [comap_comap_comp, (∘), dense_embedding.subtype_emb, uniformity_subtype, ue.right.symm]⟩ lemma uniform_extend_subtype {α : Type*} {β : Type*} {γ : Type*} [uniform_space α] [uniform_space β] [uniform_space γ] [complete_space γ] [inhabited γ] [separated γ] {p : α → Prop} {e : α → β} {f : α → γ} {b : β} {s : set α} (hf : uniform_continuous (λx:subtype p, f x.val)) (he : uniform_embedding e) (hd : ∀x:β, x ∈ closure (range e)) (hb : closure (e '' s) ∈ (nhds b).sets) (hs : is_closed s) (hp : ∀x∈s, p x) : ∃c, tendsto f (comap e (nhds b)) (nhds c) := have de : dense_embedding e, from he.dense_embedding hd, have de' : dense_embedding (de.subtype_emb p), by exact de.subtype p, have ue' : uniform_embedding (de.subtype_emb p), from uniform_embedding_subtype_emb _ he de, have b ∈ closure (e '' {x | p x}), from (closure_mono $ mono_image $ hp) (mem_of_nhds hb), let ⟨c, (hc : tendsto (f ∘ subtype.val) (comap (de.subtype_emb p) (nhds ⟨b, this⟩)) (nhds c))⟩ := uniformly_extend_exists ue' de'.dense hf in begin rw [nhds_subtype_eq_comap] at hc, simp [comap_comap_comp] at hc, change (tendsto (f ∘ @subtype.val α p) (comap (e ∘ @subtype.val α p) (nhds b)) (nhds c)) at hc, rw [←comap_comap_comp] at hc, existsi c, apply tendsto_comap'' s _ _ hc, exact ⟨_, hb, assume x, begin change e x ∈ (closure (e '' s)) → x ∈ s, rw [←closure_induced, closure_eq_nhds], dsimp, rw [nhds_induced_eq_comap, de.induced], change x ∈ {x | nhds x ⊓ principal s ≠ ⊥} → x ∈ s, rw [←closure_eq_nhds, closure_eq_of_is_closed hs], exact id, exact de.inj end⟩, exact (assume x hx, ⟨⟨x, hp x hx⟩, rfl⟩) end /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : @uniformity (α×β) _ = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod uniformity uniformity) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp] lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ (@uniformity α _).sets) (hb : b ∈ (@uniformity β _).sets) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _).sets := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) uniformity uniformity := le_trans (map_mono (@le_sup_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) uniformity uniformity := le_trans (map_mono (@le_sup_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := uniform_continuous.comp (uniform_continuous.prod_mk uniform_continuous_id uniform_continuous_const) h lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := uniform_continuous.comp (uniform_continuous.prod_mk uniform_continuous_const uniform_continuous_id) h instance complete_space.prod [complete_space α] [complete_space β] : complete_space (α × β) := { complete := λ f hf, let ⟨x1, hx1⟩ := complete_space.complete $ cauchy_map uniform_continuous_fst hf in let ⟨x2, hx2⟩ := complete_space.complete $ cauchy_map uniform_continuous_snd hf in ⟨(x1, x2), by rw [nhds_prod_eq, filter.prod_def]; from filter.le_lift (λ s hs, filter.le_lift' $ λ t ht, have H1 : prod.fst ⁻¹' s ∈ f.sets := hx1 hs, have H2 : prod.snd ⁻¹' t ∈ f.sets := hx2 ht, filter.inter_mem_sets H1 H2)⟩ } lemma uniform_embedding.prod {α' : Type*} {β' : Type*} [uniform_space α] [uniform_space β] [uniform_space α'] [uniform_space β'] {e₁ : α → α'} {e₂ : β → β'} (h₁ : uniform_embedding e₁) (h₂ : uniform_embedding e₂) : uniform_embedding (λp:α×β, (e₁ p.1, e₂ p.2)) := ⟨assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, by simp [prod.mk.inj_iff]; exact assume eq₁ eq₂, ⟨h₁.left eq₁, h₂.left eq₂⟩, by simp [(∘), uniformity_prod, h₁.right.symm, h₂.right.symm, comap_inf, comap_comap_comp]⟩ lemma to_topological_space_prod [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section separation_space local attribute [instance] separation_setoid lemma uniform_continuous_quotient_lift₂ [uniform_space γ] {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ separation_rel α → (c, d) ∈ separation_rel β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split ; intro h, { exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rcases h with ⟨eqv_α, eqv_β⟩, intros r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ (p : (α × β) × α × β), ((p.fst).fst, (p.snd).fst), let p_β := λ (p : (α × β) × α × β), ((p.fst).snd, (p.snd).snd), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, by simp[p_α, eqv_α r_α r_α_in], have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, by simp[p_β, eqv_β r_β r_β_in], exact H ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated α] [separated β] : separated (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end separation_space end constructions lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ (@uniformity α _).sets, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ (@uniformity α _).sets), {y | (x, y) ∈ comp_rel m n} ⊆ c i}, have hu₁ : ∀ n ∈ (@uniformity α _).sets, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply uniformity.sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ (@uniformity α _).sets, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases compact_elim_finite_subcover_image hs hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ (@uniformity α _).sets, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂
2756605a0c94e0d2fdefdba5503ee04e32434ea1
fe84e287c662151bb313504482b218a503b972f3
/src/exercises/loh/seminorms.lean
5486c78db77411444c00e39ed6cd06dd98a37ffd
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
6,505
lean
import data.real.basic import algebra.category.Group.basic import category_theory.functor category_theory.yoneda import analysis.normed.group.SemiNormedGroup notation `Ab` := AddCommGroup universes u noncomputable theory open category_theory instance : concrete_category Ab := by apply_instance @[protect_proj, ancestor semi_normed_group] class homogeneous_semi_normed_group (E : Type*) extends semi_normed_group E := (is_homogeneous : ∀ (n : ℤ) (a : E), norm ( n • a ) = (abs n) * (norm a)) @[reducible] def homogeneous_semi_normed_group.induced {F} [homogeneous_semi_normed_group F] {E} [add_comm_group E] (f : E →+ F) : homogeneous_semi_normed_group E := { is_homogeneous := λ n a, by { change ∥ f (n • a) ∥ = _ * ∥ f a ∥, rw[add_monoid_hom.map_zsmul, homogeneous_semi_normed_group.is_homogeneous] }, .. semi_normed_group.induced f } instance : bundled_hom.parent_projection @homogeneous_semi_normed_group.to_semi_normed_group := ⟨⟩ def homogeneous_normed_group_hom (V W : Type*) [homogeneous_semi_normed_group V] [homogeneous_semi_normed_group W] := normed_group_hom V W def HSNAb : Type (u + 1) := bundled homogeneous_semi_normed_group namespace HSNAb attribute [derive [large_category, concrete_category]] HSNAb instance : has_coe_to_sort HSNAb (Type u) := bundled.has_coe_to_sort def of (M : Type u) [homogeneous_semi_normed_group M] : HSNAb := bundled.of M instance (M : HSNAb) : homogeneous_semi_normed_group M := M.str end HSNAb def HSNAb₁ : Type (u+1) := bundled homogeneous_semi_normed_group namespace HSNAb₁ instance : has_coe_to_sort HSNAb₁ (Type u) := bundled.has_coe_to_sort instance : large_category.{u} HSNAb₁ := { hom := λ X Y, { f : normed_group_hom X Y // f.norm_noninc }, id := λ X, ⟨normed_group_hom.id X, normed_group_hom.norm_noninc.id⟩, comp := λ X Y Z f g, ⟨(g : normed_group_hom Y Z).comp (f : normed_group_hom X Y), g.2.comp f.2⟩, } @[ext] lemma hom_ext {M N : HSNAb₁} (f g : M ⟶ N) (w : (f : M → N) = (g : M → N)) : f = g := subtype.eq (normed_group_hom.ext (congr_fun w)) instance : concrete_category.{u} HSNAb₁ := { forget := { obj := λ X, X, map := λ X Y f, f, }, forget_faithful := {} } instance has_forget_Ab : category_theory.has_forget₂ HSNAb₁ Ab := { forget₂ := { obj := λ A, AddCommGroup.of A, map := λ A B f, AddCommGroup.of_hom (normed_group_hom.to_add_monoid_hom f) } } notation `U` := HSNAb₁.has_forget_Ab.forget₂ instance (A : HSNAb₁) : homogeneous_semi_normed_group (AddCommGroup.of A) := A.str end HSNAb₁ def transfer {A : Ab} {A' : HSNAb₁} (f : A ≅ AddCommGroup.of A') : homogeneous_semi_normed_group A := homogeneous_semi_normed_group.induced f.hom variables {C : Type*} [category C] def is_wf_pair {F : C ⥤ Ab} {X Y : C} (α : F.obj X) (β : F.obj Y) := ∀ (n : ℕ), ∃ (m : ℤ) (f : X ⟶ Y), m.nat_abs ≥ n ∧ (F.map f) α = m • β def is_weakly_flexible {F : C ⥤ Ab} {Y : C} (β : F.obj Y) := ∃ (X : C) (α : F.obj X), is_wf_pair α β structure functorial_semi_norm (F : C ⥤ Ab) := (lift : C ⥤ HSNAb₁) (lift_iso : F ≅ (lift ⋙ U)) example (n : ℕ) (x : ℝ) : n • x = (n : ℝ) * x := by library_search example (n m : ℕ) (h : n ≤ m) : (n : ℝ) ≤ (m : ℝ) := nat.cast_le.mpr h example (x y z : ℝ) (h : 0 ≤ x) (h' : y ≤ z) : x * y ≤ x * z := mul_le_mul_of_nonneg_left h' h lemma is_zero_of_bounds {c d : ℝ} (hc : c ≥ 0) (hd : d ≥ 0) (h : ∀ n : ℕ, ∃ m : ℕ, n ≤ m ∧ (m : ℝ) * c ≤ d ) : c = 0 := begin by_contra h', change c ≠ 0 at h', replace h' := lt_of_le_of_ne hc h'.symm, rcases (archimedean.arch (d + 1) h') with ⟨n, hn⟩, rw[nsmul_eq_mul] at hn, rcases (h n) with ⟨m, hnm, hm⟩, exact not_le_of_gt (lt_add_one d) (le_trans hn (le_trans (mul_le_mul_of_nonneg_right (nat.cast_le.mpr hnm) hc) hm)) end lemma zero_norm_of_fsn {F : C ⥤ Ab} (F' : functorial_semi_norm F) {Y : C} {β : F.obj Y} (h : is_weakly_flexible β) : (norm : F'.lift.obj Y → ℝ) ((F'.lift_iso.app Y).hom β) = 0 := begin rcases h with ⟨X,α,hα⟩, let fX : F.obj X ≅ AddCommGroup.of (F'.lift.obj X) := F'.lift_iso.app X, let fY : F.obj Y ≅ AddCommGroup.of (F'.lift.obj Y) := F'.lift_iso.app Y, let α' := fX.hom α, let β' := fY.hom β, change ∥ β' ∥ = 0, apply is_zero_of_bounds (norm_nonneg β') (norm_nonneg α'), intro n, rcases (hα n) with ⟨m, g, hnm, hg⟩, use m.nat_abs, split, exact hnm, rw[int.cast_nat_abs, ← homogeneous_semi_normed_group.is_homogeneous], let g' : F'.lift.obj X ⟶ F'.lift.obj Y := F'.lift.map g, have : g' α' = m • β' := by { have := congr_hom (F'.lift_iso.hom.naturality g) α, change fY.hom ((F.map g) α) = g' (fX.hom α) at this, rw[hg, fY.hom.map_zsmul] at this, symmetry, exact this }, rw[← this], exact g'.property α' end def is_indiscrete (A : HSNAb₁) := ∀ (a : A), ∥ a ∥ = 0 def UAb : Ab ⥤ Type u := AddCommGroup.concrete_category.forget lemma corep_is_wf {F : C ⥤ Ab} [functor.corepresentable (F ⋙ UAb)] {Y : C} (β : F.obj Y) : is_weakly_flexible β := begin have c : functor.corepresentable (F ⋙ UAb) := by apply_instance, rcases c with ⟨T, p, hp⟩, let T' : C := opposite.unop T, haveI := hp, let p' : (T' ⟶ Y) → (F.obj Y) := p.app Y, let p'' : (F.obj Y) → (T' ⟶ Y) := ((as_iso p).app Y).inv, let u : (F.obj T') := p.app T' (𝟙 T'), let v : ∀ (n : ℤ), T' ⟶ Y := λ n, p'' (n • β), have hv : ∀ (n : ℤ), (F.map (v n)) u = n • β := λ n, begin have h : p' (v n) = (p' ∘ p'') (n • β) := rfl, have : p' ∘ p'' = id := ((as_iso p).app Y).inv_hom_id, rw[this, id.def] at h, rw[← h], have : p' (v n) = p' ((coyoneda.obj T).map (v n) (𝟙 T')) := by simp, rw[this], change (F.map (v n)) (p.app T' (𝟙 T')) = (p.app Y) _, have := (congr_hom (p.naturality (v n)) (𝟙 T')).symm, exact this, end, use T', use u, intro n, use n, use (v n), split, exact le_refl _, exact hv n end lemma corep_fsn_indiscrete {F : C ⥤ Ab} [functor.corepresentable (F ⋙ UAb)] (F' : functorial_semi_norm F) : ∀ (X : C), is_indiscrete (F'.lift.obj X) := begin intros Y β', let β : F.obj Y := (F'.lift_iso.app Y).inv β', have : β' = (F'.lift_iso.app Y).hom β := (congr_hom (F'.lift_iso.app Y).inv_hom_id β').symm, rw[this], exact zero_norm_of_fsn F' (corep_is_wf β), end
ba03f1b49e5fee0d2eca52b99ee399e5399fbefa
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/monoidal/internal/functor_category.lean
11f40f0aa9533f4b4a8fe8a88af23c3240b60129
[ "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
7,132
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.CommMon_ import category_theory.monoidal.functor_category /-! # `Mon_ (C ⥤ D) ≌ C ⥤ Mon_ D` When `D` is a monoidal category, monoid objects in `C ⥤ D` are the same thing as functors from `C` into the monoid objects of `D`. This is formalised as: * `Mon_functor_category_equivalence : Mon_ (C ⥤ D) ≌ C ⥤ Mon_ D` The intended application is that as `Ring ≌ Mon_ Ab` (not yet constructed!), we have `presheaf Ring X ≌ presheaf (Mon_ Ab) X ≌ Mon_ (presheaf Ab X)`, and we can model a module over a presheaf of rings as a module object in `presheaf Ab X`. ## Future work Presumably this statement is not specific to monoids, and could be generalised to any internal algebraic objects, if the appropriate framework was available. -/ universes v₁ v₂ u₁ u₂ open category_theory open category_theory.monoidal_category namespace category_theory.monoidal variables (C : Type u₁) [category.{v₁} C] variables (D : Type u₂) [category.{v₂} D] [monoidal_category.{v₂} D] namespace Mon_functor_category_equivalence variables {C D} /-- Functor translating a monoid object in a functor category to a functor into the category of monoid objects. -/ @[simps] def functor : Mon_ (C ⥤ D) ⥤ (C ⥤ Mon_ D) := { obj := λ A, { obj := λ X, { X := A.X.obj X, one := A.one.app X, mul := A.mul.app X, one_mul' := congr_app A.one_mul X, mul_one' := congr_app A.mul_one X, mul_assoc' := congr_app A.mul_assoc X, }, map := λ X Y f, { hom := A.X.map f, one_hom' := by { rw [←A.one.naturality, tensor_unit_map], dsimp, rw [category.id_comp], }, mul_hom' := by { dsimp, rw [←A.mul.naturality, tensor_obj_map], }, }, map_id' := λ X, by { ext, dsimp, rw [category_theory.functor.map_id], }, map_comp' := λ X Y Z f g, by { ext, dsimp, rw [functor.map_comp], }, }, map := λ A B f, { app := λ X, { hom := f.hom.app X, one_hom' := congr_app f.one_hom X, mul_hom' := congr_app f.mul_hom X, }, }, } /-- Functor translating a functor into the category of monoid objects to a monoid object in the functor category -/ @[simps] def inverse : (C ⥤ Mon_ D) ⥤ Mon_ (C ⥤ D) := { obj := λ F, { X := F ⋙ Mon_.forget D, one := { app := λ X, (F.obj X).one, }, mul := { app := λ X, (F.obj X).mul, }, one_mul' := by { ext X, exact (F.obj X).one_mul, }, mul_one' := by { ext X, exact (F.obj X).mul_one, }, mul_assoc' := by { ext X, exact (F.obj X).mul_assoc, }, }, map := λ F G α, { hom := { app := λ X, (α.app X).hom, naturality' := λ X Y f, congr_arg Mon_.hom.hom (α.naturality f), }, one_hom' := by { ext x, dsimp, rw [(α.app x).one_hom], }, mul_hom' := by { ext x, dsimp, rw [(α.app x).mul_hom], }, }, } /-- The unit for the equivalence `Mon_ (C ⥤ D) ≌ C ⥤ Mon_ D`. -/ @[simps] def unit_iso : 𝟭 (Mon_ (C ⥤ D)) ≅ functor ⋙ inverse := nat_iso.of_components (λ A, { hom := { hom := { app := λ _, 𝟙 _ }, one_hom' := by { ext X, dsimp, simp only [category.comp_id], }, mul_hom' := by { ext X, dsimp, simp only [tensor_id, category.id_comp, category.comp_id], }, }, inv := { hom := { app := λ _, 𝟙 _ }, one_hom' := by { ext X, dsimp, simp only [category.comp_id], }, mul_hom' := by { ext X, dsimp, simp only [tensor_id, category.id_comp, category.comp_id], }, }, }) (λ A B f, begin ext X, simp only [functor.id_map, functor.comp_map, functor_map_app_hom, Mon_.comp_hom', category.id_comp, category.comp_id, inverse_map_hom_app, nat_trans.comp_app], end) /-- The counit for the equivalence `Mon_ (C ⥤ D) ≌ C ⥤ Mon_ D`. -/ @[simps] def counit_iso : inverse ⋙ functor ≅ 𝟭 (C ⥤ Mon_ D) := nat_iso.of_components (λ A, nat_iso.of_components (λ X, { hom := { hom := 𝟙 _ }, inv := { hom := 𝟙 _ } }) (by tidy)) (by tidy) end Mon_functor_category_equivalence open Mon_functor_category_equivalence /-- When `D` is a monoidal category, monoid objects in `C ⥤ D` are the same thing as functors from `C` into the monoid objects of `D`. -/ @[simps] def Mon_functor_category_equivalence : Mon_ (C ⥤ D) ≌ C ⥤ Mon_ D := { functor := functor, inverse := inverse, unit_iso := unit_iso, counit_iso := counit_iso, } variables [braided_category.{v₂} D] namespace CommMon_functor_category_equivalence variables {C D} /-- Functor translating a commutative monoid object in a functor category to a functor into the category of commutative monoid objects. -/ @[simps] def functor : CommMon_ (C ⥤ D) ⥤ (C ⥤ CommMon_ D) := { obj := λ A, { obj := λ X, { mul_comm' := congr_app A.mul_comm X, ..((Mon_functor_category_equivalence C D).functor.obj A.to_Mon_).obj X, }, ..((Mon_functor_category_equivalence C D).functor.obj A.to_Mon_) }, map := λ A B f, { app := λ X, ((Mon_functor_category_equivalence C D).functor.map f).app X, }, } /-- Functor translating a functor into the category of commutative monoid objects to a commutative monoid object in the functor category -/ @[simps] def inverse : (C ⥤ CommMon_ D) ⥤ CommMon_ (C ⥤ D) := { obj := λ F, { mul_comm' := by { ext X, exact (F.obj X).mul_comm, }, ..(Mon_functor_category_equivalence C D).inverse.obj (F ⋙ CommMon_.forget₂_Mon_ D), }, map := λ F G α, (Mon_functor_category_equivalence C D).inverse.map (whisker_right α _), } /-- The unit for the equivalence `CommMon_ (C ⥤ D) ≌ C ⥤ CommMon_ D`. -/ @[simps] def unit_iso : 𝟭 (CommMon_ (C ⥤ D)) ≅ functor ⋙ inverse := nat_iso.of_components (λ A, { hom := { hom := { app := λ _, 𝟙 _ }, one_hom' := by { ext X, dsimp, simp only [category.comp_id], }, mul_hom' := by { ext X, dsimp, simp only [tensor_id, category.id_comp, category.comp_id], }, }, inv := { hom := { app := λ _, 𝟙 _ }, one_hom' := by { ext X, dsimp, simp only [category.comp_id], }, mul_hom' := by { ext X, dsimp, simp only [tensor_id, category.id_comp, category.comp_id], }, }, }) (λ A B f, begin ext X, dsimp, simp only [category.id_comp, category.comp_id], end) /-- The counit for the equivalence `CommMon_ (C ⥤ D) ≌ C ⥤ CommMon_ D`. -/ @[simps] def counit_iso : inverse ⋙ functor ≅ 𝟭 (C ⥤ CommMon_ D) := nat_iso.of_components (λ A, nat_iso.of_components (λ X, { hom := { hom := 𝟙 _ }, inv := { hom := 𝟙 _ } }) (by tidy)) (by tidy) end CommMon_functor_category_equivalence open CommMon_functor_category_equivalence /-- When `D` is a braided monoidal category, commutative monoid objects in `C ⥤ D` are the same thing as functors from `C` into the commutative monoid objects of `D`. -/ @[simps] def CommMon_functor_category_equivalence : CommMon_ (C ⥤ D) ≌ C ⥤ CommMon_ D := { functor := functor, inverse := inverse, unit_iso := unit_iso, counit_iso := counit_iso, } end category_theory.monoidal
a6d687ecb2a77006e07f289f46a5d72dde8e8330
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/finset/pairwise.lean
d71306e29b6c148d4f27fdf605cea003332f4c7a
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
3,485
lean
/- Copyright (c) 2021 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.lattice /-! # Relations holding pairwise on finite sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove a few results about the interaction of `set.pairwise_disjoint` and `finset`, as well as the interaction of `list.pairwise disjoint` and the condition of `disjoint` on `list.to_finset`, in `set` form. -/ open finset variables {α ι ι' : Type*} instance [decidable_eq α] {r : α → α → Prop} [decidable_rel r] {s : finset α} : decidable ((s : set α).pairwise r) := decidable_of_iff' (∀ a ∈ s, ∀ b ∈ s, a ≠ b → r a b) iff.rfl lemma finset.pairwise_disjoint_range_singleton : (set.range (singleton : α → finset α)).pairwise_disjoint id := begin rintro _ ⟨a, rfl⟩ _ ⟨b, rfl⟩ h, exact disjoint_singleton.2 (ne_of_apply_ne _ h), end namespace set lemma pairwise_disjoint.elim_finset {s : set ι} {f : ι → finset α} (hs : s.pairwise_disjoint f) {i j : ι} (hi : i ∈ s) (hj : j ∈ s) (a : α) (hai : a ∈ f i) (haj : a ∈ f j) : i = j := hs.elim hi hj (finset.not_disjoint_iff.2 ⟨a, hai, haj⟩) lemma pairwise_disjoint.image_finset_of_le [decidable_eq ι] [semilattice_inf α] [order_bot α] {s : finset ι} {f : ι → α} (hs : (s : set ι).pairwise_disjoint f) {g : ι → ι} (hf : ∀ a, f (g a) ≤ f a) : (s.image g : set ι).pairwise_disjoint f := begin rw coe_image, exact hs.image_of_le hf, end variables [lattice α] [order_bot α] /-- Bind operation for `set.pairwise_disjoint`. In a complete lattice, you can use `set.pairwise_disjoint.bUnion`. -/ lemma pairwise_disjoint.bUnion_finset {s : set ι'} {g : ι' → finset ι} {f : ι → α} (hs : s.pairwise_disjoint (λ i' : ι', (g i').sup f)) (hg : ∀ i ∈ s, (g i : set ι).pairwise_disjoint f) : (⋃ i ∈ s, ↑(g i)).pairwise_disjoint f := begin rintro a ha b hb hab, simp_rw set.mem_Union at ha hb, obtain ⟨c, hc, ha⟩ := ha, obtain ⟨d, hd, hb⟩ := hb, obtain hcd | hcd := eq_or_ne (g c) (g d), { exact hg d hd (by rwa hcd at ha) hb hab }, { exact (hs hc hd (ne_of_apply_ne _ hcd)).mono (finset.le_sup ha) (finset.le_sup hb) } end end set namespace list variables {β : Type*} [decidable_eq α] {r : α → α → Prop} {l : list α} lemma pairwise_of_coe_to_finset_pairwise (hl : (l.to_finset : set α).pairwise r) (hn : l.nodup) : l.pairwise r := by { rw coe_to_finset at hl, exact hn.pairwise_of_set_pairwise hl } lemma pairwise_iff_coe_to_finset_pairwise (hn : l.nodup) (hs : symmetric r) : (l.to_finset : set α).pairwise r ↔ l.pairwise r := by { rw [coe_to_finset, hn.pairwise_coe], exact ⟨hs⟩ } lemma pairwise_disjoint_of_coe_to_finset_pairwise_disjoint {α ι} [semilattice_inf α] [order_bot α] [decidable_eq ι] {l : list ι} {f : ι → α} (hl : (l.to_finset : set ι).pairwise_disjoint f) (hn : l.nodup) : l.pairwise (_root_.disjoint on f) := pairwise_of_coe_to_finset_pairwise hl hn lemma pairwise_disjoint_iff_coe_to_finset_pairwise_disjoint {α ι} [semilattice_inf α] [order_bot α] [decidable_eq ι] {l : list ι} {f : ι → α} (hn : l.nodup) : (l.to_finset : set ι).pairwise_disjoint f ↔ l.pairwise (_root_.disjoint on f) := pairwise_iff_coe_to_finset_pairwise hn (symmetric_disjoint.comap f) end list
a713ce0612c876215181615c1891497f9dbd288d
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world2/level2.lean
605724b38b6d8f32a2b7310101ebcacb43624f8f
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
1,911
lean
import mynat.definition -- hide import mynat.add -- hide import game.world2.level1 -- hide namespace mynat -- hide /- # Addition world Don't forget to use the drop down boxes on the left to see your tactics and what you have proved so far. ## Level 2: `add_assoc` -- associativity of addition. It's well-known that (1 + 2) + 3 = 1 + (2 + 3) -- if we have three numbers to add up, it doesn't matter which of the additions we do first. This fact is called *associativity of addition* by mathematicians, and it is *not* obvious. For example, subtraction really is not associative: $(6 - 2) - 1$ is really not equal to $6 - (2 - 1)$. We are going to have to prove that addition, as defined the way we've defined it, is associative. See if you can prove associativity of addition. Hint: because addition was defined by recursion on the right-most variable, use induction on the right-most variable (try other variables at your peril!). Note that when Lean writes `a + b + c`, it means `(a + b) + c`. If it wants to talk about `a + (b + c)` it will put the brackets in explictly. Reminder: you are done when you see "Proof complete!" in the top right, and an empty box (no errors) in the bottom right. You can move between levels and worlds (i.e. you can go back and review old stuff) without losing anything. Once you're done with associativity (sub-boss), we can move on to commutativity (boss). -/ /- Lemma On the set of natural numbers, addition is associative. In other words, for all natural numbers $a, b$ and $c$, we have $$ (a + b) + c = a + (b + c). $$ -/ lemma add_assoc (a b c : mynat) : (a + b) + c = a + (b + c) := begin [nat_num_game] induction c with d hd, { -- ⊢ a + b + 0 = a + (b + 0) rw add_zero, rw add_zero, refl }, { -- ⊢ (a + b) + succ d = a + (b + succ d) rw add_succ, rw add_succ, rw add_succ, rw hd, refl, } end end mynat -- hide
86c4c3498e90b1f069033c174d430f4b6e72d4c7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/group/bounds.lean
85767cd6b059e00038902148803e03580399f13e
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,162
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 order.bounds.basic import algebra.order.group.defs /-! # Least upper bound and the greatest lower bound in linear ordered additive commutative groups -/ variables {α : Type*} section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] {s : set α} {a ε : α} lemma is_glb.exists_between_self_add (h : is_glb s a) (hε : 0 < ε) : ∃ b ∈ s, a ≤ b ∧ b < a + ε := h.exists_between $ lt_add_of_pos_right _ hε lemma is_glb.exists_between_self_add' (h : is_glb s a) (h₂ : a ∉ s) (hε : 0 < ε) : ∃ b ∈ s, a < b ∧ b < a + ε := h.exists_between' h₂ $ lt_add_of_pos_right _ hε lemma is_lub.exists_between_sub_self (h : is_lub s a) (hε : 0 < ε) : ∃ b ∈ s, a - ε < b ∧ b ≤ a := h.exists_between $ sub_lt_self _ hε lemma is_lub.exists_between_sub_self' (h : is_lub s a) (h₂ : a ∉ s) (hε : 0 < ε) : ∃ b ∈ s, a - ε < b ∧ b < a := h.exists_between' h₂ $ sub_lt_self _ hε end linear_ordered_add_comm_group
e295b2341b33954838e8f9fd8aaf1f55050dc3be
78630e908e9624a892e24ebdd21260720d29cf55
/src/logic_first_order/fol_20.lean
7b47ede5e494a43908a3611f88843273b8c5c28a
[ "CC0-1.0" ]
permissive
tomasz-lisowski/lean-logic-examples
84e612466776be0a16c23a0439ff8ef6114ddbe1
2b2ccd467b49c3989bf6c92ec0358a8d6ee68c5d
refs/heads/master
1,683,334,199,431
1,621,938,305,000
1,621,938,305,000
365,041,573
1
0
null
null
null
null
UTF-8
Lean
false
false
526
lean
namespace fol_20 variable U : Type variable R : U → U → Prop theorem fol_20 : (∀ x y, R x y → R y x) → (∀ x y z, (R x y ∧ R y z) → R x z) → (∀ x y, R x y → R x x) := assume h1: ∀ x y, R x y → R y x, assume h2: ∀ x y z, (R x y ∧ R y z) → R x z, assume t: U, assume s: U, have h3: R t s → R s t, from h1 t s, have h4: (R t s ∧ R s t) → R t t, from h2 t s t, assume h5: R t s, have h6: R s t, from h3 h5, have h7: R t s ∧ R s t, from and.intro h5 h6, show R t t, from h4 h7 end fol_20
6f633ae481e2df722f229ead7658ce71cf4ab37e
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/data/padics/padic_integers.lean
43303ce7b1f4cbf509f56125b4a09112b17343c4
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
10,423
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis, Mario Carneiro -/ import data.padics.padic_numbers ring_theory.ideals data.int.modeq /-! # p-adic integers This file defines the p-adic integers ℤ_p as the subtype of ℚ_p with norm ≤ 1. We show that ℤ_p is a complete nonarchimedean normed local ring. ## Important definitions * `padic_int` : the type of p-adic numbers ## Notation We introduce the notation ℤ_[p] for the p-adic integers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking (prime p) as a type class argument. Coercions into ℤ_p are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * https://en.wikipedia.org/wiki/P-adic_number ## Tags p-adic, p adic, padic, p-adic integer -/ open nat padic metric noncomputable theory open_locale classical /-- The p-adic integers ℤ_p are the p-adic numbers with norm ≤ 1. -/ def padic_int (p : ℕ) [p.prime] := {x : ℚ_[p] // ∥x∥ ≤ 1} notation `ℤ_[`p`]` := padic_int p namespace padic_int variables {p : ℕ} [nat.prime p] /-- Addition on ℤ_p is inherited from ℚ_p. -/ def add : ℤ_[p] → ℤ_[p] → ℤ_[p] | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x+y, le_trans (padic_norm_e.nonarchimedean _ _) (max_le_iff.2 ⟨hx,hy⟩)⟩ /-- Multiplication on ℤ_p is inherited from ℚ_p. -/ def mul : ℤ_[p] → ℤ_[p] → ℤ_[p] | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x*y, begin rw padic_norm_e.mul, apply mul_le_one; {assumption <|> apply norm_nonneg} end⟩ /-- Negation on ℤ_p is inherited from ℚ_p. -/ def neg : ℤ_[p] → ℤ_[p] | ⟨x, hx⟩ := ⟨-x, by simpa⟩ instance : ring ℤ_[p] := begin refine { add := add, mul := mul, neg := neg, zero := ⟨0, by simp [zero_le_one]⟩, one := ⟨1, by simp⟩, .. }; {repeat {rintro ⟨_, _⟩}, simp [mul_assoc, left_distrib, right_distrib, add, mul, neg]} end lemma zero_def : ∀ x : ℤ_[p], x = 0 ↔ x.val = 0 | ⟨x, _⟩ := ⟨subtype.mk.inj, λ h, by simp at h; simp only [h]; refl⟩ @[simp] lemma add_def : ∀ (x y : ℤ_[p]), (x+y).val = x.val + y.val | ⟨x, hx⟩ ⟨y, hy⟩ := rfl @[simp] lemma mul_def : ∀ (x y : ℤ_[p]), (x*y).val = x.val * y.val | ⟨x, hx⟩ ⟨y, hy⟩ := rfl @[simp] lemma mk_zero {h} : (⟨0, h⟩ : ℤ_[p]) = (0 : ℤ_[p]) := rfl instance : has_coe ℤ_[p] ℚ_[p] := ⟨subtype.val⟩ @[simp] lemma val_eq_coe (z : ℤ_[p]) : z.val = ↑z := rfl @[simp, move_cast] lemma coe_add : ∀ (z1 z2 : ℤ_[p]), (↑(z1 + z2) : ℚ_[p]) = ↑z1 + ↑z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, move_cast] lemma coe_mul : ∀ (z1 z2 : ℤ_[p]), (↑(z1 * z2) : ℚ_[p]) = ↑z1 * ↑z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, move_cast] lemma coe_neg : ∀ (z1 : ℤ_[p]), (↑(-z1) : ℚ_[p]) = -↑z1 | ⟨_, _⟩ := rfl @[simp, move_cast] lemma coe_sub : ∀ (z1 z2 : ℤ_[p]), (↑(z1 - z2) : ℚ_[p]) = ↑z1 - ↑z2 | ⟨_, _⟩ ⟨_, _⟩ := rfl @[simp, squash_cast] lemma coe_one : (↑(1 : ℤ_[p]) : ℚ_[p]) = 1 := rfl @[simp, squash_cast] lemma coe_coe : ∀ n : ℕ, (↑(↑n : ℤ_[p]) : ℚ_[p]) = (↑n : ℚ_[p]) | 0 := rfl | (k+1) := by simp [coe_coe] @[simp, squash_cast] lemma coe_zero : (↑(0 : ℤ_[p]) : ℚ_[p]) = 0 := rfl @[simp, move_cast] lemma cast_pow (x : ℤ_[p]) : ∀ (n : ℕ), (↑(x^n) : ℚ_[p]) = (↑x : ℚ_[p])^n | 0 := by simp | (k+1) := by simp [monoid.pow, pow]; congr; apply cast_pow lemma mk_coe : ∀ (k : ℤ_[p]), (⟨↑k, k.2⟩ : ℤ_[p]) = k | ⟨_, _⟩ := rfl /-- The inverse of a p-adic integer with norm equal to 1 is also a p-adic integer. Otherwise, the inverse is defined to be 0. -/ def inv : ℤ_[p] → ℤ_[p] | ⟨k, _⟩ := if h : ∥k∥ = 1 then ⟨1/k, by simp [h]⟩ else 0 end padic_int section instances variables {p : ℕ} [nat.prime p] @[reducible] def padic_norm_z (z : ℤ_[p]) : ℝ := ∥z.val∥ instance : metric_space ℤ_[p] := subtype.metric_space instance : has_norm ℤ_[p] := ⟨padic_norm_z⟩ instance : normed_ring ℤ_[p] := { dist_eq := λ ⟨_, _⟩ ⟨_, _⟩, rfl, norm_mul := λ ⟨_, _⟩ ⟨_, _⟩, norm_mul_le _ _ } instance padic_norm_z.is_absolute_value : is_absolute_value (λ z : ℤ_[p], ∥z∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ ⟨_, _⟩, by simp [norm_eq_zero, padic_int.zero_def], abv_add := λ ⟨_,_⟩ ⟨_, _⟩, norm_triangle _ _, abv_mul := λ _ _, by unfold norm; simp [padic_norm_z] } protected lemma padic_int.pmul_comm : ∀ z1 z2 : ℤ_[p], z1*z2 = z2*z1 | ⟨q1, h1⟩ ⟨q2, h2⟩ := show (⟨q1*q2, _⟩ : ℤ_[p]) = ⟨q2*q1, _⟩, by simp [mul_comm] instance : comm_ring ℤ_[p] := { mul_comm := padic_int.pmul_comm, ..padic_int.ring } protected lemma padic_int.zero_ne_one : (0 : ℤ_[p]) ≠ 1 := show (⟨(0 : ℚ_[p]), _⟩ : ℤ_[p]) ≠ ⟨(1 : ℚ_[p]), _⟩, from mt subtype.ext.1 zero_ne_one protected lemma padic_int.eq_zero_or_eq_zero_of_mul_eq_zero : ∀ (a b : ℤ_[p]), a * b = 0 → a = 0 ∨ b = 0 | ⟨a, ha⟩ ⟨b, hb⟩ := λ h : (⟨a * b, _⟩ : ℤ_[p]) = ⟨0, _⟩, have a * b = 0, from subtype.ext.1 h, (mul_eq_zero_iff_eq_zero_or_eq_zero.1 this).elim (λ h1, or.inl (by simp [h1]; refl)) (λ h2, or.inr (by simp [h2]; refl)) instance : integral_domain ℤ_[p] := { eq_zero_or_eq_zero_of_mul_eq_zero := padic_int.eq_zero_or_eq_zero_of_mul_eq_zero, zero_ne_one := padic_int.zero_ne_one, ..padic_int.comm_ring } end instances namespace padic_norm_z variables {p : ℕ} [nat.prime p] lemma le_one : ∀ z : ℤ_[p], ∥z∥ ≤ 1 | ⟨_, h⟩ := h @[simp] lemma one : ∥(1 : ℤ_[p])∥ = 1 := by simp [norm, padic_norm_z] @[simp] lemma mul (z1 z2 : ℤ_[p]) : ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ := by unfold norm; simp [padic_norm_z] @[simp] lemma pow (z : ℤ_[p]) : ∀ n : ℕ, ∥z^n∥ = ∥z∥^n | 0 := by simp | (k+1) := show ∥z*z^k∥ = ∥z∥*∥z∥^k, by {rw mul, congr, apply pow} theorem nonarchimedean : ∀ (q r : ℤ_[p]), ∥q + r∥ ≤ max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.nonarchimedean _ _ theorem add_eq_max_of_ne : ∀ {q r : ℤ_[p]}, ∥q∥ ≠ ∥r∥ → ∥q+r∥ = max (∥q∥) (∥r∥) | ⟨_, _⟩ ⟨_, _⟩ := padic_norm_e.add_eq_max_of_ne @[simp] lemma norm_one : ∥(1 : ℤ_[p])∥ = 1 := normed_field.norm_one lemma eq_of_norm_add_lt_right {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {z1 z2 : ℤ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_z.add_eq_max_of_ne hne; apply le_max_left) h @[simp] lemma padic_norm_e_of_padic_int (z : ℤ_[p]) : ∥(↑z : ℚ_[p])∥ = ∥z∥ := by simp [norm, padic_norm_z] @[simp] lemma padic_norm_z_eq_padic_norm_e {q : ℚ_[p]} (hq : ∥q∥ ≤ 1) : @norm ℤ_[p] _ ⟨q, hq⟩ = ∥q∥ := rfl end padic_norm_z private lemma mul_lt_one {α} [decidable_linear_ordered_comm_ring α] {a b : α} (hbz : 0 < b) (ha : a < 1) (hb : b < 1) : a * b < 1 := suffices a*b < 1*1, by simpa, mul_lt_mul ha (le_of_lt hb) hbz zero_le_one private lemma mul_lt_one_of_le_of_lt {α} [decidable_linear_ordered_comm_ring α] {a b : α} (ha : a ≤ 1) (hbz : 0 ≤ b) (hb : b < 1) : a * b < 1 := if hb' : b = 0 then by simpa [hb'] using zero_lt_one else if ha' : a = 1 then by simpa [ha'] else mul_lt_one (lt_of_le_of_ne hbz (ne.symm hb')) (lt_of_le_of_ne ha ha') hb namespace padic_int variables {p : ℕ} [nat.prime p] local attribute [reducible] padic_int lemma mul_inv : ∀ {z : ℤ_[p]}, ∥z∥ = 1 → z * z.inv = 1 | ⟨k, _⟩ h := begin have hk : k ≠ 0, from λ h', @zero_ne_one ℚ_[p] _ (by simpa [h'] using h), unfold padic_int.inv, split_ifs, { change (⟨k * (1/k), _⟩ : ℤ_[p]) = 1, simp [hk], refl }, { apply subtype.ext.2, simp [mul_inv_cancel hk] } end lemma inv_mul {z : ℤ_[p]} (hz : ∥z∥ = 1) : z.inv * z = 1 := by rw [mul_comm, mul_inv hz] lemma is_unit_iff {z : ℤ_[p]} : is_unit z ↔ ∥z∥ = 1 := ⟨λ h, begin rcases is_unit_iff_dvd_one.1 h with ⟨w, eq⟩, refine le_antisymm (padic_norm_z.le_one _) _, have := mul_le_mul_of_nonneg_left (padic_norm_z.le_one w) (norm_nonneg z), rwa [mul_one, ← padic_norm_z.mul, ← eq, padic_norm_z.one] at this end, λ h, ⟨⟨z, z.inv, mul_inv h, inv_mul h⟩, rfl⟩⟩ lemma norm_lt_one_add {z1 z2 : ℤ_[p]} (hz1 : ∥z1∥ < 1) (hz2 : ∥z2∥ < 1) : ∥z1 + z2∥ < 1 := lt_of_le_of_lt (padic_norm_z.nonarchimedean _ _) (max_lt hz1 hz2) lemma norm_lt_one_mul {z1 z2 : ℤ_[p]} (hz2 : ∥z2∥ < 1) : ∥z1 * z2∥ < 1 := calc ∥z1 * z2∥ = ∥z1∥ * ∥z2∥ : by simp ... < 1 : mul_lt_one_of_le_of_lt (padic_norm_z.le_one _) (norm_nonneg _) hz2 @[simp] lemma mem_nonunits {z : ℤ_[p]} : z ∈ nonunits ℤ_[p] ↔ ∥z∥ < 1 := by rw lt_iff_le_and_ne; simp [padic_norm_z.le_one z, nonunits, is_unit_iff] instance : local_ring ℤ_[p] := local_of_nonunits_ideal zero_ne_one $ λ x y, by simp; exact norm_lt_one_add private def cau_seq_to_rat_cau_seq (f : cau_seq ℤ_[p] norm) : cau_seq ℚ_[p] (λ a, ∥a∥) := ⟨ λ n, f n, λ _ hε, by simpa [norm, padic_norm_z] using f.cauchy hε ⟩ instance complete : cau_seq.is_complete ℤ_[p] norm := ⟨ λ f, have hqn : ∥cau_seq.lim (cau_seq_to_rat_cau_seq f)∥ ≤ 1, from padic_norm_e_lim_le zero_lt_one (λ _, padic_norm_z.le_one _), ⟨ ⟨_, hqn⟩, λ ε, by simpa [norm, padic_norm_z] using cau_seq.equiv_lim (cau_seq_to_rat_cau_seq f) ε⟩⟩ end padic_int namespace padic_norm_z variables {p : ℕ} [nat.prime p] lemma padic_val_of_cong_pow_p {z1 z2 : ℤ} {n : ℕ} (hz : z1 ≡ z2 [ZMOD ↑(p^n)]) : ∥(z1 - z2 : ℚ_[p])∥ ≤ ↑(↑p ^ (-n : ℤ) : ℚ) := have hdvd : ↑(p^n) ∣ z2 - z1, from int.modeq.modeq_iff_dvd.1 hz, have (z2 - z1 : ℚ_[p]) = ↑(↑(z2 - z1) : ℚ), by norm_cast, begin rw [norm_sub_rev, this, padic_norm_e.eq_padic_norm], exact_mod_cast padic_norm.le_of_dvd p hdvd end end padic_norm_z
c9335435e0d5e0e0ba17d128e8586299f0749b95
f3be49eddff7edf577d3d3666e314d995f7a6357
/TBA/Eulerian/Solution.lean
fe41b6fea55a21f3b065144a40ea3ad979c58cda
[]
no_license
IPDSnelting/tba-2021
8b930bcd2f4aae44a2ddc86e72b77f84e6d46e82
b6390e55b768423d3266969e81d19290129c5914
refs/heads/master
1,686,754,693,583
1,625,135,602,000
1,625,136,365,000
355,124,341
50
7
null
1,625,133,762,000
1,617,699,824,000
Lean
UTF-8
Lean
false
false
806
lean
/- Eulerian circuits -/ /- We provide you with a formalization of some facts about lists being equal up to permutation and lists being sublists of their permutation -/ import TBA.Eulerian.List open List namespace Eulerian -- We model graphs as lists of pairs on a type with decidable equality. variable {α : Type} (E : List (α × α)) [DecidableEq α] def isNonEmpty : Prop := E.length > 0 -- Now it's your turn to fill out the following definitions and prove the characterization! def isStronglyConnected (E : List (α × α)) : Prop := _ def hasEqualInOutDegrees (E : List (α × α)) : Prop := _ def isEulerian (E : List (α × α)) : Prop := _ theorem eulerian_degrees (hne : isNonEmpty E) (sc : isStronglyConnected E) (ed : hasEqualInOutDegrees E) : isEulerian E := _ end Eulerian
1878691720cad1db244b5d566f8b0917baff430b
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/order/category/NonemptyFinLinOrd.lean
6b649ed7be99ee421bae0c7bdbe669866043354d
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
2,324
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 data.fintype.sort import data.fin import order.category.LinearOrder /-! # Nonempty finite linear orders Nonempty finite linear orders form the index category for simplicial objects. -/ universe variables u v open category_theory set_option old_structure_cmd true section prio -- see note [default priority] set_option default_priority 100 /-- A typeclass for nonempty finite linear orders. -/ class nonempty_fin_lin_ord (α : Type*) extends fintype α, decidable_linear_order α, order_bot α, order_top α. end prio instance punit.nonempty_fin_lin_ord : nonempty_fin_lin_ord punit := begin refine_struct { .. punit.decidable_linear_ordered_cancel_add_comm_monoid, .. punit.fintype }; { intros, exact punit.star <|> exact dec_trivial } end section open_locale classical instance fin.nonempty_fin_lin_ord (n : ℕ) : nonempty_fin_lin_ord (fin (n+1)) := { top := fin.last n, le_top := fin.le_last, bot := 0, bot_le := fin.zero_le, .. fin.fintype _, .. fin.decidable_linear_order } end instance ulift.nonempty_fin_lin_ord (α : Type u) [nonempty_fin_lin_ord α] : nonempty_fin_lin_ord (ulift.{v} α) := { top := ulift.up ⊤, bot := ulift.up ⊥, le_top := λ ⟨a⟩, show a ≤ ⊤, from le_top, bot_le := λ ⟨a⟩, show ⊥ ≤ a, from bot_le, decidable_le := λ ⟨a⟩ ⟨b⟩, decidable_linear_order.decidable_le _ _, .. linear_order.lift equiv.ulift (equiv.injective _), .. ulift.fintype _ } /-- The category of nonempty finite linear orders. -/ def NonemptyFinLinOrd := bundled nonempty_fin_lin_ord namespace NonemptyFinLinOrd instance : bundled_hom.parent_projection (λ α i, @decidable_linear_order.to_linear_order _ (@nonempty_fin_lin_ord.to_decidable_linear_order α i)) := ⟨⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] NonemptyFinLinOrd /-- Construct a bundled NonemptyFinLinOrd from the underlying type and typeclass. -/ def of (α : Type*) [nonempty_fin_lin_ord α] : NonemptyFinLinOrd := bundled.of α instance : inhabited NonemptyFinLinOrd := ⟨of punit⟩ instance (α : NonemptyFinLinOrd) : nonempty_fin_lin_ord α := α.str end NonemptyFinLinOrd
6062e8f970b8cea5af75b2730215c253cd000282
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/group_theory/monoid_localization.lean
4c4faa9ceddbf87ecf30b7b220f34bc2b6445df1
[ "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
13,992
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import group_theory.congruence import algebra.associated import algebra.punit_instances /-! # Localizations of commutative monoids Localizing a commutative ring at one of its submonoids does not rely on the ring's addition, so we can generalize localizations to commutative monoids. We characterize the localization of a commutative monoid `M` at a submonoid `S` up to isomorphism; that is, a commutative monoid `N` is the localization of `M` at `S` iff we can find a monoid homomorphism `f : M →* N` satisfying 3 properties: 1. For all `y ∈ S`, `f y` is a unit; 2. For all `z : N`, there exists `(x, y) : M × S` such that `z * f y = f x`; 3. For all `x, y : M`, `f x = f y` iff there exists `c ∈ S` such that `x * c = y * c`. We also define the quotient of `M × S` by the unique congruence relation (equivalence relation preserving a binary operation) `r` such that for any other congruence relation `s` on `M × S` satisfying '`∀ y ∈ S`, `(1, 1) ∼ (y, y)` under `s`', we have that `(x₁, y₁) ∼ (x₂, y₂)` by `s` whenever `(x₁, y₁) ∼ (x₂, y₂)` by `r`. We show this relation is equivalent to the standard localization relation. This defines the localization as a quotient type, but the majority of subsequent lemmas in the file are given in terms of localizations up to isomorphism, using maps which satisfy the characteristic predicate. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. The infimum form of the localization congruence relation is chosen as 'canonical' here, since it shortens some proofs. ## Tags localization, monoid localization, quotient monoid, congruence relation, characteristic predicate, commutative monoid -/ namespace add_submonoid variables {M : Type*} [add_comm_monoid M] (S : add_submonoid M) (N : Type*) [add_comm_monoid N] /-- The type of add_monoid homomorphisms satisfying the characteristic predicate: if `f : M →+ N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ @[nolint has_inhabited_instance] structure localization_map := (to_fun : M →+ N) (map_add_units : ∀ y : S, is_add_unit (to_fun y)) (surj : ∀ z : N, ∃ x : M × S, z + to_fun x.2 = to_fun x.1) (eq_iff_exists : ∀ x y, to_fun x = to_fun y ↔ ∃ c : S, x + c = y + c) end add_submonoid variables {M : Type*} [comm_monoid M] (S : submonoid M) (N : Type*) [comm_monoid N] {P : Type*} [comm_monoid P] namespace submonoid /-- The type of monoid homomorphisms satisfying the characteristic predicate: if `f : M →* N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ @[nolint has_inhabited_instance] structure localization_map := (to_fun : M →* N) (map_units : ∀ y : S, is_unit (to_fun y)) (surj : ∀ z : N, ∃ x : M × S, z * to_fun x.2 = to_fun x.1) (eq_iff_exists : ∀ x y, to_fun x = to_fun y ↔ ∃ c : S, x * c = y * c) attribute [to_additive add_submonoid.localization_map] submonoid.localization_map namespace localization /-- The congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M × S` such that for any other congruence relation `s` on `M × S` where for all `y ∈ S`, `(1, 1) ∼ (y, y)` under `s`, we have that `(x₁, y₁) ∼ (x₂, y₂)` by `r` implies `(x₁, y₁) ∼ (x₂, y₂)` by `s`. -/ @[to_additive "The congruence relation on `M × S`, `M` an `add_comm_monoid` and `S` an `add_submonoid` of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M × S` such that for any other congruence relation `s` on `M × S` where for all `y ∈ S`, `(0, 0) ∼ (y, y)` under `s`, we have that `(x₁, y₁) ∼ (x₂, y₂)` by `r` implies `(x₁, y₁) ∼ (x₂, y₂)` by `s`."] def r (S : submonoid M) : con (M × S) := Inf {c | ∀ y : S, c 1 (y, y)} /-- An alternate form of the congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`. Its equivalence to `r` can be useful for proofs. -/ @[to_additive "An alternate form of the congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`. Its equivalence to `r` can be useful for proofs."] def r' : con (M × S) := begin refine { r := λ a b : M × S, ∃ c : S, a.1 * b.2 * c = b.1 * a.2 * c, iseqv := ⟨λ a, ⟨1, rfl⟩, λ a b ⟨c, hc⟩, ⟨c, hc.symm⟩, _⟩, .. }, { rintros a b c ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, use b.2 * t₁ * t₂, simp only [submonoid.coe_mul], calc a.1 * c.2 * (b.2 * t₁ * t₂) = a.1 * b.2 * t₁ * c.2 * t₂ : by ac_refl ... = b.1 * c.2 * t₂ * a.2 * t₁ : by { rw ht₁, ac_refl } ... = c.1 * a.2 * (b.2 * t₁ * t₂) : by { rw ht₂, ac_refl } }, { rintros a b c d ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, use t₁ * t₂, calc (a.1 * c.1) * (b.2 * d.2) * (t₁ * t₂) = (a.1 * b.2 * t₁) * (c.1 * d.2 * t₂) : by ac_refl ... = (b.1 * d.1) * (a.2 * c.2) * (t₁ * t₂) : by { rw [ht₁, ht₂], ac_refl } } end /-- The congruence relation used to localize a `comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `localization.r`) or explicitly (see `localization.r'`). -/ @[to_additive "The additive congruence relation used to localize an `add_comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `localization.r`) or explicitly (see `localization.r'`)."] theorem r_eq_r' : r S = r' S := le_antisymm (Inf_le $ λ _, ⟨1, by simp⟩) $ le_Inf $ λ b H ⟨p, q⟩ y ⟨t, ht⟩, begin rw [← mul_one (p, q), ← mul_one y], refine b.trans (b.mul (b.refl _) (H (y.2 * t))) _, convert b.symm (b.mul (b.refl y) (H (q * t))); simp only [], rw [prod.mk_mul_mk, submonoid.coe_mul, ← mul_assoc, ht, mul_left_comm, mul_assoc], refl end variables {S} @[to_additive] lemma r_iff_exists {x y : M × S} : r S x y ↔ ∃ c : S, x.1 * y.2 * c = y.1 * x.2 * c := by rw r_eq_r' S; refl end localization /-- The localization of a `comm_monoid` at one of its submonoids (as a quotient type). -/ @[to_additive "The localization of an `add_comm_monoid` at one of its submonoids (as a quotient type)."] def localization := (localization.r S).quotient @[to_additive] instance localization.inhabited : inhabited (localization S) := con.quotient.inhabited namespace localization_map variables (S) {N} /-- Given a map `f : M →* N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x * (f y)⁻¹ = z` if there always exists such an element. -/ @[to_additive "Given a map `f : M →+ N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x - f y = z` if there always exists such an element."] noncomputable def sec (f : M →* N) := @classical.epsilon (N → M × S) ⟨λ z, 1⟩ (λ g, ∀ z, z * f (g z).2 = f (g z).1) variables {S} @[simp, to_additive] lemma sec_spec {f : M →* N} (h : ∀ z : N, ∃ x : M × S, z * f x.2 = f x.1) (z : N) : z * f (sec S f z).2 = f (sec S f z).1 := @classical.epsilon_spec (N → M × S) (λ g, ∀ z, z * f (g z).2 = f (g z).1) ⟨λ y, classical.some $ h y, λ y, classical.some_spec $ h y⟩ z @[simp, to_additive] lemma sec_spec' {f : M →* N} (h : ∀ z : N, ∃ x : M × S, z * f x.2 = f x.1) (z : N) : f (sec S f z).1 = f (sec S f z).2 * z := by rw [mul_comm, sec_spec h] @[simp, to_additive] lemma mul_inv_left {f : M →* N} (h : ∀ y : S, is_unit (f y)) (y : S) (w z) : w * ↑(is_unit.lift_right (f.restrict S) h y)⁻¹ = z ↔ w = f y * z := by rw mul_comm; convert units.inv_mul_eq_iff_eq_mul _; exact (is_unit.coe_lift_right (f.restrict S) h _).symm @[simp, to_additive] lemma mul_inv_right {f : M →* N} (h : ∀ y : S, is_unit (f y)) (y : S) (w z) : z = w * ↑(is_unit.lift_right (f.restrict S) h y)⁻¹ ↔ z * f y = w := by rw [eq_comm, mul_inv_left h, mul_comm, eq_comm] @[simp, to_additive] lemma mul_inv {f : M →* N} (h : ∀ y : S, is_unit (f y)) {x₁ x₂} {y₁ y₂ : S} : f x₁ * ↑(is_unit.lift_right (f.restrict S) h y₁)⁻¹ = f x₂ * ↑(is_unit.lift_right (f.restrict S) h y₂)⁻¹ ↔ f (x₁ * y₂) = f (x₂ * y₁) := by rw [mul_inv_right h, mul_assoc, mul_comm _ (f y₂), ←mul_assoc, mul_inv_left h, mul_comm x₂, f.map_mul, f.map_mul] @[to_additive] lemma inv_inj {f : M →* N} (hf : ∀ y : S, is_unit (f y)) {y z} (h : (is_unit.lift_right (f.restrict S) hf y)⁻¹ = (is_unit.lift_right (f.restrict S) hf z)⁻¹) : f y = f z := by rw [←mul_one (f y), eq_comm, ←mul_inv_left hf y (f z) 1, h]; convert units.inv_mul _; exact (is_unit.coe_lift_right (f.restrict S) hf _).symm @[to_additive] lemma inv_unique {f : M →* N} (h : ∀ y : S, is_unit (f y)) {y : S} {z} (H : f y * z = 1) : ↑(is_unit.lift_right (f.restrict S) h y)⁻¹ = z := by rw [←one_mul ↑(_)⁻¹, mul_inv_left, ←H] variables (f : localization_map S N) /-- Given a localization map `f : M →* N`, the surjection sending `(x, y) : M × S` to `f x * (f y)⁻¹`. -/ @[to_additive "Given a localization map `f : M →+ N`, the surjection sending `(x, y) : M × S` to `f x - f y`."] noncomputable def mk' (f : localization_map S N) (x : M) (y : S) : N := f.1 x * ↑(is_unit.lift_right (f.1.restrict S) f.2 y)⁻¹ @[simp, to_additive] lemma mk'_mul (x₁ x₂ : M) (y₁ y₂ : S) : f.mk' (x₁ * x₂) (y₁ * y₂) = f.mk' x₁ y₁ * f.mk' x₂ y₂ := (mul_inv_left f.2 _ _ _).2 $ show _ = _ * (_ * _ * (_ * _)), by rw [←mul_assoc, ←mul_assoc, mul_inv_right f.2, mul_assoc, mul_assoc, mul_comm _ (f.1 x₂), ←mul_assoc, ←mul_assoc, mul_inv_right f.2, submonoid.coe_mul, f.1.map_mul, f.1.map_mul]; ac_refl @[to_additive] lemma mk'_one (x) : f.mk' x (1 : S) = f.1 x := by rw [mk', monoid_hom.map_one]; simp @[simp, to_additive] lemma mk'_sec (z : N) : f.mk' (sec S f.1 z).1 (sec S f.1 z).2 = z := show _ * _ = _, by rw [←sec_spec f.3, mul_inv_left, mul_comm] @[to_additive] lemma mk'_surjective (z : N) : ∃ x (y : S), f.mk' x y = z := ⟨(sec S f.1 z).1, (sec S f.1 z).2, f.mk'_sec z⟩ @[to_additive] lemma mk'_spec (x) (y : S) : f.mk' x y * f.1 y = f.1 x := show _ * _ * _ = _, by rw [mul_assoc, mul_comm _ (f.1 y), ←mul_assoc, mul_inv_left, mul_comm] @[to_additive] lemma mk'_spec' (x) (y : S) : f.1 y * f.mk' x y = f.1 x := by rw [mul_comm, mk'_spec] @[simp, to_additive] theorem eq_mk'_iff_mul_eq {x} {y : S} {z} : z = f.mk' x y ↔ z * f.1 y = f.1 x := ⟨λ H, by rw [H, mk'_spec], λ H, by erw [mul_inv_right, H]; refl⟩ @[simp, to_additive] theorem mk'_eq_iff_eq_mul {x} {y : S} {z} : f.mk' x y = z ↔ f.1 x = z * f.1 y := by rw [eq_comm, eq_mk'_iff_mul_eq, eq_comm] @[to_additive] lemma mk'_eq_iff_eq {x₁ x₂} {y₁ y₂ : S} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ f.1 (x₁ * y₂) = f.1 (x₂ * y₁) := ⟨λ H, by rw [f.1.map_mul, f.mk'_eq_iff_eq_mul.1 H, mul_assoc, mul_comm (f.1 _), ←mul_assoc, mk'_spec, f.1.map_mul], λ H, by rw [mk'_eq_iff_eq_mul, mk', mul_assoc, mul_comm _ (f.1 y₁), ←mul_assoc, ←f.1.map_mul, ←H, f.1.map_mul, mul_inv_right f.2]⟩ @[to_additive] protected lemma eq {a₁ b₁} {a₂ b₂ : S} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ ∃ c : S, a₁ * b₂ * c = b₁ * a₂ * c := f.mk'_eq_iff_eq.trans $ f.4 _ _ @[to_additive] protected lemma eq' {a₁ b₁} {a₂ b₂ : S} : f.mk' a₁ a₂ = f.mk' b₁ b₂ ↔ localization.r S (a₁, a₂) (b₁, b₂) := by rw [f.eq, localization.r_iff_exists] @[to_additive] lemma eq_iff_eq (g : localization_map S P) {x y} : f.1 x = f.1 y ↔ g.1 x = g.1 y := (f.4 _ _).trans (g.4 _ _).symm @[to_additive] lemma mk'_eq_iff_mk'_eq (g : localization_map S P) {x₁ x₂} {y₁ y₂ : S} : f.mk' x₁ y₁ = f.mk' x₂ y₂ ↔ g.mk' x₁ y₁ = g.mk' x₂ y₂ := f.eq'.trans g.eq'.symm @[to_additive] lemma exists_of_sec_mk' (x) (y : S) : ∃ c : S, x * (sec S f.1 $ f.mk' x y).2 * c = (sec S f.1 $ f.mk' x y).1 * y * c := (f.4 _ _).1 $ f.mk'_eq_iff_eq.1 $ (mk'_sec _ _).symm @[to_additive] lemma exists_of_sec (x) : ∃ c : S, x * (sec S f.1 $ f.1 x).2 * c = (sec S f.1 $ f.1 x).1 * c := (f.4 _ _).1 $ by rw f.1.map_mul; exact sec_spec f.3 _ @[to_additive] lemma mk'_eq_of_eq {a₁ b₁ : M} {a₂ b₂ : S} (H : b₁ * a₂ = a₁ * b₂) : f.mk' a₁ a₂ = f.mk' b₁ b₂ := f.mk'_eq_iff_eq.2 $ H ▸ rfl @[simp, to_additive] lemma mk'_self (y : S) : f.mk' (y : M) y = 1 := show _ * _ = _, by rw [mul_inv_left, mul_one] @[simp, to_additive] lemma mk'_self' (x) (H : x ∈ S) : f.mk' x ⟨x, H⟩ = 1 := by convert mk'_self _ _; refl @[simp, to_additive] lemma mul_mk'_eq_mk'_of_mul (x₁ x₂) (y : S) : f.1 x₁ * f.mk' x₂ y = f.mk' (x₁ * x₂) y := by rw [←mk'_one, ←mk'_mul, one_mul] @[simp, to_additive] lemma mk'_mul_eq_mk'_of_mul (x₁ x₂) (y : S) : f.mk' x₂ y * f.1 x₁ = f.mk' (x₁ * x₂) y := by rw [mul_comm, mul_mk'_eq_mk'_of_mul] @[simp, to_additive] lemma mul_mk'_one_eq_mk' (x) (y : S) : f.1 x * f.mk' 1 y = f.mk' x y := by rw [mul_mk'_eq_mk'_of_mul, mul_one] @[simp, to_additive] lemma mk'_mul_cancel_right (x : M) (y : S) : f.mk' (x * y) y = f.1 x := by rw [←mul_mk'_one_eq_mk', f.1.map_mul, mul_assoc, mul_mk'_one_eq_mk', mk'_self, mul_one] @[simp, to_additive] lemma mk'_mul_cancel_left (x) (y : S) : f.mk' ((y : M) * x) y = f.1 x := by rw [mul_comm, mk'_mul_cancel_right] end localization_map end submonoid
3b4593b7ee373892122ca2ed5360118ee8313586
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/minpoly/is_integrally_closed.lean
6a10a09a9738e44bac247266d025f2bdf69e4658
[ "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,821
lean
/- Copyright (c) 2019 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca, Paul Lezeau, Junyan Xu -/ import ring_theory.adjoin_root import field_theory.minpoly.field import ring_theory.polynomial.gauss_lemma /-! # Minimal polynomials over a GCD monoid > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file specializes the theory of minpoly to the case of an algebra over a GCD monoid. ## Main results * `is_integrally_closed_eq_field_fractions`: For integrally closed domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. * `is_integrally_closed_dvd` : For integrally closed domains, the minimal polynomial divides any primitive polynomial that has the integral element as root. * `is_integrally_closed_unique` : The minimal polynomial of an element `x` is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has `x` as a root, then this polynomial is equal to the minimal polynomial of `x`. -/ open_locale classical polynomial open polynomial set function minpoly namespace minpoly variables {R S : Type*} [comm_ring R] [comm_ring S] [is_domain R] [algebra R S] section variables (K L : Type*) [field K] [algebra R K] [is_fraction_ring R K] [field L] [algebra R L] [algebra S L] [algebra K L] [is_scalar_tower R K L] [is_scalar_tower R S L] variables [is_integrally_closed R] /-- For integrally closed domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. See `minpoly.is_integrally_closed_eq_field_fractions'` if `S` is already a `K`-algebra. -/ theorem is_integrally_closed_eq_field_fractions [is_domain S] {s : S} (hs : is_integral R s) : minpoly K (algebra_map S L s) = (minpoly R s).map (algebra_map R K) := begin refine (eq_of_irreducible_of_monic _ _ _).symm, { exact (polynomial.monic.irreducible_iff_irreducible_map_fraction_map (monic hs)).1 (irreducible hs) }, { rw [aeval_map_algebra_map, aeval_algebra_map_apply, aeval, map_zero] }, { exact (monic hs).map _ } end /-- For integrally closed domains, the minimal polynomial over the ring is the same as the minimal polynomial over the fraction field. Compared to `minpoly.is_integrally_closed_eq_field_fractions`, this version is useful if the element is in a ring that is already a `K`-algebra. -/ theorem is_integrally_closed_eq_field_fractions' [is_domain S] [algebra K S] [is_scalar_tower R K S] {s : S} (hs : is_integral R s) : minpoly K s = (minpoly R s).map (algebra_map R K) := begin let L := fraction_ring S, rw [← is_integrally_closed_eq_field_fractions K L hs], refine minpoly.eq_of_algebra_map_eq (is_fraction_ring.injective S L) (is_integral_of_is_scalar_tower hs) rfl end end variables [is_domain S] [no_zero_smul_divisors R S] variable [is_integrally_closed R] /-- For integrally closed rings, the minimal polynomial divides any polynomial that has the integral element as root. See also `minpoly.dvd` which relaxes the assumptions on `S` in exchange for stronger assumptions on `R`. -/ theorem is_integrally_closed_dvd [nontrivial R] {s : S} (hs : is_integral R s) {p : R[X]} (hp : polynomial.aeval s p = 0) : minpoly R s ∣ p := begin let K := fraction_ring R, let L := fraction_ring S, have : minpoly K (algebra_map S L s) ∣ map (algebra_map R K) (p %ₘ (minpoly R s)), { rw [map_mod_by_monic _ (minpoly.monic hs), mod_by_monic_eq_sub_mul_div], refine dvd_sub (minpoly.dvd K (algebra_map S L s) _) _, rw [← map_aeval_eq_aeval_map, hp, map_zero], rw [← is_scalar_tower.algebra_map_eq, ← is_scalar_tower.algebra_map_eq], apply dvd_mul_of_dvd_left, rw is_integrally_closed_eq_field_fractions K L hs, exact monic.map _ (minpoly.monic hs) }, rw [is_integrally_closed_eq_field_fractions _ _ hs, map_dvd_map (algebra_map R K) (is_fraction_ring.injective R K) (minpoly.monic hs)] at this, rw [← dvd_iff_mod_by_monic_eq_zero (minpoly.monic hs)], refine polynomial.eq_zero_of_dvd_of_degree_lt this (degree_mod_by_monic_lt p $ minpoly.monic hs), all_goals { apply_instance } end theorem is_integrally_closed_dvd_iff [nontrivial R] {s : S} (hs : is_integral R s) (p : R[X]) : polynomial.aeval s p = 0 ↔ minpoly R s ∣ p := ⟨λ hp, is_integrally_closed_dvd hs hp, λ hp, by simpa only [ring_hom.mem_ker, ring_hom.coe_comp, coe_eval_ring_hom, coe_map_ring_hom, function.comp_app, eval_map, ← aeval_def] using aeval_eq_zero_of_dvd_aeval_eq_zero hp (minpoly.aeval R s)⟩ lemma ker_eval {s : S} (hs : is_integral R s) : ((polynomial.aeval s).to_ring_hom : R[X] →+* S).ker = ideal.span ({minpoly R s} : set R[X] ):= by ext p ; simp_rw [ring_hom.mem_ker, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom, is_integrally_closed_dvd_iff hs, ← ideal.mem_span_singleton] /-- If an element `x` is a root of a nonzero polynomial `p`, then the degree of `p` is at least the degree of the minimal polynomial of `x`. See also `minpoly.degree_le_of_ne_zero` which relaxes the assumptions on `S` in exchange for stronger assumptions on `R`. -/ lemma is_integrally_closed.degree_le_of_ne_zero {s : S} (hs : is_integral R s) {p : R[X]} (hp0 : p ≠ 0) (hp : polynomial.aeval s p = 0) : degree (minpoly R s) ≤ degree p := begin rw [degree_eq_nat_degree (minpoly.ne_zero hs), degree_eq_nat_degree hp0], norm_cast, exact nat_degree_le_of_dvd ((is_integrally_closed_dvd_iff hs _).mp hp) hp0 end /-- The minimal polynomial of an element `x` is uniquely characterized by its defining property: if there is another monic polynomial of minimal degree that has `x` as a root, then this polynomial is equal to the minimal polynomial of `x`. See also `minpoly.unique` which relaxes the assumptions on `S` in exchange for stronger assumptions on `R`. -/ lemma is_integrally_closed.minpoly.unique {s : S} {P : R[X]} (hmo : P.monic) (hP : polynomial.aeval s P = 0) (Pmin : ∀ Q : R[X], Q.monic → polynomial.aeval s Q = 0 → degree P ≤ degree Q) : P = minpoly R s := begin have hs : is_integral R s := ⟨P, hmo, hP⟩, symmetry, apply eq_of_sub_eq_zero, by_contra hnz, have := is_integrally_closed.degree_le_of_ne_zero hs hnz (by simp [hP]), contrapose! this, refine degree_sub_lt _ (ne_zero hs) _, { exact le_antisymm (min R s hmo hP) (Pmin (minpoly R s) (monic hs) (aeval R s)) }, { rw [(monic hs).leading_coeff, hmo.leading_coeff] } end theorem prime_of_is_integrally_closed {x : S} (hx : is_integral R x) : _root_.prime (minpoly R x) := begin refine ⟨(minpoly.monic hx).ne_zero, ⟨by by_contra h_contra ; exact (ne_of_lt (minpoly.degree_pos hx)) (degree_eq_zero_of_is_unit h_contra).symm, λ a b h, or_iff_not_imp_left.mpr (λ h', _)⟩⟩, rw ← minpoly.is_integrally_closed_dvd_iff hx at ⊢ h' h, rw aeval_mul at h, exact eq_zero_of_ne_zero_of_mul_left_eq_zero h' h, end section adjoin_root noncomputable theory open algebra polynomial adjoin_root variables {R} {x : S} lemma to_adjoin.injective (hx : is_integral R x) : function.injective (minpoly.to_adjoin R x) := begin refine (injective_iff_map_eq_zero _).2 (λ P₁ hP₁, _), obtain ⟨P, hP⟩ := mk_surjective (minpoly.monic hx) P₁, by_cases hPzero : P = 0, { simpa [hPzero] using hP.symm }, rw [← hP, minpoly.to_adjoin_apply', lift_hom_mk, ← subalgebra.coe_eq_zero, aeval_subalgebra_coe, set_like.coe_mk, is_integrally_closed_dvd_iff hx] at hP₁, obtain ⟨Q, hQ⟩ := hP₁, rw [← hP, hQ, ring_hom.map_mul, mk_self, zero_mul], end /-- The algebra isomorphism `adjoin_root (minpoly R x) ≃ₐ[R] adjoin R x` -/ @[simps] def equiv_adjoin (hx : is_integral R x) : adjoin_root (minpoly R x) ≃ₐ[R] adjoin R ({x} : set S) := alg_equiv.of_bijective (minpoly.to_adjoin R x) ⟨minpoly.to_adjoin.injective hx, minpoly.to_adjoin.surjective R x⟩ /-- The `power_basis` of `adjoin R {x}` given by `x`. See `algebra.adjoin.power_basis` for a version over a field. -/ @[simps] def _root_.algebra.adjoin.power_basis' (hx : is_integral R x) : power_basis R (algebra.adjoin R ({x} : set S)) := power_basis.map (adjoin_root.power_basis' (minpoly.monic hx)) (minpoly.equiv_adjoin hx) /-- The power basis given by `x` if `B.gen ∈ adjoin R {x}`. -/ @[simps] noncomputable def _root_.power_basis.of_gen_mem_adjoin' (B : power_basis R S) (hint : is_integral R x) (hx : B.gen ∈ adjoin R ({x} : set S)) : power_basis R S := (algebra.adjoin.power_basis' hint).map $ (subalgebra.equiv_of_eq _ _ $ power_basis.adjoin_eq_top_of_gen_mem_adjoin hx).trans subalgebra.top_equiv end adjoin_root end minpoly
4efc744eb5e3d62e5163a8ff6f09a3224567ea19
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/02_True_False/00_intro.lean
9afe02a95e2cec9501bee926be92c4966f4d4bce
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
5,374
lean
/- So far, all of the propositions that we've seen are in the form of assertions about equalities: 0 = 0, 1 = 1, 2 + 3 = 4, and so on. And we've seen how to prove propositions of this kind (that are actually true) using eq.refl and rfl as a shorthand. We are now about to set out to explore the different forms of propositions that arise in predicate logic. In this unit, we meet the simplest of all propositions, even simpler than equality statements, namely the propositions that in lean are called "true" and "false". First, true is the proposition that is always trivially provable. -/ /- The "true introduction" inference rule -/ /- Here's the inference rule for true. Note that it doesn't require an inputs/premises at all. It is truly an axiom. Makes sense: You can alway assume that the proposition true is true. -------- (true.intro) pf: true The true.intro inference rule is called true.intro because it is an introduction rule in the sense that it introduces a true in the conclusion that wasn't in the premises (of which there are none here). Here then is a formal (mathematically precise) and mechanically checked proof of the proposition, true, in Lean. -/ theorem t : true := true.intro #check t #reduce t /- We could of course have used tactics as well. EXERCISE prove t' : true using a tactic script. -/ lemma t' : true := begin apply true.intro end /- That's it! Super easy. -/ /- There is no introduction rule for false! -/ /- Whereas true is trivially provable, the proposition, false, has not proof and can never be proved. Viewed as a type, it has no values at all. It's what we call an uninhabited type. Therefore there can be no inference rule or sequence of rules that derive a proof of false, because such a thing simply does not exist! That is after all the meaning of false: it is not true, so there must be no proof of it, otherwise it would be true, and that would be a fatal contradiction. -/ /- The difference between tt/ff and the propositions, true and false. -/ /- To clarify one major potential point of confusion it's imperative to see that the propositions, true and false, are not the same as the boolean truth values, which in Lean are called tt and ff. In some other languages, they're called "true" and "false", which really is a source of possible confusion. -/ /- First, let's confirm that the types of tt and ff are bool. -/ #check tt #check ff /- You will recall that we can assign these values to variables of type bool -/ def boolean_false := ff #check boolean_false #reduce boolean_false /- By contrast, we cannot assign the value tt as a proof of true. It's not even of the right type. Uncomment the following line to see that this is the case. Read the error message carefully. EXERCISE: Read and explain the error message to a colleague in your class. -/ -- theorem bad : true := tt /- * EX FALSO QUOD LIBET * -/ /- Now we come to a very fundamental concept in logic: from a contradiction, you can derive a proof of any proposition whatsoever. To put it in English terms, if the impossible has happened, then anything goes! The inference rule for this says that if you're given a proof of false, let's call it f, and any proposition, P, whatsoever (any value, P, of type Prop!), then you can derive a proof of P, and the false disappears from the conclusion (which is why we call this inference rule false elimination). Here's the rule: P : Prop, f : false ------------------- false.elim pf : P Note that the proposition argument, P, is not to be given explicitly as an argument to false.elim, but is to be inferred from context, instead. -/ /- Let's see how this works in Lean. Let's start by simply asserting as an axiom, without proof, that f is a proof of false. -/ axiom f : false /- Well, it was probably a bad idea. It just says, "trust me and accept that the impossible just occurred." The problem is that our logic is now inconsistent and anything at all can be proved. We just feed our proof of false to false.elim to prove any proposition at all. Let's try to prove 0 = 1. -/ theorem zeqo : 0 = 1 := false.elim f /- It will very occasionally be useful to add an axiom to Lean, but one must take extraordinary care to ensure that it is consistent with the underlying logic of lean. The axiom that there is a proof of false immediately makes the whole logic useful because it collapses the distinction between true and false entirely, and in this case, any claim can be proven true, and that would put us logically in a post-truth work, which would be a bad and useless place to be. -/ /- EXERCISE: Prove true = false (given that we've assume there is a proof of false). -/ /- As a final observation, we note that there are some propositions that one might think of as being false, and thus provable from a contradiction, but that we cannot even state in Lean. For example, we can't even state the claim that 1 = tt because Lean requires that the types of the arguments on each side of the = be the same. EXERCISE: Try it. The error message that appears is a little bit complicate but in a nutshell it's saying "I can't find a way to coerce/convert 1 into a bool, and so I can't do anything with this expression." In simple terms, the expression 1 = tt has a type error. It's not even a well formed expression. -/
b240857746f3d1a8ae7097884b08bc5e7a6d55cf
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/nielsen_schreier.lean
c36283d3646de7bb2509c0c55f6777a4a9e9ad28
[ "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,088
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 category_theory.action import combinatorics.quiver.arborescence import combinatorics.quiver.connected_component import group_theory.is_free_group /-! # The Nielsen-Schreier theorem This file proves that a subgroup of a free group is itself free. ## Main result - `subgroup_is_free_of_is_free H`: an instance saying that a subgroup of a free group is free. ## Proof overview The proof is analogous to the proof using covering spaces and fundamental groups of graphs, but we work directly with groupoids instead of topological spaces. Under this analogy, - `is_free_groupoid G` corresponds to saying that a space is a graph. - `End_mul_equiv_subgroup H` plays the role of replacing 'subgroup of fundamental group' with 'fundamental group of covering space'. - `action_groupoid_is_free G A` corresponds to the fact that a covering of a (single-vertex) graph is a graph. - `End_is_free T` corresponds to the fact that, given a spanning tree `T` of a graph, its fundamental group is free (generated by loops from the complement of the tree). ## Implementation notes Our definition of `is_free_groupoid` is nonstandard. Normally one would require that functors `G ⥤ X` to any _groupoid_ `X` are given by graph homomorphisms from the generators, but we only consider _groups_ `X`. This simplifies the argument since functor equality is complicated in general, but simple for functors to single object categories. ## References https://ncatlab.org/nlab/show/Nielsen-Schreier+theorem ## Tags free group, free groupoid, Nielsen-Schreier -/ noncomputable theory open_locale classical universes v u open category_theory category_theory.action_category category_theory.single_obj quiver is_free_group as fgp /-- `is_free_groupoid.generators G` is a type synonym for `G`. We think of this as the vertices of the generating quiver of `G` when `G` is free. We can't use `G` directly, since `G` already has a quiver instance from being a groupoid. -/ @[nolint unused_arguments has_nonempty_instance] def is_free_groupoid.generators (G) [groupoid G] := G /-- A groupoid `G` is free when we have the following data: - a quiver on `is_free_groupoid.generators G` (a type synonym for `G`) - a function `of` taking a generating arrow to a morphism in `G` - such that a functor from `G` to any group `X` is uniquely determined by assigning labels in `X` to the generating arrows. This definition is nonstandard. Normally one would require that functors `G ⥤ X` to any _groupoid_ `X` are given by graph homomorphisms from `generators`. -/ class is_free_groupoid (G) [groupoid.{v} G] := (quiver_generators : quiver.{v+1} (is_free_groupoid.generators G)) (of : Π {a b : is_free_groupoid.generators G}, (a ⟶ b) → ((show G, from a) ⟶ b)) (unique_lift : ∀ {X : Type v} [group X] (f : labelling (is_free_groupoid.generators G) X), ∃! F : G ⥤ single_obj X, ∀ a b (g : a ⟶ b), F.map (of g) = f g) namespace is_free_groupoid attribute [instance] quiver_generators /-- Two functors from a free groupoid to a group are equal when they agree on the generating quiver. -/ @[ext] lemma ext_functor {G} [groupoid.{v} G] [is_free_groupoid G] {X : Type v} [group X] (f g : G ⥤ single_obj X) (h : ∀ a b (e : a ⟶ b), f.map (of e) = g.map (of e)) : f = g := let ⟨_, _, u⟩ := @unique_lift G _ _ X _ (λ (a b : generators G) (e : a ⟶ b), g.map (of e)) in trans (u _ h) (u _ (λ _ _ _, rfl)).symm /-- An action groupoid over a free froup is free. More generally, one could show that the groupoid of elements over a free groupoid is free, but this version is easier to prove and suffices for our purposes. Analogous to the fact that a covering space of a graph is a graph. (A free groupoid is like a graph, and a groupoid of elements is like a covering space.) -/ instance action_groupoid_is_free {G A : Type u} [group G] [is_free_group G] [mul_action G A] : is_free_groupoid (action_category G A) := { quiver_generators := ⟨λ a b, { e : fgp.generators G // fgp.of e • a.back = b.back }⟩, of := λ a b e, ⟨fgp.of e, e.property⟩, unique_lift := begin introsI X _ f, let f' : fgp.generators G → (A → X) ⋊[mul_aut_arrow] G := λ e, ⟨λ b, @f ⟨(), _⟩ ⟨(), b⟩ ⟨e, smul_inv_smul _ b⟩, fgp.of e⟩, rcases fgp.unique_lift f' with ⟨F', hF', uF'⟩, refine ⟨uncurry F' _, _, _⟩, { suffices : semidirect_product.right_hom.comp F' = monoid_hom.id _, { exact monoid_hom.ext_iff.mp this }, ext, rw [monoid_hom.comp_apply, hF'], refl }, { rintros ⟨⟨⟩, a : A⟩ ⟨⟨⟩, b⟩ ⟨e, h : fgp.of e • a = b⟩, change (F' (fgp.of _)).left _ = _, rw hF', cases (inv_smul_eq_iff.mpr h.symm), refl }, { intros E hE, have : curry E = F', { apply uF', intro e, ext, { convert hE _ _ _, refl }, { refl } }, apply functor.hext, { intro, apply unit.ext }, { refine action_category.cases _, intros, simp only [←this, uncurry_map, curry_apply_left, coe_back, hom_of_pair.val] } }, end } namespace spanning_tree /- In this section, we suppose we have a free groupoid with a spanning tree for its generating quiver. The goal is to prove that the vertex group at the root is free. A picture to have in mind is that we are 'pulling' the endpoints of all the edges of the quiver along the spanning tree to the root. -/ variables {G : Type u} [groupoid.{u} G] [is_free_groupoid G] (T : wide_subquiver (symmetrify $ generators G)) [arborescence T] /-- The root of `T`, except its type is `G` instead of the type synonym `T`. -/ private def root' : G := show T, from root T /-- A path in the tree gives a hom, by composition. -/ -- this has to be marked noncomputable, see issue #451. -- It might be nicer to define this in terms of `compose_path` noncomputable def hom_of_path : Π {a : G}, path (root T) a → (root' T ⟶ a) | _ path.nil := 𝟙 _ | a (path.cons p f) := hom_of_path p ≫ sum.rec_on f.val (λ e, of e) (λ e, inv (of e)) /-- For every vertex `a`, there is a canonical hom from the root, given by the path in the tree. -/ def tree_hom (a : G) : root' T ⟶ a := hom_of_path T default /-- Any path to `a` gives `tree_hom T a`, since paths in the tree are unique. -/ lemma tree_hom_eq {a : G} (p : path (root T) a) : tree_hom T a = hom_of_path T p := by rw [tree_hom, unique.default_eq] @[simp] lemma tree_hom_root : tree_hom T (root' T) = 𝟙 _ := -- this should just be `tree_hom_eq T path.nil`, but Lean treats `hom_of_path` with suspicion. trans (tree_hom_eq T path.nil) rfl /-- Any hom in `G` can be made into a loop, by conjugating with `tree_hom`s. -/ def loop_of_hom {a b : G} (p : a ⟶ b) : End (root' T) := tree_hom T a ≫ p ≫ inv (tree_hom T b) /-- Turning an edge in the spanning tree into a loop gives the indentity loop. -/ lemma loop_of_hom_eq_id {a b : generators G} (e ∈ wide_subquiver_symmetrify T a b) : loop_of_hom T (of e) = 𝟙 (root' T) := begin rw [loop_of_hom, ←category.assoc, is_iso.comp_inv_eq, category.id_comp], cases H, { rw [tree_hom_eq T (path.cons default ⟨sum.inl e, H⟩), hom_of_path], refl }, { rw [tree_hom_eq T (path.cons default ⟨sum.inr e, H⟩), hom_of_path], simp only [is_iso.inv_hom_id, category.comp_id, category.assoc, tree_hom] } end /-- Since a hom gives a loop, any homomorphism from the vertex group at the root extends to a functor on the whole groupoid. -/ @[simps] def functor_of_monoid_hom {X} [monoid X] (f : End (root' T) →* X) : G ⥤ single_obj X := { obj := λ _, (), map := λ a b p, f (loop_of_hom T p), map_id' := begin intro a, rw [loop_of_hom, category.id_comp, is_iso.hom_inv_id, ←End.one_def, f.map_one, id_as_one], end, map_comp' := begin intros, rw [comp_as_mul, ←f.map_mul], simp only [is_iso.inv_hom_id_assoc, loop_of_hom, End.mul_def, category.assoc] end } /-- Given a free groupoid and an arborescence of its generating quiver, the vertex group at the root is freely generated by loops coming from generating arrows in the complement of the tree. -/ def End_is_free : is_free_group (End (root' T)) := is_free_group.of_unique_lift ((wide_subquiver_equiv_set_total $ wide_subquiver_symmetrify T)ᶜ : set _) (λ e, loop_of_hom T (of e.val.hom)) begin introsI X _ f, let f' : labelling (generators G) X := λ a b e, if h : e ∈ wide_subquiver_symmetrify T a b then 1 else f ⟨⟨a, b, e⟩, h⟩, rcases unique_lift f' with ⟨F', hF', uF'⟩, refine ⟨F'.map_End _, _, _⟩, { suffices : ∀ {x y} (q : x ⟶ y), F'.map (loop_of_hom T q) = (F'.map q : X), { rintro ⟨⟨a, b, e⟩, h⟩, rw [functor.map_End_apply, this, hF'], exact dif_neg h }, intros, suffices : ∀ {a} (p : path (root' T) a), F'.map (hom_of_path T p) = 1, { simp only [this, tree_hom, comp_as_mul, inv_as_inv, loop_of_hom, inv_one, mul_one, one_mul, functor.map_inv, functor.map_comp] }, intros a p, induction p with b c p e ih, { rw [hom_of_path, F'.map_id, id_as_one] }, rw [hom_of_path, F'.map_comp, comp_as_mul, ih, mul_one], rcases e with ⟨e | e, eT⟩, { rw hF', exact dif_pos (or.inl eT) }, { rw [F'.map_inv, inv_as_inv, inv_eq_one, hF'], exact dif_pos (or.inr eT) } }, { intros E hE, ext, suffices : (functor_of_monoid_hom T E).map x = F'.map x, { simpa only [loop_of_hom, functor_of_monoid_hom_map, is_iso.inv_id, tree_hom_root, category.id_comp, category.comp_id] using this }, congr, apply uF', intros a b e, change E (loop_of_hom T _) = dite _ _ _, split_ifs, { rw [loop_of_hom_eq_id T e h, ←End.one_def, E.map_one] }, { exact hE ⟨⟨a, b, e⟩, h⟩ } } end end spanning_tree /-- Another name for the identity function `G → G`, to help type checking. -/ private def symgen {G : Type u} [groupoid.{v} G] [is_free_groupoid G] : G → symmetrify (generators G) := id /-- If there exists a morphism `a → b` in a free groupoid, then there also exists a zigzag from `a` to `b` in the generating quiver. -/ lemma path_nonempty_of_hom {G} [groupoid.{u u} G] [is_free_groupoid G] {a b : G} : nonempty (a ⟶ b) → nonempty (path (symgen a) (symgen b)) := begin rintro ⟨p⟩, rw [←@weakly_connected_component.eq (generators G), eq_comm, ←free_group.of_injective.eq_iff, ←mul_inv_eq_one], let X := free_group (weakly_connected_component $ generators G), let f : G → X := λ g, free_group.of (weakly_connected_component.mk g), let F : G ⥤ single_obj X := single_obj.difference_functor f, change F.map p = ((category_theory.functor.const G).obj ()).map p, congr, ext, rw [functor.const_obj_map, id_as_one, difference_functor_map, mul_inv_eq_one], apply congr_arg free_group.of, apply (weakly_connected_component.eq _ _).mpr, exact ⟨hom.to_path (sum.inr e)⟩, end /-- Given a connected free groupoid, its generating quiver is rooted-connected. -/ instance generators_connected (G) [groupoid.{u u} G] [is_connected G] [is_free_groupoid G] (r : G) : rooted_connected (symgen r) := ⟨λ b, path_nonempty_of_hom (category_theory.nonempty_hom_of_connected_groupoid r b)⟩ /-- A vertex group in a free connected groupoid is free. With some work one could drop the connectedness assumption, by looking at connected components. -/ instance End_is_free_of_connected_free {G} [groupoid G] [is_connected G] [is_free_groupoid G] (r : G) : is_free_group (End r) := spanning_tree.End_is_free $ geodesic_subtree (symgen r) end is_free_groupoid /-- The Nielsen-Schreier theorem: a subgroup of a free group is free. -/ instance subgroup_is_free_of_is_free {G : Type u} [group G] [is_free_group G] (H : subgroup G) : is_free_group H := is_free_group.of_mul_equiv (End_mul_equiv_subgroup H)
6cc79819d2792d8379670274e6a233a2ab31a55f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/basic_monitor2.lean
9040b4878ba5988f84cf51cb098b4073953d5360
[ "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
848
lean
meta def get_file (fn : name) : vm format := do { d ← vm.get_decl fn, some n ← return (vm_decl.olean d) | failure, return (to_fmt n) } <|> return (to_fmt "<curr file>") meta def pos_info (fn : name) : vm format := do { d ← vm.get_decl fn, some pos ← return (vm_decl.pos d) | failure, file ← get_file fn, return (file ++ ":" ++ pos.1 ++ ":" ++ pos.2) } <|> return (to_fmt "<position not available>") @[vm_monitor] meta def basic_monitor : vm_monitor nat := { init := 1000, step := λ sz, do csz ← vm.call_stack_size, if sz = csz then return sz else do fn ← vm.curr_fn, pos ← pos_info fn, vm.trace (to_fmt "[" ++ csz ++ "]: " ++ to_fmt fn ++ " @ " ++ pos), return csz } set_option debugger true def f : nat → nat | 0 := 0 | (a+1) := f a #eval trace "a" (f 4)
881ce919d06acb9d540e91876b2e7a5a74121311
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/tests/lean/run/empty_set_inside_quotations.lean
960fb6f996d811f46a0442b866938ead20fffe82
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
402
lean
constant union_is_assoc {α} : is_associative (set α) (∪) attribute [instance] union_is_assoc #check ({} : set nat) open tactic expr meta def is_assoc_bin_app : expr → tactic (expr × expr) | (app (app op a1) a2) := do h ← to_expr ``(is_associative.assoc %%op), return (op, h) | _ := failed #eval to_expr ``(({} : set nat) ∪ {}) >>= is_assoc_bin_app >>= λ p, trace p.2
30fc9236432be2d8d4d2a3b75a358048f38128f0
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/inf_tree2.lean
11636a5bda7f9556432ea262f1140a847a6063da
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,119
lean
import logic data.nat.basic open nat inductive inftree (A : Type) : Type := leaf : A → inftree A, node : (nat → inftree A) → inftree A → inftree A namespace inftree inductive dsub {A : Type} : inftree A → inftree A → Prop := intro₁ : Π (f : nat → inftree A) (a : nat) (t : inftree A), dsub (f a) (node f t), intro₂ : Π (f : nat → inftree A) (a : nat) (t : inftree A), dsub t (node f t) definition dsub.node.acc {A : Type} (f : nat → inftree A) (hf : ∀a, acc dsub (f a)) (t : inftree A) (ht : acc dsub t) : acc dsub (node f t) := acc.intro (node f t) (λ (y : inftree A) (hlt : dsub y (node f t)), by cases hlt; apply (hf a); apply ht) definition dsub.leaf.acc {A : Type} (a : A) : acc dsub (leaf a) := acc.intro (leaf a) (λ (y : inftree A) (hlt : dsub y (leaf a)), by cases hlt) definition dsub.wf (A : Type) : well_founded (@dsub A) := well_founded.intro (λ (t : inftree A), rec_on t (λ a, dsub.leaf.acc a) (λ f t (ihf :∀a, acc dsub (f a)) (iht : acc dsub t), dsub.node.acc f ihf t iht)) end inftree
3af2e302966b4278848f6156a9a278e5a87db544
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/order/liminf_limsup.lean
9a0e5e493cbb582d3f2a4c6b69e432e29c14419a
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
16,957
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Johannes Hölzl -/ import order.filter.partial import order.filter.at_top_bot /-! # liminfs and limsups of functions and filters Defines the Liminf/Limsup of a function taking values in a conditionally complete lattice, with respect to an arbitrary filter. We define `f.Limsup` (`f.Liminf`) where `f` is a filter taking values in a conditionally complete lattice. `f.Limsup` is the smallest element `a` such that, eventually, `u ≤ a` (and vice versa for `f.Liminf`). To work with the Limsup along a function `u` use `(f.map u).Limsup`. Usually, one defines the Limsup as `Inf (Sup s)` where the Inf is taken over all sets in the filter. For instance, in ℕ along a function `u`, this is `Inf_n (Sup_{k ≥ n} u k)` (and the latter quantity decreases with `n`, so this is in fact a limit.). There is however a difficulty: it is well possible that `u` is not bounded on the whole space, only eventually (think of `Limsup (λx, 1/x)` on ℝ. Then there is no guarantee that the quantity above really decreases (the value of the `Sup` beforehand is not really well defined, as one can not use ∞), so that the Inf could be anything. So one can not use this `Inf Sup ...` definition in conditionally complete lattices, and one has to use a less tractable definition. In conditionally complete lattices, the definition is only useful for filters which are eventually bounded above (otherwise, the Limsup would morally be +∞, which does not belong to the space) and which are frequently bounded below (otherwise, the Limsup would morally be -∞, which is not in the space either). We start with definitions of these concepts for arbitrary filters, before turning to the definitions of Limsup and Liminf. In complete lattices, however, it coincides with the `Inf Sup` definition. -/ open filter set open_locale filter variables {α : Type*} {β : Type*} namespace filter section relation /-- `f.is_bounded (≺)`: the filter `f` is eventually bounded w.r.t. the relation `≺`, i.e. eventually, it is bounded by some uniform bound. `r` will be usually instantiated with `≤` or `≥`. -/ def is_bounded (r : α → α → Prop) (f : filter α) := ∃ b, ∀ᶠ x in f, r x b /-- `f.is_bounded_under (≺) u`: the image of the filter `f` under `u` is eventually bounded w.r.t. the relation `≺`, i.e. eventually, it is bounded by some uniform bound. -/ def is_bounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (f.map u).is_bounded r variables {r : α → α → Prop} {f g : filter α} /-- `f` is eventually bounded if and only if, there exists an admissible set on which it is bounded. -/ lemma is_bounded_iff : f.is_bounded r ↔ (∃s∈f.sets, ∃b, s ⊆ {x | r x b}) := iff.intro (assume ⟨b, hb⟩, ⟨{a | r a b}, hb, b, subset.refl _⟩) (assume ⟨s, hs, b, hb⟩, ⟨b, mem_sets_of_superset hs hb⟩) /-- A bounded function `u` is in particular eventually bounded. -/ lemma is_bounded_under_of {f : filter β} {u : β → α} : (∃b, ∀x, r (u x) b) → f.is_bounded_under r u | ⟨b, hb⟩ := ⟨b, show ∀ᶠ x in f, r (u x) b, from eventually_of_forall hb⟩ lemma is_bounded_bot : is_bounded r ⊥ ↔ nonempty α := by simp [is_bounded, exists_true_iff_nonempty] lemma is_bounded_top : is_bounded r ⊤ ↔ (∃t, ∀x, r x t) := by simp [is_bounded, eq_univ_iff_forall] lemma is_bounded_principal (s : set α) : is_bounded r (𝓟 s) ↔ (∃t, ∀x∈s, r x t) := by simp [is_bounded, subset_def] lemma is_bounded_sup [is_trans α r] (hr : ∀b₁ b₂, ∃b, r b₁ b ∧ r b₂ b) : is_bounded r f → is_bounded r g → is_bounded r (f ⊔ g) | ⟨b₁, h₁⟩ ⟨b₂, h₂⟩ := let ⟨b, rb₁b, rb₂b⟩ := hr b₁ b₂ in ⟨b, eventually_sup.mpr ⟨h₁.mono (λ x h, trans h rb₁b), h₂.mono (λ x h, trans h rb₂b)⟩⟩ lemma is_bounded.mono (h : f ≤ g) : is_bounded r g → is_bounded r f | ⟨b, hb⟩ := ⟨b, h hb⟩ lemma is_bounded_under.mono {f g : filter β} {u : β → α} (h : f ≤ g) : g.is_bounded_under r u → f.is_bounded_under r u := λ hg, hg.mono (map_mono h) lemma is_bounded.is_bounded_under {q : β → β → Prop} {u : α → β} (hf : ∀a₀ a₁, r a₀ a₁ → q (u a₀) (u a₁)) : f.is_bounded r → f.is_bounded_under q u | ⟨b, h⟩ := ⟨u b, show ∀ᶠ x in f, q (u x) (u b), from h.mono (λ x, hf x b)⟩ /-- `is_cobounded (≺) f` states that the filter `f` does not tend to infinity w.r.t. `≺`. This is also called frequently bounded. Will be usually instantiated with `≤` or `≥`. There is a subtlety in this definition: we want `f.is_cobounded` to hold for any `f` in the case of complete lattices. This will be relevant to deduce theorems on complete lattices from their versions on conditionally complete lattices with additional assumptions. We have to be careful in the edge case of the trivial filter containing the empty set: the other natural definition `¬ ∀ a, ∀ᶠ n in f, a ≤ n` would not work as well in this case. -/ def is_cobounded (r : α → α → Prop) (f : filter α) := ∃b, ∀a, (∀ᶠ x in f, r x a) → r b a /-- `is_cobounded_under (≺) f u` states that the image of the filter `f` under the map `u` does not tend to infinity w.r.t. `≺`. This is also called frequently bounded. Will be usually instantiated with `≤` or `≥`. -/ def is_cobounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (f.map u).is_cobounded r /-- To check that a filter is frequently bounded, it suffices to have a witness which bounds `f` at some point for every admissible set. This is only an implication, as the other direction is wrong for the trivial filter.-/ lemma is_cobounded.mk [is_trans α r] (a : α) (h : ∀s∈f, ∃x∈s, r a x) : f.is_cobounded r := ⟨a, assume y s, let ⟨x, h₁, h₂⟩ := h _ s in trans h₂ h₁⟩ /-- A filter which is eventually bounded is in particular frequently bounded (in the opposite direction). At least if the filter is not trivial. -/ lemma is_bounded.is_cobounded_flip [is_trans α r] [ne_bot f] : f.is_bounded r → f.is_cobounded (flip r) | ⟨a, ha⟩ := ⟨a, assume b hb, let ⟨x, rxa, rbx⟩ := (ha.and hb).exists in show r b a, from trans rbx rxa⟩ lemma is_cobounded_bot : is_cobounded r ⊥ ↔ (∃b, ∀x, r b x) := by simp [is_cobounded] lemma is_cobounded_top : is_cobounded r ⊤ ↔ nonempty α := by simp [is_cobounded, eq_univ_iff_forall, exists_true_iff_nonempty] {contextual := tt} lemma is_cobounded_principal (s : set α) : (𝓟 s).is_cobounded r ↔ (∃b, ∀a, (∀x∈s, r x a) → r b a) := by simp [is_cobounded, subset_def] lemma is_cobounded.mono (h : f ≤ g) : f.is_cobounded r → g.is_cobounded r | ⟨b, hb⟩ := ⟨b, assume a ha, hb a (h ha)⟩ end relation lemma is_cobounded_le_of_bot [order_bot α] {f : filter α} : f.is_cobounded (≤) := ⟨⊥, assume a h, bot_le⟩ lemma is_cobounded_ge_of_top [order_top α] {f : filter α} : f.is_cobounded (≥) := ⟨⊤, assume a h, le_top⟩ lemma is_bounded_le_of_top [order_top α] {f : filter α} : f.is_bounded (≤) := ⟨⊤, eventually_of_forall $ λ _, le_top⟩ lemma is_bounded_ge_of_bot [order_bot α] {f : filter α} : f.is_bounded (≥) := ⟨⊥, eventually_of_forall $ λ _, bot_le⟩ lemma is_bounded_under_sup [semilattice_sup α] {f : filter β} {u v : β → α} : f.is_bounded_under (≤) u → f.is_bounded_under (≤) v → f.is_bounded_under (≤) (λa, u a ⊔ v a) | ⟨bu, (hu : ∀ᶠ x in f, u x ≤ bu)⟩ ⟨bv, (hv : ∀ᶠ x in f, v x ≤ bv)⟩ := ⟨bu ⊔ bv, show ∀ᶠ x in f, u x ⊔ v x ≤ bu ⊔ bv, by filter_upwards [hu, hv] assume x, sup_le_sup⟩ lemma is_bounded_under_inf [semilattice_inf α] {f : filter β} {u v : β → α} : f.is_bounded_under (≥) u → f.is_bounded_under (≥) v → f.is_bounded_under (≥) (λa, u a ⊓ v a) | ⟨bu, (hu : ∀ᶠ x in f, u x ≥ bu)⟩ ⟨bv, (hv : ∀ᶠ x in f, v x ≥ bv)⟩ := ⟨bu ⊓ bv, show ∀ᶠ x in f, u x ⊓ v x ≥ bu ⊓ bv, by filter_upwards [hu, hv] assume x, inf_le_inf⟩ /-- Filters are automatically bounded or cobounded in complete lattices. To use the same statements in complete and conditionally complete lattices but let automation fill automatically the boundedness proofs in complete lattices, we use the tactic `is_bounded_default` in the statements, in the form `(hf : f.is_bounded (≥) . is_bounded_default)`. -/ meta def is_bounded_default : tactic unit := tactic.applyc ``is_cobounded_le_of_bot <|> tactic.applyc ``is_cobounded_ge_of_top <|> tactic.applyc ``is_bounded_le_of_top <|> tactic.applyc ``is_bounded_ge_of_bot section conditionally_complete_lattice variables [conditionally_complete_lattice α] /-- The `Limsup` of a filter `f` is the infimum of the `a` such that, eventually for `f`, holds `x ≤ a`. -/ def Limsup (f : filter α) : α := Inf { a | ∀ᶠ n in f, n ≤ a } /-- The `Liminf` of a filter `f` is the supremum of the `a` such that, eventually for `f`, holds `x ≥ a`. -/ def Liminf (f : filter α) : α := Sup { a | ∀ᶠ n in f, a ≤ n } /-- The `limsup` of a function `u` along a filter `f` is the infimum of the `a` such that, eventually for `f`, holds `u x ≤ a`. -/ def limsup (f : filter β) (u : β → α) : α := (f.map u).Limsup /-- The `liminf` of a function `u` along a filter `f` is the supremum of the `a` such that, eventually for `f`, holds `u x ≥ a`. -/ def liminf (f : filter β) (u : β → α) : α := (f.map u).Liminf section variables {f : filter β} {u : β → α} theorem limsup_eq : f.limsup u = Inf { a | ∀ᶠ n in f, u n ≤ a } := rfl theorem liminf_eq : f.liminf u = Sup { a | ∀ᶠ n in f, a ≤ u n } := rfl end theorem Limsup_le_of_le {f : filter α} {a} (hf : f.is_cobounded (≤) . is_bounded_default) (h : ∀ᶠ n in f, n ≤ a) : f.Limsup ≤ a := cInf_le hf h theorem le_Liminf_of_le {f : filter α} {a} (hf : f.is_cobounded (≥) . is_bounded_default) (h : ∀ᶠ n in f, a ≤ n) : a ≤ f.Liminf := le_cSup hf h theorem le_Limsup_of_le {f : filter α} {a} (hf : f.is_bounded (≤) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, n ≤ b) → a ≤ b) : a ≤ f.Limsup := le_cInf hf h theorem Liminf_le_of_le {f : filter α} {a} (hf : f.is_bounded (≥) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, b ≤ n) → b ≤ a) : f.Liminf ≤ a := cSup_le hf h theorem Liminf_le_Limsup {f : filter α} [ne_bot f] (h₁ : f.is_bounded (≤) . is_bounded_default) (h₂ : f.is_bounded (≥) . is_bounded_default) : f.Liminf ≤ f.Limsup := Liminf_le_of_le h₂ $ assume a₀ ha₀, le_Limsup_of_le h₁ $ assume a₁ ha₁, show a₀ ≤ a₁, from let ⟨b, hb₀, hb₁⟩ := (ha₀.and ha₁).exists in le_trans hb₀ hb₁ lemma Liminf_le_Liminf {f g : filter α} (hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default) (h : ∀ a, (∀ᶠ n in f, a ≤ n) → ∀ᶠ n in g, a ≤ n) : f.Liminf ≤ g.Liminf := cSup_le_cSup hg hf h lemma Limsup_le_Limsup {f g : filter α} (hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default) (h : ∀ a, (∀ᶠ n in g, n ≤ a) → ∀ᶠ n in f, n ≤ a) : f.Limsup ≤ g.Limsup := cInf_le_cInf hf hg h lemma Limsup_le_Limsup_of_le {f g : filter α} (h : f ≤ g) (hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default) : f.Limsup ≤ g.Limsup := Limsup_le_Limsup hf hg (assume a ha, h ha) lemma Liminf_le_Liminf_of_le {f g : filter α} (h : g ≤ f) (hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default) : f.Liminf ≤ g.Liminf := Liminf_le_Liminf hf hg (assume a ha, h ha) lemma limsup_le_limsup {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : u ≤ᶠ[f] v) (hu : f.is_cobounded_under (≤) u . is_bounded_default) (hv : f.is_bounded_under (≤) v . is_bounded_default) : f.limsup u ≤ f.limsup v := Limsup_le_Limsup hu hv $ assume b, h.trans lemma liminf_le_liminf {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : ∀ᶠ a in f, u a ≤ v a) (hu : f.is_bounded_under (≥) u . is_bounded_default) (hv : f.is_cobounded_under (≥) v . is_bounded_default) : f.liminf u ≤ f.liminf v := @limsup_le_limsup (order_dual β) α _ _ _ _ h hv hu theorem Limsup_principal {s : set α} (h : bdd_above s) (hs : s.nonempty) : (𝓟 s).Limsup = Sup s := by simp [Limsup]; exact cInf_upper_bounds_eq_cSup h hs theorem Liminf_principal {s : set α} (h : bdd_below s) (hs : s.nonempty) : (𝓟 s).Liminf = Inf s := @Limsup_principal (order_dual α) _ s h hs lemma limsup_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : ∀ᶠ a in f, u a = v a) : limsup f u = limsup f v := begin rw limsup_eq, congr' with b, exact eventually_congr (h.mono $ λ x hx, by simp [hx]) end lemma liminf_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : ∀ᶠ a in f, u a = v a) : liminf f u = liminf f v := @limsup_congr (order_dual β) _ _ _ _ _ h lemma limsup_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} [ne_bot f] (b : β) : limsup f (λ x, b) = b := begin rw limsup_eq, apply le_antisymm, { exact cInf_le ⟨b, λ a, eventually_const.1⟩ (eventually_le.refl _ _) }, { exact le_cInf ⟨b, eventually_le.refl _ _⟩ (λ a, eventually_const.1) } end lemma liminf_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} [ne_bot f] (b : β) : liminf f (λ x, b) = b := @limsup_const (order_dual β) α _ f _ b end conditionally_complete_lattice section complete_lattice variables [complete_lattice α] @[simp] theorem Limsup_bot : (⊥ : filter α).Limsup = ⊥ := bot_unique $ Inf_le $ by simp @[simp] theorem Liminf_bot : (⊥ : filter α).Liminf = ⊤ := top_unique $ le_Sup $ by simp @[simp] theorem Limsup_top : (⊤ : filter α).Limsup = ⊤ := top_unique $ le_Inf $ by simp [eq_univ_iff_forall]; exact assume b hb, (top_unique $ hb _) @[simp] theorem Liminf_top : (⊤ : filter α).Liminf = ⊥ := bot_unique $ Sup_le $ by simp [eq_univ_iff_forall]; exact assume b hb, (bot_unique $ hb _) lemma liminf_le_limsup {f : filter β} [ne_bot f] {u : β → α} : liminf f u ≤ limsup f u := Liminf_le_Limsup is_bounded_le_of_top is_bounded_ge_of_bot theorem has_basis.Limsup_eq_infi_Sup {ι} {p : ι → Prop} {s} {f : filter α} (h : f.has_basis p s) : f.Limsup = ⨅ i (hi : p i), Sup (s i) := le_antisymm (le_binfi $ λ i hi, Inf_le $ h.eventually_iff.2 ⟨i, hi, λ x, le_Sup⟩) (le_Inf $ assume a ha, let ⟨i, hi, ha⟩ := h.eventually_iff.1 ha in infi_le_of_le _ $ infi_le_of_le hi $ Sup_le ha) theorem Limsup_eq_infi_Sup {f : filter α} : f.Limsup = ⨅ s ∈ f, Sup s := f.basis_sets.Limsup_eq_infi_Sup /-- In a complete lattice, the limsup of a function is the infimum over sets `s` in the filter of the supremum of the function over `s` -/ theorem limsup_eq_infi_supr {f : filter β} {u : β → α} : f.limsup u = ⨅ s ∈ f, ⨆ a ∈ s, u a := (f.basis_sets.map u).Limsup_eq_infi_Sup.trans $ by simp only [Sup_image, id] lemma limsup_eq_infi_supr_of_nat {u : ℕ → α} : limsup at_top u = ⨅n:ℕ, ⨆i≥n, u i := (at_top_basis.map u).Limsup_eq_infi_Sup.trans $ by simp only [Sup_image, infi_const]; refl theorem Liminf_eq_supr_Inf {f : filter α} : f.Liminf = ⨆ s ∈ f, Inf s := @Limsup_eq_infi_Sup (order_dual α) _ _ /-- In a complete lattice, the liminf of a function is the infimum over sets `s` in the filter of the supremum of the function over `s` -/ theorem liminf_eq_supr_infi {f : filter β} {u : β → α} : f.liminf u = ⨆ s ∈ f, ⨅ a ∈ s, u a := @limsup_eq_infi_supr (order_dual α) β _ _ _ lemma liminf_eq_supr_infi_of_nat {u : ℕ → α} : liminf at_top u = ⨆n:ℕ, ⨅i≥n, u i := @limsup_eq_infi_supr_of_nat (order_dual α) _ u end complete_lattice section conditionally_complete_linear_order lemma eventually_lt_of_lt_liminf {f : filter α} [conditionally_complete_linear_order β] {u : α → β} {b : β} (h : b < liminf f u) (hu : f.is_bounded_under (≥) u . is_bounded_default) : ∀ᶠ a in f, b < u a := begin obtain ⟨c, hc, hbc⟩ : ∃ (c : β) (hc : c ∈ {c : β | ∀ᶠ (n : α) in f, c ≤ u n}), b < c := exists_lt_of_lt_cSup hu h, exact hc.mono (λ x hx, lt_of_lt_of_le hbc hx) end lemma eventually_lt_of_limsup_lt {f : filter α} [conditionally_complete_linear_order β] {u : α → β} {b : β} (h : limsup f u < b) (hu : f.is_bounded_under (≤) u . is_bounded_default) : ∀ᶠ a in f, u a < b := @eventually_lt_of_lt_liminf _ (order_dual β) _ _ _ _ h hu end conditionally_complete_linear_order end filter
6da1da63dcf387f746f8ecc1f3183e7a6bcfcf78
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/local_homeomorph.lean
f5acc6167e97aee5b2eae95aed3d4a9225c2c0a0
[ "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
47,449
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.equiv.local_equiv import topology.opens /-! # Local homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions `e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout instead of `e.to_fun x` and `e.inv_fun x`. ## Main definitions `homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with source = target = univ `local_homeomorph.symm` : the inverse of a local homeomorphism `local_homeomorph.trans` : the composition of two local homeomorphisms `local_homeomorph.refl` : the identity local homeomorphism `local_homeomorph.of_set`: the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local homeomorphisms ## Implementation notes Most statements are copied from their local_equiv versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `local_equiv.lean`. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `local_equiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ open function set filter topological_space (second_countable_topology) open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- local homeomorphisms, defined on open subsets of the space -/ @[nolint has_inhabited_instance] structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends local_equiv α β := (open_source : is_open source) (open_target : is_open target) (continuous_to_fun : continuous_on to_fun source) (continuous_inv_fun : continuous_on inv_fun target) /-- A homeomorphism induces a local homeomorphism on the whole space -/ def homeomorph.to_local_homeomorph (e : α ≃ₜ β) : local_homeomorph α β := { open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun }, continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun }, ..e.to_equiv.to_local_equiv } namespace local_homeomorph variables (e : local_homeomorph α β) (e' : local_homeomorph β γ) instance : has_coe_to_fun (local_homeomorph α β) := ⟨_, λ e, e.to_local_equiv.to_fun⟩ /-- The inverse of a local homeomorphism -/ protected def symm : local_homeomorph β α := { open_source := e.open_target, open_target := e.open_source, continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, ..e.to_local_equiv.symm } /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (e : local_homeomorph α β) : α → β := e /-- See Note [custom simps projection] -/ def simps.symm_apply (e : local_homeomorph α β) : β → α := e.symm initialize_simps_projections local_homeomorph (to_local_equiv_to_fun → apply, to_local_equiv_inv_fun → symm_apply, to_local_equiv_source → source, to_local_equiv_target → target, -to_local_equiv) protected lemma continuous_on : continuous_on e e.source := e.continuous_to_fun lemma continuous_on_symm : continuous_on e.symm e.target := e.continuous_inv_fun @[simp, mfld_simps] lemma mk_coe (e : local_equiv α β) (a b c d) : (local_homeomorph.mk e a b c d : α → β) = e := rfl @[simp, mfld_simps] lemma mk_coe_symm (e : local_equiv α β) (a b c d) : ((local_homeomorph.mk e a b c d).symm : β → α) = e.symm := rfl /- Register a few simp lemmas to make sure that `simp` puts the application of a local homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp, mfld_simps] lemma to_fun_eq_coe (e : local_homeomorph α β) : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_eq_coe (e : local_homeomorph α β) : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma coe_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma coe_coe_symm : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source protected lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩ protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on /-- Replace `to_local_equiv` field to provide better definitional equalities. -/ def replace_equiv (e : local_homeomorph α β) (e' : local_equiv α β) (h : e.to_local_equiv = e') : local_homeomorph α β := { to_local_equiv := e', open_source := h ▸ e.open_source, open_target := h ▸ e.open_target, continuous_to_fun := h ▸ e.continuous_to_fun, continuous_inv_fun := h ▸ e.continuous_inv_fun } lemma replace_equiv_eq_self (e : local_homeomorph α β) (e' : local_equiv α β) (h : e.to_local_equiv = e') : e.replace_equiv e' h = e := by { cases e, subst e', refl } lemma source_preimage_target : e.source ⊆ e ⁻¹' e.target := e.maps_to lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β} (h : e.to_local_equiv = e'.to_local_equiv) : e = e' := by { cases e, cases e', cases h, refl } lemma eventually_left_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 x, e.symm (e y) = y := (e.open_source.eventually_mem hx).mono e.left_inv' lemma eventually_left_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 (e.symm x), e.symm (e y) = y := e.eventually_left_inverse (e.map_target hx) lemma eventually_right_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 x, e (e.symm y) = y := (e.open_target.eventually_mem hx).mono e.right_inv' lemma eventually_right_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 (e x), e (e.symm y) = y := e.eventually_right_inverse (e.map_source hx) lemma eventually_ne_nhds_within (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ x' in 𝓝[{x}ᶜ] x, e x' ≠ e x := eventually_nhds_within_iff.2 $ (e.eventually_left_inverse hx).mono $ λ x' hx', mt $ λ h, by rw [mem_singleton_iff, ← e.left_inv hx, ← h, hx'] lemma nhds_within_source_inter {x} (hx : x ∈ e.source) (s : set α) : 𝓝[e.source ∩ s] x = 𝓝[s] x := nhds_within_inter_of_mem (mem_nhds_within_of_mem_nhds $ is_open.mem_nhds e.open_source hx) lemma nhds_within_target_inter {x} (hx : x ∈ e.target) (s : set β) : 𝓝[e.target ∩ s] x = 𝓝[s] x := e.symm.nhds_within_source_inter hx s lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h lemma image_source_inter_eq' (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_source_inter_eq' s lemma image_source_inter_eq (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := e.to_local_equiv.image_source_inter_eq s lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_target_inter_eq (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := e.to_local_equiv.source_inter_preimage_inv_preimage s lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma source_inter_preimage_target_inter (s : set β) : e.source ∩ (e ⁻¹' (e.target ∩ s)) = e.source ∩ (e ⁻¹' s) := e.to_local_equiv.source_inter_preimage_target_inter s /-- Two local homeomorphisms are equal when they have equal `to_fun`, `inv_fun` and `source`. It is not sufficient to have equal `to_fun` and `source`, as this only determines `inv_fun` on the target. This would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/ @[ext] protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e x = e' x) (hinv : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := eq_of_local_equiv_eq (local_equiv.ext h hinv hs) @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl -- The following lemmas are already simp via local_equiv lemma symm_source : e.symm.source = e.target := rfl lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp /-- A local homeomorphism is continuous at any point of its source -/ protected lemma continuous_at {x : α} (h : x ∈ e.source) : continuous_at e x := (e.continuous_on x h).continuous_at (is_open.mem_nhds e.open_source h) /-- A local homeomorphism inverse is continuous at any point of its target -/ lemma continuous_at_symm {x : β} (h : x ∈ e.target) : continuous_at e.symm x := e.symm.continuous_at h lemma tendsto_symm {x} (hx : x ∈ e.source) : tendsto e.symm (𝓝 (e x)) (𝓝 x) := by simpa only [continuous_at, e.left_inv hx] using e.continuous_at_symm (e.map_source hx) lemma map_nhds_eq {x} (hx : x ∈ e.source) : map e (𝓝 x) = 𝓝 (e x) := le_antisymm (e.continuous_at hx) $ le_map_of_right_inverse (e.eventually_right_inverse' hx) (e.tendsto_symm hx) lemma symm_map_nhds_eq {x} (hx : x ∈ e.source) : map e.symm (𝓝 (e x)) = 𝓝 x := (e.symm.map_nhds_eq $ e.map_source hx).trans $ by rw e.left_inv hx lemma image_mem_nhds {x} (hx : x ∈ e.source) {s : set α} (hs : s ∈ 𝓝 x) : e '' s ∈ 𝓝 (e x) := e.map_nhds_eq hx ▸ filter.image_mem_map hs lemma map_nhds_within_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) (s : set α) : map e (𝓝[s] x) = 𝓝[e '' (e.source ∩ s)] (e x) := calc map e (𝓝[s] x) = map e (𝓝[e.source ∩ s] x) : congr_arg (map e) (e.nhds_within_source_inter hx _).symm ... = 𝓝[e '' (e.source ∩ s)] (e x) : (e.left_inv_on.mono $ inter_subset_left _ _).map_nhds_within_eq (e.left_inv hx) (e.continuous_at_symm (e.map_source hx)).continuous_within_at (e.continuous_at hx).continuous_within_at lemma map_nhds_within_preimage_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) (s : set β) : map e (𝓝[e ⁻¹' s] x) = 𝓝[s] (e x) := by rw [e.map_nhds_within_eq hx, e.image_source_inter_eq', e.target_inter_inv_preimage_preimage, e.nhds_within_target_inter (e.map_source hx)] lemma preimage_open_of_open {s : set β} (hs : is_open s) : is_open (e.source ∩ e ⁻¹' s) := e.continuous_on.preimage_open_of_open e.open_source hs /-! ### `local_homeomorph.is_image` relation We say that `t : set β` is an image of `s : set α` under a local homeomorphism `e` if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). This definition is a restatement of `local_equiv.is_image` for local homeomorphisms. In this section we transfer API about `local_equiv.is_image` to local homeomorphisms and add a few `local_homeomorph`-specific lemmas like `local_homeomorph.is_image.closure`. -/ /-- We say that `t : set β` is an image of `s : set α` under a local homeomorphism `e` if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). -/ def is_image (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace is_image variables {e} {s : set α} {t : set β} {x : α} {y : β} lemma to_local_equiv (h : e.is_image s t) : e.to_local_equiv.is_image s t := h lemma apply_mem_iff (h : e.is_image s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx protected lemma symm (h : e.is_image s t) : e.symm.is_image t s := h.to_local_equiv.symm lemma symm_apply_mem_iff (h : e.is_image s t) (hy : y ∈ e.target) : (e.symm y ∈ s ↔ y ∈ t) := h.symm hy @[simp] lemma symm_iff : e.symm.is_image t s ↔ e.is_image s t := ⟨λ h, h.symm, λ h, h.symm⟩ protected lemma maps_to (h : e.is_image s t) : maps_to e (e.source ∩ s) (e.target ∩ t) := h.to_local_equiv.maps_to lemma symm_maps_to (h : e.is_image s t) : maps_to e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.maps_to lemma image_eq (h : e.is_image s t) : e '' (e.source ∩ s) = e.target ∩ t := h.to_local_equiv.image_eq lemma symm_image_eq (h : e.is_image s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq lemma iff_preimage_eq : e.is_image s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s := local_equiv.is_image.iff_preimage_eq alias iff_preimage_eq ↔ local_homeomorph.is_image.preimage_eq local_homeomorph.is_image.of_preimage_eq lemma iff_symm_preimage_eq : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t := symm_iff.symm.trans iff_preimage_eq alias iff_symm_preimage_eq ↔ local_homeomorph.is_image.symm_preimage_eq local_homeomorph.is_image.of_symm_preimage_eq lemma iff_symm_preimage_eq' : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' (e.source ∩ s) = e.target ∩ t := by rw [iff_symm_preimage_eq, ← image_source_inter_eq, ← image_source_inter_eq'] alias iff_symm_preimage_eq' ↔ local_homeomorph.is_image.symm_preimage_eq' local_homeomorph.is_image.of_symm_preimage_eq' lemma iff_preimage_eq' : e.is_image s t ↔ e.source ∩ e ⁻¹' (e.target ∩ t) = e.source ∩ s := symm_iff.symm.trans iff_symm_preimage_eq' alias iff_preimage_eq' ↔ local_homeomorph.is_image.preimage_eq' local_homeomorph.is_image.of_preimage_eq' lemma of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.is_image s t := local_equiv.is_image.of_image_eq h lemma of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.is_image s t := local_equiv.is_image.of_symm_image_eq h protected lemma compl (h : e.is_image s t) : e.is_image sᶜ tᶜ := λ x hx, not_congr (h hx) protected lemma inter {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∩ s') (t ∩ t') := λ x hx, and_congr (h hx) (h' hx) protected lemma union {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∪ s') (t ∪ t') := λ x hx, or_congr (h hx) (h' hx) protected lemma diff {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s \ s') (t \ t') := h.inter h'.compl lemma left_inv_on_piecewise {e' : local_homeomorph α β} [∀ i, decidable (i ∈ s)] [∀ i, decidable (i ∈ t)] (h : e.is_image s t) (h' : e'.is_image s t) : left_inv_on (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) := h.to_local_equiv.left_inv_on_piecewise h' lemma inter_eq_of_inter_eq_of_eq_on {e' : local_homeomorph α β} (h : e.is_image s t) (h' : e'.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : e.target ∩ t = e'.target ∩ t := h.to_local_equiv.inter_eq_of_inter_eq_of_eq_on h' hs Heq lemma symm_eq_on_of_inter_eq_of_eq_on {e' : local_homeomorph α β} (h : e.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : eq_on e.symm e'.symm (e.target ∩ t) := h.to_local_equiv.symm_eq_on_of_inter_eq_of_eq_on hs Heq lemma map_nhds_within_eq (h : e.is_image s t) (hx : x ∈ e.source) : map e (𝓝[s] x) = 𝓝[t] (e x) := by rw [e.map_nhds_within_eq hx, h.image_eq, e.nhds_within_target_inter (e.map_source hx)] protected lemma closure (h : e.is_image s t) : e.is_image (closure s) (closure t) := λ x hx, by simp only [mem_closure_iff_nhds_within_ne_bot, ← h.map_nhds_within_eq hx, map_ne_bot_iff] protected lemma interior (h : e.is_image s t) : e.is_image (interior s) (interior t) := by simpa only [closure_compl, compl_compl] using h.compl.closure.compl protected lemma frontier (h : e.is_image s t) : e.is_image (frontier s) (frontier t) := h.closure.diff h.interior lemma is_open_iff (h : e.is_image s t) : is_open (e.source ∩ s) ↔ is_open (e.target ∩ t) := ⟨λ hs, h.symm_preimage_eq' ▸ e.symm.preimage_open_of_open hs, λ hs, h.preimage_eq' ▸ e.preimage_open_of_open hs⟩ /-- Restrict a `local_homeomorph` to a pair of corresponding open sets. -/ @[simps to_local_equiv] def restr (h : e.is_image s t) (hs : is_open (e.source ∩ s)) : local_homeomorph α β := { to_local_equiv := h.to_local_equiv.restr, open_source := hs, open_target := h.is_open_iff.1 hs, continuous_to_fun := e.continuous_on.mono (inter_subset_left _ _), continuous_inv_fun := e.symm.continuous_on.mono (inter_subset_left _ _) } end is_image lemma is_image_source_target : e.is_image e.source e.target := e.to_local_equiv.is_image_source_target lemma is_image_source_target_of_disjoint (e' : local_homeomorph α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) : e.is_image e'.source e'.target := e.to_local_equiv.is_image_source_target_of_disjoint e'.to_local_equiv hs ht /-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted to the source. -/ lemma preimage_interior (s : set β) : e.source ∩ e ⁻¹' (interior s) = e.source ∩ interior (e ⁻¹' s) := (is_image.of_preimage_eq rfl).interior.preimage_eq lemma preimage_closure (s : set β) : e.source ∩ e ⁻¹' (closure s) = e.source ∩ closure (e ⁻¹' s) := (is_image.of_preimage_eq rfl).closure.preimage_eq lemma preimage_frontier (s : set β) : e.source ∩ e ⁻¹' (frontier s) = e.source ∩ frontier (e ⁻¹' s) := (is_image.of_preimage_eq rfl).frontier.preimage_eq lemma preimage_open_of_open_symm {s : set α} (hs : is_open s) : is_open (e.target ∩ e.symm ⁻¹' s) := e.symm.continuous_on.preimage_open_of_open e.open_target hs /-- The image of an open set in the source is open. -/ lemma image_open_of_open {s : set α} (hs : is_open s) (h : s ⊆ e.source) : is_open (e '' s) := begin have : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h, rw this, exact e.continuous_on_symm.preimage_open_of_open e.open_target hs end /-- The image of the restriction of an open set to the source is open. -/ lemma image_open_of_open' {s : set α} (hs : is_open s) : is_open (e '' (e.source ∩ s)) := image_open_of_open _ (is_open.inter e.open_source hs) (inter_subset_left _ _) /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open_restrict (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map (e.source.restrict e)) (hs : is_open e.source) : local_homeomorph α β := { to_local_equiv := e, open_source := hs, open_target := by simpa only [range_restrict, e.image_source_eq_target] using ho.is_open_range, continuous_to_fun := hc, continuous_inv_fun := e.image_source_eq_target ▸ ho.continuous_on_image_of_left_inv_on e.left_inv_on } /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map e) (hs : is_open e.source) : local_homeomorph α β := of_continuous_open_restrict e hc (ho.restrict hs) hs /-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its local_equiv is defeq to local_equiv.restr -/ protected def restr_open (s : set α) (hs : is_open s) : local_homeomorph α β := (@is_image.of_symm_preimage_eq α β _ _ e s (e.symm ⁻¹' s) rfl).restr (is_open.inter e.open_source hs) @[simp, mfld_simps] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) : (e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl -- Already simp via local_equiv lemma restr_open_source (s : set α) (hs : is_open s) : (e.restr_open s hs).source = e.source ∩ s := rfl /-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since local homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of local equivalences -/ @[simps apply symm_apply (mfld_cfg), simps source target {attrs := []}] protected def restr (s : set α) : local_homeomorph α β := e.restr_open (interior s) is_open_interior @[simp, mfld_simps] lemma restr_to_local_equiv (s : set α) : (e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s := by rw [e.restr_source, hs.interior_eq] lemma restr_to_local_equiv' (s : set α) (hs : is_open s): (e.restr s).to_local_equiv = e.to_local_equiv.restr s := by rw [e.restr_to_local_equiv, hs.interior_eq] lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := begin apply eq_of_local_equiv_eq, rw restr_to_local_equiv, apply local_equiv.restr_eq_of_source_subset, exact interior_maximal h e.open_source end @[simp, mfld_simps] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s := begin refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _, simp [e.open_source.interior_eq, ← inter_assoc] end /-- The identity on the whole space as a local homeomorphism. -/ @[simps apply (mfld_cfg), simps source target {attrs := []}] protected def refl (α : Type*) [topological_space α] : local_homeomorph α α := (homeomorph.refl α).to_local_homeomorph @[simp, mfld_simps] lemma refl_local_equiv : (local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl @[simp, mfld_simps] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α := rfl section variables {s : set α} (hs : is_open s) /-- The identity local equiv on a set `s` -/ @[simps apply (mfld_cfg), simps source target {attrs := []}] def of_set (s : set α) (hs : is_open s) : local_homeomorph α α := { open_source := hs, open_target := hs, continuous_to_fun := continuous_id.continuous_on, continuous_inv_fun := continuous_id.continuous_on, ..local_equiv.of_set s } @[simp, mfld_simps] lemma of_set_to_local_equiv : (of_set s hs).to_local_equiv = local_equiv.of_set s := rfl @[simp, mfld_simps] lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl @[simp, mfld_simps] lemma of_set_univ_eq_refl : of_set univ is_open_univ = local_homeomorph.refl α := by ext; simp end /-- Composition of two local homeomorphisms when the target of the first and the source of the second coincide. -/ protected def trans' (h : e.target = e'.source) : local_homeomorph α γ := { open_source := e.open_source, open_target := e'.open_target, continuous_to_fun := begin apply continuous_on.comp e'.continuous_to_fun e.continuous_to_fun, rw ← h, exact e.to_local_equiv.source_subset_preimage_target end, continuous_inv_fun := begin apply continuous_on.comp e.continuous_inv_fun e'.continuous_inv_fun, rw h, exact e'.to_local_equiv.target_subset_preimage_source end, ..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h } /-- Composing two local homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_homeomorph α γ := local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm (e'.restr_open e.target e.open_target) (by simp [inter_comm]) @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := local_equiv.trans_source e.to_local_equiv e'.to_local_equiv lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_homeomorph γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv @[simp, mfld_simps] lemma trans_refl : e.trans (local_homeomorph.refl β) = e := eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv @[simp, mfld_simps] lemma refl_trans : (local_homeomorph.refl α).trans e = e := eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv lemma trans_of_set {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e ⁻¹' s) := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, (e.preimage_interior _).symm, hs.interior_eq] lemma trans_of_set' {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e.source ∩ e ⁻¹' s) := by rw [trans_of_set, restr_source_inter] lemma of_set_trans {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr s := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, hs.interior_eq, inter_comm] lemma of_set_trans' {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr (e.source ∩ s) := by rw [of_set_trans, restr_source_inter] @[simp, mfld_simps] lemma of_set_trans_of_set {s : set α} (hs : is_open s) {s' : set α} (hs' : is_open s') : (of_set s hs).trans (of_set s' hs') = of_set (s ∩ s') (is_open.inter hs hs') := begin rw (of_set s hs).trans_of_set hs', ext; simp [hs'.interior_eq] end lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s) /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same local equiv. -/ def eq_on_source (e e' : local_homeomorph α β) : Prop := e.source = e'.source ∧ (eq_on e e' e.source) lemma eq_on_source_iff (e e' : local_homeomorph α β) : eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv := iff.rfl /-- `eq_on_source` is an equivalence relation -/ instance : setoid (local_homeomorph α β) := { r := eq_on_source, iseqv := ⟨ λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv, λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h), λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2 ((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- If two local homeomorphisms are equivalent, so are their inverses -/ lemma eq_on_source.symm' {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm := local_equiv.eq_on_source.symm' h /-- Two equivalent local homeomorphisms have the same source -/ lemma eq_on_source.source_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local homeomorphisms have the same target -/ lemma eq_on_source.target_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target := h.symm'.1 /-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/ lemma eq_on_source.eq_on {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e e' e.source := h.2 /-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/ lemma eq_on_source.symm_eq_on_target {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.2 /-- Composition of local homeomorphisms respects equivalence -/ lemma eq_on_source.trans' {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := local_equiv.eq_on_source.trans' he hf /-- Restriction of local homeomorphisms respects equivalence -/ lemma eq_on_source.restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := local_equiv.eq_on_source.restr he _ /-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source := local_equiv.trans_self_symm _ lemma trans_symm_self : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := e.symm.trans_self_symm lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t section prod /-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/ @[simps to_local_equiv apply (mfld_cfg), simps source target symm_apply {attrs := []}] def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) := { open_source := e.open_source.prod e'.open_source, open_target := e.open_target.prod e'.open_target, continuous_to_fun := e.continuous_on.prod_map e'.continuous_on, continuous_inv_fun := e.continuous_on_symm.prod_map e'.continuous_on_symm, to_local_equiv := e.to_local_equiv.prod e'.to_local_equiv } @[simp, mfld_simps] lemma prod_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := rfl @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} [topological_space η] [topological_space ε] (e : local_homeomorph α β) (f : local_homeomorph β γ) (e' : local_homeomorph δ η) (f' : local_homeomorph η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := local_homeomorph.eq_of_local_equiv_eq $ by dsimp only [trans_to_local_equiv, prod_to_local_equiv]; apply local_equiv.prod_trans end prod section piecewise /-- Combine two `local_homeomorph`s using `set.piecewise`. The source of the new `local_homeomorph` is `s.ite e.source e'.source = e.source ∩ s ∪ e'.source \ s`, and similarly for target. The function sends `e.source ∩ s` to `e.target ∩ t` using `e` and `e'.source \ s` to `e'.target \ t` using `e'`, and similarly for the inverse function. To ensure that the maps `to_fun` and `inv_fun` are inverse of each other on the new `source` and `target`, the definition assumes that the sets `s` and `t` are related both by `e.is_image` and `e'.is_image`. To ensure that the new maps are continuous on `source`/`target`, it also assumes that `e.source` and `e'.source` meet `frontier s` on the same set and `e x = e' x` on this intersection. -/ @[simps to_local_equiv apply {fully_applied := ff}] def piecewise (e e' : local_homeomorph α β) (s : set α) (t : set β) [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) (Hs : e.source ∩ frontier s = e'.source ∩ frontier s) (Heq : eq_on e e' (e.source ∩ frontier s)) : local_homeomorph α β := { to_local_equiv := e.to_local_equiv.piecewise e'.to_local_equiv s t H H', open_source := e.open_source.ite e'.open_source Hs, open_target := e.open_target.ite e'.open_target $ H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq, continuous_to_fun := continuous_on_piecewise_ite e.continuous_on e'.continuous_on Hs Heq, continuous_inv_fun := continuous_on_piecewise_ite e.continuous_on_symm e'.continuous_on_symm (H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq) (H.frontier.symm_eq_on_of_inter_eq_of_eq_on Hs Heq) } @[simp] lemma symm_piecewise (e e' : local_homeomorph α β) {s : set α} {t : set β} [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) (Hs : e.source ∩ frontier s = e'.source ∩ frontier s) (Heq : eq_on e e' (e.source ∩ frontier s)) : (e.piecewise e' s t H H' Hs Heq).symm = e.symm.piecewise e'.symm t s H.symm H'.symm (H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq) (H.frontier.symm_eq_on_of_inter_eq_of_eq_on Hs Heq) := rfl /-- Combine two `local_homeomorph`s with disjoint sources and disjoint targets. We reuse `local_homeomorph.piecewise` then override `to_local_equiv` to `local_equiv.disjoint_union`. This way we have better definitional equalities for `source` and `target`. -/ def disjoint_union (e e' : local_homeomorph α β) [∀ x, decidable (x ∈ e.source)] [∀ y, decidable (y ∈ e.target)] (Hs : disjoint e.source e'.source) (Ht : disjoint e.target e'.target) : local_homeomorph α β := (e.piecewise e' e.source e.target e.is_image_source_target (e'.is_image_source_target_of_disjoint e Hs.symm Ht.symm) (by rw [e.open_source.inter_frontier_eq, e'.open_source.inter_frontier_eq_empty_of_disjoint Hs]) (by { rw e.open_source.inter_frontier_eq, exact eq_on_empty _ _ })).replace_equiv (e.to_local_equiv.disjoint_union e'.to_local_equiv Hs Ht) (local_equiv.disjoint_union_eq_piecewise _ _ _ _).symm end piecewise section pi variables {ι : Type*} [fintype ι] {Xi Yi : ι → Type*} [Π i, topological_space (Xi i)] [Π i, topological_space (Yi i)] (ei : Π i, local_homeomorph (Xi i) (Yi i)) /-- The product of a finite family of `local_homeomorph`s. -/ @[simps to_local_equiv] def pi : local_homeomorph (Π i, Xi i) (Π i, Yi i) := { to_local_equiv := local_equiv.pi (λ i, (ei i).to_local_equiv), open_source := is_open_set_pi finite_univ $ λ i hi, (ei i).open_source, open_target := is_open_set_pi finite_univ $ λ i hi, (ei i).open_target, continuous_to_fun := continuous_on_pi.2 $ λ i, (ei i).continuous_on.comp (continuous_apply _).continuous_on (λ f hf, hf i trivial), continuous_inv_fun := continuous_on_pi.2 $ λ i, (ei i).continuous_on_symm.comp (continuous_apply _).continuous_on (λ f hf, hf i trivial) } end pi section continuity /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_within_at_iff_continuous_within_at_comp_right {f : β → γ} {s : set β} {x : β} (h : x ∈ e.target) : continuous_within_at f s x ↔ continuous_within_at (f ∘ e) (e ⁻¹' s) (e.symm x) := by simp_rw [continuous_within_at, ← @tendsto_map'_iff _ _ _ _ e, e.map_nhds_within_preimage_eq (e.map_target h), (∘), e.right_inv h] /-- Continuity at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_at_iff_continuous_at_comp_right {f : β → γ} {x : β} (h : x ∈ e.target) : continuous_at f x ↔ continuous_at (f ∘ e) (e.symm x) := by rw [← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_right h, preimage_univ, continuous_within_at_univ] /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the right is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) : continuous_on f s ↔ continuous_on (f ∘ e) (e.source ∩ e ⁻¹' s) := begin simp only [← e.symm_image_eq_source_inter_preimage h, continuous_on, ball_image_iff], refine forall_congr (λ x, forall_congr $ λ hx, _), rw [e.continuous_within_at_iff_continuous_within_at_comp_right (h hx), e.symm_image_eq_source_inter_preimage h, inter_comm, continuous_within_at_inter], exact is_open.mem_nhds e.open_source (e.map_target (h hx)) end /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_within_at_iff_continuous_within_at_comp_left {f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ 𝓝[s] x) : continuous_within_at f s x ↔ continuous_within_at (e ∘ f) s x := begin refine ⟨(e.continuous_at hx).tendsto.comp, λ fe_cont, _⟩, rw [← continuous_within_at_inter' h] at fe_cont ⊢, have : continuous_within_at (e.symm ∘ (e ∘ f)) (s ∩ f ⁻¹' e.source) x, { have : continuous_within_at e.symm univ (e (f x)) := (e.continuous_at_symm (e.map_source hx)).continuous_within_at, exact continuous_within_at.comp this fe_cont (subset_univ _) }, exact this.congr (λy hy, by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) end /-- Continuity at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_at_iff_continuous_at_comp_left {f : γ → α} {x : γ} (h : f ⁻¹' e.source ∈ 𝓝 x) : continuous_at f x ↔ continuous_at (e ∘ f) x := begin have hx : f x ∈ e.source := (mem_of_mem_nhds h : _), have h' : f ⁻¹' e.source ∈ 𝓝[univ] x, by rwa nhds_within_univ, rw [← continuous_within_at_univ, ← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_left hx h'] end /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the left is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' e.source) : continuous_on f s ↔ continuous_on (e ∘ f) s := forall_congr $ λ x, forall_congr $ λ hx, e.continuous_within_at_iff_continuous_within_at_comp_left (h hx) (mem_sets_of_superset self_mem_nhds_within h) end continuity /-- A local homeomrphism defines a homeomorphism between its source and target. -/ def to_homeomorph_source_target : e.source ≃ₜ e.target := { to_fun := e.maps_to.restrict _ _ _, inv_fun := e.symm_maps_to.restrict _ _ _, left_inv := λ x, subtype.eq $ e.left_inv x.2, right_inv := λ x, subtype.eq $ e.right_inv x.2, continuous_to_fun := continuous_subtype_mk _ $ continuous_on_iff_continuous_restrict.1 e.continuous_on, continuous_inv_fun := continuous_subtype_mk _ $ continuous_on_iff_continuous_restrict.1 e.symm.continuous_on } lemma second_countable_topology_source [second_countable_topology β] (e : local_homeomorph α β) : second_countable_topology e.source := e.to_homeomorph_source_target.second_countable_topology /-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ @[simps apply symm_apply (mfld_cfg)] def to_homeomorph_of_source_eq_univ_target_eq_univ (h : e.source = (univ : set α)) (h' : e.target = univ) : α ≃ₜ β := { to_fun := e, inv_fun := e.symm, left_inv := λx, e.left_inv $ by { rw h, exact mem_univ _ }, right_inv := λx, e.right_inv $ by { rw h', exact mem_univ _ }, continuous_to_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_to_fun, rw h end, continuous_inv_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_inv_fun, rw h' end } /-- A local homeomorphism whose source is all of `α` defines an open embedding of `α` into `β`. The converse is also true; see `open_embedding.to_local_homeomorph`. -/ lemma to_open_embedding (h : e.source = set.univ) : open_embedding e := begin apply open_embedding_of_continuous_injective_open, { apply continuous_iff_continuous_on_univ.mpr, rw ← h, exact e.continuous_to_fun }, { apply set.injective_iff_inj_on_univ.mpr, rw ← h, exact e.inj_on }, { intros U hU, simpa only [h, subset_univ] with mfld_simps using e.image_open_of_open hU} end end local_homeomorph namespace homeomorph variables (e : α ≃ₜ β) (e' : β ≃ₜ γ) /- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ attribute [simps apply source target {simp_rhs := tt, .. mfld_cfg}] to_local_homeomorph @[simp, mfld_simps] lemma to_local_homeomorph_coe_symm : (e.to_local_homeomorph.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma refl_to_local_homeomorph : (homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_homeomorph : e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl @[simp, mfld_simps] lemma trans_to_local_homeomorph : (e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph := local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _ end homeomorph namespace open_embedding variables (f : α → β) (h : open_embedding f) /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local homeomorphism whose source is all of `α`. The converse is also true; see `local_homeomorph.to_open_embedding`. -/ @[simps apply source target (mfld_cfg)] noncomputable def to_local_homeomorph [nonempty α] : local_homeomorph α β := local_homeomorph.of_continuous_open ((h.to_embedding.inj.inj_on univ).to_local_equiv _ _) h.continuous.continuous_on h.is_open_map is_open_univ lemma continuous_at_iff {f : α → β} {g : β → γ} (hf : open_embedding f) {x : α} : continuous_at (g ∘ f) x ↔ continuous_at g (f x) := begin haveI : nonempty α := ⟨x⟩, convert (((hf.to_local_homeomorph f).continuous_at_iff_continuous_at_comp_right) _).symm, { apply (local_homeomorph.left_inv _ _).symm, simp, }, { simp, }, end end open_embedding namespace topological_space.opens open topological_space variables (s : opens α) [nonempty s] /-- The inclusion of an open subset `s` of a space `α` into `α` is a local homeomorphism from the subtype `s` to `α`. -/ noncomputable def local_homeomorph_subtype_coe : local_homeomorph s α := open_embedding.to_local_homeomorph _ s.2.open_embedding_subtype_coe @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_coe : (s.local_homeomorph_subtype_coe : s → α) = coe := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_source : s.local_homeomorph_subtype_coe.source = set.univ := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_target : s.local_homeomorph_subtype_coe.target = s := by { simp only [local_homeomorph_subtype_coe, subtype.range_coe_subtype] with mfld_simps, refl } end topological_space.opens namespace local_homeomorph open topological_space variables (e : local_homeomorph α β) variables (s : opens α) [nonempty s] /-- The restriction of a local homeomorphism `e` to an open subset `s` of the domain type produces a local homeomorphism whose domain is the subtype `s`.-/ noncomputable def subtype_restr : local_homeomorph s β := s.local_homeomorph_subtype_coe.trans e lemma subtype_restr_def : e.subtype_restr s = s.local_homeomorph_subtype_coe.trans e := rfl @[simp, mfld_simps] lemma subtype_restr_coe : ((e.subtype_restr s : local_homeomorph s β) : s → β) = set.restrict (e : α → β) s := rfl @[simp, mfld_simps] lemma subtype_restr_source : (e.subtype_restr s).source = coe ⁻¹' e.source := by simp only [subtype_restr_def] with mfld_simps /- This lemma characterizes the transition functions of an open subset in terms of the transition functions of the original space. -/ lemma subtype_restr_symm_trans_subtype_restr (f f' : local_homeomorph α β) : (f.subtype_restr s).symm.trans (f'.subtype_restr s) ≈ (f.symm.trans f').restr (f.target ∩ (f.symm) ⁻¹' s) := begin simp only [subtype_restr_def, trans_symm_eq_symm_trans_symm], have openness₁ : is_open (f.target ∩ f.symm ⁻¹' s) := f.preimage_open_of_open_symm s.2, rw [← of_set_trans _ openness₁, ← trans_assoc, ← trans_assoc], refine eq_on_source.trans' _ (eq_on_source_refl _), -- f' has been eliminated !!! have sets_identity : f.symm.source ∩ (f.target ∩ (f.symm) ⁻¹' s) = f.symm.source ∩ f.symm ⁻¹' s, { mfld_set_tac }, have openness₂ : is_open (s : set α) := s.2, rw [of_set_trans', sets_identity, ← trans_of_set' _ openness₂, trans_assoc], refine eq_on_source.trans' (eq_on_source_refl _) _, -- f has been eliminated !!! refine setoid.trans (trans_symm_self s.local_homeomorph_subtype_coe) _, simp only with mfld_simps, end end local_homeomorph
a5c5ffd1598f3f29174cea36f100b22d370f1036
78630e908e9624a892e24ebdd21260720d29cf55
/src/logic_first_order/fol_18.lean
6912d544c9ac096242fd974ef0822db6d18608af
[ "CC0-1.0" ]
permissive
tomasz-lisowski/lean-logic-examples
84e612466776be0a16c23a0439ff8ef6114ddbe1
2b2ccd467b49c3989bf6c92ec0358a8d6ee68c5d
refs/heads/master
1,683,334,199,431
1,621,938,305,000
1,621,938,305,000
365,041,573
1
0
null
null
null
null
UTF-8
Lean
false
false
565
lean
namespace fol_18 variable U : Type variables P Q : U → Prop variable c : U theorem fol_18 (h : ∃ x, P x ∧ Q x ∧ ∀ y, P y → x = y) : P c → Q c := assume h1: P c, have h2: P c ∧ Q c ∧ ∀ y, P y → c = y, from exists.elim h (assume s (h3: P s ∧ Q s ∧ ∀ y, P y → s = y), have h4: _, from and.right h3, have h5: _, from and.right h4, have h6: P c → s = c, from h5 c, have h7: s = c, from h6 h1, have h8: c = s, from eq.symm h7, begin rw h8, from h3 end), show Q c, from and.left (and.right h2) end fol_18
12d7c145c3ecbd2ec4440fe029859999e9694fbd
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/set_theory/game/nim.lean
b57ee3e96be3dc5a5e7cb8f00fbc293bbbd20f8c
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,609
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson, Markus Himmel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.bitwise import Mathlib.set_theory.game.impartial import Mathlib.set_theory.ordinal_arithmetic import Mathlib.PostPort universes u_1 u namespace Mathlib /-! # Nim and the Sprague-Grundy theorem This file contains the definition for nim for any ordinal `O`. In the game of `nim O₁` both players may move to `nim O₂` for any `O₂ < O₁`. We also define a Grundy value for an impartial game `G` and prove the Sprague-Grundy theorem, that `G` is equivalent to `nim (grundy_value G)`. Finally, we compute the sum of finite Grundy numbers: if `G` and `H` have Grundy values `n` and `m`, where `n` and `m` are natural numbers, then `G + H` has the Grundy value `n xor m`. ## Implementation details The pen-and-paper definition of nim defines the possible moves of `nim O` to be `{O' | O' < O}`. However, this definition does not work for us because it would make the type of nim `ordinal.{u} → pgame.{u + 1}`, which would make it impossible for us to state the Sprague-Grundy theorem, since that requires the type of `nim` to be `ordinal.{u} → pgame.{u}`. For this reason, we instead use `O.out.α` for the possible moves, which makes proofs significantly more messy and tedious, but avoids the universe bump. The lemma `nim_def` is somewhat prone to produce "motive is not type correct" errors. If you run into this problem, you may find the lemmas `exists_ordinal_move_left_eq` and `exists_move_left_eq` useful. -/ /-- `ordinal.out` and `ordinal.type_out'` are required to make the definition of nim computable. `ordinal.out` performs the same job as `quotient.out` but is specific to ordinals. -/ def ordinal.out (o : ordinal) : Well_order := Well_order.mk (Well_order.α (quotient.out o)) (fun (x y : Well_order.α (quotient.out o)) => Well_order.r (quotient.out o) x y) sorry /-- This is the same as `ordinal.type_out` but defined to use `ordinal.out`. -/ theorem ordinal.type_out' (o : ordinal) : ordinal.type (Well_order.r (ordinal.out o)) = o := ordinal.type_out /-- The definition of single-heap nim, which can be viewed as a pile of stones where each player can take a positive number of stones from it on their turn. -/ def nim : ordinal → pgame := sorry namespace pgame namespace nim theorem nim_def (O : ordinal) : nim O = mk (Well_order.α (ordinal.out O)) (Well_order.α (ordinal.out O)) (fun (O₂ : Well_order.α (ordinal.out O)) => nim (ordinal.typein (Well_order.r (ordinal.out O)) O₂)) fun (O₂ : Well_order.α (ordinal.out O)) => nim (ordinal.typein (Well_order.r (ordinal.out O)) O₂) := sorry theorem nim_wf_lemma {O₁ : ordinal} (O₂ : Well_order.α (ordinal.out O₁)) : ordinal.typein (Well_order.r (ordinal.out O₁)) O₂ < O₁ := sorry protected instance nim_impartial (O : ordinal) : impartial (nim O) := sorry theorem exists_ordinal_move_left_eq (O : ordinal) (i : left_moves (nim O)) : ∃ (O' : ordinal), ∃ (H : O' < O), move_left (nim O) i = nim O' := sorry theorem exists_move_left_eq (O : ordinal) (O' : ordinal) (H : O' < O) : ∃ (i : left_moves (nim O)), move_left (nim O) i = nim O' := sorry theorem zero_first_loses : first_loses (nim 0) := sorry theorem non_zero_first_wins (O : ordinal) (hO : O ≠ 0) : first_wins (nim O) := sorry theorem sum_first_loses_iff_eq (O₁ : ordinal) (O₂ : ordinal) : first_loses (nim O₁ + nim O₂) ↔ O₁ = O₂ := sorry theorem sum_first_wins_iff_neq (O₁ : ordinal) (O₂ : ordinal) : first_wins (nim O₁ + nim O₂) ↔ O₁ ≠ O₂ := sorry theorem equiv_iff_eq (O₁ : ordinal) (O₂ : ordinal) : equiv (nim O₁) (nim O₂) ↔ O₁ = O₂ := sorry end nim /-- This definition will be used in the proof of the Sprague-Grundy theorem. It takes a function from some type to ordinals and returns a nonempty set of ordinals with empty intersection with the image of the function. It is guaranteed that the smallest ordinal not in the image will be in the set, i.e. we can use this to find the mex. -/ def nonmoves {α : Type u} (M : α → ordinal) : set ordinal := set_of fun (O : ordinal) => ¬∃ (a : α), M a = O theorem nonmoves_nonempty {α : Type u} (M : α → ordinal) : ∃ (O : ordinal), O ∈ nonmoves M := sorry /-- The Grundy value of an impartial game, the ordinal which corresponds to the game of nim that the game is equivalent to -/ def grundy_value (G : pgame) [impartial G] : ordinal := sorry theorem grundy_value_def (G : pgame) [impartial G] : grundy_value G = ordinal.omin (nonmoves fun (i : left_moves G) => grundy_value (move_left G i)) (nonmoves_nonempty fun (i : left_moves G) => grundy_value (move_left G i)) := sorry /-- The Sprague-Grundy theorem which states that every impartial game is equivalent to a game of nim, namely the game of nim corresponding to the games Grundy value -/ theorem equiv_nim_grundy_value (G : pgame) [impartial G] : equiv G (nim (grundy_value G)) := sorry theorem equiv_nim_iff_grundy_value_eq (G : pgame) [impartial G] (O : ordinal) : equiv G (nim O) ↔ grundy_value G = O := sorry theorem nim.grundy_value (O : ordinal) : grundy_value (nim O) = O := eq.mpr (id (Eq._oldrec (Eq.refl (grundy_value (nim O) = O)) (Eq.symm (propext (equiv_nim_iff_grundy_value_eq (nim O) O))))) (equiv_refl (nim O)) theorem equiv_iff_grundy_value_eq (G : pgame) (H : pgame) [impartial G] [impartial H] : equiv G H ↔ grundy_value G = grundy_value H := iff.trans (iff.mp equiv_congr_left (equiv_nim_grundy_value H) G) (equiv_nim_iff_grundy_value_eq G (grundy_value H)) theorem grundy_value_zero : grundy_value 0 = 0 := sorry theorem equiv_zero_iff_grundy_value (G : pgame) [impartial G] : equiv G 0 ↔ grundy_value G = 0 := eq.mpr (id (Eq._oldrec (Eq.refl (equiv G 0 ↔ grundy_value G = 0)) (propext (equiv_iff_grundy_value_eq G 0)))) (eq.mpr (id (Eq._oldrec (Eq.refl (grundy_value G = grundy_value 0 ↔ grundy_value G = 0)) grundy_value_zero)) (iff.refl (grundy_value G = 0))) theorem grundy_value_nim_add_nim (n : ℕ) (m : ℕ) : grundy_value (nim ↑n + nim ↑m) = ↑(nat.lxor n m) := sorry theorem nim_add_nim_equiv {n : ℕ} {m : ℕ} : equiv (nim ↑n + nim ↑m) (nim ↑(nat.lxor n m)) := sorry theorem grundy_value_add (G : pgame) (H : pgame) [impartial G] [impartial H] {n : ℕ} {m : ℕ} (hG : grundy_value G = ↑n) (hH : grundy_value H = ↑m) : grundy_value (G + H) = ↑(nat.lxor n m) := sorry
632b17e9c65a67c36e45d8b32d1bdc88460c28ac
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/core.lean
377922527518bb2024f1a337b38b54da5ec4d91a
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,894
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura notation, basic datatypes and type classes -/ prelude notation `Prop` := Sort 0 /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr ` ∧ `:35 reserve infixr ` /\ `:35 reserve infixr ` \/ `:30 reserve infixr ` ∨ `:30 reserve infix ` <-> `:20 reserve infix ` ↔ `:20 reserve infix ` = `:50 reserve infix ` == `:50 reserve infix ` ≠ `:50 reserve infix ` ≈ `:50 reserve infix ` ~ `:50 reserve infix ` ≡ `:50 reserve infixl ` ⬝ `:75 reserve infixr ` ▸ `:75 reserve infixr ` ▹ `:75 /- types and type constructors -/ reserve infixr ` ⊕ `:30 reserve infixr ` × `:35 /- arithmetic operations -/ reserve infixl ` + `:65 reserve infixl ` - `:65 reserve infixl ` * `:70 reserve infixl ` / `:70 reserve infixl ` % `:70 reserve prefix `-`:100 reserve infix ` ^ `:80 reserve infixr ` ∘ `:90 -- input with \comp reserve infix ` <= `:50 reserve infix ` ≤ `:50 reserve infix ` < `:50 reserve infix ` >= `:50 reserve infix ` ≥ `:50 reserve infix ` > `:50 /- boolean operations -/ reserve infixl ` && `:70 reserve infixl ` || `:65 /- set operations -/ reserve infix ` ∈ `:50 reserve infix ` ∉ `:50 reserve infixl ` ∩ `:70 reserve infixl ` ∪ `:65 reserve infix ` ⊆ `:50 reserve infix ` ⊇ `:50 reserve infix ` ⊂ `:50 reserve infix ` ⊃ `:50 reserve infix ` \ `:70 /- other symbols -/ reserve infix ` ∣ `:50 reserve infixl ` ++ `:65 reserve infixr ` :: `:67 reserve infixl `; `:1 universe variables u v /-- Gadget for optional parameter support. -/ @[reducible] def opt_param (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def out_param (α : Sort u) : Sort u := α inductive punit : Sort u | star : punit inductive unit : Type | star : unit /-- Gadget for defining thunks, thunk parameters have special treatment. Example: given def f (s : string) (t : thunk nat) : nat an application f "hello" 10 is converted into f "hello" (λ _, 10) -/ @[reducible] def thunk (α : Type u) : Type u := unit → α inductive true : Prop | intro : true inductive false : Prop inductive empty : Type def not (a : Prop) := a → false prefix `¬` := not inductive eq {α : Sort u} (a : α) : α → Prop | refl : eq a init_quotient inductive heq {α : Sort u} (a : α) : Π {β : Sort u}, β → Prop | refl : heq a structure prod (α : Type u) (β : Type v) := (fst : α) (snd : β) /- Similar to prod, but α and β can be propositions. We use this type internally to automatically generate the brec_on recursor. -/ structure pprod (α : Sort u) (β : Sort v) := (fst : α) (snd : β) inductive and (a b : Prop) : Prop | intro : a → b → and def and.elim_left {a b : Prop} (h : and a b) : a := and.rec (λ ha hb, ha) h def and.left := @and.elim_left def and.elim_right {a b : Prop} (h : and a b) : b := and.rec (λ ha hb, hb) h def and.right := @and.elim_right inductive sum (α : Type u) (β : Type v) | inl {} : α → sum | inr {} : β → sum inductive psum (α : Sort u) (β : Sort v) | inl {} : α → psum | inr {} : β → psum inductive or (a b : Prop) : Prop | inl {} : a → or | inr {} : b → or def or.intro_left {a : Prop} (b : Prop) (ha : a) : or a b := or.inl ha def or.intro_right (a : Prop) {b : Prop} (hb : b) : or a b := or.inr hb structure sigma {α : Type u} (β : α → Type v) := mk :: (fst : α) (snd : β fst) structure psigma {α : Sort u} (β : α → Sort v) := mk :: (fst : α) (snd : β fst) inductive pos_num : Type | one : pos_num | bit1 : pos_num → pos_num | bit0 : pos_num → pos_num namespace pos_num def succ : pos_num → pos_num | one := bit0 one | (bit1 n) := bit0 (succ n) | (bit0 n) := bit1 n end pos_num inductive num : Type | zero : num | pos : pos_num → num namespace num open pos_num def succ : num → num | zero := pos one | (pos p) := pos (pos_num.succ p) end num inductive bool : Type | ff : bool | tt : bool /- Remark: subtype must take a Sort instead of Type because of the axiom strong_indefinite_description. -/ structure subtype {α : Sort u} (p : α → Prop) := tag :: (elt_of : α) (has_property : p elt_of) class inductive decidable (p : Prop) | is_false : ¬p → decidable | is_true : p → decidable @[reducible] def decidable_pred {α : Sort u} (r : α → Prop) := Π (a : α), decidable (r a) @[reducible] def decidable_rel {α : Sort u} (r : α → α → Prop) := Π (a b : α), decidable (r a b) @[reducible] def decidable_eq (α : Sort u) := decidable_rel (@eq α) inductive option (α : Type u) | none {} : option | some : α → option export option (none some) export bool (ff tt) inductive list (T : Type u) | nil {} : list | cons : T → list → list inductive nat | zero : nat | succ : nat → nat structure unification_constraint := {α : Type u} (lhs : α) (rhs : α) infix ` ≟ `:50 := unification_constraint.mk infix ` =?= `:50 := unification_constraint.mk structure unification_hint := (pattern : unification_constraint) (constraints : list unification_constraint) /- Declare builtin and reserved notation -/ class has_zero (α : Type u) := (zero : α) class has_one (α : Type u) := (one : α) class has_add (α : Type u) := (add : α → α → α) class has_mul (α : Type u) := (mul : α → α → α) class has_inv (α : Type u) := (inv : α → α) class has_neg (α : Type u) := (neg : α → α) class has_sub (α : Type u) := (sub : α → α → α) class has_div (α : Type u) := (div : α → α → α) class has_dvd (α : Type u) := (dvd : α → α → Prop) class has_mod (α : Type u) := (mod : α → α → α) class has_le (α : Type u) := (le : α → α → Prop) class has_lt (α : Type u) := (lt : α → α → Prop) class has_append (α : Type u) := (append : α → α → α) class has_andthen (α : Type u) := (andthen : α → α → α) class has_union (α : Type u) := (union : α → α → α) class has_inter (α : Type u) := (inter : α → α → α) class has_sdiff (α : Type u) := (sdiff : α → α → α) class has_subset (α : Type u) := (subset : α → α → Prop) class has_ssubset (α : Type u) := (ssubset : α → α → Prop) /- Type classes has_emptyc and has_insert are used to implement polymorphic notation for collections. Example: {a, b, c}. -/ class has_emptyc (α : Type u) := (emptyc : α) class has_insert (α : out_param (Type u)) (γ : Type v) := (insert : α → γ → γ) /- Type class used to implement the notation { a ∈ c | p a } -/ class has_sep (α : out_param (Type u)) (γ : Type v) := (sep : (α → Prop) → γ → γ) /- Type class for set-like membership -/ class has_mem (α : out_param (Type u)) (γ : Type v) := (mem : α → γ → Prop) def zero {α : Type u} [has_zero α] : α := has_zero.zero α def one {α : Type u} [has_one α] : α := has_one.one α def add {α : Type u} [has_add α] : α → α → α := has_add.add def mul {α : Type u} [has_mul α] : α → α → α := has_mul.mul def sub {α : Type u} [has_sub α] : α → α → α := has_sub.sub def div {α : Type u} [has_div α] : α → α → α := has_div.div def dvd {α : Type u} [has_dvd α] : α → α → Prop := has_dvd.dvd def mod {α : Type u} [has_mod α] : α → α → α := has_mod.mod def neg {α : Type u} [has_neg α] : α → α := has_neg.neg def inv {α : Type u} [has_inv α] : α → α := has_inv.inv def le {α : Type u} [has_le α] : α → α → Prop := has_le.le def lt {α : Type u} [has_lt α] : α → α → Prop := has_lt.lt def append {α : Type u} [has_append α] : α → α → α := has_append.append def andthen {α : Type u} [has_andthen α] : α → α → α := has_andthen.andthen def union {α : Type u} [has_union α] : α → α → α := has_union.union def inter {α : Type u} [has_inter α] : α → α → α := has_inter.inter def sdiff {α : Type u} [has_sdiff α] : α → α → α := has_sdiff.sdiff def subset {α : Type u} [has_subset α] : α → α → Prop := has_subset.subset def ssubset {α : Type u} [has_ssubset α] : α → α → Prop := has_ssubset.ssubset @[reducible] def ge {α : Type u} [has_le α] (a b : α) : Prop := le b a @[reducible] def gt {α : Type u} [has_lt α] (a b : α) : Prop := lt b a @[reducible] def superset {α : Type u} [has_subset α] (a b : α) : Prop := subset b a @[reducible] def ssuperset {α : Type u} [has_ssubset α] (a b : α) : Prop := ssubset b a def bit0 {α : Type u} [s : has_add α] (a : α) : α := add a a def bit1 {α : Type u} [s₁ : has_one α] [s₂ : has_add α] (a : α) : α := add (bit0 a) one attribute [pattern] zero one bit0 bit1 add neg def insert {α : Type u} {γ : Type v} [has_insert α γ] : α → γ → γ := has_insert.insert /- The empty collection -/ def emptyc {α : Type u} [has_emptyc α] : α := has_emptyc.emptyc α def singleton {α : Type u} {γ : Type v} [has_emptyc γ] [has_insert α γ] (a : α) : γ := insert a emptyc def sep {α : Type u} {γ : Type v} [has_sep α γ] : (α → Prop) → γ → γ := has_sep.sep def mem {α : Type u} {γ : Type v} [has_mem α γ] : α → γ → Prop := has_mem.mem /- num, pos_num instances -/ instance : has_zero num := ⟨num.zero⟩ instance : has_one num := ⟨num.pos pos_num.one⟩ instance : has_one pos_num := ⟨pos_num.one⟩ namespace pos_num def is_one : pos_num → bool | one := tt | _ := ff def pred : pos_num → pos_num | one := one | (bit1 n) := bit0 n | (bit0 one) := one | (bit0 n) := bit1 (pred n) def size : pos_num → pos_num | one := one | (bit0 n) := succ (size n) | (bit1 n) := succ (size n) def add : pos_num → pos_num → pos_num | one b := succ b | a one := succ a | (bit0 a) (bit0 b) := bit0 (add a b) | (bit1 a) (bit1 b) := bit0 (succ (add a b)) | (bit0 a) (bit1 b) := bit1 (add a b) | (bit1 a) (bit0 b) := bit1 (add a b) end pos_num instance : has_add pos_num := ⟨pos_num.add⟩ namespace num open pos_num def add : num → num → num | zero a := a | b zero := b | (pos a) (pos b) := pos (pos_num.add a b) end num instance : has_add num := ⟨num.add⟩ def std.priority.default : num := 1000 def std.priority.max : num := 4294967295 /- nat basic instances -/ namespace nat protected def prio := num.add std.priority.default 100 protected def add : nat → nat → nat | a zero := a | a (succ b) := succ (add a b) def of_pos_num : pos_num → nat | pos_num.one := succ zero | (pos_num.bit0 a) := let r := of_pos_num a in nat.add r r | (pos_num.bit1 a) := let r := of_pos_num a in succ (nat.add r r) def of_num : num → nat | num.zero := zero | (num.pos p) := of_pos_num p end nat instance : has_zero nat := ⟨nat.zero⟩ instance : has_one nat := ⟨nat.succ (nat.zero)⟩ instance : has_add nat := ⟨nat.add⟩ /- Global declarations of right binding strength If a module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-c C-k" to see how to input it. -/ def std.prec.max : num := 1024 -- the strength of application, identifiers, (, [, etc. def std.prec.arrow : num := 25 /- The next def is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ def std.prec.max_plus := num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ std.prec.max))))))))) reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv infix = := eq infix == := heq infix ∈ := mem notation a ∉ s := ¬ mem a s infix + := add infix * := mul infix - := sub infix / := div infix ∣ := dvd infix % := mod prefix - := neg postfix ⁻¹ := inv infix <= := le infix >= := ge infix ≤ := le infix ≥ := ge infix < := lt infix > := gt infix ++ := append infix ; := andthen notation `∅` := emptyc infix ∪ := union infix ∩ := inter infix ⊆ := subset infix ⊇ := superset infix ⊂ := ssubset infix ⊃ := ssuperset infix \ := sdiff notation α × β := prod α β -- notation for n-ary tuples notation `(` h `, ` t:(foldr `, ` (e r, prod.mk e r)) `)` := prod.mk h t /- eq basic support -/ attribute [refl] eq.refl @[pattern] def rfl {α : Sort u} {a : α} : a = a := eq.refl a @[elab_as_eliminator, subst] lemma eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b := eq.rec h₂ h₁ notation h1 ▸ h2 := eq.subst h1 h2 @[trans] lemma eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c := h₂ ▸ h₁ @[symm] lemma eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a := h ▸ rfl /- sizeof -/ class has_sizeof (α : Sort u) := (sizeof : α → nat) def sizeof {α : Sort u} [s : has_sizeof α] : α → nat := has_sizeof.sizeof /- Declare sizeof instances and lemmas for types declared before has_sizeof. From now on, the inductive compiler will automatically generate sizeof instances and lemmas. -/ /- Every type `α` has a default has_sizeof instance that just returns 0 for every element of `α` -/ instance default_has_sizeof (α : Sort u) : has_sizeof α := ⟨λ a, nat.zero⟩ /- TODO(Leo): the [simp.sizeof] annotations are not really necessary. What we need is a robust way of unfolding sizeof definitions. -/ attribute [simp.sizeof] lemma default_has_sizeof_eq (α : Sort u) (a : α) : @sizeof α (default_has_sizeof α) a = 0 := rfl instance : has_sizeof nat := ⟨λ a, a⟩ attribute [simp.sizeof] lemma sizeof_nat_eq (a : nat) : sizeof a = a := rfl protected def prod.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (prod α β) → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (prod α β) := ⟨prod.sizeof⟩ attribute [simp.sizeof] lemma sizeof_prod_eq {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] (a : α) (b : β) : sizeof (prod.mk a b) = 1 + sizeof a + sizeof b := rfl protected def sum.sizeof {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] : (sum α β) → nat | (sum.inl a) := 1 + sizeof a | (sum.inr b) := 1 + sizeof b instance (α : Type u) (β : Type v) [has_sizeof α] [has_sizeof β] : has_sizeof (sum α β) := ⟨sum.sizeof⟩ attribute [simp.sizeof] lemma sizeof_sum_eq_left {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] (a : α) : sizeof (@sum.inl α β a) = 1 + sizeof a := rfl attribute [simp.sizeof] lemma sizeof_sum_eq_right {α : Type u} {β : Type v} [has_sizeof α] [has_sizeof β] (b : β) : sizeof (@sum.inr α β b) = 1 + sizeof b := rfl protected def sigma.sizeof {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] : sigma β → nat | ⟨a, b⟩ := 1 + sizeof a + sizeof b instance (α : Type u) (β : α → Type v) [has_sizeof α] [∀ a, has_sizeof (β a)] : has_sizeof (sigma β) := ⟨sigma.sizeof⟩ attribute [simp.sizeof] lemma sizeof_sigma_eq {α : Type u} {β : α → Type v} [has_sizeof α] [∀ a, has_sizeof (β a)] (a : α) (b : β a) : sizeof (@sigma.mk α β a b) = 1 + sizeof a + sizeof b := rfl instance : has_sizeof unit := ⟨λ u, 1⟩ attribute [simp.sizeof] lemma sizeof_unit_eq (u : unit) : sizeof u = 1 := rfl instance : has_sizeof punit := ⟨λ u, 1⟩ attribute [simp.sizeof] lemma sizeof_punit_eq (u : punit) : sizeof u = 1 := rfl instance : has_sizeof bool := ⟨λ u, 1⟩ attribute [simp.sizeof] lemma sizeof_bool_eq (b : bool) : sizeof b = 1 := rfl instance : has_sizeof pos_num := ⟨nat.of_pos_num⟩ attribute [simp.sizeof] lemma sizeof_pos_num_eq (p : pos_num) : sizeof p = nat.of_pos_num p := rfl instance : has_sizeof num := ⟨nat.of_num⟩ attribute [simp.sizeof] lemma sizeof_num_eq (n : num) : sizeof n = nat.of_num n := rfl protected def option.sizeof {α : Type u} [has_sizeof α] : option α → nat | none := 1 | (some a) := 1 + sizeof a instance (α : Type u) [has_sizeof α] : has_sizeof (option α) := ⟨option.sizeof⟩ attribute [simp.sizeof] lemma sizeof_option_none_eq (α : Type u) [has_sizeof α] : sizeof (@none α) = 1 := rfl attribute [simp.sizeof] lemma sizeof_option_some_eq {α : Type u} [has_sizeof α] (a : α) : sizeof (some a) = 1 + sizeof a := rfl protected def list.sizeof {α : Type u} [has_sizeof α] : list α → nat | list.nil := 1 | (list.cons a l) := 1 + sizeof a + list.sizeof l instance (α : Type u) [has_sizeof α] : has_sizeof (list α) := ⟨list.sizeof⟩ attribute [simp.sizeof] lemma sizeof_list_nil_eq (α : Type u) [has_sizeof α] : sizeof (@list.nil α) = 1 := rfl attribute [simp.sizeof] lemma sizeof_list_cons_eq {α : Type u} [has_sizeof α] (a : α) (l : list α) : sizeof (list.cons a l) = 1 + sizeof a + sizeof l := rfl attribute [simp.sizeof] lemma nat_add_zero (n : nat) : n + 0 = n := rfl /- Combinator calculus -/ namespace combinator universe variables u₁ u₂ u₃ def I {α : Type u₁} (a : α) := a def K {α : Type u₁} {β : Type u₂} (a : α) (b : β) := a def S {α : Type u₁} {β : Type u₂} {γ : Type u₃} (x : α → β → γ) (y : α → β) (z : α) := x z (y z) end combinator
1f082fc9dfa07e3081c5a19b79f9ccb163de956f
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed_space/basic.lean
d9c4f5b32215ec247f74a6e5685692242aa4c8fc
[ "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
22,501
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import analysis.normed.normed_field import analysis.normed.group.infinite_sum import data.matrix.basic import topology.sequences /-! # Normed spaces In this file we define (semi)normed spaces and algebras. We also prove some theorems about these definitions. -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space big_operators nnreal ennreal uniformity pointwise section semi_normed_group section prio set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[normed_space α β] : module α β` -- to take precedence over `semiring.to_module` as this leads to instance paths with better -- unification properties. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. Note that since this requires `semi_normed_group` and not `normed_group`, this typeclass can be used for "semi normed spaces" too, just as `module` can be used for "semi modules". -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [semi_normed_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) end prio variables [normed_field α] [semi_normed_group β] @[priority 100] -- see Note [lower instance priority] instance normed_space.has_bounded_smul [normed_space α β] : has_bounded_smul α β := { dist_smul_pair' := λ x y₁ y₂, by simpa [dist_eq_norm, smul_sub] using normed_space.norm_smul_le x (y₁ - y₂), dist_pair_smul' := λ x₁ x₂ y, by simpa [dist_eq_norm, sub_smul] using normed_space.norm_smul_le (x₁ - x₂) y } instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (norm_mul a b) } lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin by_cases h : s = 0, { simp [h] }, { refine le_antisymm (normed_space.norm_smul_le s x) _, calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul₀ h] ... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : mul_le_mul_of_nonneg_left (normed_space.norm_smul_le _ _) (norm_nonneg _) ... = ∥s • x∥ : by rw [norm_inv, ← mul_assoc, mul_inv_cancel (mt norm_eq_zero.1 h), one_mul] } end @[simp] lemma abs_norm_eq_norm (z : β) : |∥z∥| = ∥z∥ := (abs_eq (norm_nonneg z)).mpr (or.inl rfl) lemma inv_norm_smul_mem_closed_unit_ball [normed_space ℝ β] (x : β) : ∥x∥⁻¹ • x ∈ closed_ball (0 : β) 1 := by simp only [mem_closed_ball_zero_iff, norm_smul, norm_inv, norm_norm, ← div_eq_inv_mul, div_self_le_one] lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥₊ = ∥s∥₊ * ∥x∥₊ := nnreal.eq $ norm_smul s x lemma nndist_smul [normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = ∥s∥₊ * nndist x y := nnreal.eq $ dist_smul s x y lemma lipschitz_with_smul [normed_space α β] (s : α) : lipschitz_with ∥s∥₊ ((•) s : β → β) := lipschitz_with_iff_dist_le_mul.2 $ λ x y, by rw [dist_smul, coe_nnnorm] lemma norm_smul_of_nonneg [normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ∥t • x∥ = t * ∥x∥ := by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht] variables {E : Type*} [semi_normed_group E] [normed_space α E] variables {F : Type*} [semi_normed_group F] [normed_space α F] theorem eventually_nhds_norm_smul_sub_lt (c : α) (x : E) {ε : ℝ} (h : 0 < ε) : ∀ᶠ y in 𝓝 x, ∥c • (y - x)∥ < ε := have tendsto (λ y, ∥c • (y - x)∥) (𝓝 x) (𝓝 0), from ((continuous_id.sub continuous_const).const_smul _).norm.tendsto' _ _ (by simp), this.eventually (gt_mem_nhds h) lemma filter.tendsto.zero_smul_is_bounded_under_le {f : ι → α} {g : ι → E} {l : filter ι} (hf : tendsto f l (𝓝 0)) (hg : is_bounded_under (≤) l (norm ∘ g)) : tendsto (λ x, f x • g x) l (𝓝 0) := hf.op_zero_is_bounded_under_le hg (•) (λ x y, (norm_smul x y).le) lemma filter.is_bounded_under.smul_tendsto_zero {f : ι → α} {g : ι → E} {l : filter ι} (hf : is_bounded_under (≤) l (norm ∘ f)) (hg : tendsto g l (𝓝 0)) : tendsto (λ x, f x • g x) l (𝓝 0) := hg.op_zero_is_bounded_under_le hf (flip (•)) (λ x y, ((norm_smul y x).trans (mul_comm _ _)).le) theorem closure_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : closure (ball x r) = closed_ball x r := begin refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico (@zero_ne_one ℝ _ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, replace hr : 0 < r, from ((norm_nonneg _).trans hy).lt_of_ne hr.symm, apply mul_lt_mul'; assumption } end theorem frontier_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, is_open_ball.interior_eq], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : interior (closed_ball x r) = ball x r := begin cases hr.lt_or_lt with hr hr, { rw [closed_ball_eq_empty.2 hr, ball_eq_empty.2 hr.le, interior_empty] }, refine set.subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases (mem_closed_ball.1 $ interior_subset hy).lt_or_eq with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem frontier_closed_ball [normed_space ℝ E] (x : E) {r : ℝ} (hr : r ≠ 0) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] /-- A (semi) normed real vector space is homeomorphic to the unit ball in the same space. This homeomorphism sends `x : E` to `(1 + ∥x∥)⁻¹ • x`. In many cases the actual implementation is not important, so we don't mark the projection lemmas `homeomorph_unit_ball_apply_coe` and `homeomorph_unit_ball_symm_apply` as `@[simp]`. -/ @[simps { attrs := [] }] def homeomorph_unit_ball {E : Type*} [semi_normed_group E] [normed_space ℝ E] : E ≃ₜ ball (0 : E) 1 := { to_fun := λ x, ⟨(1 + ∥x∥)⁻¹ • x, begin have : ∥x∥ < |1 + ∥x∥| := (lt_one_add _).trans_le (le_abs_self _), rwa [mem_ball_zero_iff, norm_smul, real.norm_eq_abs, abs_inv, ← div_eq_inv_mul, div_lt_one ((norm_nonneg x).trans_lt this)], end⟩, inv_fun := λ x, (1 - ∥(x : E)∥)⁻¹ • (x : E), left_inv := λ x, begin have : 0 < 1 + ∥x∥ := (norm_nonneg x).trans_lt (lt_one_add _), field_simp [this.ne', abs_of_pos this, norm_smul, smul_smul, real.norm_eq_abs, abs_div] end, right_inv := λ x, subtype.ext begin have : 0 < 1 - ∥(x : E)∥ := sub_pos.2 (mem_ball_zero_iff.1 x.2), field_simp [norm_smul, smul_smul, real.norm_eq_abs, abs_div, abs_of_pos this, this.ne'] end, continuous_to_fun := continuous_subtype_mk _ $ ((continuous_const.add continuous_norm).inv₀ (λ x, ((norm_nonneg x).trans_lt (lt_one_add _)).ne')).smul continuous_id, continuous_inv_fun := continuous.smul ((continuous_const.sub continuous_subtype_coe.norm).inv₀ $ λ x, (sub_pos.2 $ mem_ball_zero_iff.1 x.2).ne') continuous_subtype_coe } variables (α) lemma ne_neg_of_mem_sphere [char_zero α] {r : ℝ} (hr : r ≠ 0) (x : sphere (0:E) r) : x ≠ - x := λ h, ne_zero_of_mem_sphere hr x ((self_eq_neg α _).mp (by { conv_lhs {rw h}, simp })) lemma ne_neg_of_mem_unit_sphere [char_zero α] (x : sphere (0:E) 1) : x ≠ - x := ne_neg_of_mem_sphere α one_ne_zero x variables {α} open normed_field /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance prod.normed_space : normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.norm_def, norm_smul, mul_max_of_nonneg], ..prod.normed_group, ..prod.module } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, semi_normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ show (↑(finset.sup finset.univ (λ (b : ι), ∥a • f b∥₊)) : ℝ) = ∥a∥₊ * ↑(finset.sup finset.univ (λ (b : ι), ∥f b∥₊)), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 R : Type*} [has_scalar 𝕜 R] [normed_field 𝕜] [ring R] {E : Type*} [semi_normed_group E] [normed_space 𝕜 E] [module R E] [is_scalar_tower 𝕜 R E] (s : submodule R E) : normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } /-- If there is a scalar `c` with `∥c∥>1`, then any element with nonzero norm can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell_semi_normed {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : ∥x∥ ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos ((ne.symm hx).le_iff_lt.1 (norm_nonneg x)) εpos, rcases exists_mem_Ico_zpow xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_zpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ < ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_lt_iff cnpos, mul_comm, norm_zpow], exact (div_lt_iff εpos).1 (hn.2) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_zpow, zpow_add₀ (ne_of_gt cpos), zpow_one, mul_inv_rev, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (zpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv, norm_zpow, zpow_add₀ (ne_of_gt cpos), zpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end end semi_normed_group section normed_group variables [normed_field α] variables {E : Type*} [normed_group E] [normed_space α E] variables {F : Type*} [normed_group F] [normed_space α F] open normed_field /-- While this may appear identical to `normed_space.to_module`, it contains an implicit argument involving `normed_group.to_semi_normed_group` that typeclass inference has trouble inferring. Specifically, the following instance cannot be found without this `normed_space.to_module'`: ```lean example (𝕜 ι : Type*) (E : ι → Type*) [normed_field 𝕜] [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] : Π i, module 𝕜 (E i) := by apply_instance ``` [This Zulip thread](https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Typeclass.20resolution.20under.20binders/near/245151099) gives some more context. -/ @[priority 100] instance normed_space.to_module' : module α F := normed_space.to_module theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : interior (closed_ball x r) = ball x r := begin rcases eq_or_ne r 0 with rfl|hr, { rw [closed_ball_zero, ball_zero, interior_singleton] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball] variables {α} /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := rescale_to_shell_semi_normed hc εpos (ne_of_lt (norm_pos_iff.2 hx)).symm end normed_group section normed_space_nondiscrete variables (𝕜 E : Type*) [nondiscrete_normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] [nontrivial E] include 𝕜 /-- If `E` is a nontrivial normed space over a nondiscrete normed field `𝕜`, then `E` is unbounded: for any `c : ℝ`, there exists a vector `x : E` with norm strictly greater than `c`. -/ lemma normed_space.exists_lt_norm (c : ℝ) : ∃ x : E, c < ∥x∥ := begin rcases exists_ne (0 : E) with ⟨x, hx⟩, rcases normed_field.exists_lt_norm 𝕜 (c / ∥x∥) with ⟨r, hr⟩, use r • x, rwa [norm_smul, ← div_lt_iff], rwa norm_pos_iff end protected lemma normed_space.unbounded_univ : ¬bounded (set.univ : set E) := λ h, let ⟨R, hR⟩ := bounded_iff_forall_norm_le.1 h, ⟨x, hx⟩ := normed_space.exists_lt_norm 𝕜 E R in hx.not_le (hR x trivial) /-- A normed vector space over a nondiscrete normed field is a noncompact space. This cannot be an instance because in order to apply it, Lean would have to search for `normed_space 𝕜 E` with unknown `𝕜`. We register this as an instance in two cases: `𝕜 = E` and `𝕜 = ℝ`. -/ protected lemma normed_space.noncompact_space : noncompact_space E := ⟨λ h, normed_space.unbounded_univ 𝕜 _ h.bounded⟩ @[priority 100] instance nondiscrete_normed_field.noncompact_space : noncompact_space 𝕜 := normed_space.noncompact_space 𝕜 𝕜 omit 𝕜 @[priority 100] instance real_normed_space.noncompact_space [normed_space ℝ E] : noncompact_space E := normed_space.noncompact_space ℝ E end normed_space_nondiscrete section normed_algebra /-- A normed algebra `𝕜'` over `𝕜` is normed module that is also an algebra. See the implementation notes for `algebra` for a discussion about non-unital algebras. Following the strategy there, a non-unital *normed* algebra can be written as: ```lean variables [normed_field 𝕜] [non_unital_semi_normed_ring 𝕜'] variables [normed_module 𝕜 𝕜'] [smul_comm_class 𝕜 𝕜' 𝕜'] [is_scalar_tower 𝕜 𝕜' 𝕜'] ``` -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_smul_le : ∀ (r : 𝕜) (x : 𝕜'), ∥r • x∥ ≤ ∥r∥ * ∥x∥) variables {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[priority 100] instance normed_algebra.to_normed_space : normed_space 𝕜 𝕜' := { norm_smul_le := normed_algebra.norm_smul_le } /-- While this may appear identical to `normed_algebra.to_normed_space`, it contains an implicit argument involving `normed_ring.to_semi_normed_ring` that typeclass inference has trouble inferring. Specifically, the following instance cannot be found without this `normed_space.to_module'`: ```lean example (𝕜 ι : Type*) (E : ι → Type*) [normed_field 𝕜] [Π i, normed_ring (E i)] [Π i, normed_algebra 𝕜 (E i)] : Π i, module 𝕜 (E i) := by apply_instance ``` See `normed_space.to_module'` for a similar situation. -/ @[priority 100] instance normed_algebra.to_normed_space' {𝕜'} [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := by apply_instance lemma norm_algebra_map (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ * ∥(1 : 𝕜')∥ := begin rw algebra.algebra_map_eq_smul_one, exact norm_smul _ _, end lemma nnnorm_algebra_map (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥₊ = ∥x∥₊ * ∥(1 : 𝕜')∥₊ := subtype.ext $ norm_algebra_map 𝕜' x @[simp] lemma norm_algebra_map' [norm_one_class 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := by rw [norm_algebra_map, norm_one, mul_one] @[simp] lemma nnnorm_algebra_map' [norm_one_class 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥₊ = ∥x∥₊ := subtype.ext $ norm_algebra_map' _ _ variables (𝕜 𝕜') /-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/ lemma algebra_map_isometry [norm_one_class 𝕜'] : isometry (algebra_map 𝕜 𝕜') := begin refine isometry_emetric_iff_metric.2 (λx y, _), rw [dist_eq_norm, dist_eq_norm, ← ring_hom.map_sub, norm_algebra_map'], end /-- The inclusion of the base field in a normed algebra as a continuous linear map. -/ @[simps] def algebra_map_clm : 𝕜 →L[𝕜] 𝕜' := { to_fun := algebra_map 𝕜 𝕜', map_add' := (algebra_map 𝕜 𝕜').map_add, map_smul' := λ r x, by rw [algebra.id.smul_eq_mul, map_mul, ring_hom.id_apply, algebra.smul_def], cont := have lipschitz_with ∥(1 : 𝕜')∥₊ (algebra_map 𝕜 𝕜') := λ x y, begin rw [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm_sub, ←map_sub, ←ennreal.coe_mul, ennreal.coe_le_coe, mul_comm], exact (nnnorm_algebra_map _ _).le, end, this.continuous } lemma algebra_map_clm_coe : (algebra_map_clm 𝕜 𝕜' : 𝕜 → 𝕜') = (algebra_map 𝕜 𝕜' : 𝕜 → 𝕜') := rfl lemma algebra_map_clm_to_linear_map : (algebra_map_clm 𝕜 𝕜').to_linear_map = algebra.linear_map 𝕜 𝕜' := rfl instance normed_algebra.id : normed_algebra 𝕜 𝕜 := { .. normed_field.to_normed_space, .. algebra.id 𝕜} /-- Any normed characteristic-zero division ring that is a normed_algebra over the reals is also a normed algebra over the rationals. Phrased another way, if `𝕜` is a normed algebra over the reals, then `algebra_rat` respects that norm. -/ instance normed_algebra_rat {𝕜} [normed_division_ring 𝕜] [char_zero 𝕜] [normed_algebra ℝ 𝕜] : normed_algebra ℚ 𝕜 := { norm_smul_le := λ q x, by rw [←smul_one_smul ℝ q x, rat.smul_one_eq_coe, norm_smul, rat.norm_cast_real], } instance punit.normed_algebra : normed_algebra 𝕜 punit := { norm_smul_le := λ q x, by simp only [punit.norm_eq_zero, mul_zero] } /-- The product of two normed algebras is a normed algebra, with the sup norm. -/ instance prod.normed_algebra {E F : Type*} [semi_normed_ring E] [semi_normed_ring F] [normed_algebra 𝕜 E] [normed_algebra 𝕜 F] : normed_algebra 𝕜 (E × F) := { ..prod.normed_space } /-- The product of finitely many normed algebras is a normed algebra, with the sup norm. -/ instance pi.normed_algebra {E : ι → Type*} [fintype ι] [Π i, semi_normed_ring (E i)] [Π i, normed_algebra 𝕜 (E i)] : normed_algebra 𝕜 (Π i, E i) := { .. pi.normed_space, .. pi.algebra _ E } end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type*) [semi_normed_group E] [normed_space 𝕜' E] instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : semi_normed_group E] : semi_normed_group (restrict_scalars 𝕜 𝕜' E) := I instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_group E] : normed_group (restrict_scalars 𝕜 𝕜' E) := I /-- If `E` is a normed space over `𝕜'` and `𝕜` is a normed algebra over `𝕜'`, then `restrict_scalars.module` is additionally a `normed_space`. -/ instance : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) := { norm_smul_le := λ c x, (normed_space.norm_smul_le (algebra_map 𝕜 𝕜' c) (_ : E)).trans_eq $ by rw norm_algebra_map', ..restrict_scalars.module 𝕜 𝕜' E } /-- The action of the original normed_field on `restrict_scalars 𝕜 𝕜' E`. This is not an instance as it would be contrary to the purpose of `restrict_scalars`. -/ -- If you think you need this, consider instead reproducing `restrict_scalars.lsmul` -- appropriately modified here. def module.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [normed_field 𝕜'] [semi_normed_group E] [I : normed_space 𝕜' E] : normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` and/or `restrict_scalars 𝕜 𝕜' E` instead. This definition allows the `restrict_scalars.normed_space` instance to be put directly on `E` rather on `restrict_scalars 𝕜 𝕜' E`. This would be a very bad instance; both because `𝕜'` cannot be inferred, and because it is likely to create instance diamonds. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := restrict_scalars.normed_space _ 𝕜' _ end restrict_scalars
bca033fefa04212894f28d9c1cd94f939324889a
0c9c1ff8e5013c525bf1d72338b62db639374733
/library/init/meta/interactive.lean
25c9061ce794d6dc4f0565f888b2bedff3130ec9
[ "Apache-2.0" ]
permissive
semorrison/lean
1f2bb450c3400098666ff6e43aa29b8e1e3cdc3a
85dcb385d5219f2fca8c73b2ebca270fe81337e0
refs/heads/master
1,638,526,143,586
1,634,825,588,000
1,634,825,588,000
258,650,844
0
0
Apache-2.0
1,587,772,955,000
1,587,772,954,000
null
UTF-8
Lean
false
false
73,588
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 -/ prelude import init.meta.tactic init.meta.type_context init.meta.rewrite_tactic init.meta.simp_tactic import init.meta.smt.congruence_closure init.control.combinators import init.meta.interactive_base init.meta.derive init.meta.match_tactic import init.meta.congr_tactic init.meta.case_tag open lean open lean.parser open native precedence `?` : max local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic /- allows metavars -/ meta def i_to_expr (q : pexpr) : tactic expr := to_expr q tt /- allow metavars and no subgoals -/ meta def i_to_expr_no_subgoals (q : pexpr) : tactic expr := to_expr q tt ff /- doesn't allows metavars -/ meta def i_to_expr_strict (q : pexpr) : tactic expr := to_expr q ff /- Auxiliary version of i_to_expr for apply-like tactics. This is a workaround for comment https://github.com/leanprover/lean/issues/1342#issuecomment-307912291 at issue #1342. In interactive mode, given a tactic apply f we want the apply tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. Before we added `i_to_expr_for_apply`, the tactic apply le_antisymm would first elaborate `le_antisymm`, and create @le_antisymm ?m_1 ?m_2 ?m_3 ?m_4 The type class resolution problem ?m_2 : weak_order ?m_1 by the elaborator since ?m_1 is not assigned yet, and the problem is discarded. Then, we would invoke `apply_core`, which would create two new metavariables for the explicit arguments, and try to unify the resulting type with the current target. After the unification, the metavariables ?m_1, ?m_3 and ?m_4 are assigned, but we lost the information about the pending type class resolution problem. With `i_to_expr_for_apply`, `le_antisymm` is elaborate into `@le_antisymm`, the apply_core tactic creates all metavariables, and solves the ones that can be solved by type class resolution. Another possible fix: we modify the elaborator to return pending type class resolution problems, and store them in the tactic_state. -/ meta def i_to_expr_for_apply (q : pexpr) : tactic expr := let aux (n : name) : tactic expr := do p ← resolve_name n, match p with | (expr.const c []) := do r ← mk_const c, save_type_info r q, return r | _ := i_to_expr p end in match q with | (expr.const c []) := aux c | (expr.local_const c _ _ _) := aux c | _ := i_to_expr q end namespace interactive open _root_.interactive interactive.types expr /-- itactic: parse a nested "interactive" tactic. That is, parse `{` tactic `}` -/ meta def itactic : Type := tactic unit meta def propagate_tags (tac : itactic) : tactic unit := do tag ← get_main_tag, if tag = [] then tac else focus1 $ do tac, gs ← get_goals, when (bnot gs.empty) $ do new_tag ← get_main_tag, when new_tag.empty $ with_enable_tags (set_main_tag tag) meta def concat_tags (tac : tactic (list (name × expr))) : tactic unit := mcond tags_enabled (do in_tag ← get_main_tag, r ← tac, /- remove assigned metavars -/ r ← r.mfilter $ λ ⟨n, m⟩, bnot <$> is_assigned m, match r with | [(_, m)] := set_tag m in_tag /- if there is only new subgoal, we just propagate `in_tag` -/ | _ := r.mmap' (λ ⟨n, m⟩, set_tag m (n::in_tag)) end) (tac >> skip) /-- If the current goal is a Pi/forall `∀ x : t, u` (resp. `let x := t in u`) then `intro` puts `x : t` (resp. `x := t`) in the local context. The new subgoal target is `u`. If the goal is an arrow `t → u`, then it puts `h : t` in the local context and the new goal target is `u`. If the goal is neither a Pi/forall nor begins with a let binder, the tactic `intro` applies the tactic `whnf` until an introduction can be applied or the goal is not head reducible. In the latter case, the tactic fails. -/ meta def intro : parse ident_? → tactic unit | none := propagate_tags (intro1 >> skip) | (some h) := propagate_tags (tactic.intro h >> skip) /-- Similar to `intro` tactic. The tactic `intros` will keep introducing new hypotheses until the goal target is not a Pi/forall or let binder. The variant `intros h₁ ... hₙ` introduces `n` new hypotheses using the given identifiers to name them. -/ meta def intros : parse ident_* → tactic unit | [] := propagate_tags (tactic.intros >> skip) | hs := propagate_tags (intro_lst hs >> skip) /-- The tactic `introv` allows the user to automatically introduce the variables of a theorem and explicitly name the hypotheses involved. The given names are used to name non-dependent hypotheses. Examples: ``` example : ∀ a b : nat, a = b → b = a := begin introv h, exact h.symm end ``` The state after `introv h` is ``` a b : ℕ, h : a = b ⊢ b = a ``` ``` example : ∀ a b : nat, a = b → ∀ c, b = c → a = c := begin introv h₁ h₂, exact h₁.trans h₂ end ``` The state after `introv h₁ h₂` is ``` a b : ℕ, h₁ : a = b, c : ℕ, h₂ : b = c ⊢ a = c ``` -/ meta def introv (ns : parse ident_*) : tactic unit := propagate_tags (tactic.introv ns >> return ()) /-- Parse a current name and new name for `rename`. -/ private meta def rename_arg_parser : parser (name × name) := prod.mk <$> ident <*> (optional (tk "->") *> ident) /-- Parse the arguments of `rename`. -/ private meta def rename_args_parser : parser (list (name × name)) := (functor.map (λ x, [x]) rename_arg_parser) <|> (tk "[" *> sep_by (tk ",") rename_arg_parser <* tk "]") /-- Rename one or more local hypotheses. The renamings are given as follows: ``` rename x y -- rename x to y rename x → y -- ditto rename [x y, a b] -- rename x to y and a to b rename [x → y, a → b] -- ditto ``` Note that if there are multiple hypotheses called `x` in the context, then `rename x y` will rename *all* of them. If you want to rename only one, use `dedup` first. -/ meta def rename (renames : parse rename_args_parser) : tactic unit := propagate_tags $ tactic.rename_many $ native.rb_map.of_list renames /-- The `apply` tactic tries to match the current goal against the conclusion of the type of term. The argument term should be a term well-formed in the local context of the main goal. If it succeeds, then the tactic returns as many subgoals as the number of premises that have not been fixed by type inference or type class resolution. Non-dependent premises are added before dependent ones. The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types. -/ meta def apply (q : parse texpr) : tactic unit := concat_tags (do h ← i_to_expr_for_apply q, tactic.apply h) /-- Similar to the `apply` tactic, but does not reorder goals. -/ meta def fapply (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.fapply) /-- Similar to the `apply` tactic, but only creates subgoals for non-dependent premises that have not been fixed by type inference or type class resolution. -/ meta def eapply (q : parse texpr) : tactic unit := concat_tags (i_to_expr_for_apply q >>= tactic.eapply) /-- Similar to the `apply` tactic, but allows the user to provide a `apply_cfg` configuration object. -/ meta def apply_with (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e cfg) /-- Similar to the `apply` tactic, but uses matching instead of unification. `apply_match t` is equivalent to `apply_with t {unify := ff}` -/ meta def mapply (q : parse texpr) : tactic unit := concat_tags (do e ← i_to_expr_for_apply q, tactic.apply e {unify := ff}) /-- This tactic tries to close the main goal `... ⊢ t` by generating a term of type `t` using type class resolution. -/ meta def apply_instance : tactic unit := tactic.apply_instance /-- This tactic behaves like `exact`, but with a big difference: the user can put underscores `_` in the expression as placeholders for holes that need to be filled, and `refine` will generate as many subgoals as there are holes. Note that some holes may be implicit. The type of each hole must either be synthesized by the system or declared by an explicit type ascription like `(_ : nat → Prop)`. -/ meta def refine (q : parse texpr) : tactic unit := tactic.refine q /-- This tactic looks in the local context for a hypothesis whose type is equal to the goal target. If it finds one, it uses it to prove the goal, and otherwise it fails. -/ meta def assumption : tactic unit := tactic.assumption /-- Try to apply `assumption` to all goals. -/ meta def assumption' : tactic unit := tactic.any_goals' tactic.assumption private meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change u` replaces the target `t` of the main goal to `u` provided that `t` is well formed with respect to the local context of the main goal and `t` and `u` are definitionally equal. `change u at h` will change a local hypothesis to `u`. `change t with u at h1 h2 ...` will replace `t` with `u` in all the supplied hypotheses (or `*`), or in the goal if no `at` clause is specified, provided that `t` and `u` are definitionally equal. -/ 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 u ← mk_meta_univ, ty ← mk_meta_var (sort u), eq ← i_to_expr ``(%%q : %%ty), ew ← i_to_expr ``(%%w : %%ty), let repl := λe : expr, e.replace (λ a n, if a = eq then some ew else none), l.try_apply (λh, do e ← infer_type h, change_core (repl e) (some h)) (do g ← target, change_core (repl g) none) /-- This tactic provides an exact proof term to solve the main goal. If `t` is the goal and `p` is a term of type `u` then `exact p` succeeds if and only if `t` and `u` can be unified. -/ meta def exact (q : parse texpr) : tactic unit := do tgt : expr ← target, i_to_expr_strict ``(%%q : %%tgt) >>= tactic.exact /-- Like `exact`, but takes a list of terms and checks that all goals are discharged after the tactic. -/ meta def exacts : parse pexpr_list_or_texpr → tactic unit | [] := done | (t :: ts) := exact t >> exacts ts /-- A synonym for `exact` that allows writing `have/suffices/show ..., from ...` in tactic mode. -/ meta def «from» := exact /-- `revert h₁ ... hₙ` applies to any goal with hypotheses `h₁` ... `hₙ`. It moves the hypotheses and their dependencies to the target of the goal. This tactic is the inverse of `intro`. -/ meta def revert (ids : parse ident*) : tactic unit := propagate_tags (do hs ← mmap tactic.get_local ids, revert_lst hs, skip) private meta def resolve_name' (n : name) : tactic expr := do { p ← resolve_name n, match p with | expr.const n _ := mk_const n -- create metavars for universe levels | _ := i_to_expr p end } /- Version of to_expr that tries to bypass the elaborator if `p` is just a constant or local constant. This is not an optimization, by skipping the elaborator we make sure that no unwanted resolution is used. Example: the elaborator will force any unassigned ?A that must have be an instance of (has_one ?A) to nat. Remark: another benefit is that auxiliary temporary metavariables do not appear in error messages. -/ meta def to_expr' (p : pexpr) : tactic expr := match p with | (const c []) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | (local_const c _ _ _) := do new_e ← resolve_name' c, save_type_info new_e p, return new_e | _ := i_to_expr p end @[derive has_reflect] meta structure rw_rule := (pos : pos) (symm : bool) (rule : pexpr) meta def get_rule_eqn_lemmas (r : rw_rule) : tactic (list name) := let aux (n : name) : tactic (list name) := do { p ← resolve_name n, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := get_eqn_lemmas_for tt n | _ := return [] end } <|> return [] in match r.rule with | const n _ := aux n | local_const n _ _ _ := aux n | _ := return [] end private meta def rw_goal (cfg : rewrite_cfg) (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_target e {symm := r.symm, ..cfg}) (eq_lemmas.empty) private meta def uses_hyp (e : expr) (h : expr) : bool := e.fold ff $ λ t _ r, r || to_bool (t = h) private meta def rw_hyp (cfg : rewrite_cfg) : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, when (not (uses_hyp e hyp)) $ rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, rewrite_hyp e hyp {symm := r.symm, ..cfg} >>= rw_hyp rs) (eq_lemmas.empty) meta def rw_rule_p (ep : parser pexpr) : parser rw_rule := rw_rule.mk <$> cur_pos <*> (option.is_some <$> (with_desc "←" (tk "←" <|> tk "<-"))?) <*> ep @[derive has_reflect] meta structure rw_rules_t := (rules : list rw_rule) (end_pos : option pos) -- accepts the same content as `pexpr_list_or_texpr`, but with correct goal info pos annotations meta def rw_rules : parser rw_rules_t := (tk "[" *> rw_rules_t.mk <$> sep_by (skip_info (tk ",")) (set_goal_info_pos $ rw_rule_p (parser.pexpr 0)) <*> (some <$> cur_pos <* set_goal_info_pos (tk "]"))) <|> rw_rules_t.mk <$> (list.ret <$> rw_rule_p texpr) <*> return none private meta def rw_core (rs : parse rw_rules) (loca : parse location) (cfg : rewrite_cfg) : tactic unit := match loca with | loc.wildcard := loca.try_apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) | _ := loca.apply (rw_hyp cfg rs.rules) (rw_goal cfg rs.rules) end >> try (reflexivity reducible) >> (returnopt rs.end_pos >>= save_info <|> skip) /-- `rewrite e` applies identity `e` as a rewrite rule to the target of the main goal. If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction. If `e` is a defined constant, then the equational lemmas associated with `e` are used. This provides a convenient way to unfold `e`. `rewrite [e₁, ..., eₙ]` applies the given rules sequentially. `rewrite e at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal. -/ meta def rewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) /-- An abbreviation for `rewrite`. -/ meta def rw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := propagate_tags (rw_core q l cfg) /-- `rewrite` followed by `assumption`. -/ meta def rwa (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {}) : tactic unit := rewrite q l cfg >> try assumption /-- A variant of `rewrite` that uses the unifier more aggressively, unfolding semireducible definitions. -/ meta def erewrite (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := propagate_tags (rw_core q l cfg) /-- An abbreviation for `erewrite`. -/ meta def erw (q : parse rw_rules) (l : parse location) (cfg : rewrite_cfg := {md := semireducible}) : tactic unit := propagate_tags (rw_core q l cfg) /-- Returns the unique names of all hypotheses (local constants) in the context. -/ private meta def hyp_unique_names : tactic name_set := do ctx ← local_context, pure $ ctx.foldl (λ r h, r.insert h.local_uniq_name) mk_name_set /-- Returns all hypotheses (local constants) from the context except those whose unique names are in `hyp_uids`. -/ private meta def hyps_except (hyp_uids : name_set) : tactic (list expr) := do ctx ← local_context, pure $ ctx.filter (λ (h : expr), ¬ hyp_uids.contains h.local_uniq_name) /-- Apply `t` to the main goal and revert any new hypothesis in the generated goals. If `t` is a supported tactic or chain of supported tactics (e.g. `induction`, `cases`, `apply`, `constructor`), the generated goals are also tagged with case tags. You can then use `case` to focus such tagged goals. Two typical uses of `with_cases`: 1. Applying a custom eliminator: ``` lemma my_nat_rec : ∀ n {P : ℕ → Prop} (zero : P 0) (succ : ∀ n, P n → P (n + 1)), P n := ... example (n : ℕ) : n = n := begin with_cases { apply my_nat_rec n }, case zero { refl }, case succ : m ih { refl } end ``` 2. Enabling the use of `case` after a chain of case-splitting tactics: ``` example (n m : ℕ) : unit := begin with_cases { cases n; induction m }, case nat.zero nat.zero { exact () }, case nat.zero nat.succ : k { exact () }, case nat.succ nat.zero : i { exact () }, case nat.succ nat.succ : k i ih_i { exact () } end ``` -/ meta def with_cases (t : itactic) : tactic unit := with_enable_tags $ focus1 $ do input_hyp_uids ← hyp_unique_names, t, all_goals' $ do in_tag ← get_main_tag, new_hyps ← hyps_except input_hyp_uids, n ← revert_lst new_hyps, set_main_tag (case_tag.from_tag_pi in_tag n).render 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 /-- `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`. -/ 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 >> intro1 >> 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 meta def cases_arg_p : parser (option name × pexpr) := with_desc "(id :)? expr" $ do t ← texpr, match t with | (local_const x _ _ _) := (tk ":" *> do t ← texpr, pure (some x, t)) <|> pure (none, t) | _ := pure (none, t) end /-- Updates the tags of new subgoals produced by `cases` or `induction`. `in_tag` is the initial tag, i.e. the tag of the goal on which `cases`/`induction` was applied. `rs` should contain, for each subgoal, the constructor name associated with that goal and the hypotheses that were introduced. -/ private meta def set_cases_tags (in_tag : tag) (rs : list (name × list expr)) : tactic unit := do gs ← get_goals, match gs with -- if only one goal was produced, we should not make the tag longer | [g] := set_tag g in_tag | _ := let tgs : list (name × list expr × expr) := rs.map₂ (λ ⟨n, new_hyps⟩ g, ⟨n, new_hyps, g⟩) gs in tgs.mmap' $ λ ⟨n, new_hyps, g⟩, with_enable_tags $ set_tag g $ (case_tag.from_tag_hyps (n :: in_tag) (new_hyps.map expr.local_uniq_name)).render end precedence `generalizing` : 0 /-- Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor and an inductive hypothesis is added for each recursive argument to the constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the inductive hypothesis incorporates that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (nat.succ a)` and `ih₁ : P a → Q a` and target `Q (nat.succ a)`. Here the names `a` and `ih₁` ire chosen automatically. `induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable. `induction e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors and inductive hypotheses, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. Note that for long sequences of names, the `case` tactic provides a more convenient naming mechanism. `induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables `induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized. `induction h : t` will introduce an equality of the form `h : t = C x y`, asserting that the input term is equal to the current constructor case, to the context. -/ meta def induction (hp : parse cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do in_tag ← get_main_tag, focus1 $ do { -- process `h : t` case e ← match hp with | (some h, p) := do x ← get_unused_name, generalize h () (p, x), get_local x | (none, p) := i_to_expr p end, -- generalize major premise e ← if e.is_local_constant then pure e else tactic.generalize e >> intro1, -- generalize major premise args (e, newvars, locals) ← do { none ← pure rec_name | pure (e, [], []), t ← infer_type e, t ← whnf_ginductive t, const n _ ← pure t.get_app_fn | pure (e, [], []), env ← get_env, tt ← pure $ env.is_inductive n | pure (e, [], []), let (locals, nonlocals) := (t.get_app_args.drop $ env.inductive_num_params n).partition (λ arg : expr, arg.is_local_constant), _ :: _ ← pure nonlocals | pure (e, [], []), n ← tactic.revert e, newvars ← nonlocals.mmap $ λ arg, do { n ← revert_kdeps arg, tactic.generalize arg, h ← intro1, intron n, -- now try to clear hypotheses that may have been abstracted away let locals := arg.fold [] (λ e _ acc, if e.is_local_constant then e::acc else acc), locals.mmap' (try ∘ clear), pure h }, intron (n-1), e ← intro1, pure (e, newvars, locals) }, -- revert `generalizing` params (and their dependencies, if any) to_generalize ← (revert.get_or_else []).mmap tactic.get_local, num_generalized ← revert_lst to_generalize, -- perform the induction rs ← tactic.induction e ids rec_name, -- re-introduce the generalized hypotheses gen_hyps ← all_goals $ do { new_hyps ← intron' num_generalized, clear_lst (newvars.map local_pp_name), (e::locals).mmap' (try ∘ clear), pure new_hyps }, set_cases_tags in_tag $ @list.map₂ (name × list expr × list (name × expr)) _ (name × list expr) (λ ⟨n, hyps, _⟩ gen_hyps, ⟨n, hyps ++ gen_hyps⟩) rs gen_hyps } open case_tag.match_result private meta def goals_with_matching_tag (ns : list name) : tactic (list (expr × case_tag) × list (expr × case_tag)) := do gs ← get_goals, (gs : list (expr × tag)) ← gs.mmap (λ g, do t ← get_tag g, pure (g, t)), pure $ gs.foldr (λ ⟨g, t⟩ ⟨exact_matches, suffix_matches⟩, match case_tag.parse t with | none := ⟨exact_matches, suffix_matches⟩ | some t := match case_tag.match_tag ns t with | exact_match := ⟨⟨g, t⟩ :: exact_matches, suffix_matches⟩ | fuzzy_match := ⟨exact_matches, ⟨g, t⟩ :: suffix_matches⟩ | no_match := ⟨exact_matches, suffix_matches⟩ end end) ([], []) private meta def goal_with_matching_tag (ns : list name) : tactic (expr × case_tag) := do ⟨exact_matches, suffix_matches⟩ ← goals_with_matching_tag ns, match exact_matches, suffix_matches with | [] , [] := fail format! "Invalid `case`: there is no goal tagged with suffix {ns}." | [] , [g] := pure g | [] , _ := let tags : list (list name) := suffix_matches.map (λ ⟨_, t⟩, t.case_names.reverse) in fail format! "Invalid `case`: there is more than one goal tagged with suffix {ns}.\nMatching tags: {tags}" | [g], _ := pure g | _ , _ := fail format! "Invalid `case`: there is more than one goal tagged with tag {ns}." end meta def case_arg_parser : lean.parser (list name × option (list name)) := prod.mk <$> ident_* <*> (tk ":" *> ident_*)? meta def case_parser : lean.parser (list (list name × option (list name))) := (list_of case_arg_parser) <|> (functor.map (λ x, [x]) case_arg_parser) /-- Focuses on a goal ('case') generated by `induction`, `cases` or `with_cases`. The goal is selected by giving one or more names which must match exactly one goal. A goal is matched if the given names are a suffix of its goal tag. Additionally, each name in the sequence can be abbreviated to a suffix of the corresponding name in the goal tag. Thus, a goal with tag ``` nat.zero, list.nil ``` can be selected with any of these invocations (among others): ``` case nat.zero list.nil {...} case nat.zero nil {...} case zero nil {...} case nil {...} ``` Additionally, the form ``` case C : N₀ ... Nₙ {...} ``` can be used to rename hypotheses introduced by the preceding `cases`/`induction`/`with_cases`, using the names `Nᵢ`. For example: ``` example (xs : list ℕ) : xs = xs := begin induction xs, case nil { reflexivity }, case cons : x xs ih { -- x : ℕ, xs : list ℕ, ih : xs = xs reflexivity } end ``` Note that this renaming functionality only work reliably *directly after* an `induction`/`cases`/`with_cases`. If you need to perform additional work after an `induction` or `cases` (e.g. introduce hypotheses in all goals), use `with_cases`. Multiple cases can be handled by the same tactic block with ``` case [A : N₀ ... Nₙ, B : M₀ ... Mₙ] {...} ``` -/ /- TODO `case` could be generalised to work with zero names as well. The form case : x y z { ... } would select the first goal (or the first goal with a case tag), renaming hypotheses to `x, y, z`. The renaming functionality would be available only if the goal has a case tag. -/ meta def case (args : parse case_parser) (tac : itactic) : tactic unit := do target_goals ← args.mmap (λ ⟨ns, ids⟩, do ⟨goal, tag⟩ ← goal_with_matching_tag ns, let ids := ids.get_or_else [], let num_ids := ids.length, goals ← get_goals, let other_goals := goals.filter (≠ goal), set_goals [goal], match tag with | (case_tag.pi _ num_args) := do intro_lst ids, when (num_ids < num_args) $ intron (num_args - num_ids) | (case_tag.hyps _ new_hyp_names) := do let num_new_hyps := new_hyp_names.length, when (num_ids > num_new_hyps) $ fail format! ("Invalid `case`: You gave {num_ids} names, but the case introduces " ++ "{num_new_hyps} new hypotheses."), let renamings := native.rb_map.of_list (new_hyp_names.zip ids), propagate_tags $ tactic.rename_many renamings tt tt end, goals ← get_goals, set_goals other_goals, match goals with | [g] := return g | _ := fail "Unexpected goals introduced by renaming" end), remaining_goals ← get_goals, set_goals target_goals, tac, unsolved_goals ← get_goals, match unsolved_goals with | [] := set_goals remaining_goals | _ := fail "case tactic failed, focused goals have not been solved" end /-- Assuming `x` is a variable in the local context with an inductive type, `destruct x` splits the main goal, producing one goal for each constructor of the inductive type, in which `x` is assumed to be a general instance of that constructor. In contrast to `cases`, the local context is unchanged, i.e. no elements are reverted or introduced. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `destruct n` produces one goal with target `n = 0 → Q n`, and one goal with target `∀ (a : ℕ), (λ (w : ℕ), n = w → Q n) (nat.succ a)`. Here the name `a` is chosen automatically. -/ meta def destruct (p : parse texpr) : tactic unit := i_to_expr p >>= tactic.destruct meta def cases_core (e : expr) (ids : list name := []) : tactic unit := do in_tag ← get_main_tag, focus1 $ do rs ← tactic.cases e ids, set_cases_tags in_tag rs /-- Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal, producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor. If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward, so that the case split affects that hypothesis as well. For example, given `n : nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`, and one goal with hypothesis `h : P (nat.succ a)` and target `Q (nat.succ a)`. Here the name `a` is chosen automatically. `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable. `cases e with y₁ ... yₙ`, where `e` is a variable or an expression, specifies that the sequence of names `y₁ ... yₙ` should be used for the arguments to the constructors, including implicit arguments. If the list does not include enough names for all of the arguments, additional names are generated automatically. If too many names are given, the extra ones are ignored. Underscores can be used in the list, in which case the corresponding names are generated automatically. `cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case. -/ meta def cases : parse cases_arg_p → parse with_ident_list → tactic unit | (none, p) ids := do e ← i_to_expr p, cases_core e ids | (some h, p) ids := do x ← get_unused_name, generalize h () (p, x), hx ← get_local x, cases_core hx ids private meta def find_matching_hyp (ps : list pattern) : tactic expr := any_hyp $ λ h, do type ← infer_type h, ps.mfirst $ λ p, do match_pattern p type, return h /-- `cases_matching p` applies the `cases` tactic to a hypothesis `h : type` if `type` matches the pattern `p`. `cases_matching [p_1, ..., p_n]` applies the `cases` tactic to a hypothesis `h : type` if `type` matches one of the given patterns. `cases_matching* p` more efficient and compact version of `focus1 { repeat { cases_matching p } }`. It is more efficient because the pattern is compiled once. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_matching* [_ ∨ _, _ ∧ _] ``` -/ meta def cases_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := do ps ← ps.mmap pexpr_to_pattern, if rec.is_none then find_matching_hyp ps >>= cases_core else tactic.focus1 $ tactic.repeat $ find_matching_hyp ps >>= cases_core /-- Shorthand for `cases_matching` -/ meta def casesm (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := cases_matching rec ps private meta def try_cases_for_types (type_names : list name) (at_most_one : bool) : tactic unit := any_hyp $ λ h, do I ← expr.get_app_fn <$> (infer_type h >>= head_beta), guard I.is_constant, guard (I.const_name ∈ type_names), tactic.focus1 (cases_core h >> if at_most_one then do n ← num_goals, guard (n <= 1) else skip) /-- `cases_type I` applies the `cases` tactic to a hypothesis `h : (I ...)` `cases_type I_1 ... I_n` applies the `cases` tactic to a hypothesis `h : (I_1 ...)` or ... or `h : (I_n ...)` `cases_type* I` is shorthand for `focus1 { repeat { cases_type I } }` `cases_type! I` only applies `cases` if the number of resulting subgoals is <= 1. Example: The following tactic destructs all conjunctions and disjunctions in the current goal. ``` cases_type* or and ``` -/ meta def cases_type (one : parse $ (tk "!")?) (rec : parse $ (tk "*")?) (type_names : parse ident*) : tactic unit := do type_names ← type_names.mmap resolve_constant, if rec.is_none then try_cases_for_types type_names (bnot one.is_none) else tactic.focus1 $ tactic.repeat $ try_cases_for_types type_names (bnot one.is_none) /-- Tries to solve the current goal using a canonical proof of `true`, or the `reflexivity` tactic, or the `contradiction` tactic. -/ meta def trivial : tactic unit := tactic.triv <|> tactic.reflexivity <|> tactic.contradiction <|> fail "trivial tactic failed" /-- Closes the main goal using `sorry`. -/ meta def admit : tactic unit := tactic.admit /-- Closes the main goal using `sorry`. -/ meta def «sorry» : tactic unit := tactic.admit /-- The contradiction tactic attempts to find in the current local context a hypothesis that is equivalent to an empty inductive type (e.g. `false`), a hypothesis of the form `c_1 ... = c_2 ...` where `c_1` and `c_2` are distinct constructors, or two contradictory hypotheses. -/ meta def contradiction : tactic unit := tactic.contradiction /-- `iterate { t }` repeatedly applies tactic `t` until `t` fails. `iterate { t }` always succeeds. `iterate n { t }` applies `t` `n` times. -/ meta def iterate (n : parse small_nat?) (t : itactic) : tactic unit := match n with | none := tactic.iterate' t | some n := iterate_exactly' n t end /-- `repeat { t }` applies `t` to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat { t }` never fails. -/ meta def repeat : itactic → tactic unit := tactic.repeat /-- `try { t }` tries to apply tactic `t`, but succeeds whether or not `t` succeeds. -/ meta def try : itactic → tactic unit := tactic.try /-- A do-nothing tactic that always succeeds. -/ meta def skip : tactic unit := tactic.skip /-- `solve1 { t }` applies the tactic `t` to the main goal and fails if it is not solved. -/ meta def solve1 : itactic → tactic unit := tactic.solve1 /-- `abstract id { t }` tries to use tactic `t` to solve the main goal. If it succeeds, it abstracts the goal as an independent definition or theorem with name `id`. If `id` is omitted, a name is generated automatically. -/ meta def abstract (id : parse ident?) (tac : itactic) : tactic unit := tactic.abstract tac id /-- `all_goals { t }` applies the tactic `t` to every goal, and succeeds if each application succeeds. -/ meta def all_goals : itactic → tactic unit := tactic.all_goals' /-- `any_goals { t }` applies the tactic `t` to every goal, and succeeds if at least one application succeeds. -/ meta def any_goals : itactic → tactic unit := tactic.any_goals' /-- `focus { t }` temporarily hides all goals other than the first, applies `t`, and then restores the other goals. It fails if there are no goals. -/ meta def focus (tac : itactic) : tactic unit := tactic.focus1 tac private meta def assume_core (n : name) (ty : pexpr) := do t ← target, when (not $ t.is_pi ∨ t.is_let) whnf_target, t ← target, when (not $ t.is_pi ∨ t.is_let) $ fail "assume tactic failed, Pi/let expression expected", ty ← i_to_expr ``(%%ty : Sort*), unify ty t.binding_domain, intro_core n >> skip /-- Assuming the target of the goal is a Pi or a let, `assume h : t` unifies the type of the binder with `t` and introduces it with name `h`, just like `intro h`. If `h` is absent, the tactic uses the name `this`. If `t` is omitted, it will be inferred. `assume (h₁ : t₁) ... (hₙ : tₙ)` introduces multiple hypotheses. Any of the types may be omitted, but the names must be present. -/ meta def «assume» : parse (sum.inl <$> (tk ":" *> texpr) <|> sum.inr <$> parse_binders tac_rbp) → tactic unit | (sum.inl ty) := assume_core `this ty | (sum.inr binders) := binders.mmap' $ λ b, assume_core b.local_pp_name b.local_type /-- `have h : t := p` adds the hypothesis `h : t` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `have h : t` adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr ``(%%e : Sort*), v ← i_to_expr ``(%%p : %%t), tactic.assertv h t v | none, some p := do p ← i_to_expr p, tactic.note h none p | some e, none := i_to_expr ``(%%e : Sort*) >>= tactic.assert h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.assert h e end >> skip /-- `let h : t := p` adds the hypothesis `h : t := p` to the current goal if `p` a term of type `t`. If `t` is omitted, it will be inferred. `let h : t` adds the hypothesis `h : t := ?M` to the current goal and opens a new subgoal `?M : t`. The new subgoal becomes the main goal. If `t` is omitted, it will be replaced by a fresh metavariable. If `h` is omitted, the name `this` is used. -/ meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← i_to_expr ``(%%e : Sort*), v ← i_to_expr ``(%%p : %%t), tactic.definev h t v | none, some p := do p ← i_to_expr p, tactic.pose h none p | some e, none := i_to_expr ``(%%e : Sort*) >>= tactic.define h | none, none := do u ← mk_meta_univ, e ← mk_meta_var (sort u), tactic.define h e end >> skip /-- `suffices h : t` is the same as `have h : t, tactic.swap`. In other words, it adds the hypothesis `h : t` to the current goal and opens a new subgoal with target `t`. -/ meta def «suffices» (h : parse ident?) (t : parse (tk ":" *> texpr)?) : tactic unit := «have» h t none >> tactic.swap /-- This tactic displays the current state in the tracing buffer. -/ meta def trace_state : tactic unit := tactic.trace_state /-- `trace a` displays `a` in the tracing buffer. -/ meta def trace {α : Type} [has_to_tactic_format α] (a : α) : tactic unit := tactic.trace a /-- `existsi e` will instantiate an existential quantifier in the target with `e` and leave the instantiated body as the new target. More generally, it applies to any inductive type with one constructor and at least two arguments, applying the constructor with `e` as the first argument and leaving the remaining arguments as goals. `existsi [e₁, ..., eₙ]` iteratively does the same for each expression in the list. -/ meta def existsi : parse pexpr_list_or_texpr → tactic unit | [] := return () | (p::ps) := i_to_expr p >>= tactic.existsi >> existsi ps /-- This tactic applies to a goal such that its conclusion is an inductive type (say `I`). It tries to apply each constructor of `I` until it succeeds. -/ meta def constructor : tactic unit := concat_tags tactic.constructor /-- Similar to `constructor`, but only non-dependent premises are added as new goals. -/ meta def econstructor : tactic unit := concat_tags tactic.econstructor /-- Applies the first constructor when the type of the target is an inductive data type with two constructors. -/ meta def left : tactic unit := concat_tags tactic.left /-- Applies the second constructor when the type of the target is an inductive data type with two constructors. -/ meta def right : tactic unit := concat_tags tactic.right /-- Applies the constructor when the type of the target is an inductive data type with one constructor. -/ meta def split : tactic unit := concat_tags tactic.split private meta def constructor_matching_aux (ps : list pattern) : tactic unit := do t ← target, ps.mfirst (λ p, match_pattern p t), constructor meta def constructor_matching (rec : parse $ (tk "*")?) (ps : parse pexpr_list_or_texpr) : tactic unit := do ps ← ps.mmap pexpr_to_pattern, if rec.is_none then constructor_matching_aux ps else tactic.focus1 $ tactic.repeat $ constructor_matching_aux ps /-- Replaces the target of the main goal by `false`. -/ meta def exfalso : tactic unit := tactic.exfalso /-- The `injection` tactic is based on the fact that constructors of inductive data types are injections. That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too. If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂` placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂` should be constructor applications of the same constructor. Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal. The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses. -/ meta def injection (q : parse texpr) (hs : parse with_ident_list) : tactic unit := do e ← i_to_expr q, tactic.injection_with e hs, try assumption /-- `injections with h₁ ... hₙ` iteratively applies `injection` to hypotheses using the names `h₁ ... hₙ`. -/ meta def injections (hs : parse with_ident_list) : tactic unit := do tactic.injections_with hs, try assumption end interactive meta structure simp_config_ext extends simp_config := (discharger : tactic unit := failed) section mk_simp_set open expr interactive.types @[derive has_reflect] meta inductive simp_arg_type : Type | all_hyps : simp_arg_type | except : name → simp_arg_type | expr : pexpr → simp_arg_type | symm_expr : pexpr → simp_arg_type meta instance simp_arg_type_to_tactic_format : has_to_tactic_format simp_arg_type := ⟨λ a, match a with | simp_arg_type.all_hyps := pure "*" | (simp_arg_type.except n) := pure format!"-{n}" | (simp_arg_type.expr e) := i_to_expr_no_subgoals e >>= pp | (simp_arg_type.symm_expr e) := ((++) "←") <$> (i_to_expr_no_subgoals e >>= pp) end⟩ meta def simp_arg : parser simp_arg_type := (tk "*" *> return simp_arg_type.all_hyps) <|> (tk "-" *> simp_arg_type.except <$> ident) <|> (tk "<-" *> simp_arg_type.symm_expr <$> texpr) <|> (simp_arg_type.expr <$> texpr) meta def simp_arg_list : parser (list simp_arg_type) := (tk "*" *> return [simp_arg_type.all_hyps]) <|> list_of simp_arg <|> return [] private meta def resolve_exception_ids (all_hyps : bool) : list name → list name → list name → tactic (list name × list name) | [] gex hex := return (gex.reverse, hex.reverse) | (id::ids) gex hex := do p ← resolve_name id, let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := resolve_exception_ids ids (n::gex) hex | local_const n _ _ _ := when (not all_hyps) (fail $ sformat! "invalid local exception {id}, '*' was not used") >> resolve_exception_ids ids gex (n::hex) | _ := fail $ sformat! "invalid exception {id}, unknown identifier" end /-- Decode a list of `simp_arg_type` into lists for each type. This is a backwards-compatibility version of `decode_simp_arg_list_with_symm`. This version fails when an argument of the form `simp_arg_type.symm_expr` is included, so that `simp`-like tactics that do not (yet) support backwards rewriting should properly report an error but function normally on other inputs. -/ meta def decode_simp_arg_list (hs : list simp_arg_type) : tactic $ list pexpr × list name × list name × bool := do (hs, ex, all) ← hs.mfoldl (λ (r : (list pexpr × list name × bool)) h, do let (es, ex, all) := r, match h with | simp_arg_type.all_hyps := pure (es, ex, tt) | simp_arg_type.except id := pure (es, id::ex, all) | simp_arg_type.expr e := pure (e::es, ex, all) | simp_arg_type.symm_expr _ := fail "arguments of the form '←...' are not supported" end) ([], [], ff), (gex, hex) ← resolve_exception_ids all ex [] [], return (hs.reverse, gex, hex, all) /-- Decode a list of `simp_arg_type` into lists for each type. This is the newer version of `decode_simp_arg_list`, and has a new name for backwards compatibility. This version indicates the direction of a `simp` lemma by including a `bool` with the `pexpr`. -/ meta def decode_simp_arg_list_with_symm (hs : list simp_arg_type) : tactic $ list (pexpr × bool) × list name × list name × bool := do let (hs, ex, all) := hs.foldl (λ r h, match r, h with | (es, ex, all), simp_arg_type.all_hyps := (es, ex, tt) | (es, ex, all), simp_arg_type.except id := (es, id::ex, all) | (es, ex, all), simp_arg_type.expr e := ((e, ff)::es, ex, all) | (es, ex, all), simp_arg_type.symm_expr e := ((e, tt)::es, ex, all) end) ([], [], ff), (gex, hex) ← resolve_exception_ids all ex [] [], return (hs.reverse, gex, hex, all) private meta def add_simps : simp_lemmas → list (name × bool) → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n.fst n.snd, add_simps s' ns private meta def report_invalid_simp_lemma {α : Type} (n : name): tactic α := fail format!"invalid simplification lemma '{n}' (use command 'set_option trace.simp_lemmas true' for more details)" private meta def check_no_overload (p : pexpr) : tactic unit := when p.is_choice_macro $ match p with | macro _ ps := fail $ to_fmt "ambiguous overload, possible interpretations" ++ format.join (ps.map (λ p, (to_fmt p).indent 4)) | _ := failed end private meta def simp_lemmas.resolve_and_add (s : simp_lemmas) (u : list name) (n : name) (ref : pexpr) (symm : bool) : tactic (simp_lemmas × list name) := do p ← resolve_name n, check_no_overload p, -- unpack local refs let e := p.erase_annotations.get_app_fn.erase_annotations, match e with | const n _ := (do b ← is_valid_simp_lemma_cnst n, guard b, save_const_type_info n ref, s ← s.add_simp n symm, return (s, u)) <|> (do eqns ← get_eqn_lemmas_for tt n, guard (eqns.length > 0), save_const_type_info n ref, s ← add_simps s (eqns.map (λ e, (e, ff))), return (s, u)) <|> (do env ← get_env, guard (env.is_projection n).is_some, return (s, n::u)) <|> report_invalid_simp_lemma n | _ := (do e ← i_to_expr_no_subgoals p, b ← is_valid_simp_lemma e, guard b, try (save_type_info e ref), s ← s.add e symm, return (s, u)) <|> report_invalid_simp_lemma n end private meta def simp_lemmas.add_pexpr (s : simp_lemmas) (u : list name) (p : pexpr) (symm : bool) : tactic (simp_lemmas × list name) := match p with | (const c []) := simp_lemmas.resolve_and_add s u c p symm | (local_const c _ _ _) := simp_lemmas.resolve_and_add s u c p symm | _ := do new_e ← i_to_expr_no_subgoals p, s ← s.add new_e symm, return (s, u) end private meta def simp_lemmas.append_pexprs : simp_lemmas → list name → list (pexpr × bool) → tactic (simp_lemmas × list name) | s u [] := return (s, u) | s u (l::ls) := do (s, u) ← simp_lemmas.add_pexpr s u l.fst l.snd, simp_lemmas.append_pexprs s u ls meta def mk_simp_set_core (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) (at_star : bool) : tactic (bool × simp_lemmas × list name) := do (hs, gex, hex, all_hyps) ← decode_simp_arg_list_with_symm hs, when (all_hyps ∧ at_star ∧ not hex.empty) $ fail "A tactic of the form `simp [*, -h] at *` is currently not supported", s ← join_user_simp_lemmas no_dflt attr_names, -- Erase `h` from the default simp set for calls of the form `simp [←h]`. let to_erase := hs.foldl (λ l h, match h with | (const id _, tt) := id :: l | (local_const id _ _ _, tt) := id :: l | _ := l end ) [], let s := s.erase to_erase, (s, u) ← simp_lemmas.append_pexprs s [] hs, s ← if not at_star ∧ all_hyps then do ctx ← collect_ctx_simps, let ctx := ctx.filter (λ h, h.local_uniq_name ∉ hex), -- remove local exceptions s.append ctx else return s, -- add equational lemmas, if any gex ← gex.mmap (λ n, list.cons n <$> get_eqn_lemmas_for tt n), return (all_hyps, simp_lemmas.erase s $ gex.join, u) meta def mk_simp_set (no_dflt : bool) (attr_names : list name) (hs : list simp_arg_type) : tactic (simp_lemmas × list name) := prod.snd <$> (mk_simp_set_core no_dflt attr_names hs ff) end mk_simp_set namespace interactive open _root_.interactive interactive.types expr meta def simp_core_aux (cfg : simp_config) (discharger : tactic unit) (s : simp_lemmas) (u : list name) (hs : list expr) (tgt : bool) : tactic name_set := do (to_remove, lmss) ← @list.mfoldl tactic _ (list expr × name_set) _ (λ ⟨hs, lms⟩ h, do h_type ← infer_type h, (do (new_h_type, pr, new_lms) ← simplify s u h_type cfg `eq discharger, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact >> return (h::hs, lms.union new_lms)) <|> (return (hs, lms))) ([], mk_name_set) hs, (lms, goal_simplified) ← if tgt then (simp_target s u cfg discharger >>= λ ns, return (ns, tt)) <|> (return (mk_name_set, ff)) else (return (mk_name_set, ff)), guard (cfg.fail_if_unchanged = ff ∨ to_remove.length > 0 ∨ goal_simplified) <|> fail "simplify tactic failed to simplify", to_remove.reverse.mmap' (λ h, try (clear h)), return (lmss.union lms) meta def simp_core (cfg : simp_config) (discharger : tactic unit) (no_dflt : bool) (hs : list simp_arg_type) (attr_names : list name) (locat : loc) : tactic name_set := do lms ← match locat with | loc.wildcard := do (all_hyps, s, u) ← mk_simp_set_core no_dflt attr_names hs tt, if all_hyps then tactic.simp_all s u cfg discharger else do hyps ← non_dep_prop_hyps, simp_core_aux cfg discharger s u hyps tt | _ := do (s, u) ← mk_simp_set no_dflt attr_names hs, ns ← locat.get_locals, simp_core_aux cfg discharger s u ns locat.include_goal end, try tactic.triv, try (tactic.reflexivity reducible), return lms /-- The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants. `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`. `simp [h₁ h₂ ... hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If `hᵢ` is preceded by left arrow (`←` or `<-`), the simplification is performed in the reverse direction. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`. `simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses. `simp *` is a shorthand for `simp [*]`. `simp only [h₁ h₂ ... hₙ]` is like `simp [h₁ h₂ ... hₙ]` but does not use `[simp]` lemmas `simp [-id_1, ... -id_n]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`. `simp at h₁ h₂ ... hₙ` simplifies the non-dependent hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. The tactic fails if the target or another hypothesis depends on one of them. The token `⊢` or `|-` can be added to the list to include the target. `simp at *` simplifies all the hypotheses and the target. `simp * at *` simplifies target and all (non-dependent propositional) hypotheses using the other hypotheses. `simp with attr₁ ... attrₙ` simplifies the main goal target using the lemmas tagged with any of the attributes `[attr₁]`, ..., `[attrₙ]` or `[simp]`. -/ meta def simp (use_iota_eqn : parse $ (tk "!")?) (trace_lemmas : parse $ (tk "?")?) (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 cfg := match use_iota_eqn, trace_lemmas with | none , none := cfg | (some _), none := {iota_eqn := tt, ..cfg} | none , (some _) := {trace_lemmas := tt, ..cfg} | (some _), (some _) := {iota_eqn := tt, trace_lemmas := tt, ..cfg} end in propagate_tags $ do lms ← simp_core cfg.to_simp_config cfg.discharger no_dflt hs attr_names locat, if cfg.trace_lemmas then trace (↑"Try this: simp only " ++ to_fmt lms.to_list) else skip /-- Just construct the simp set and trace it. Used for debugging. -/ meta def trace_simp_set (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) : tactic unit := do (s, _) ← mk_simp_set no_dflt attr_names hs, s.pp >>= trace /-- `simp_intros h₁ h₂ ... hₙ` is similar to `intros h₁ h₂ ... hₙ` except that each hypothesis is simplified as it is introduced, and each introduced hypothesis is used to simplify later ones and the final target. As with `simp`, a list of simplification lemmas can be provided. The modifiers `only` and `with` behave as with `simp`. -/ meta def simp_intros (ids : parse ident_*) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (cfg : simp_intros_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names hs, when (¬u.empty) (fail (sformat! "simp_intros tactic does not support {u}")), tactic.simp_intros s u ids cfg, try triv >> try (reflexivity reducible) private meta def to_simp_arg_list (symms : list bool) (es : list pexpr) : list simp_arg_type := (symms.zip es).map (λ ⟨s, e⟩, if s then simp_arg_type.symm_expr e else simp_arg_type.expr e) /-- `dsimp` is similar to `simp`, except that it only uses definitional equalities. -/ meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list) (l : parse location) (cfg : dsimp_config := {}) : tactic unit := do (s, u) ← mk_simp_set no_dflt attr_names es, match l with | loc.wildcard := /- Remark: we cannot revert frozen local instances. We disable zeta expansion because to prevent `intron n` from failing. Another option is to put a "marker" at the current target, and implement `intro_upto_marker`. -/ do n ← revert_all, dsimp_target s u {zeta := ff ..cfg}, intron n | _ := l.apply (λ h, dsimp_hyp h s u cfg) (dsimp_target s u cfg) end /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a reflexive relation, that is, a relation which has a reflexivity lemma tagged with the attribute `[refl]`. The tactic checks whether `t` and `u` are definitionally equal and then solves the goal. -/ meta def reflexivity : tactic unit := tactic.reflexivity /-- Shorter name for the tactic `reflexivity`. -/ meta def refl : tactic unit := tactic.reflexivity /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a symmetric relation, that is, a relation which has a symmetry lemma tagged with the attribute `[symm]`. It replaces the target with `u ~ t`. -/ meta def symmetry : tactic unit := tactic.symmetry /-- This tactic applies to a goal whose target has the form `t ~ u` where `~` is a transitive relation, that is, a relation which has a transitivity lemma tagged with the attribute `[trans]`. `transitivity s` replaces the goal with the two subgoals `t ~ s` and `s ~ u`. If `s` is omitted, then a metavariable is used instead. -/ meta def transitivity (q : parse texpr?) : tactic unit := tactic.transitivity >> match q with | none := skip | some q := do (r, lhs, rhs) ← target_lhs_rhs, i_to_expr q >>= unify rhs end /-- Proves a goal with target `s = t` when `s` and `t` are equal up to the associativity and commutativity of their binary operations. -/ meta def ac_reflexivity : tactic unit := tactic.ac_refl /-- An abbreviation for `ac_reflexivity`. -/ meta def ac_refl : tactic unit := tactic.ac_refl /-- Tries to prove the main goal using congruence closure. -/ meta def cc : tactic unit := tactic.cc /-- Given hypothesis `h : x = t` or `h : t = x`, where `x` is a local constant, `subst h` substitutes `x` by `t` everywhere in the main goal and then clears `h`. -/ meta def subst (q : parse texpr) : tactic unit := i_to_expr q >>= tactic.subst >> try (tactic.reflexivity reducible) /-- Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`. -/ meta def subst_vars : tactic unit := tactic.subst_vars /-- `clear h₁ ... hₙ` tries to clear each hypothesis `hᵢ` from the local context. -/ meta def clear : parse ident* → tactic unit := tactic.clear_lst private meta def to_qualified_name_core : name → list name → tactic name | n [] := fail $ "unknown declaration '" ++ to_string n ++ "'" | n (ns::nss) := do curr ← return $ ns ++ n, env ← get_env, if env.contains curr then return curr else to_qualified_name_core n nss private meta def to_qualified_name (n : name) : tactic name := do env ← get_env, if env.contains n then return n else do ns ← open_namespaces, to_qualified_name_core n ns private meta def to_qualified_names : list name → tactic (list name) | [] := return [] | (c::cs) := do new_c ← to_qualified_name c, new_cs ← to_qualified_names cs, return (new_c::new_cs) /-- Similar to `unfold`, but only uses definitional equalities. -/ meta def dunfold (cs : parse ident*) (l : parse location) (cfg : dunfold_config := {}) : tactic unit := match l with | (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, dunfold_target new_cs cfg, intron n | _ := do new_cs ← to_qualified_names cs, l.apply (λ h, dunfold_hyp cs h cfg) (dunfold_target new_cs cfg) end private meta def delta_hyps : list name → list name → tactic unit | cs [] := skip | cs (h::hs) := get_local h >>= delta_hyp cs >> delta_hyps cs hs /-- Similar to `dunfold`, but performs a raw delta reduction, rather than using an equation associated with the defined constants. -/ meta def delta : parse ident* → parse location → tactic unit | cs (loc.wildcard) := do ls ← tactic.local_context, n ← revert_lst ls, new_cs ← to_qualified_names cs, delta_target new_cs, intron n | cs l := do new_cs ← to_qualified_names cs, l.apply (delta_hyp new_cs) (delta_target new_cs) private meta def unfold_projs_hyps (cfg : unfold_proj_config := {}) (hs : list name) : tactic bool := hs.mfoldl (λ r h, do h ← get_local h, (unfold_projs_hyp h cfg >> return tt) <|> return r) ff /-- This tactic unfolds all structure projections. -/ meta def unfold_projs (l : parse location) (cfg : unfold_proj_config := {}) : tactic unit := match l with | loc.wildcard := do ls ← local_context, b₁ ← unfold_projs_hyps cfg (ls.map expr.local_pp_name), b₂ ← (tactic.unfold_projs_target cfg >> return tt) <|> return ff, when (not b₁ ∧ not b₂) (fail "unfold_projs failed to simplify") | _ := l.try_apply (λ h, unfold_projs_hyp h cfg) (tactic.unfold_projs_target cfg) <|> fail "unfold_projs failed to simplify" end end interactive meta def ids_to_simp_arg_list (tac_name : name) (cs : list name) : tactic (list simp_arg_type) := cs.mmap $ λ c, do n ← resolve_name c, hs ← get_eqn_lemmas_for ff n.const_name, env ← get_env, let p := env.is_projection n.const_name, when (hs.empty ∧ p.is_none) (fail (sformat! "{tac_name} tactic failed, {c} does not have equational lemmas nor is a projection")), return $ simp_arg_type.expr (expr.const c []) structure unfold_config extends simp_config := (zeta := ff) (proj := ff) (eta := ff) (canonize_instances := ff) (constructor_eq := ff) namespace interactive open _root_.interactive interactive.types expr /-- Given defined constants `e₁ ... eₙ`, `unfold e₁ ... eₙ` iteratively unfolds all occurrences in the target of the main goal, using equational lemmas associated with the definitions. As with `simp`, the `at` modifier can be used to specify locations for the unfolding. -/ meta def unfold (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {}) : tactic unit := do es ← ids_to_simp_arg_list "unfold" cs, let no_dflt := tt, simp_core cfg.to_simp_config failed no_dflt es [] locat, skip /-- Similar to `unfold`, but does not iterate the unfolding. -/ meta def unfold1 (cs : parse ident*) (locat : parse location) (cfg : unfold_config := {single_pass := tt}) : tactic unit := unfold cs locat cfg /-- If the target of the main goal is an `opt_param`, assigns the default value. -/ meta def apply_opt_param : tactic unit := tactic.apply_opt_param /-- If the target of the main goal is an `auto_param`, executes the associated tactic. -/ meta def apply_auto_param : tactic unit := tactic.apply_auto_param /-- Fails if the given tactic succeeds. -/ meta def fail_if_success (tac : itactic) : tactic unit := tactic.fail_if_success tac /-- Succeeds if the given tactic fails. -/ meta def success_if_fail (tac : itactic) : tactic unit := tactic.success_if_fail tac meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (alpha_eqv 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 /-- `guard_hyp h : t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. -/ meta def guard_hyp (n : parse ident) (ty : parse (tk ":" *> texpr)?) (val : parse (tk ":=" *> texpr)?) : tactic unit := do h ← get_local n, ldecl ← tactic.unsafe.type_context.run (do lctx ← unsafe.type_context.get_local_context, pure $ lctx.get_local_decl h.local_uniq_name), ldecl ← ldecl | fail format!"hypothesis {h} not found", match ty with | some p := guard_expr_eq ldecl.type p | none := skip end, match ldecl.value, val with | none, some _ := fail format!"{h} is not a let binding" | some _, none := fail format!"{h} is a let binding" | some hval, some val := guard_expr_eq hval val | none, none := skip end /-- `match_target t` fails if target does not match pattern `t`. -/ meta def match_target (t : parse texpr) (m := reducible) : tactic unit := tactic.match_target t m >> skip /-- `by_cases p` splits the main goal into two cases, assuming `h : p` in the first branch, and `h : ¬ p` in the second branch. You can specify the name of the new hypothesis using the syntax `by_cases h : p`. -/ meta def by_cases : parse cases_arg_p → tactic unit | (n, q) := concat_tags $ do p ← tactic.to_expr_strict q, tactic.by_cases p (n.get_or_else `h), pos_g :: neg_g :: rest ← get_goals, return [(`pos, pos_g), (`neg, neg_g)] /-- Apply function extensionality and introduce new hypotheses. The tactic `funext` will keep applying new the `funext` lemma until the goal target is not reducible to ``` |- ((fun x, ...) = (fun x, ...)) ``` The variant `funext h₁ ... hₙ` applies `funext` `n` times, and uses the given identifiers to name the new hypotheses. -/ meta def funext : parse ident_* → tactic unit | [] := tactic.funext >> skip | hs := funext_lst hs >> skip /-- If the target of the main goal is a proposition `p`, `by_contradiction` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. `by_contradiction h` can be used to name the hypothesis `h : ¬ p`. This tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning. -/ meta def by_contradiction (n : parse ident?) : tactic unit := tactic.by_contradiction (n.get_or_else `h) $> () /-- If the target of the main goal is a proposition `p`, `by_contra` reduces the goal to proving `false` using the additional hypothesis `h : ¬ p`. `by_contra h` can be used to name the hypothesis `h : ¬ p`. This tactic will attempt to use decidability of `p` if available, and will otherwise fall back on classical reasoning. -/ meta def by_contra (n : parse ident?) : tactic unit := by_contradiction n /-- Type check the given expression, and trace its type. -/ meta def type_check (p : parse texpr) : tactic unit := do e ← to_expr p, tactic.type_check e, infer_type e >>= trace /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := tactic.done private meta def show_aux (p : pexpr) : list expr → list expr → tactic unit | [] r := fail "show tactic failed" | (g::gs) r := do do {set_goals [g], g_ty ← target, ty ← i_to_expr p, unify g_ty ty, set_goals (g :: r.reverse ++ gs), tactic.change ty} <|> show_aux gs (g::r) /-- `show t` finds the first goal whose target unifies with `t`. It makes that the main goal, performs the unification, and replaces the target with the unified version of `t`. -/ meta def «show» (q : parse texpr) : tactic unit := do gs ← get_goals, show_aux q gs [] /-- The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`. The premises of this hypothesis, either universal quantifications or non-dependent implications, are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`. The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one. -/ meta def specialize (p : parse texpr) : tactic unit := focus1 $ do e ← i_to_expr p, let h := expr.get_app_fn e, if h.is_local_constant then tactic.note h.local_pp_name none e >> try (tactic.clear h) >> rotate 1 else tactic.fail "specialize requires a term of the form `h x_1 .. x_n` where `h` appears in the local context" meta def congr := tactic.congr end interactive end tactic section add_interactive open tactic /- See add_interactive -/ private meta def add_interactive_aux (new_namespace : name) : list name → command | [] := return () | (n::ns) := do env ← get_env, d_name ← resolve_constant n, (declaration.defn _ ls ty val hints trusted) ← env.get d_name, (name.mk_string h _) ← return d_name, let new_name := new_namespace <.> h, add_decl (declaration.defn new_name ls ty (expr.const d_name (ls.map level.param)) hints trusted), do { doc ← doc_string d_name, add_doc_string new_name doc } <|> skip, add_interactive_aux ns /-- Copy a list of meta definitions in the current namespace to tactic.interactive. This command is useful when we want to update tactic.interactive without closing the current namespace. -/ meta def add_interactive (ns : list name) (p : name := `tactic.interactive) : command := add_interactive_aux p ns meta def has_dup : tactic bool := do ctx ← local_context, let p : name_set × bool := ctx.foldl (λ ⟨s, r⟩ h, if r then (s, r) else if s.contains h.local_pp_name then (s, tt) else (s.insert h.local_pp_name, ff)) (mk_name_set, ff), return p.2 /-- Renames hypotheses with the same name. -/ meta def dedup : tactic unit := mwhen has_dup $ do ctx ← local_context, n ← revert_lst ctx, intron n end add_interactive namespace tactic /- Helper tactic for `mk_inj_eq -/ protected meta def apply_inj_lemma : tactic unit := do h ← intro `h, some (lhs, rhs) ← expr.is_eq <$> infer_type h, (expr.const C _) ← return lhs.get_app_fn, -- We disable auto_param and opt_param support to address issue #1943 applyc (name.mk_string "inj" C) {auto_param := ff, opt_param := ff}, assumption /- Auxiliary tactic for proving `I.C.inj_eq` lemmas. These lemmas are automatically generated by the equation compiler. Example: ``` list.cons.inj_eq : forall h1 h2 t1 t2, (h1::t1 = h2::t2) = (h1 = h2 ∧ t1 = t2) := by mk_inj_eq ``` -/ meta def mk_inj_eq : tactic unit := `[ intros, /- We use `_root_.*` in the following tactics because names are resolved at tactic execution time in interactive mode. See PR #1913 TODO(Leo): This is probably not the only instance of this problem. `[ ... ] blocks are convenient to use because they allow us to use the interactive mode to write non interactive tactics. One potential fix for this issue is to resolve names in `[ ... ] at tactic compilation time. After this issue is fixed, we should remove the `_root_.*` workaround. -/ apply _root_.propext, apply _root_.iff.intro, { tactic.apply_inj_lemma }, { intro _, try { cases_matching* _ ∧ _ }, refl <|> { congr; { assumption <|> subst_vars } } } ] end tactic /- Define inj_eq lemmas for inductive datatypes that were declared before `mk_inj_eq` -/ universes u v lemma sum.inl.inj_eq {α : Type u} (β : Type v) (a₁ a₂ : α) : (@sum.inl α β a₁ = sum.inl a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma sum.inr.inj_eq (α : Type u) {β : Type v} (b₁ b₂ : β) : (@sum.inr α β b₁ = sum.inr b₂) = (b₁ = b₂) := by tactic.mk_inj_eq lemma psum.inl.inj_eq {α : Sort u} (β : Sort v) (a₁ a₂ : α) : (@psum.inl α β a₁ = psum.inl a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma psum.inr.inj_eq (α : Sort u) {β : Sort v} (b₁ b₂ : β) : (@psum.inr α β b₁ = psum.inr b₂) = (b₁ = b₂) := by tactic.mk_inj_eq lemma sigma.mk.inj_eq {α : Type u} {β : α → Type v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (sigma.mk a₁ b₁ = sigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) := by tactic.mk_inj_eq lemma psigma.mk.inj_eq {α : Sort u} {β : α → Sort v} (a₁ : α) (b₁ : β a₁) (a₂ : α) (b₂ : β a₂) : (psigma.mk a₁ b₁ = psigma.mk a₂ b₂) = (a₁ = a₂ ∧ b₁ == b₂) := by tactic.mk_inj_eq lemma subtype.mk.inj_eq {α : Sort u} {p : α → Prop} (a₁ : α) (h₁ : p a₁) (a₂ : α) (h₂ : p a₂) : (subtype.mk a₁ h₁ = subtype.mk a₂ h₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma option.some.inj_eq {α : Type u} (a₁ a₂ : α) : (some a₁ = some a₂) = (a₁ = a₂) := by tactic.mk_inj_eq lemma list.cons.inj_eq {α : Type u} (h₁ : α) (t₁ : list α) (h₂ : α) (t₂ : list α) : (list.cons h₁ t₁ = list.cons h₂ t₂) = (h₁ = h₂ ∧ t₁ = t₂) := by tactic.mk_inj_eq lemma nat.succ.inj_eq (n₁ n₂ : nat) : (nat.succ n₁ = nat.succ n₂) = (n₁ = n₂) := by tactic.mk_inj_eq
1617cfd7caf14754eb8689102e5998401170e499
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_topology/dold_kan/notations.lean
0bfe1a14e6162fe85c1e95213f8076577818d0db
[ "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
780
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.alternating_face_map_complex /-! # Notations for the Dold-Kan equivalence This file defines the notation `K[X] : chain_complex C ℕ` for the alternating face map complex of `(X : simplicial_object C)` where `C` is a preadditive category, as well as `N[X]` for the normalized subcomplex in the case `C` is an abelian category. -/ localized "notation (name := alternating_face_map_complex) `K[`X`]` := algebraic_topology.alternating_face_map_complex.obj X" in dold_kan localized "notation (name := normalized_Moore_complex) `N[`X`]` := algebraic_topology.normalized_Moore_complex.obj X" in dold_kan
0ad2396925a0a9c7182d10cdfb4b1c2a7f863403
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/nat/totient.lean
97859c572b98c4f696ffbd2e1d4ff2e760fad79d
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,717
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.big_operators.basic open finset open_locale big_operators namespace nat /-- Euler's totient function. This counts the number of positive integers less than `n` which are coprime with `n`. -/ def totient (n : ℕ) : ℕ := ((range n).filter (nat.coprime n)).card localized "notation `φ` := nat.totient" in nat @[simp] theorem totient_zero : φ 0 = 0 := rfl lemma totient_le (n : ℕ) : φ n ≤ n := calc totient n ≤ (range n).card : card_filter_le _ _ ... = n : card_range _ lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ h, card_pos.2 ⟨1, mem_filter.2 ⟨mem_range.2 dec_trivial, coprime_one_right _⟩⟩ lemma sum_totient (n : ℕ) : ∑ m in (range n.succ).filter (∣ n), φ m = n := if hn0 : n = 0 then by rw hn0; refl else calc ∑ m in (range n.succ).filter (∣ n), φ m = ∑ d in (range n.succ).filter (∣ n), ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card : eq.symm $ sum_bij (λ d _, n / d) (λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩) (λ _ _, rfl) (λ a b ha hb h, have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2, have 0 < (n / a), from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *), by rw [← nat.mul_left_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2]) (λ b hb, have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb, have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩, have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn, ⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩, by rw [← nat.mul_left_inj (nat.pos_of_ne_zero hnb0), nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩) ... = ∑ d in (range n.succ).filter (∣ n), ((range n).filter (λ m, gcd n m = d)).card : sum_congr rfl (λ d hd, have hd : d ∣ n, from (mem_filter.1 hd).2, have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)), card_congr (λ m hm, d * m) (λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm, mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸ (mul_lt_mul_left hd0).2 hm.1, by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩) (λ a b ha hb h, (nat.mul_right_inj hd0).1 h) (λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb, ⟨b / d, mem_filter.2 ⟨mem_range.2 ((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1 (by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _), nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)), hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩, hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩)) ... = ((filter (∣ n) (range n.succ)).bUnion (λ d, (range n).filter (λ m, gcd n m = d))).card : (card_bUnion (by intros; apply disjoint_filter.2; cc)).symm ... = (range n).card : congr_arg card (finset.ext (λ m, ⟨by finish, λ hm, have h : m < n, from mem_range.1 hm, mem_bUnion.2 ⟨gcd n m, mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (zero_le _) h) (gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩)) ... = n : card_range _ end nat
4fd81067e519fc68bca053d0c963a4f8d76464f4
7cdf3413c097e5d36492d12cdd07030eb991d394
/src/game/world1/level3.lean
470710d5e9c4146233b41b727d10a9b4360676d3
[]
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,434
lean
/- We just restarted Lean behind the scenes, so let's re-import the natural numbers, but this time without addition and multiplication. -/ import mynat.definition -- import Peano's definition of the natural numbers {0,1,2,3,4,...} namespace mynat -- hide /- Axiom : one_eq_succ_zero 1 = succ(0) -/ /- # World 1 : Tutorial world ## Level 3: Peano's axioms. The import above gives us the type `mynat` of natural numbers. But it also gives us some other things, which we'll take a look at now: * a term `0 : mynat`, interpreted as the number zero. * a function `succ : mynat → mynat`, with `succ n` interpreted as "the number after $n$". * The principle of mathematical induction. These axioms are essentially the axioms isolated by Peano which uniquely characterise the natural numbers (we also need recursion, but we can ignore it until world 7 or so). If you've not seen these things before, I guess they might look intimidating, so let's just go through them briefly. Firstly, notice that they are all standard facts about the natural numbers $\{0,1,2,3,\ldots\}$. The first axiom says that 0 is a natural number. The second says that there is a `succ` function which eats a number and spits out the number after it, so succ(0)=1, succ(1)=2 and so on. Peano's last axiom is the principle of mathematical induction. This is a deeper fact. It says that if we have infinitely many true/false statements $P(0)$, $P(1)$, $P(2)$ and so on, and if $P(0)$ is true, and if for every natural number $d$ we know that $P(d)$ implies $P(\operatorname{succ}(d))$, then $P(n)$ must be true for every natural number $n$. One can think of it as saying that every natural number can be built by starting at 0 and then applying `succ` a finite number of times. Peano's insights were firstly that these axioms completely characterise the natural numbers, and secondly that these axioms alone can be used to build a whole bunch of other structure on the natural numbers, for example addition, multiplication and so on. This game is all about seeing how far these axioms of Peano can take us. The import also gives us usual numerical notation 0 and 1, where 0 is Peano's 0, and `1 = succ(0)`. It's sometimes useful to know that `one_eq_succ_zero` is a proof of the theorem that `1 = succ(0)`. I've added this to your list of useful theorems -- check that you can find it in "theorem statements" for "World 1 - Tutorial World". Let's practice our use of the `rw` tactic in the following example. Our hypothesis `h` is a proof that `succ(a) = b` and we want to prove that `succ(succ(a))=succ(b)`. In words, we're going to prove that if `b` is the number after `a` then `succ(b)` is the number after `succ(a)`. Now here's a tricky question. If our goal is `⊢ succ (succ a) = succ b`, and our hypothesis is `h : succ a = b`, then what will the goal change to when we type `rw h,` and hit enter whilst not forgetting the comma? Remember that `rw h` will look for the *left* hand side of `h` in the goal, and will replace it with the *right* hand side. Try and figure out how the goal will change, and then try it. The answer: Lean changed `succ a` into `b`, so the goal became `succ b = succ b`. That goal is of the form `X = X`, so you can prove this new goal with `refl,` on the line after `rw h,`. Don't forget blah blah blah. **Important note** : the tactic `rw` expects a proof afterwards (e.g. `rw h1`). But `refl` is just `refl`. Note also that the system sometimes drops brackets when they're not necessary, and `succ b` just means `succ(b)`. You may be wondering whether we could have just substituted in the definition of `b` and proved the goal that way. To do that, we would want to replace the right hand side of `h` with the left hand side. You do this in Lean by writing `rw ← h`. You get the left-arrow by typing `\l` and then a space. You can just edit your proof and try it. You may also be wondering why we keep writing `succ(b)` instead of `b+1`. This is because we haven't defined addition yet! On the next level, the final level of Tutorial World, we will introduce addition, and then we'll be ready to enter Addition World. -/ /- Lemma : no-side-bar If $\operatorname{succ}(a) = b$, then $$\operatorname{succ}(\operatorname{succ}(a)) = \operatorname{succ}(b).$$ -/ lemma example4 (a b : mynat) (h : succ a = b) : succ(succ(a)) = succ(b) := begin [less_leaky] rw h, refl, end end mynat -- hide
dfdcaaf9fe45e5b95ad7d8b6d55c01303a567108
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/elabissues/bind_with_existential_types.lean
6e571d9622711afd990b3138d1f91f0c9293f9aa
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,560
lean
/- Problem: existential types do not play well with monads. ``` class HasBind (m : Type u → Type v) := (bind : ∀ {α β : Type u}, m α → (α → m β) → m β) ``` Even if we fix a universe-polymorphic monad M.{u v} : Type u -> Type v, the bind operator forces the universes of the two applications of M to be the same. So, we can not naively write: -/ universes u v axiom Foo : Type u → Type v @[instance] axiom fooMonad : Monad Foo noncomputable def doesNotWork : Foo Unit := do x ← pure (5 : Nat); y ← pure $ x + 3; Z ← pure (Nat : Type); pure () /- It yields the following error: << bind_with_existential_types.lean:18:18: error: type mismatch at application pure Nat term Nat has type Type : Type 1 but is expected to have type ?m_1 : Type >> -/ /- We can make it work by adding a bunch of ups and downs: -/ noncomputable def moreTedious : Foo Unit := ULift.down <$> do x ← pure $ ULift.up (5 : Nat); y ← pure $ ULift.up (ULift.down x + 5); z ← pure (Nat : Type); pure $ ULift.up () /- Without special elaborator support to insert all the ups and downs, it would be highly annoying to write State monad code that uses an existential type, e.g. a structure that simulates a Coq/ML module by bundling a type and a map API on the type. Note that one cannot vary universes at all in generic monadic combinators, no matter how many lifts and downlifts you are willing to perform, since only definitions can be universe polymorphic. If a definition takes a monad as an argument, its universe is already fixed. -/
31ab269a3d7bebb918c442c9131f4dd2f7bd1b54
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/martingale/optional_stopping.lean
3645319aa2ac2b0458f90e67db7b820b3c6e45e9
[ "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
12,341
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import probability.process.hitting_time import probability.martingale.basic /-! # Optional stopping theorem (fair game theorem) > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The optional stopping theorem states that an adapted integrable process `f` is a submartingale if and only if for all bounded stopping times `τ` and `π` such that `τ ≤ π`, the stopped value of `f` at `τ` has expectation smaller than its stopped value at `π`. This file also contains Doob's maximal inequality: given a non-negative submartingale `f`, for all `ε : ℝ≥0`, we have `ε • μ {ε ≤ f* n} ≤ ∫ ω in {ε ≤ f* n}, f n` where `f* n ω = max_{k ≤ n}, f k ω`. ### Main results * `measure_theory.submartingale_iff_expected_stopped_value_mono`: the optional stopping theorem. * `measure_theory.submartingale.stopped_process`: the stopped process of a submartingale with respect to a stopping time is a submartingale. * `measure_theory.maximal_ineq`: Doob's maximal inequality. -/ open_locale nnreal ennreal measure_theory probability_theory namespace measure_theory variables {Ω : Type*} {m0 : measurable_space Ω} {μ : measure Ω} {𝒢 : filtration ℕ m0} {f : ℕ → Ω → ℝ} {τ π : Ω → ℕ} -- We may generalize the below lemma to functions taking value in a `normed_lattice_add_comm_group`. -- Similarly, generalize `(super/)submartingale.set_integral_le`. /-- Given a submartingale `f` and bounded stopping times `τ` and `π` such that `τ ≤ π`, the expectation of `stopped_value f τ` is less than or equal to the expectation of `stopped_value f π`. This is the forward direction of the optional stopping theorem. -/ lemma submartingale.expected_stopped_value_mono [sigma_finite_filtration μ 𝒢] (hf : submartingale f 𝒢 μ) (hτ : is_stopping_time 𝒢 τ) (hπ : is_stopping_time 𝒢 π) (hle : τ ≤ π) {N : ℕ} (hbdd : ∀ ω, π ω ≤ N) : μ[stopped_value f τ] ≤ μ[stopped_value f π] := begin rw [← sub_nonneg, ← integral_sub', stopped_value_sub_eq_sum' hle hbdd], { simp only [finset.sum_apply], have : ∀ i, measurable_set[𝒢 i] {ω : Ω | τ ω ≤ i ∧ i < π ω}, { intro i, refine (hτ i).inter _, convert (hπ i).compl, ext x, simpa }, rw integral_finset_sum, { refine finset.sum_nonneg (λ i hi, _), rw [integral_indicator (𝒢.le _ _ (this _)), integral_sub', sub_nonneg], { exact hf.set_integral_le (nat.le_succ i) (this _) }, { exact (hf.integrable _).integrable_on }, { exact (hf.integrable _).integrable_on } }, intros i hi, exact integrable.indicator (integrable.sub (hf.integrable _) (hf.integrable _)) (𝒢.le _ _ (this _)) }, { exact hf.integrable_stopped_value hπ hbdd }, { exact hf.integrable_stopped_value hτ (λ ω, le_trans (hle ω) (hbdd ω)) } end /-- The converse direction of the optional stopping theorem, i.e. an adapted integrable process `f` is a submartingale if for all bounded stopping times `τ` and `π` such that `τ ≤ π`, the stopped value of `f` at `τ` has expectation smaller than its stopped value at `π`. -/ lemma submartingale_of_expected_stopped_value_mono [is_finite_measure μ] (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) (hf : ∀ τ π : Ω → ℕ, is_stopping_time 𝒢 τ → is_stopping_time 𝒢 π → τ ≤ π → (∃ N, ∀ ω, π ω ≤ N) → μ[stopped_value f τ] ≤ μ[stopped_value f π]) : submartingale f 𝒢 μ := begin refine submartingale_of_set_integral_le hadp hint (λ i j hij s hs, _), classical, specialize hf (s.piecewise (λ _, i) (λ _, j)) _ (is_stopping_time_piecewise_const hij hs) (is_stopping_time_const 𝒢 j) (λ x, (ite_le_sup _ _ _).trans (max_eq_right hij).le) ⟨j, λ x, le_rfl⟩, rwa [stopped_value_const, stopped_value_piecewise_const, integral_piecewise (𝒢.le _ _ hs) (hint _).integrable_on (hint _).integrable_on, ← integral_add_compl (𝒢.le _ _ hs) (hint j), add_le_add_iff_right] at hf, end /-- **The optional stopping theorem** (fair game theorem): an adapted integrable process `f` is a submartingale if and only if for all bounded stopping times `τ` and `π` such that `τ ≤ π`, the stopped value of `f` at `τ` has expectation smaller than its stopped value at `π`. -/ lemma submartingale_iff_expected_stopped_value_mono [is_finite_measure μ] (hadp : adapted 𝒢 f) (hint : ∀ i, integrable (f i) μ) : submartingale f 𝒢 μ ↔ ∀ τ π : Ω → ℕ, is_stopping_time 𝒢 τ → is_stopping_time 𝒢 π → τ ≤ π → (∃ N, ∀ x, π x ≤ N) → μ[stopped_value f τ] ≤ μ[stopped_value f π] := ⟨λ hf _ _ hτ hπ hle ⟨N, hN⟩, hf.expected_stopped_value_mono hτ hπ hle hN, submartingale_of_expected_stopped_value_mono hadp hint⟩ /-- The stopped process of a submartingale with respect to a stopping time is a submartingale. -/ @[protected] lemma submartingale.stopped_process [is_finite_measure μ] (h : submartingale f 𝒢 μ) (hτ : is_stopping_time 𝒢 τ) : submartingale (stopped_process f τ) 𝒢 μ := begin rw submartingale_iff_expected_stopped_value_mono, { intros σ π hσ hπ hσ_le_π hπ_bdd, simp_rw stopped_value_stopped_process, obtain ⟨n, hπ_le_n⟩ := hπ_bdd, exact h.expected_stopped_value_mono (hσ.min hτ) (hπ.min hτ) (λ ω, min_le_min (hσ_le_π ω) le_rfl) (λ ω, (min_le_left _ _).trans (hπ_le_n ω)), }, { exact adapted.stopped_process_of_discrete h.adapted hτ, }, { exact λ i, h.integrable_stopped_value ((is_stopping_time_const _ i).min hτ) (λ ω, min_le_left _ _), }, end section maximal open finset lemma smul_le_stopped_value_hitting [is_finite_measure μ] (hsub : submartingale f 𝒢 μ) {ε : ℝ≥0} (n : ℕ) : ε • μ {ω | (ε : ℝ) ≤ (range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)} ≤ ennreal.of_real (∫ ω in {ω | (ε : ℝ) ≤ (range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)}, stopped_value f (hitting f {y : ℝ | ↑ε ≤ y} 0 n) ω ∂μ) := begin have hn : set.Icc 0 n = {k | k ≤ n}, { ext x, simp }, have : ∀ ω, ((ε : ℝ) ≤ (range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)) → (ε : ℝ) ≤ stopped_value f (hitting f {y : ℝ | ↑ε ≤ y} 0 n) ω, { intros x hx, simp_rw [le_sup'_iff, mem_range, nat.lt_succ_iff] at hx, refine stopped_value_hitting_mem _, simp only [set.mem_set_of_eq, exists_prop, hn], exact let ⟨j, hj₁, hj₂⟩ := hx in ⟨j, hj₁, hj₂⟩ }, have h := set_integral_ge_of_const_le (measurable_set_le measurable_const (finset.measurable_range_sup'' (λ n _, (hsub.strongly_measurable n).measurable.le (𝒢.le n)))) (measure_ne_top _ _) this (integrable.integrable_on (hsub.integrable_stopped_value (hitting_is_stopping_time hsub.adapted measurable_set_Ici) hitting_le)), rw [ennreal.le_of_real_iff_to_real_le, ennreal.to_real_smul], { exact h }, { exact ennreal.mul_ne_top (by simp) (measure_ne_top _ _) }, { exact le_trans (mul_nonneg ε.coe_nonneg ennreal.to_real_nonneg) h } end /-- **Doob's maximal inequality**: Given a non-negative submartingale `f`, for all `ε : ℝ≥0`, we have `ε • μ {ε ≤ f* n} ≤ ∫ ω in {ε ≤ f* n}, f n` where `f* n ω = max_{k ≤ n}, f k ω`. In some literature, the Doob's maximal inequality refers to what we call Doob's Lp inequality (which is a corollary of this lemma and will be proved in an upcomming PR). -/ lemma maximal_ineq [is_finite_measure μ] (hsub : submartingale f 𝒢 μ) (hnonneg : 0 ≤ f) {ε : ℝ≥0} (n : ℕ) : ε • μ {ω | (ε : ℝ) ≤ (range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)} ≤ ennreal.of_real (∫ ω in {ω | (ε : ℝ) ≤ (range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)}, f n ω ∂μ) := begin suffices : ε • μ {ω | (ε : ℝ) ≤ (range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)} + ennreal.of_real (∫ ω in {ω | ((range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)) < ε}, f n ω ∂μ) ≤ ennreal.of_real (μ[f n]), { have hadd : ennreal.of_real (∫ ω, f n ω ∂μ) = ennreal.of_real (∫ ω in {ω | ↑ε ≤ ((range (n + 1)).sup' nonempty_range_succ (λ k, f k ω))}, f n ω ∂μ) + ennreal.of_real (∫ ω in {ω | ((range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)) < ↑ε}, f n ω ∂μ), { rw [← ennreal.of_real_add, ← integral_union], { conv_lhs { rw ← integral_univ }, convert rfl, ext ω, change (ε : ℝ) ≤ _ ∨ _ < (ε : ℝ) ↔ _, simp only [le_or_lt, true_iff] }, { rw disjoint_iff_inf_le, rintro ω ⟨hω₁ : _ ≤ _, hω₂ : _ < _⟩, exact (not_le.2 hω₂) hω₁ }, { exact (measurable_set_lt (finset.measurable_range_sup'' (λ n _, (hsub.strongly_measurable n).measurable.le (𝒢.le n))) measurable_const) }, exacts [(hsub.integrable _).integrable_on, (hsub.integrable _).integrable_on, integral_nonneg (hnonneg _), integral_nonneg (hnonneg _)] }, rwa [hadd, ennreal.add_le_add_iff_right ennreal.of_real_ne_top] at this }, calc ε • μ {ω | (ε : ℝ) ≤ (range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)} + ennreal.of_real (∫ ω in {ω | ((range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)) < ε}, f n ω ∂μ) ≤ ennreal.of_real (∫ ω in {ω | (ε : ℝ) ≤ (range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)}, stopped_value f (hitting f {y : ℝ | ↑ε ≤ y} 0 n) ω ∂μ) + ennreal.of_real (∫ ω in {ω | ((range (n + 1)).sup' nonempty_range_succ (λ k, f k ω)) < ε}, stopped_value f (hitting f {y : ℝ | ↑ε ≤ y} 0 n) ω ∂μ) : begin refine add_le_add (smul_le_stopped_value_hitting hsub _) (ennreal.of_real_le_of_real (set_integral_mono_on (hsub.integrable n).integrable_on (integrable.integrable_on (hsub.integrable_stopped_value (hitting_is_stopping_time hsub.adapted measurable_set_Ici) hitting_le)) (measurable_set_lt (finset.measurable_range_sup'' (λ n _, (hsub.strongly_measurable n).measurable.le (𝒢.le n))) measurable_const) _)), intros ω hω, rw set.mem_set_of_eq at hω, have : hitting f {y : ℝ | ↑ε ≤ y} 0 n ω = n, { simp only [hitting, set.mem_set_of_eq, exists_prop, pi.coe_nat, nat.cast_id, ite_eq_right_iff, forall_exists_index, and_imp], intros m hm hεm, exact false.elim ((not_le.2 hω) ((le_sup'_iff _).2 ⟨m, mem_range.2 (nat.lt_succ_of_le hm.2), hεm⟩)) }, simp_rw [stopped_value, this], end ... = ennreal.of_real (∫ ω, stopped_value f (hitting f {y : ℝ | ↑ε ≤ y} 0 n) ω ∂μ) : begin rw [← ennreal.of_real_add, ← integral_union], { conv_rhs { rw ← integral_univ }, convert rfl, ext ω, change _ ↔ (ε : ℝ) ≤ _ ∨ _ < (ε : ℝ), simp only [le_or_lt, iff_true] }, { rw disjoint_iff_inf_le, rintro ω ⟨hω₁ : _ ≤ _, hω₂ : _ < _⟩, exact (not_le.2 hω₂) hω₁ }, { exact (measurable_set_lt (finset.measurable_range_sup'' (λ n _, (hsub.strongly_measurable n).measurable.le (𝒢.le n))) measurable_const) }, { exact (integrable.integrable_on (hsub.integrable_stopped_value (hitting_is_stopping_time hsub.adapted measurable_set_Ici) hitting_le)) }, { exact (integrable.integrable_on (hsub.integrable_stopped_value (hitting_is_stopping_time hsub.adapted measurable_set_Ici) hitting_le)) }, exacts [integral_nonneg (λ x, hnonneg _ _), integral_nonneg (λ x, hnonneg _ _)], end ... ≤ ennreal.of_real (μ[f n]) : begin refine ennreal.of_real_le_of_real _, rw ← stopped_value_const f n, exact hsub.expected_stopped_value_mono (hitting_is_stopping_time hsub.adapted measurable_set_Ici) (is_stopping_time_const _ _) (λ ω, hitting_le ω) (λ ω, le_rfl : ∀ ω, n ≤ n), end end end maximal end measure_theory
0c010bc2438b00d75eb352ca5c3f904ed3aa9f9c
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/computability/turing_machine.lean
41b9350b4b86d4422d9394c69fbcda4e04ea7096
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
109,906
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 algebra.order import data.fintype.basic import data.pfun import tactic.apply_fun import logic.function.iterate /-! # Turing machines This file defines a sequence of simple machine languages, starting with Turing machines and working up to more complex languages based on Wang B-machines. ## Naming conventions Each model of computation in this file shares a naming convention for the elements of a model of computation. These are the parameters for the language: * `Γ` is the alphabet on the tape. * `Λ` is the set of labels, or internal machine states. * `σ` is the type of internal memory, not on the tape. This does not exist in the TM0 model, and later models achieve this by mixing it into `Λ`. * `K` is used in the TM2 model, which has multiple stacks, and denotes the number of such stacks. All of these variables denote "essentially finite" types, but for technical reasons it is convenient to allow them to be infinite anyway. When using an infinite type, we will be interested to prove that only finitely many values of the type are ever interacted with. Given these parameters, there are a few common structures for the model that arise: * `stmt` is the set of all actions that can be performed in one step. For the TM0 model this set is finite, and for later models it is an infinite inductive type representing "possible program texts". * `cfg` is the set of instantaneous configurations, that is, the state of the machine together with its environment. * `machine` is the set of all machines in the model. Usually this is approximately a function `Λ → stmt`, although different models have different ways of halting and other actions. * `step : cfg → option cfg` is the function that describes how the state evolves over one step. If `step c = none`, then `c` is a terminal state, and the result of the computation is read off from `c`. Because of the type of `step`, these models are all deterministic by construction. * `init : input → cfg` sets up the initial state. The type `input` depends on the model; in most cases it is `list Γ`. * `eval : machine → input → roption output`, given a machine `M` and input `i`, starts from `init i`, runs `step` until it reaches an output, and then applies a function `cfg → output` to the final state to obtain the result. The type `output` depends on the model. * `supports : machine → finset Λ → Prop` asserts that a machine `M` starts in `S : finset Λ`, and can only ever jump to other states inside `S`. This implies that the behavior of `M` on any input cannot depend on its values outside `S`. We use this to allow `Λ` to be an infinite set when convenient, and prove that only finitely many of these states are actually accessible. This formalizes "essentially finite" mentioned above. -/ open relation open nat (iterate) open function (update iterate_succ iterate_succ_apply iterate_succ' iterate_succ_apply' iterate_zero_apply) namespace turing /-- The `blank_extends` partial order holds of `l₁` and `l₂` if `l₂` is obtained by adding blanks (`default Γ`) to the end of `l₁`. -/ def blank_extends {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := ∃ n, l₂ = l₁ ++ list.repeat (default Γ) n @[refl] theorem blank_extends.refl {Γ} [inhabited Γ] (l : list Γ) : blank_extends l l := ⟨0, by simp⟩ @[trans] theorem blank_extends.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_extends l₁ l₂ → blank_extends l₂ l₃ → blank_extends l₁ l₃ := by rintro ⟨i, rfl⟩ ⟨j, rfl⟩; exact ⟨i+j, by simp [list.repeat_add]⟩ theorem blank_extends.below_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l l₁ → blank_extends l l₂ → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, rfl⟩ h, use j - i, simp only [list.length_append, add_le_add_iff_left, list.length_repeat] at h, simp only [← list.repeat_add, nat.add_sub_cancel' h, list.append_assoc], end /-- Any two extensions by blank `l₁,l₂` of `l` have a common join (which can be taken to be the longer of `l₁` and `l₂`). -/ def blank_extends.above {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} (h₁ : blank_extends l l₁) (h₂ : blank_extends l l₂) : {l' // blank_extends l₁ l' ∧ blank_extends l₂ l'} := if h : l₁.length ≤ l₂.length then ⟨l₂, h₁.below_of_le h₂ h, blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, h₂.below_of_le h₁ (le_of_not_ge h)⟩ theorem blank_extends.above_of_le {Γ} [inhabited Γ] {l l₁ l₂ : list Γ} : blank_extends l₁ l → blank_extends l₂ l → l₁.length ≤ l₂.length → blank_extends l₁ l₂ := begin rintro ⟨i, rfl⟩ ⟨j, e⟩ h, use i - j, refine list.append_right_cancel (e.symm.trans _), rw [list.append_assoc, ← list.repeat_add, nat.sub_add_cancel], apply_fun list.length at e, simp only [list.length_append, list.length_repeat] at e, rwa [ge, ← add_le_add_iff_left, e, add_le_add_iff_right] end /-- `blank_rel` is the symmetric closure of `blank_extends`, turning it into an equivalence relation. Two lists are related by `blank_rel` if one extends the other by blanks. -/ def blank_rel {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : Prop := blank_extends l₁ l₂ ∨ blank_extends l₂ l₁ @[refl] theorem blank_rel.refl {Γ} [inhabited Γ] (l : list Γ) : blank_rel l l := or.inl (blank_extends.refl _) @[symm] theorem blank_rel.symm {Γ} [inhabited Γ] {l₁ l₂ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₁ := or.symm @[trans] theorem blank_rel.trans {Γ} [inhabited Γ] {l₁ l₂ l₃ : list Γ} : blank_rel l₁ l₂ → blank_rel l₂ l₃ → blank_rel l₁ l₃ := begin rintro (h₁|h₁) (h₂|h₂), { exact or.inl (h₁.trans h₂) }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.above_of_le h₂ h) }, { exact or.inr (h₂.above_of_le h₁ h) } }, { cases le_total l₁.length l₃.length with h h, { exact or.inl (h₁.below_of_le h₂ h) }, { exact or.inr (h₂.below_of_le h₁ h) } }, { exact or.inr (h₂.trans h₁) }, end /-- Given two `blank_rel` lists, there exists (constructively) a common join. -/ def blank_rel.above {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l₁ l ∧ blank_extends l₂ l} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₂, or.elim h id (λ h', _), blank_extends.refl _⟩ else ⟨l₁, blank_extends.refl _, or.elim h (λ h', _) id⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end /-- Given two `blank_rel` lists, there exists (constructively) a common meet. -/ def blank_rel.below {Γ} [inhabited Γ] {l₁ l₂ : list Γ} (h : blank_rel l₁ l₂) : {l // blank_extends l l₁ ∧ blank_extends l l₂} := begin refine if hl : l₁.length ≤ l₂.length then ⟨l₁, blank_extends.refl _, or.elim h id (λ h', _)⟩ else ⟨l₂, or.elim h (λ h', _) id, blank_extends.refl _⟩, exact (blank_extends.refl _).above_of_le h' hl, exact (blank_extends.refl _).above_of_le h' (le_of_not_ge hl) end theorem blank_rel.equivalence (Γ) [inhabited Γ] : equivalence (@blank_rel Γ _) := ⟨blank_rel.refl, @blank_rel.symm _ _, @blank_rel.trans _ _⟩ /-- Construct a setoid instance for `blank_rel`. -/ def blank_rel.setoid (Γ) [inhabited Γ] : setoid (list Γ) := ⟨_, blank_rel.equivalence _⟩ /-- A `list_blank Γ` is a quotient of `list Γ` by extension by blanks at the end. This is used to represent half-tapes of a Turing machine, so that we can pretend that the list continues infinitely with blanks. -/ def list_blank (Γ) [inhabited Γ] := quotient (blank_rel.setoid Γ) instance list_blank.inhabited {Γ} [inhabited Γ] : inhabited (list_blank Γ) := ⟨quotient.mk' []⟩ instance list_blank.has_emptyc {Γ} [inhabited Γ] : has_emptyc (list_blank Γ) := ⟨quotient.mk' []⟩ /-- A modified version of `quotient.lift_on'` specialized for `list_blank`, with the stronger precondition `blank_extends` instead of `blank_rel`. -/ @[elab_as_eliminator, reducible] protected def list_blank.lift_on {Γ} [inhabited Γ] {α} (l : list_blank Γ) (f : list Γ → α) (H : ∀ a b, blank_extends a b → f a = f b) : α := l.lift_on' f $ by rintro a b (h|h); [exact H _ _ h, exact (H _ _ h).symm] /-- The quotient map turning a `list` into a `list_blank`. -/ def list_blank.mk {Γ} [inhabited Γ] : list Γ → list_blank Γ := quotient.mk' @[elab_as_eliminator] protected lemma list_blank.induction_on {Γ} [inhabited Γ] {p : list_blank Γ → Prop} (q : list_blank Γ) (h : ∀ a, p (list_blank.mk a)) : p q := quotient.induction_on' q h /-- The head of a `list_blank` is well defined. -/ def list_blank.head {Γ} [inhabited Γ] (l : list_blank Γ) : Γ := l.lift_on list.head begin rintro _ _ ⟨i, rfl⟩, cases a, {cases i; refl}, refl end @[simp] theorem list_blank.head_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.head (list_blank.mk l) = l.head := rfl /-- The tail of a `list_blank` is well defined (up to the tail of blanks). -/ def list_blank.tail {Γ} [inhabited Γ] (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk l.tail) begin rintro _ _ ⟨i, rfl⟩, refine quotient.sound' (or.inl _), cases a; [{cases i; [exact ⟨0, rfl⟩, exact ⟨i, rfl⟩]}, exact ⟨i, rfl⟩] end @[simp] theorem list_blank.tail_mk {Γ} [inhabited Γ] (l : list Γ) : list_blank.tail (list_blank.mk l) = list_blank.mk l.tail := rfl /-- We can cons an element onto a `list_blank`. -/ def list_blank.cons {Γ} [inhabited Γ] (a : Γ) (l : list_blank Γ) : list_blank Γ := l.lift_on (λ l, list_blank.mk (list.cons a l)) begin rintro _ _ ⟨i, rfl⟩, exact quotient.sound' (or.inl ⟨i, rfl⟩), end @[simp] theorem list_blank.cons_mk {Γ} [inhabited Γ] (a : Γ) (l : list Γ) : list_blank.cons a (list_blank.mk l) = list_blank.mk (a :: l) := rfl @[simp] theorem list_blank.head_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).head = a := quotient.ind' $ by exact λ l, rfl @[simp] theorem list_blank.tail_cons {Γ} [inhabited Γ] (a : Γ) : ∀ (l : list_blank Γ), (l.cons a).tail = l := quotient.ind' $ by exact λ l, rfl /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ @[simp] theorem list_blank.cons_head_tail {Γ} [inhabited Γ] : ∀ (l : list_blank Γ), l.tail.cons l.head = l := quotient.ind' begin refine (λ l, quotient.sound' (or.inr _)), cases l, {exact ⟨1, rfl⟩}, {refl}, end /-- The `cons` and `head`/`tail` functions are mutually inverse, unlike in the case of `list` where this only holds for nonempty lists. -/ theorem list_blank.exists_cons {Γ} [inhabited Γ] (l : list_blank Γ) : ∃ a l', l = list_blank.cons a l' := ⟨_, _, (list_blank.cons_head_tail _).symm⟩ /-- The n-th element of a `list_blank` is well defined for all `n : ℕ`, unlike in a `list`. -/ def list_blank.nth {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : Γ := l.lift_on (λ l, list.inth l n) begin rintro l _ ⟨i, rfl⟩, simp only [list.inth], cases lt_or_le _ _ with h h, {rw list.nth_append h}, rw list.nth_len_le h, cases le_or_lt _ _ with h₂ h₂, {rw list.nth_len_le h₂}, rw [list.nth_le_nth h₂, list.nth_le_append_right h, list.nth_le_repeat] end @[simp] theorem list_blank.nth_mk {Γ} [inhabited Γ] (l : list Γ) (n : ℕ) : (list_blank.mk l).nth n = l.inth n := rfl @[simp] theorem list_blank.nth_zero {Γ} [inhabited Γ] (l : list_blank Γ) : l.nth 0 = l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[simp] theorem list_blank.nth_succ {Γ} [inhabited Γ] (l : list_blank Γ) (n : ℕ) : l.nth (n + 1) = l.tail.nth n := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l.tail (λ l, rfl) end @[ext] theorem list_blank.ext {Γ} [inhabited Γ] {L₁ L₂ : list_blank Γ} : (∀ i, L₁.nth i = L₂.nth i) → L₁ = L₂ := list_blank.induction_on L₁ $ λ l₁, list_blank.induction_on L₂ $ λ l₂ H, begin wlog h : l₁.length ≤ l₂.length using l₁ l₂, swap, { exact (this $ λ i, (H i).symm).symm }, refine quotient.sound' (or.inl ⟨l₂.length - l₁.length, _⟩), refine list.ext_le _ (λ i h h₂, eq.symm _), { simp only [nat.add_sub_of_le h, list.length_append, list.length_repeat] }, simp at H, cases lt_or_le i l₁.length with h' h', { simpa only [list.nth_le_append _ h', list.nth_le_nth h, list.nth_le_nth h', option.iget] using H i }, { simpa only [list.nth_le_append_right h', list.nth_le_repeat, list.nth_le_nth h, list.nth_len_le h', option.iget] using H i }, end /-- Apply a function to a value stored at the nth position of the list. -/ @[simp] def list_blank.modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) : ℕ → list_blank Γ → list_blank Γ | 0 L := L.tail.cons (f L.head) | (n+1) L := (L.tail.modify_nth n).cons L.head theorem list_blank.nth_modify_nth {Γ} [inhabited Γ] (f : Γ → Γ) (n i) (L : list_blank Γ) : (L.modify_nth f n).nth i = if i = n then f (L.nth i) else L.nth i := begin induction n with n IH generalizing i L, { cases i; simp only [list_blank.nth_zero, if_true, list_blank.head_cons, list_blank.modify_nth, eq_self_iff_true, list_blank.nth_succ, if_false, list_blank.tail_cons] }, { cases i, { rw if_neg (nat.succ_ne_zero _).symm, simp only [list_blank.nth_zero, list_blank.head_cons, list_blank.modify_nth] }, { simp only [IH, list_blank.modify_nth, list_blank.nth_succ, list_blank.tail_cons], congr } } end /-- A pointed map of `inhabited` types is a map that sends one default value to the other. -/ structure {u v} pointed_map (Γ : Type u) (Γ' : Type v) [inhabited Γ] [inhabited Γ'] : Type (max u v) := (f : Γ → Γ') (map_pt' : f (default _) = default _) instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : inhabited (pointed_map Γ Γ') := ⟨⟨λ _, default _, rfl⟩⟩ instance {Γ Γ'} [inhabited Γ] [inhabited Γ'] : has_coe_to_fun (pointed_map Γ Γ') := ⟨_, pointed_map.f⟩ @[simp] theorem pointed_map.mk_val {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : Γ → Γ') (pt) : (pointed_map.mk f pt : Γ → Γ') = f := rfl @[simp] theorem pointed_map.map_pt {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : f (default _) = default _ := pointed_map.map_pt' _ @[simp] theorem pointed_map.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (l.map f).head = f l.head := by cases l; [exact (pointed_map.map_pt f).symm, refl] /-- The `map` function on lists is well defined on `list_blank`s provided that the map is pointed. -/ def list_blank.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.map f l)) begin rintro l _ ⟨i, rfl⟩, refine quotient.sound' (or.inl ⟨i, _⟩), simp only [pointed_map.map_pt, list.map_append, list.map_repeat], end @[simp] theorem list_blank.map_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (list_blank.mk l).map f = list_blank.mk (l.map f) := rfl @[simp] theorem list_blank.head_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).head = f l.head := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.tail_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) : (l.map f).tail = l.tail.map f := begin conv {to_lhs, rw [← list_blank.cons_head_tail l]}, exact quotient.induction_on' l (λ a, rfl) end @[simp] theorem list_blank.map_cons {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (a : Γ) : (l.cons a).map f = (l.map f).cons (f a) := begin refine (list_blank.cons_head_tail _).symm.trans _, simp only [list_blank.head_map, list_blank.head_cons, list_blank.tail_map, list_blank.tail_cons] end @[simp] theorem list_blank.nth_map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list_blank Γ) (n : ℕ) : (l.map f).nth n = f (l.nth n) := l.induction_on begin intro l, simp only [list.nth_map, list_blank.map_mk, list_blank.nth_mk, list.inth], cases l.nth n, {exact f.2.symm}, {refl} end /-- The `i`-th projection as a pointed map. -/ def proj {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) : pointed_map (∀ i, Γ i) (Γ i) := ⟨λ a, a i, rfl⟩ theorem proj_map_nth {ι : Type*} {Γ : ι → Type*} [∀ i, inhabited (Γ i)] (i : ι) (L n) : (list_blank.map (@proj ι Γ _ i) L).nth n = L.nth n i := by rw list_blank.nth_map; refl theorem list_blank.map_modify_nth {Γ Γ'} [inhabited Γ] [inhabited Γ'] (F : pointed_map Γ Γ') (f : Γ → Γ) (f' : Γ' → Γ') (H : ∀ x, F (f x) = f' (F x)) (n) (L : list_blank Γ) : (L.modify_nth f n).map F = (L.map F).modify_nth f' n := by induction n with n IH generalizing L; simp only [*, list_blank.head_map, list_blank.modify_nth, list_blank.map_cons, list_blank.tail_map] /-- Append a list on the left side of a list_blank. -/ @[simp] def list_blank.append {Γ} [inhabited Γ] : list Γ → list_blank Γ → list_blank Γ | [] L := L | (a :: l) L := list_blank.cons a (list_blank.append l L) @[simp] theorem list_blank.append_mk {Γ} [inhabited Γ] (l₁ l₂ : list Γ) : list_blank.append l₁ (list_blank.mk l₂) = list_blank.mk (l₁ ++ l₂) := by induction l₁; simp only [*, list_blank.append, list.nil_append, list.cons_append, list_blank.cons_mk] theorem list_blank.append_assoc {Γ} [inhabited Γ] (l₁ l₂ : list Γ) (l₃ : list_blank Γ) : list_blank.append (l₁ ++ l₂) l₃ = list_blank.append l₁ (list_blank.append l₂ l₃) := l₃.induction_on $ by intro; simp only [list_blank.append_mk, list.append_assoc] /-- The `bind` function on lists is well defined on `list_blank`s provided that the default element is sent to a sequence of default elements. -/ def list_blank.bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list_blank Γ) (f : Γ → list Γ') (hf : ∃ n, f (default _) = list.repeat (default _) n) : list_blank Γ' := l.lift_on (λ l, list_blank.mk (list.bind l f)) begin rintro l _ ⟨i, rfl⟩, cases hf with n e, refine quotient.sound' (or.inl ⟨i * n, _⟩), rw [list.bind_append, mul_comm], congr, induction i with i IH, refl, simp only [IH, e, list.repeat_add, nat.mul_succ, add_comm, list.repeat_succ, list.cons_bind], end @[simp] lemma list_blank.bind_mk {Γ Γ'} [inhabited Γ] [inhabited Γ'] (l : list Γ) (f : Γ → list Γ') (hf) : (list_blank.mk l).bind f hf = list_blank.mk (l.bind f) := rfl @[simp] lemma list_blank.cons_bind {Γ Γ'} [inhabited Γ] [inhabited Γ'] (a : Γ) (l : list_blank Γ) (f : Γ → list Γ') (hf) : (l.cons a).bind f hf = (l.bind f hf).append (f a) := l.induction_on $ by intro; simp only [list_blank.append_mk, list_blank.bind_mk, list_blank.cons_mk, list.cons_bind] /-- The tape of a Turing machine is composed of a head element (which we imagine to be the current position of the head), together with two `list_blank`s denoting the portions of the tape going off to the left and right. When the Turing machine moves right, an element is pulled from the right side and becomes the new head, while the head element is consed onto the left side. -/ structure tape (Γ : Type*) [inhabited Γ] := (head : Γ) (left : list_blank Γ) (right : list_blank Γ) instance tape.inhabited {Γ} [inhabited Γ] : inhabited (tape Γ) := ⟨by constructor; apply default⟩ /-- A direction for the turing machine `move` command, either left or right. -/ @[derive decidable_eq, derive inhabited] inductive dir | left | right /-- The "inclusive" left side of the tape, including both `left` and `head`. -/ def tape.left₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.left.cons T.head /-- The "inclusive" right side of the tape, including both `right` and `head`. -/ def tape.right₀ {Γ} [inhabited Γ] (T : tape Γ) : list_blank Γ := T.right.cons T.head /-- Move the tape in response to a motion of the Turing machine. Note that `T.move dir.left` makes `T.left` smaller; the Turing machine is moving left and the tape is moving right. -/ def tape.move {Γ} [inhabited Γ] : dir → tape Γ → tape Γ | dir.left ⟨a, L, R⟩ := ⟨L.head, L.tail, R.cons a⟩ | dir.right ⟨a, L, R⟩ := ⟨R.head, L.cons a, R.tail⟩ @[simp] theorem tape.move_left_right {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.left).move dir.right = T := by cases T; simp [tape.move] @[simp] theorem tape.move_right_left {Γ} [inhabited Γ] (T : tape Γ) : (T.move dir.right).move dir.left = T := by cases T; simp [tape.move] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : tape Γ := ⟨R.head, L, R.tail⟩ @[simp] theorem tape.mk'_left {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).left = L := rfl @[simp] theorem tape.mk'_head {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).head = R.head := rfl @[simp] theorem tape.mk'_right {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right = R.tail := rfl @[simp] theorem tape.mk'_right₀ {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).right₀ = R := list_blank.cons_head_tail _ @[simp] theorem tape.mk'_left_right₀ {Γ} [inhabited Γ] (T : tape Γ) : tape.mk' T.left T.right₀ = T := by cases T; simp only [tape.right₀, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] theorem tape.exists_mk' {Γ} [inhabited Γ] (T : tape Γ) : ∃ L R, T = tape.mk' L R := ⟨_, _, (tape.mk'_left_right₀ _).symm⟩ @[simp] theorem tape.move_left_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.left = tape.mk' L.tail (R.cons L.head) := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] @[simp] theorem tape.move_right_mk' {Γ} [inhabited Γ] (L R : list_blank Γ) : (tape.mk' L R).move dir.right = tape.mk' (L.cons R.head) R.tail := by simp only [tape.move, tape.mk', list_blank.head_cons, eq_self_iff_true, list_blank.cons_head_tail, and_self, list_blank.tail_cons] /-- Construct a tape from a left side and an inclusive right side. -/ def tape.mk₂ {Γ} [inhabited Γ] (L R : list Γ) : tape Γ := tape.mk' (list_blank.mk L) (list_blank.mk R) /-- Construct a tape from a list, with the head of the list at the TM head and the rest going to the right. -/ def tape.mk₁ {Γ} [inhabited Γ] (l : list Γ) : tape Γ := tape.mk₂ [] l /-- The `nth` function of a tape is integer-valued, with index `0` being the head, negative indexes on the left and positive indexes on the right. (Picture a number line.) -/ def tape.nth {Γ} [inhabited Γ] (T : tape Γ) : ℤ → Γ | 0 := T.head | (n+1:ℕ) := T.right.nth n | -[1+ n] := T.left.nth n @[simp] theorem tape.nth_zero {Γ} [inhabited Γ] (T : tape Γ) : T.nth 0 = T.1 := rfl theorem tape.right₀_nth {Γ} [inhabited Γ] (T : tape Γ) (n : ℕ) : T.right₀.nth n = T.nth n := by cases n; simp only [tape.nth, tape.right₀, int.coe_nat_zero, list_blank.nth_zero, list_blank.nth_succ, list_blank.head_cons, list_blank.tail_cons] @[simp] theorem tape.mk'_nth_nat {Γ} [inhabited Γ] (L R : list_blank Γ) (n : ℕ) : (tape.mk' L R).nth n = R.nth n := by rw [← tape.right₀_nth, tape.mk'_right₀] @[simp] theorem tape.move_left_nth {Γ} [inhabited Γ] : ∀ (T : tape Γ) (i : ℤ), (T.move dir.left).nth i = T.nth (i-1) | ⟨a, L, R⟩ -[1+ n] := (list_blank.nth_succ _ _).symm | ⟨a, L, R⟩ 0 := (list_blank.nth_zero _).symm | ⟨a, L, R⟩ 1 := (list_blank.nth_zero _).trans (list_blank.head_cons _ _) | ⟨a, L, R⟩ ((n+1:ℕ)+1) := begin rw add_sub_cancel, change (R.cons a).nth (n+1) = R.nth n, rw [list_blank.nth_succ, list_blank.tail_cons] end @[simp] theorem tape.move_right_nth {Γ} [inhabited Γ] (T : tape Γ) (i : ℤ) : (T.move dir.right).nth i = T.nth (i+1) := by conv {to_rhs, rw ← T.move_right_left}; rw [tape.move_left_nth, add_sub_cancel] @[simp] theorem tape.move_right_n_head {Γ} [inhabited Γ] (T : tape Γ) (i : ℕ) : ((tape.move dir.right)^[i] T).head = T.nth i := by induction i generalizing T; [refl, simp only [*, tape.move_right_nth, int.coe_nat_succ, iterate_succ]] /-- Replace the current value of the head on the tape. -/ def tape.write {Γ} [inhabited Γ] (b : Γ) (T : tape Γ) : tape Γ := {head := b, ..T} @[simp] theorem tape.write_self {Γ} [inhabited Γ] : ∀ (T : tape Γ), T.write T.1 = T := by rintro ⟨⟩; refl @[simp] theorem tape.write_nth {Γ} [inhabited Γ] (b : Γ) : ∀ (T : tape Γ) {i : ℤ}, (T.write b).nth i = if i = 0 then b else T.nth i | ⟨a, L, R⟩ 0 := rfl | ⟨a, L, R⟩ (n+1:ℕ) := rfl | ⟨a, L, R⟩ -[1+ n] := rfl @[simp] theorem tape.write_mk' {Γ} [inhabited Γ] (a b : Γ) (L R : list_blank Γ) : (tape.mk' L (R.cons a)).write b = tape.mk' L (R.cons b) := by simp only [tape.write, tape.mk', list_blank.head_cons, list_blank.tail_cons, eq_self_iff_true, and_self] /-- Apply a pointed map to a tape to change the alphabet. -/ def tape.map {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) : tape Γ' := ⟨f T.1, T.2.map f, T.3.map f⟩ @[simp] theorem tape.map_fst {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') : ∀ (T : tape Γ), (T.map f).1 = f T.1 := by rintro ⟨⟩; refl @[simp] theorem tape.map_write {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (b : Γ) : ∀ (T : tape Γ), (T.write b).map f = (T.map f).write (f b) := by rintro ⟨⟩; refl @[simp] theorem tape.write_move_right_n {Γ} [inhabited Γ] (f : Γ → Γ) (L R : list_blank Γ) (n : ℕ) : ((tape.move dir.right)^[n] (tape.mk' L R)).write (f (R.nth n)) = ((tape.move dir.right)^[n] (tape.mk' L (R.modify_nth f n))) := begin induction n with n IH generalizing L R, { simp only [list_blank.nth_zero, list_blank.modify_nth, iterate_zero_apply], rw [← tape.write_mk', list_blank.cons_head_tail] }, simp only [list_blank.head_cons, list_blank.nth_succ, list_blank.modify_nth, tape.move_right_mk', list_blank.tail_cons, iterate_succ_apply, IH] end theorem tape.map_move {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (T : tape Γ) (d) : (T.move d).map f = (T.map f).move d := by cases T; cases d; simp only [tape.move, tape.map, list_blank.head_map, eq_self_iff_true, list_blank.map_cons, and_self, list_blank.tail_map] theorem tape.map_mk' {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list_blank Γ) : (tape.mk' L R).map f = tape.mk' (L.map f) (R.map f) := by simp only [tape.mk', tape.map, list_blank.head_map, eq_self_iff_true, and_self, list_blank.tail_map] theorem tape.map_mk₂ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (L R : list Γ) : (tape.mk₂ L R).map f = tape.mk₂ (L.map f) (R.map f) := by simp only [tape.mk₂, tape.map_mk', list_blank.map_mk] theorem tape.map_mk₁ {Γ Γ'} [inhabited Γ] [inhabited Γ'] (f : pointed_map Γ Γ') (l : list Γ) : (tape.mk₁ l).map f = tape.mk₁ (l.map f) := tape.map_mk₂ _ _ _ /-- Run a state transition function `σ → option σ` "to completion". The return value is the last state returned before a `none` result. If the state transition function always returns `some`, then the computation diverges, returning `roption.none`. -/ def eval {σ} (f : σ → option σ) : σ → roption σ := pfun.fix (λ s, roption.some $ (f s).elim (sum.inl s) sum.inr) /-- The reflexive transitive closure of a state transition function. `reaches f a b` means there is a finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation permits zero steps of the state transition function. -/ def reaches {σ} (f : σ → option σ) : σ → σ → Prop := refl_trans_gen (λ a b, b ∈ f a) /-- The transitive closure of a state transition function. `reaches₁ f a b` means there is a nonempty finite sequence of steps `f a = some a₁`, `f a₁ = some a₂`, ... such that `aₙ = b`. This relation does not permit zero steps of the state transition function. -/ def reaches₁ {σ} (f : σ → option σ) : σ → σ → Prop := trans_gen (λ a b, b ∈ f a) theorem reaches₁_eq {σ} {f : σ → option σ} {a b c} (h : f a = f b) : reaches₁ f a c ↔ reaches₁ f b c := trans_gen.head'_iff.trans (trans_gen.head'_iff.trans $ by rw h).symm theorem reaches_total {σ} {f : σ → option σ} {a b c} : reaches f a b → reaches f a c → reaches f b c ∨ reaches f c b := refl_trans_gen.total_of_right_unique $ λ _ _ _, option.mem_unique theorem reaches₁_fwd {σ} {f : σ → option σ} {a b c} (h₁ : reaches₁ f a c) (h₂ : b ∈ f a) : reaches f b c := begin rcases trans_gen.head'_iff.1 h₁ with ⟨b', hab, hbc⟩, cases option.mem_unique hab h₂, exact hbc end /-- A variation on `reaches`. `reaches₀ f a b` holds if whenever `reaches₁ f b c` then `reaches₁ f a c`. This is a weaker property than `reaches` and is useful for replacing states with equivalent states without taking a step. -/ def reaches₀ {σ} (f : σ → option σ) (a b : σ) : Prop := ∀ c, reaches₁ f b c → reaches₁ f a c theorem reaches₀.trans {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h₂ : reaches₀ f b c) : reaches₀ f a c | d h₃ := h₁ _ (h₂ _ h₃) @[refl] theorem reaches₀.refl {σ} {f : σ → option σ} (a : σ) : reaches₀ f a a | b h := h theorem reaches₀.single {σ} {f : σ → option σ} {a b : σ} (h : b ∈ f a) : reaches₀ f a b | c h₂ := h₂.head h theorem reaches₀.head {σ} {f : σ → option σ} {a b c : σ} (h : b ∈ f a) (h₂ : reaches₀ f b c) : reaches₀ f a c := (reaches₀.single h).trans h₂ theorem reaches₀.tail {σ} {f : σ → option σ} {a b c : σ} (h₁ : reaches₀ f a b) (h : c ∈ f b) : reaches₀ f a c := h₁.trans (reaches₀.single h) theorem reaches₀_eq {σ} {f : σ → option σ} {a b} (e : f a = f b) : reaches₀ f a b | d h := (reaches₁_eq e).2 h theorem reaches₁.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches₁ f a b) : reaches₀ f a b | c h₂ := h.trans h₂ theorem reaches.to₀ {σ} {f : σ → option σ} {a b : σ} (h : reaches f a b) : reaches₀ f a b | c h₂ := h₂.trans_right h theorem reaches₀.tail' {σ} {f : σ → option σ} {a b c : σ} (h : reaches₀ f a b) (h₂ : c ∈ f b) : reaches₁ f a c := h _ (trans_gen.single h₂) /-- (co-)Induction principle for `eval`. If a property `C` holds of any point `a` evaluating to `b` which is either terminal (meaning `a = b`) or where the next point also satisfies `C`, then it holds of any point where `eval f a` evaluates to `b`. This formalizes the notion that if `eval f a` evaluates to `b` then it reaches terminal state `b` in finitely many steps. -/ @[elab_as_eliminator] def eval_induction {σ} {f : σ → option σ} {b : σ} {C : σ → Sort*} {a : σ} (h : b ∈ eval f a) (H : ∀ a, b ∈ eval f a → (∀ a', b ∈ eval f a' → f a = some a' → C a') → C a) : C a := pfun.fix_induction h (λ a' ha' h', H _ ha' $ λ b' hb' e, h' _ hb' $ roption.mem_some_iff.2 $ by rw e; refl) theorem mem_eval {σ} {f : σ → option σ} {a b} : b ∈ eval f a ↔ reaches f a b ∧ f b = none := ⟨λ h, begin refine eval_induction h (λ a h IH, _), cases e : f a with a', { rw roption.mem_unique h (pfun.mem_fix_iff.2 $ or.inl $ roption.mem_some_iff.2 $ by rw e; refl), exact ⟨refl_trans_gen.refl, e⟩ }, { rcases pfun.mem_fix_iff.1 h with h | ⟨_, h, h'⟩; rw e at h; cases roption.mem_some_iff.1 h, cases IH a' h' (by rwa e) with h₁ h₂, exact ⟨refl_trans_gen.head e h₁, h₂⟩ } end, λ ⟨h₁, h₂⟩, begin refine refl_trans_gen.head_induction_on h₁ _ (λ a a' h _ IH, _), { refine pfun.mem_fix_iff.2 (or.inl _), rw h₂, apply roption.mem_some }, { refine pfun.mem_fix_iff.2 (or.inr ⟨_, _, IH⟩), rw show f a = _, from h, apply roption.mem_some } end⟩ theorem eval_maximal₁ {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) (c) : ¬ reaches₁ f b c | bc := let ⟨ab, b0⟩ := mem_eval.1 h, ⟨b', h', _⟩ := trans_gen.head'_iff.1 bc in by cases b0.symm.trans h' theorem eval_maximal {σ} {f : σ → option σ} {a b} (h : b ∈ eval f a) {c} : reaches f b c ↔ c = b := let ⟨ab, b0⟩ := mem_eval.1 h in refl_trans_gen_iff_eq $ λ b' h', by cases b0.symm.trans h' theorem reaches_eval {σ} {f : σ → option σ} {a b} (ab : reaches f a b) : eval f a = eval f b := roption.ext $ λ c, ⟨λ h, let ⟨ac, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨(or_iff_left_of_imp $ by exact λ cb, (eval_maximal h).1 cb ▸ refl_trans_gen.refl).1 (reaches_total ab ac), c0⟩, λ h, let ⟨bc, c0⟩ := mem_eval.1 h in mem_eval.2 ⟨ab.trans bc, c0⟩,⟩ /-- Given a relation `tr : σ₁ → σ₂ → Prop` between state spaces, and state transition functions `f₁ : σ₁ → option σ₁` and `f₂ : σ₂ → option σ₂`, `respects f₁ f₂ tr` means that if `tr a₁ a₂` holds initially and `f₁` takes a step to `a₂` then `f₂` will take one or more steps before reaching a state `b₂` satisfying `tr a₂ b₂`, and if `f₁ a₁` terminates then `f₂ a₂` also terminates. Such a relation `tr` is also known as a refinement. -/ def respects {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂ → Prop) := ∀ ⦃a₁ a₂⦄, tr a₁ a₂ → (match f₁ a₁ with | some b₁ := ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ | none := f₂ a₂ = none end : Prop) theorem tr_reaches₁ {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches₁ f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches₁ f₂ a₂ b₂ := begin induction ab with c₁ ac c₁ d₁ ac cd IH, { have := H aa, rwa (show f₁ a₁ = _, from ac) at this }, { rcases IH with ⟨c₂, cc, ac₂⟩, have := H cc, rw (show f₁ c₁ = _, from cd) at this, rcases this with ⟨d₂, dd, cd₂⟩, exact ⟨_, dd, ac₂.trans cd₂⟩ } end theorem tr_reaches {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₁} (ab : reaches f₁ a₁ b₁) : ∃ b₂, tr b₁ b₂ ∧ reaches f₂ a₂ b₂ := begin rcases refl_trans_gen_iff_eq_or_trans_gen.1 ab with rfl | ab, { exact ⟨_, aa, refl_trans_gen.refl⟩ }, { exact let ⟨b₂, bb, h⟩ := tr_reaches₁ H aa ab in ⟨b₂, bb, h.to_refl⟩ } end theorem tr_reaches_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) {b₂} (ab : reaches f₂ a₂ b₂) : ∃ c₁ c₂, reaches f₂ b₂ c₂ ∧ tr c₁ c₂ ∧ reaches f₁ a₁ c₁ := begin induction ab with c₂ d₂ ac cd IH, { exact ⟨_, _, refl_trans_gen.refl, aa, refl_trans_gen.refl⟩ }, { rcases IH with ⟨e₁, e₂, ce, ee, ae⟩, rcases refl_trans_gen.cases_head ce with rfl | ⟨d', cd', de⟩, { have := H ee, revert this, cases eg : f₁ e₁ with g₁; simp only [respects, and_imp, exists_imp_distrib], { intro c0, cases cd.symm.trans c0 }, { intros g₂ gg cg, rcases trans_gen.head'_iff.1 cg with ⟨d', cd', dg⟩, cases option.mem_unique cd cd', exact ⟨_, _, dg, gg, ae.tail eg⟩ } }, { cases option.mem_unique cd cd', exact ⟨_, _, de, ee, ae⟩ } } end theorem tr_eval {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₁ a₂} (aa : tr a₁ a₂) (ab : b₁ ∈ eval f₁ a₁) : ∃ b₂, tr b₁ b₂ ∧ b₂ ∈ eval f₂ a₂ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches H aa ab with ⟨b₂, bb, ab⟩, refine ⟨_, bb, mem_eval.2 ⟨ab, _⟩⟩, have := H bb, rwa b0 at this end theorem tr_eval_rev {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ b₂ a₂} (aa : tr a₁ a₂) (ab : b₂ ∈ eval f₂ a₂) : ∃ b₁, tr b₁ b₂ ∧ b₁ ∈ eval f₁ a₁ := begin cases mem_eval.1 ab with ab b0, rcases tr_reaches_rev H aa ab with ⟨c₁, c₂, bc, cc, ac⟩, cases (refl_trans_gen_iff_eq (by exact option.eq_none_iff_forall_not_mem.1 b0)).1 bc, refine ⟨_, cc, mem_eval.2 ⟨ac, _⟩⟩, have := H cc, cases f₁ c₁ with d₁, {refl}, rcases this with ⟨d₂, dd, bd⟩, rcases trans_gen.head'_iff.1 bd with ⟨e, h, _⟩, cases b0.symm.trans h end theorem tr_eval_dom {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂ → Prop} (H : respects f₁ f₂ tr) {a₁ a₂} (aa : tr a₁ a₂) : (eval f₂ a₂).dom ↔ (eval f₁ a₁).dom := ⟨λ h, let ⟨b₂, tr, h, _⟩ := tr_eval_rev H aa ⟨h, rfl⟩ in h, λ h, let ⟨b₂, tr, h, _⟩ := tr_eval H aa ⟨h, rfl⟩ in h⟩ /-- A simpler version of `respects` when the state transition relation `tr` is a function. -/ def frespects {σ₁ σ₂} (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (a₂ : σ₂) : option σ₁ → Prop | (some b₁) := reaches₁ f₂ a₂ (tr b₁) | none := f₂ a₂ = none theorem frespects_eq {σ₁ σ₂} {f₂ : σ₂ → option σ₂} {tr : σ₁ → σ₂} {a₂ b₂} (h : f₂ a₂ = f₂ b₂) : ∀ {b₁}, frespects f₂ tr a₂ b₁ ↔ frespects f₂ tr b₂ b₁ | (some b₁) := reaches₁_eq h | none := by unfold frespects; rw h theorem fun_respects {σ₁ σ₂ f₁ f₂} {tr : σ₁ → σ₂} : respects f₁ f₂ (λ a b, tr a = b) ↔ ∀ ⦃a₁⦄, frespects f₂ tr (tr a₁) (f₁ a₁) := forall_congr $ λ a₁, by cases f₁ a₁; simp only [frespects, respects, exists_eq_left', forall_eq'] theorem tr_eval' {σ₁ σ₂} (f₁ : σ₁ → option σ₁) (f₂ : σ₂ → option σ₂) (tr : σ₁ → σ₂) (H : respects f₁ f₂ (λ a b, tr a = b)) (a₁) : eval f₂ (tr a₁) = tr <$> eval f₁ a₁ := roption.ext $ λ b₂, ⟨λ h, let ⟨b₁, bb, hb⟩ := tr_eval_rev H rfl h in (roption.mem_map_iff _).2 ⟨b₁, hb, bb⟩, λ h, begin rcases (roption.mem_map_iff _).1 h with ⟨b₁, ab, bb⟩, rcases tr_eval H rfl ab with ⟨_, rfl, h⟩, rwa bb at h end⟩ /-! ## The TM0 model A TM0 turing machine is essentially a Post-Turing machine, adapted for type theory. A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function `Λ → Γ → option (Λ × stmt)`, where a `stmt` can be either `move left`, `move right` or `write a` for `a : Γ`. The machine works over a "tape", a doubly-infinite sequence of elements of `Γ`, and an instantaneous configuration, `cfg`, is a label `q : Λ` indicating the current internal state of the machine, and a `tape Γ` (which is essentially `ℤ →₀ Γ`). The evolution is described by the `step` function: * If `M q T.head = none`, then the machine halts. * If `M q T.head = some (q', s)`, then the machine performs action `s : stmt` and then transitions to state `q'`. The initial state takes a `list Γ` and produces a `tape Γ` where the head of the list is the head of the tape and the rest of the list extends to the right, with the left side all blank. The final state takes the entire right side of the tape right or equal to the current position of the machine. (This is actually a `list_blank Γ`, not a `list Γ`, because we don't know, at this level of generality, where the output ends. If equality to `default Γ` is decidable we can trim the list to remove the infinite tail of blanks.) -/ namespace TM0 section parameters (Γ : Type*) [inhabited Γ] -- type of tape symbols parameters (Λ : Type*) [inhabited Λ] -- type of "labels" or TM states /-- A Turing machine "statement" is just a command to either move left or right, or write a symbol on the tape. -/ inductive stmt | move : dir → stmt | write : Γ → stmt instance stmt.inhabited : inhabited stmt := ⟨stmt.write (default _)⟩ /-- A Post-Turing machine with symbol type `Γ` and label type `Λ` is a function which, given the current state `q : Λ` and the tape head `a : Γ`, either halts (returns `none`) or returns a new state `q' : Λ` and a `stmt` describing what to do, either a move left or right, or a write command. Both `Λ` and `Γ` are required to be inhabited; the default value for `Γ` is the "blank" tape value, and the default value of `Λ` is the initial state. -/ @[nolint unused_arguments] -- [inhabited Λ]: this is a deliberate addition, see comment def machine := Λ → Γ → option (Λ × stmt) instance machine.inhabited : inhabited machine := by unfold machine; apply_instance /-- The configuration state of a Turing machine during operation consists of a label (machine state), and a tape, represented in the form `(a, L, R)` meaning the tape looks like `L.rev ++ [a] ++ R` with the machine currently reading the `a`. The lists are automatically extended with blanks as the machine moves around. -/ structure cfg := (q : Λ) (tape : tape Γ) instance cfg.inhabited : inhabited cfg := ⟨⟨default _, default _⟩⟩ parameters {Γ Λ} /-- Execution semantics of the Turing machine. -/ def step (M : machine) : cfg → option cfg | ⟨q, T⟩ := (M q T.1).map (λ ⟨q', a⟩, ⟨q', match a with | stmt.move d := T.move d | stmt.write a := T.write a end⟩) /-- The statement `reaches M s₁ s₂` means that `s₂` is obtained starting from `s₁` after a finite number of steps from `s₂`. -/ def reaches (M : machine) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- The initial configuration. -/ def init (l : list Γ) : cfg := ⟨default Λ, tape.mk₁ l⟩ /-- Evaluate a Turing machine on initial input to a final state, if it terminates. -/ def eval (M : machine) (l : list Γ) : roption (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) /-- The raw definition of a Turing machine does not require that `Γ` and `Λ` are finite, and in practice we will be interested in the infinite `Λ` case. We recover instead a notion of "effectively finite" Turing machines, which only make use of a finite subset of their states. We say that a set `S ⊆ Λ` supports a Turing machine `M` if `S` is closed under the transition function and contains the initial state. -/ def supports (M : machine) (S : set Λ) := default Λ ∈ S ∧ ∀ {q a q' s}, (q', s) ∈ M q a → q ∈ S → q' ∈ S theorem step_supports (M : machine) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.q ∈ S → c'.q ∈ S | ⟨q, T⟩ c' h₁ h₂ := begin rcases option.map_eq_some'.1 h₁ with ⟨⟨q', a⟩, h, rfl⟩, exact ss.2 h h₂, end theorem univ_supports (M : machine) : supports M set.univ := ⟨trivial, λ q a q' s h₁ h₂, trivial⟩ end section variables {Γ : Type*} [inhabited Γ] variables {Γ' : Type*} [inhabited Γ'] variables {Λ : Type*} [inhabited Λ] variables {Λ' : Type*} [inhabited Λ'] /-- Map a TM statement across a function. This does nothing to move statements and maps the write values. -/ def stmt.map (f : pointed_map Γ Γ') : stmt Γ → stmt Γ' | (stmt.move d) := stmt.move d | (stmt.write a) := stmt.write (f a) /-- Map a configuration across a function, given `f : Γ → Γ'` a map of the alphabets and `g : Λ → Λ'` a map of the machine states. -/ def cfg.map (f : pointed_map Γ Γ') (g : Λ → Λ') : cfg Γ Λ → cfg Γ' Λ' | ⟨q, T⟩ := ⟨g q, T.map f⟩ variables (M : machine Γ Λ) (f₁ : pointed_map Γ Γ') (f₂ : pointed_map Γ' Γ) (g₁ : Λ → Λ') (g₂ : Λ' → Λ) /-- Because the state transition function uses the alphabet and machine states in both the input and output, to map a machine from one alphabet and machine state space to another we need functions in both directions, essentially an `equiv` without the laws. -/ def machine.map : machine Γ' Λ' | q l := (M (g₂ q) (f₂ l)).map (prod.map g₁ (stmt.map f₁)) theorem machine.map_step {S : set Λ} (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : ∀ c : cfg Γ Λ, c.q ∈ S → (step M c).map (cfg.map f₁ g₁) = step (M.map f₁ f₂ g₁ g₂) (cfg.map f₁ g₁ c) | ⟨q, T⟩ h := begin unfold step machine.map cfg.map, simp only [turing.tape.map_fst, g₂₁ q h, f₂₁ _], rcases M q T.1 with _|⟨q', d|a⟩, {refl}, { simp only [step, cfg.map, option.map_some', tape.map_move f₁], refl }, { simp only [step, cfg.map, option.map_some', tape.map_write], refl } end theorem map_init (g₁ : pointed_map Λ Λ') (l : list Γ) : (init l).map f₁ g₁ = init (l.map f₁) := congr (congr_arg cfg.mk g₁.map_pt) (tape.map_mk₁ _ _) theorem machine.map_respects (g₁ : pointed_map Λ Λ') (g₂ : Λ' → Λ) {S} (ss : supports M S) (f₂₁ : function.right_inverse f₁ f₂) (g₂₁ : ∀ q ∈ S, g₂ (g₁ q) = q) : respects (step M) (step (M.map f₁ f₂ g₁ g₂)) (λ a b, a.q ∈ S ∧ cfg.map f₁ g₁ a = b) | c _ ⟨cs, rfl⟩ := begin cases e : step M c with c'; unfold respects, { rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], refl }, { refine ⟨_, ⟨step_supports M ss e cs, rfl⟩, trans_gen.single _⟩, rw [← M.map_step f₁ f₂ g₁ g₂ f₂₁ g₂₁ _ cs, e], exact rfl } end end end TM0 /-! ## The TM1 model The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`. Most of the regular commands are allowed to use the current value `a` of the local variables and the value `T.head` on the tape to calculate what to write or how to change local state, but the statements themselves have a fixed structure. The `stmt`s can be as follows: * `move d q`: move left or right, and then do `q` * `write (f : Γ → σ → Γ) q`: write `f a T.head` to the tape, then do `q` * `load (f : Γ → σ → σ) q`: change the internal state to `f a T.head` * `branch (f : Γ → σ → bool) qtrue qfalse`: If `f a T.head` is true, do `qtrue`, else `qfalse` * `goto (f : Γ → σ → Λ)`: Go to label `f a T.head` * `halt`: Transition to the halting state, which halts on the following step Note that here most statements do not have labels; `goto` commands can only go to a new function. Only the `goto` and `halt` statements actually take a step; the rest is done by recursion on statements and so take 0 steps. (There is a uniform bound on many statements can be executed before the next `goto`, so this is an `O(1)` speedup with the constant depending on the machine.) The `halt` command has a one step stutter before actually halting so that any changes made before the halt have a chance to be "committed", since the `eval` relation uses the final configuration before the halt as the output, and `move` and `write` etc. take 0 steps in this model. -/ namespace TM1 section parameters (Γ : Type*) [inhabited Γ] -- Type of tape symbols parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM1 model is a simplification and extension of TM0 (Post-Turing model) in the direction of Wang B-machines. The machine's internal state is extended with a (finite) store `σ` of variables that may be accessed and updated at any time. A machine is given by a `Λ` indexed set of procedures or functions. Each function has a body which is a `stmt`, which can either be a `move` or `write` command, a `branch` (if statement based on the current tape value), a `load` (set the variable value), a `goto` (call another function), or `halt`. Note that here most statements do not have labels; `goto` commands can only go to a new function. All commands have access to the variable value and current tape value. -/ inductive stmt | move : dir → stmt → stmt | write : (Γ → σ → Γ) → stmt → stmt | load : (Γ → σ → σ) → stmt → stmt | branch : (Γ → σ → bool) → stmt → stmt → stmt | goto : (Γ → σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- The configuration of a TM1 machine is given by the currently evaluating statement, the variable store value, and the tape. -/ structure cfg := (l : option Λ) (var : σ) (tape : tape Γ) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩ parameters {Γ Λ σ} /-- The semantics of TM1 evaluation. -/ def step_aux : stmt → σ → tape Γ → cfg | (move d q) v T := step_aux q v (T.move d) | (write a q) v T := step_aux q v (T.write (a T.1 v)) | (load s q) v T := step_aux q (s T.1 v) T | (branch p q₁ q₂) v T := cond (p T.1 v) (step_aux q₁ v T) (step_aux q₂ v T) | (goto l) v T := ⟨some (l T.1 v), v, T⟩ | halt v T := ⟨none, v, T⟩ /-- The state transition function. -/ def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, T⟩ := none | ⟨some l, v, T⟩ := some (step_aux (M l) v T) /-- A set `S` of labels supports the statement `q` if all the `goto` statements in `q` refer only to other functions in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (move d q) := supports_stmt q | (write a q) := supports_stmt q | (load s q) := supports_stmt q | (branch p q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ a v, l a v ∈ S | halt := true open_locale classical /-- The subterm closure of a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(move d q) := insert Q (stmts₁ q) | Q@(write a q) := insert Q (stmts₁ q) | Q@(load s q) := insert Q (stmts₁ q) | Q@(branch p q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_union, finset.mem_singleton] at h₁₂, iterate 3 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ $ IH₁ h₁₂) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ $ IH₂ h₁₂) } }, case TM1.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM1.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ q IH _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 3 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM1.stmt.goto : l { subst h, exact hs }, case TM1.stmt.halt { subst h, trivial } end /-- The set of all statements in a turing machine, plus one extra value `none` representing the halt state. This is used in the TM1 to TM0 reduction. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- A set `S` of labels supports machine `M` if all the `goto` statements in the functions in `S` refer only to other functions in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T; intro hs, iterate 3 { exact IH _ _ hs }, case TM1.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p T.1 v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM1.stmt.goto { exact finset.some_mem_insert_none.2 (hs _ _) }, case TM1.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state, given a finite input that is placed on the tape starting at the TM head and going to the right. -/ def init (l : list Γ) : cfg := ⟨some (default _), default _, tape.mk₁ l⟩ /-- Evaluate a TM to completion, resulting in an output list on the tape (with an indeterminate number of blanks on the end). -/ def eval (M : Λ → stmt) (l : list Γ) : roption (list_blank Γ) := (eval (step M) (init l)).map (λ c, c.tape.right₀) end end TM1 /-! ## TM1 emulator in TM0 To prove that TM1 computable functions are TM0 computable, we need to reduce each TM1 program to a TM0 program. So suppose a TM1 program is given. We take the following: * The alphabet `Γ` is the same for both TM1 and TM0 * The set of states `Λ'` is defined to be `option stmt₁ × σ`, that is, a TM1 statement or `none` representing halt, and the possible settings of the internal variables. Note that this is an infinite set, because `stmt₁` is infinite. This is okay because we assume that from the initial TM1 state, only finitely many other labels are reachable, and there are only finitely many statements that appear in all of these functions. Even though `stmt₁` contains a statement called `halt`, we must separate it from `none` (`some halt` steps to `none` and `none` actually halts) because there is a one step stutter in the TM1 semantics. -/ namespace TM1to0 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := TM1.stmt Γ Λ σ local notation `cfg₁` := TM1.cfg Γ Λ σ local notation `stmt₀` := TM0.stmt Γ parameters (M : Λ → stmt₁) include M /-- The base machine state space is a pair of an `option stmt₁` representing the current program to be executed, or `none` for the halt state, and a `σ` which is the local state (stored in the TM, not the tape). Because there are an infinite number of programs, this state space is infinite, but for a finitely supported TM1 machine and a finite type `σ`, only finitely many of these states are reachable. -/ @[nolint unused_arguments] -- [inhabited Λ] [inhabited σ] (M : Λ → stmt₁): We need the M assumption -- because of the inhabited instance, but we could avoid the inhabited instances on Λ and σ here. -- But they are parameters so we cannot easily skip them for just this definition. def Λ' := option stmt₁ × σ instance : inhabited Λ' := ⟨(some (M (default _)), default _)⟩ open TM0.stmt /-- The core TM1 → TM0 translation function. Here `s` is the current value on the tape, and the `stmt₁` is the TM1 statement to translate, with local state `v : σ`. We evaluate all regular instructions recursively until we reach either a `move` or `write` command, or a `goto`; in the latter case we emit a dummy `write s` step and transition to the new target location. -/ def tr_aux (s : Γ) : stmt₁ → σ → Λ' × stmt₀ | (TM1.stmt.move d q) v := ((some q, v), move d) | (TM1.stmt.write a q) v := ((some q, v), write (a s v)) | (TM1.stmt.load a q) v := tr_aux q (a s v) | (TM1.stmt.branch p q₁ q₂) v := cond (p s v) (tr_aux q₁ v) (tr_aux q₂ v) | (TM1.stmt.goto l) v := ((some (M (l s v)), v), write s) | TM1.stmt.halt v := ((none, v), write s) local notation `cfg₀` := TM0.cfg Γ Λ' /-- The translated TM0 machine (given the TM1 machine input). -/ def tr : TM0.machine Γ Λ' | (none, v) s := none | (some q, v) s := some (tr_aux s q v) /-- Translate configurations from TM1 to TM0. -/ def tr_cfg : cfg₁ → cfg₀ | ⟨l, v, T⟩ := ⟨(l.map M, v), T⟩ theorem tr_respects : respects (TM1.step M) (TM0.step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin cases l₁ with l₁, {exact rfl}, unfold tr_cfg TM1.step frespects option.map function.comp option.bind, induction M l₁ with _ q IH _ q IH _ q IH generalizing v T, case TM1.stmt.move : d q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.write : a q IH { exact trans_gen.head rfl (IH _ _) }, case TM1.stmt.load : a q IH { exact (reaches₁_eq (by refl)).2 (IH _ _) }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold TM1.step_aux, cases e : p T.1 v, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₂ _ _) }, { exact (reaches₁_eq (by simp only [TM0.step, tr, tr_aux, e]; refl)).2 (IH₁ _ _) } }, iterate 2 { exact trans_gen.single (congr_arg some (congr (congr_arg TM0.cfg.mk rfl) (tape.write_self T))) } end theorem tr_eval (l : list Γ) : TM0.eval tr l = TM1.eval M l := (congr_arg _ (tr_eval' _ _ _ tr_respects ⟨some _, _, _⟩)).trans begin rw [roption.map_eq_map, roption.map_map, TM1.eval], congr' with ⟨⟩, refl end variables [fintype σ] /-- Given a finite set of accessible `Λ` machine states, there is a finite set of accessible machine states in the target (even though the type `Λ'` is infinite). -/ noncomputable def tr_stmts (S : finset Λ) : finset Λ' := (TM1.stmts M S).product finset.univ open_locale classical local attribute [simp] TM1.stmts₁_self theorem tr_supports {S : finset Λ} (ss : TM1.supports M S) : TM0.supports tr (↑(tr_stmts S)) := ⟨finset.mem_product.2 ⟨finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, ss.1, TM1.stmts₁_self⟩), finset.mem_univ _⟩, λ q a q' s h₁ h₂, begin rcases q with ⟨_|q, v⟩, {cases h₁}, cases q' with q' v', simp only [tr_stmts, finset.mem_coe, finset.mem_product, finset.mem_univ, and_true] at h₂ ⊢, cases q', {exact multiset.mem_cons_self _ _}, simp only [tr, option.mem_def] at h₁, have := TM1.stmts_supports_stmt ss h₂, revert this, induction q generalizing v; intro hs, case TM1.stmt.move : d q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.write : b q { cases h₁, refine TM1.stmts_trans _ h₂, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.load : b q IH { refine IH (TM1.stmts_trans _ h₂) _ h₁ hs, unfold TM1.stmts₁, exact finset.mem_insert_of_mem TM1.stmts₁_self }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { change cond (p a v) _ _ = ((some q', v'), s) at h₁, cases p a v, { refine IH₂ (TM1.stmts_trans _ h₂) _ h₁ hs.2, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_right _ TM1.stmts₁_self) }, { refine IH₁ (TM1.stmts_trans _ h₂) _ h₁ hs.1, unfold TM1.stmts₁, exact finset.mem_insert_of_mem (finset.mem_union_left _ TM1.stmts₁_self) } }, case TM1.stmt.goto : l { cases h₁, exact finset.some_mem_insert_none.2 (finset.mem_bUnion.2 ⟨_, hs _ _, TM1.stmts₁_self⟩) }, case TM1.stmt.halt { cases h₁ } end⟩ end end TM1to0 /-! ## TM1(Γ) emulator in TM1(bool) The most parsimonious Turing machine model that is still Turing complete is `TM0` with `Γ = bool`. Because our construction in the previous section reducing `TM1` to `TM0` doesn't change the alphabet, we can do the alphabet reduction on `TM1` instead of `TM0` directly. The basic idea is to use a bijection between `Γ` and a subset of `vector bool n`, where `n` is a fixed constant. Each tape element is represented as a block of `n` bools. Whenever the machine wants to read a symbol from the tape, it traverses over the block, performing `n` `branch` instructions to each any of the `2^n` results. For the `write` instruction, we have to use a `goto` because we need to follow a different code path depending on the local state, which is not available in the TM1 model, so instead we jump to a label computed using the read value and the local state, which performs the writing and returns to normal execution. Emulation overhead is `O(1)`. If not for the above `write` behavior it would be 1-1 because we are exploiting the 0-step behavior of regular commands to avoid taking steps, but there are nevertheless a bounded number of `write` calls between `goto` statements because TM1 statements are finitely long. -/ namespace TM1to1 open TM1 section parameters {Γ : Type*} [inhabited Γ] theorem exists_enc_dec [fintype Γ] : ∃ n (enc : Γ → vector bool n) (dec : vector bool n → Γ), enc (default _) = vector.repeat ff n ∧ ∀ a, dec (enc a) = a := begin rcases fintype.exists_equiv_fin Γ with ⟨n, ⟨F⟩⟩, let G : fin n ↪ fin n → bool := ⟨λ a b, a = b, λ a b h, of_to_bool_true $ (congr_fun h b).trans $ to_bool_tt rfl⟩, let H := (F.to_embedding.trans G).trans (equiv.vector_equiv_fin _ _).symm.to_embedding, classical, let enc := H.set_value (default _) (vector.repeat ff n), exact ⟨_, enc, function.inv_fun enc, H.set_value_eq _ _, function.left_inverse_inv_fun enc.2⟩ end parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₁` := stmt Γ Λ σ local notation `cfg₁` := cfg Γ Λ σ /-- The configuration state of the TM. -/ inductive Λ' : Type (max u_1 u_2 u_3) | normal : Λ → Λ' | write : Γ → stmt₁ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `stmt'` := stmt bool Λ' σ local notation `cfg'` := cfg bool Λ' σ /-- Read a vector of length `n` from the tape. -/ def read_aux : ∀ n, (vector bool n → stmt') → stmt' | 0 f := f vector.nil | (i+1) f := stmt.branch (λ a s, a) (stmt.move dir.right $ read_aux i (λ v, f (tt ::ᵥ v))) (stmt.move dir.right $ read_aux i (λ v, f (ff ::ᵥ v))) parameters {n : ℕ} (enc : Γ → vector bool n) (dec : vector bool n → Γ) /-- A move left or right corresponds to `n` moves across the super-cell. -/ def move (d : dir) (q : stmt') : stmt' := (stmt.move d)^[n] q /-- To read a symbol from the tape, we use `read_aux` to traverse the symbol, then return to the original position with `n` moves to the left. -/ def read (f : Γ → stmt') : stmt' := read_aux n (λ v, move dir.left $ f (dec v)) /-- Write a list of bools on the tape. -/ def write : list bool → stmt' → stmt' | [] q := q | (a :: l) q := stmt.write (λ _ _, a) $ stmt.move dir.right $ write l q /-- Translate a normal instruction. For the `write` command, we use a `goto` indirection so that we can access the current value of the tape. -/ def tr_normal : stmt₁ → stmt' | (stmt.move d q) := move d $ tr_normal q | (stmt.write f q) := read $ λ a, stmt.goto $ λ _ s, Λ'.write (f a s) q | (stmt.load f q) := read $ λ a, stmt.load (λ _ s, f a s) $ tr_normal q | (stmt.branch p q₁ q₂) := read $ λ a, stmt.branch (λ _ s, p a s) (tr_normal q₁) (tr_normal q₂) | (stmt.goto l) := read $ λ a, stmt.goto $ λ _ s, Λ'.normal (l a s) | stmt.halt := stmt.halt theorem step_aux_move (d q v T) : step_aux (move d q) v T = step_aux q v ((tape.move d)^[n] T) := begin suffices : ∀ i, step_aux (stmt.move d^[i] q) v T = step_aux q v (tape.move d^[i] T), from this n, intro, induction i with i IH generalizing T, {refl}, rw [iterate_succ', step_aux, IH, iterate_succ] end theorem supports_stmt_move {S d q} : supports_stmt S (move d q) = supports_stmt S q := suffices ∀ {i}, supports_stmt S (stmt.move d^[i] q) = _, from this, by intro; induction i generalizing q; simp only [*, iterate]; refl theorem supports_stmt_write {S l q} : supports_stmt S (write l q) = supports_stmt S q := by induction l with a l IH; simp only [write, supports_stmt, *] theorem supports_stmt_read {S} : ∀ {f : Γ → stmt'}, (∀ a, supports_stmt S (f a)) → supports_stmt S (read f) := suffices ∀ i (f : vector bool i → stmt'), (∀ v, supports_stmt S (f v)) → supports_stmt S (read_aux i f), from λ f hf, this n _ (by intro; simp only [supports_stmt_move, hf]), λ i f hf, begin induction i with i IH, {exact hf _}, split; apply IH; intro; apply hf, end parameter (enc0 : enc (default _) = vector.repeat ff n) section parameter {enc} include enc0 /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape' (L R : list_blank Γ) : tape bool := begin refine tape.mk' (L.bind (λ x, (enc x).to_list.reverse) ⟨n, _⟩) (R.bind (λ x, (enc x).to_list) ⟨n, _⟩); simp only [enc0, vector.repeat, list.reverse_repeat, bool.default_bool, vector.to_list_mk] end /-- The low level tape corresponding to the given tape over alphabet `Γ`. -/ def tr_tape (T : tape Γ) : tape bool := tr_tape' T.left T.right₀ theorem tr_tape_mk' (L R : list_blank Γ) : tr_tape (tape.mk' L R) = tr_tape' L R := by simp only [tr_tape, tape.mk'_left, tape.mk'_right₀] end parameters (M : Λ → stmt₁) /-- The top level program. -/ def tr : Λ' → stmt' | (Λ'.normal l) := tr_normal (M l) | (Λ'.write a q) := write (enc a).to_list $ move dir.left $ tr_normal q /-- The machine configuration translation. -/ def tr_cfg : cfg₁ → cfg' | ⟨l, v, T⟩ := ⟨l.map Λ'.normal, v, tr_tape T⟩ parameter {enc} include enc0 theorem tr_tape'_move_left (L R) : (tape.move dir.left)^[n] (tr_tape' L R) = (tr_tape' L.tail (R.cons L.head)) := begin obtain ⟨a, L, rfl⟩ := L.exists_cons, simp only [tr_tape', list_blank.cons_bind, list_blank.head_cons, list_blank.tail_cons], suffices : ∀ {L' R' l₁ l₂} (e : vector.to_list (enc a) = list.reverse_core l₁ l₂), tape.move dir.left^[l₁.length] (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = tape.mk' L' (list_blank.append (vector.to_list (enc a)) R'), { simpa only [list.length_reverse, vector.to_list_length] using this (list.reverse_reverse _).symm }, intros, induction l₁ with b l₁ IH generalizing l₂, { cases e, refl }, simp only [list.length, list.cons_append, iterate_succ_apply], convert IH e, simp only [list_blank.tail_cons, list_blank.append, tape.move_left_mk', list_blank.head_cons] end theorem tr_tape'_move_right (L R) : (tape.move dir.right)^[n] (tr_tape' L R) = (tr_tape' (L.cons R.head) R.tail) := begin suffices : ∀ i L, (tape.move dir.right)^[i] ((tape.move dir.left)^[i] L) = L, { refine (eq.symm _).trans (this n _), simp only [tr_tape'_move_left, list_blank.cons_head_tail, list_blank.head_cons, list_blank.tail_cons] }, intros, induction i with i IH, {refl}, rw [iterate_succ_apply, iterate_succ_apply', tape.move_left_right, IH] end theorem step_aux_write (q v a b L R) : step_aux (write (enc a).to_list q) v (tr_tape' L (list_blank.cons b R)) = step_aux q v (tr_tape' (list_blank.cons a L) R) := begin simp only [tr_tape', list.cons_bind, list.append_assoc], suffices : ∀ {L' R'} (l₁ l₂ l₂' : list bool) (e : l₂'.length = l₂.length), step_aux (write l₂ q) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂' R')) = step_aux q v (tape.mk' (L'.append (list.reverse_core l₂ l₁)) R'), { convert this [] _ _ ((enc b).2.trans (enc a).2.symm); rw list_blank.cons_bind; refl }, clear a b L R, intros, induction l₂ with a l₂ IH generalizing l₁ l₂', { cases list.length_eq_zero.1 e, refl }, cases l₂' with b l₂'; injection e with e, dunfold write step_aux, convert IH _ _ e, simp only [list_blank.head_cons, list_blank.tail_cons, list_blank.append, tape.move_right_mk', tape.write_mk'] end parameters (encdec : ∀ a, dec (enc a) = a) include encdec theorem step_aux_read (f v L R) : step_aux (read f) v (tr_tape' L R) = step_aux (f R.head) v (tr_tape' L R) := begin suffices : ∀ f, step_aux (read_aux n f) v (tr_tape' enc0 L R) = step_aux (f (enc R.head)) v (tr_tape' enc0 (L.cons R.head) R.tail), { rw [read, this, step_aux_move, encdec, tr_tape'_move_left enc0], simp only [list_blank.head_cons, list_blank.cons_head_tail, list_blank.tail_cons] }, obtain ⟨a, R, rfl⟩ := R.exists_cons, simp only [list_blank.head_cons, list_blank.tail_cons, tr_tape', list_blank.cons_bind, list_blank.append_assoc], suffices : ∀ i f L' R' l₁ l₂ h, step_aux (read_aux i f) v (tape.mk' (list_blank.append l₁ L') (list_blank.append l₂ R')) = step_aux (f ⟨l₂, h⟩) v (tape.mk' (list_blank.append (l₂.reverse_core l₁) L') R'), { intro f, convert this n f _ _ _ _ (enc a).2; simp }, clear f L a R, intros, subst i, induction l₂ with a l₂ IH generalizing l₁, {refl}, transitivity step_aux (read_aux l₂.length (λ v, f (a ::ᵥ v))) v (tape.mk' ((L'.append l₁).cons a) (R'.append l₂)), { dsimp [read_aux, step_aux], simp, cases a; refl }, rw [← list_blank.append, IH], refl end theorem tr_respects : respects (step M) (step tr) (λ c₁ c₂, tr_cfg c₁ = c₂) := fun_respects.2 $ λ ⟨l₁, v, T⟩, begin obtain ⟨L, R, rfl⟩ := T.exists_mk', cases l₁ with l₁, {exact rfl}, suffices : ∀ q R, reaches (step (tr enc dec M)) (step_aux (tr_normal dec q) v (tr_tape' enc0 L R)) (tr_cfg enc0 (step_aux q v (tape.mk' L R))), { refine trans_gen.head' rfl _, rw tr_tape_mk', exact this _ R }, clear R l₁, intros, induction q with _ q IH _ q IH _ q IH generalizing v L R, case TM1.stmt.move : d q IH { cases d; simp only [tr_normal, iterate, step_aux_move, step_aux, list_blank.head_cons, tape.move_left_mk', list_blank.cons_head_tail, list_blank.tail_cons, tr_tape'_move_left enc0, tr_tape'_move_right enc0]; apply IH }, case TM1.stmt.write : f q IH { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], refine refl_trans_gen.head rfl _, obtain ⟨a, R, rfl⟩ := R.exists_cons, rw [tr, tape.mk'_head, step_aux_write, list_blank.head_cons, step_aux_move, tr_tape'_move_left enc0, list_blank.head_cons, list_blank.tail_cons, tape.write_mk'], apply IH }, case TM1.stmt.load : a q IH { simp only [tr_normal, step_aux_read dec enc0 encdec], apply IH }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux], cases p R.head v; [apply IH₂, apply IH₁] }, case TM1.stmt.goto : l { simp only [tr_normal, step_aux_read dec enc0 encdec, step_aux, tr_cfg, tr_tape_mk'], apply refl_trans_gen.refl }, case TM1.stmt.halt { simp only [tr_normal, step_aux, tr_cfg, step_aux_move, tr_tape'_move_left enc0, tr_tape'_move_right enc0, tr_tape_mk'], apply refl_trans_gen.refl } end omit enc0 encdec open_locale classical parameters [fintype Γ] /-- The set of accessible `Λ'.write` machine states. -/ noncomputable def writes : stmt₁ → finset Λ' | (stmt.move d q) := writes q | (stmt.write f q) := finset.univ.image (λ a, Λ'.write a q) ∪ writes q | (stmt.load f q) := writes q | (stmt.branch p q₁ q₂) := writes q₁ ∪ writes q₂ | (stmt.goto l) := ∅ | stmt.halt := ∅ /-- The set of accessible machine states, assuming that the input machine is supported on `S`, are the normal states embedded from `S`, plus all write states accessible from these states. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (Λ'.normal l) (writes (M l))) theorem tr_supports {S} (ss : supports M S) : supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert_self _ _⟩, λ q h, begin suffices : ∀ q, supports_stmt S q → (∀ q' ∈ writes q, q' ∈ tr_supp M S) → supports_stmt (tr_supp M S) (tr_normal dec q) ∧ ∀ q' ∈ writes q, supports_stmt (tr_supp M S) (tr enc dec M q'), { rcases finset.mem_bUnion.1 h with ⟨l, hl, h⟩, have := this _ (ss.2 _ hl) (λ q' hq, finset.mem_bUnion.2 ⟨_, hl, finset.mem_insert_of_mem hq⟩), rcases finset.mem_insert.1 h with rfl | h, exacts [this.1, this.2 _ h] }, intros q hs hw, induction q, case TM1.stmt.move : d q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨_, IH.2⟩, cases d; simp only [tr_normal, iterate, supports_stmt_move, IH] }, case TM1.stmt.write : f q IH { unfold writes at hw ⊢, simp only [finset.mem_image, finset.mem_union, finset.mem_univ, exists_prop, true_and] at hw ⊢, replace IH := IH hs (λ q hq, hw q (or.inr hq)), refine ⟨supports_stmt_read _ $ λ a _ s, hw _ (or.inl ⟨_, rfl⟩), λ q' hq, _⟩, rcases hq with ⟨a, q₂, rfl⟩ | hq, { simp only [tr, supports_stmt_write, supports_stmt_move, IH.1] }, { exact IH.2 _ hq } }, case TM1.stmt.load : a q IH { unfold writes at hw ⊢, replace IH := IH hs hw, refine ⟨supports_stmt_read _ (λ a, IH.1), IH.2⟩ }, case TM1.stmt.branch : p q₁ q₂ IH₁ IH₂ { unfold writes at hw ⊢, simp only [finset.mem_union] at hw ⊢, replace IH₁ := IH₁ hs.1 (λ q hq, hw q (or.inl hq)), replace IH₂ := IH₂ hs.2 (λ q hq, hw q (or.inr hq)), exact ⟨supports_stmt_read _ (λ a, ⟨IH₁.1, IH₂.1⟩), λ q, or.rec (IH₁.2 _) (IH₂.2 _)⟩ }, case TM1.stmt.goto : l { refine ⟨_, λ _, false.elim⟩, refine supports_stmt_read _ (λ a _ s, _), exact finset.mem_bUnion.2 ⟨_, hs _ _, finset.mem_insert_self _ _⟩ }, case TM1.stmt.halt { refine ⟨_, λ _, false.elim⟩, simp only [supports_stmt, supports_stmt_move, tr_normal] } end⟩ end end TM1to1 /-! ## TM0 emulator in TM1 To establish that TM0 and TM1 are equivalent computational models, we must also have a TM0 emulator in TM1. The main complication here is that TM0 allows an action to depend on the value at the head and local state, while TM1 doesn't (in order to have more programming language-like semantics). So we use a computed `goto` to go to a state that performes the desired action and then returns to normal execution. One issue with this is that the `halt` instruction is supposed to halt immediately, not take a step to a halting state. To resolve this we do a check for `halt` first, then `goto` (with an unreachable branch). -/ namespace TM0to1 section parameters {Γ : Type*} [inhabited Γ] parameters {Λ : Type*} [inhabited Λ] /-- The machine states for a TM1 emulating a TM0 machine. States of the TM0 machine are embedded as `normal q` states, but the actual operation is split into two parts, a jump to `act s q` followed by the action and a jump to the next `normal` state. -/ inductive Λ' | normal : Λ → Λ' | act : TM0.stmt Γ → Λ → Λ' instance : inhabited Λ' := ⟨Λ'.normal (default _)⟩ local notation `cfg₀` := TM0.cfg Γ Λ local notation `stmt₁` := TM1.stmt Γ Λ' unit local notation `cfg₁` := TM1.cfg Γ Λ' unit parameters (M : TM0.machine Γ Λ) open TM1.stmt /-- The program. -/ def tr : Λ' → stmt₁ | (Λ'.normal q) := branch (λ a _, (M q a).is_none) halt $ goto (λ a _, match M q a with | none := default _ -- unreachable | some (q', s) := Λ'.act s q' end) | (Λ'.act (TM0.stmt.move d) q) := move d $ goto (λ _ _, Λ'.normal q) | (Λ'.act (TM0.stmt.write a) q) := write (λ _ _, a) $ goto (λ _ _, Λ'.normal q) /-- The configuration translation. -/ def tr_cfg : cfg₀ → cfg₁ | ⟨q, T⟩ := ⟨cond (M q T.1).is_some (some (Λ'.normal q)) none, (), T⟩ theorem tr_respects : respects (TM0.step M) (TM1.step tr) (λ a b, tr_cfg a = b) := fun_respects.2 $ λ ⟨q, T⟩, begin cases e : M q T.1, { simp only [TM0.step, tr_cfg, e]; exact eq.refl none }, cases val with q' s, simp only [frespects, TM0.step, tr_cfg, e, option.is_some, cond, option.map_some'], have : TM1.step (tr M) ⟨some (Λ'.act s q'), (), T⟩ = some ⟨some (Λ'.normal q'), (), TM0.step._match_1 T s⟩, { cases s with d a; refl }, refine trans_gen.head _ (trans_gen.head' this _), { unfold TM1.step TM1.step_aux tr has_mem.mem, rw e, refl }, cases e' : M q' _, { apply refl_trans_gen.single, unfold TM1.step TM1.step_aux tr has_mem.mem, rw e', refl }, { refl } end end end TM0to1 /-! ## The TM2 model The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks, each with elements of different types (the alphabet of stack `k : K` is `Γ k`). The statements are: * `push k (f : σ → Γ k) q` puts `f a` on the `k`-th stack, then does `q`. * `pop k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, and removes this element from the stack, then does `q`. * `peek k (f : σ → option (Γ k) → σ) q` changes the state to `f a (S k).head`, where `S k` is the value of the `k`-th stack, then does `q`. * `load (f : σ → σ) q` reads nothing but applies `f` to the internal state, then does `q`. * `branch (f : σ → bool) qtrue qfalse` does `qtrue` or `qfalse` according to `f a`. * `goto (f : σ → Λ)` jumps to label `f a`. * `halt` halts on the next step. The configuration is a tuple `(l, var, stk)` where `l : option Λ` is the current label to run or `none` for the halting state, `var : σ` is the (finite) internal state, and `stk : ∀ k, list (Γ k)` is the collection of stacks. (Note that unlike the `TM0` and `TM1` models, these are not `list_blank`s, they have definite ends that can be detected by the `pop` command.) Given a designated stack `k` and a value `L : list (Γ k)`, the initial configuration has all the stacks empty except the designated "input" stack; in `eval` this designated stack also functions as the output stack. -/ namespace TM2 section parameters {K : Type*} [decidable_eq K] -- Index type of stacks parameters (Γ : K → Type*) -- Type of stack elements parameters (Λ : Type*) -- Type of function labels parameters (σ : Type*) -- Type of variable settings /-- The TM2 model removes the tape entirely from the TM1 model, replacing it with an arbitrary (finite) collection of stacks. The operation `push` puts an element on one of the stacks, and `pop` removes an element from a stack (and modifying the internal state based on the result). `peek` modifies the internal state but does not remove an element. -/ inductive stmt | push : ∀ k, (σ → Γ k) → stmt → stmt | peek : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | pop : ∀ k, (σ → option (Γ k) → σ) → stmt → stmt | load : (σ → σ) → stmt → stmt | branch : (σ → bool) → stmt → stmt → stmt | goto : (σ → Λ) → stmt | halt : stmt open stmt instance stmt.inhabited : inhabited stmt := ⟨halt⟩ /-- A configuration in the TM2 model is a label (or `none` for the halt state), the state of local variables, and the stacks. (Note that the stacks are not `list_blank`s, they have a definite size.) -/ structure cfg := (l : option Λ) (var : σ) (stk : ∀ k, list (Γ k)) instance cfg.inhabited [inhabited σ] : inhabited cfg := ⟨⟨default _, default _, default _⟩⟩ parameters {Γ Λ σ K} /-- The step function for the TM2 model. -/ @[simp] def step_aux : stmt → σ → (∀ k, list (Γ k)) → cfg | (push k f q) v S := step_aux q v (update S k (f v :: S k)) | (peek k f q) v S := step_aux q (f v (S k).head') S | (pop k f q) v S := step_aux q (f v (S k).head') (update S k (S k).tail) | (load a q) v S := step_aux q (a v) S | (branch f q₁ q₂) v S := cond (f v) (step_aux q₁ v S) (step_aux q₂ v S) | (goto f) v S := ⟨some (f v), v, S⟩ | halt v S := ⟨none, v, S⟩ /-- The step function for the TM2 model. -/ @[simp] def step (M : Λ → stmt) : cfg → option cfg | ⟨none, v, S⟩ := none | ⟨some l, v, S⟩ := some (step_aux (M l) v S) /-- The (reflexive) reachability relation for the TM2 model. -/ def reaches (M : Λ → stmt) : cfg → cfg → Prop := refl_trans_gen (λ a b, b ∈ step M a) /-- Given a set `S` of states, `support_stmt S q` means that `q` only jumps to states in `S`. -/ def supports_stmt (S : finset Λ) : stmt → Prop | (push k f q) := supports_stmt q | (peek k f q) := supports_stmt q | (pop k f q) := supports_stmt q | (load a q) := supports_stmt q | (branch f q₁ q₂) := supports_stmt q₁ ∧ supports_stmt q₂ | (goto l) := ∀ v, l v ∈ S | halt := true open_locale classical /-- The set of subtree statements in a statement. -/ noncomputable def stmts₁ : stmt → finset stmt | Q@(push k f q) := insert Q (stmts₁ q) | Q@(peek k f q) := insert Q (stmts₁ q) | Q@(pop k f q) := insert Q (stmts₁ q) | Q@(load a q) := insert Q (stmts₁ q) | Q@(branch f q₁ q₂) := insert Q (stmts₁ q₁ ∪ stmts₁ q₂) | Q@(goto l) := {Q} | Q@halt := {Q} theorem stmts₁_self {q} : q ∈ stmts₁ q := by cases q; apply_rules [finset.mem_insert_self, finset.mem_singleton_self] theorem stmts₁_trans {q₁ q₂} : q₁ ∈ stmts₁ q₂ → stmts₁ q₁ ⊆ stmts₁ q₂ := begin intros h₁₂ q₀ h₀₁, induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁] at h₁₂ ⊢; simp only [finset.mem_insert, finset.mem_singleton, finset.mem_union] at h₁₂, iterate 4 { rcases h₁₂ with rfl | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (IH h₁₂) } }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h₁₂ with rfl | h₁₂ | h₁₂, { unfold stmts₁ at h₀₁, exact h₀₁ }, { exact finset.mem_insert_of_mem (finset.mem_union_left _ (IH₁ h₁₂)) }, { exact finset.mem_insert_of_mem (finset.mem_union_right _ (IH₂ h₁₂)) } }, case TM2.stmt.goto : l { subst h₁₂, exact h₀₁ }, case TM2.stmt.halt { subst h₁₂, exact h₀₁ } end theorem stmts₁_supports_stmt_mono {S q₁ q₂} (h : q₁ ∈ stmts₁ q₂) (hs : supports_stmt S q₂) : supports_stmt S q₁ := begin induction q₂ with _ _ q IH _ _ q IH _ _ q IH _ q IH; simp only [stmts₁, supports_stmt, finset.mem_insert, finset.mem_union, finset.mem_singleton] at h hs, iterate 4 { rcases h with rfl | h; [exact hs, exact IH h hs] }, case TM2.stmt.branch : f q₁ q₂ IH₁ IH₂ { rcases h with rfl | h | h, exacts [hs, IH₁ h hs.1, IH₂ h hs.2] }, case TM2.stmt.goto : l { subst h, exact hs }, case TM2.stmt.halt { subst h, trivial } end /-- The set of statements accessible from initial set `S` of labels. -/ noncomputable def stmts (M : Λ → stmt) (S : finset Λ) : finset (option stmt) := (S.bUnion (λ q, stmts₁ (M q))).insert_none theorem stmts_trans {M : Λ → stmt} {S q₁ q₂} (h₁ : q₁ ∈ stmts₁ q₂) : some q₂ ∈ stmts M S → some q₁ ∈ stmts M S := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h₂, ⟨_, ls, stmts₁_trans h₂ h₁⟩ variable [inhabited Λ] /-- Given a TM2 machine `M` and a set `S` of states, `supports M S` means that all states in `S` jump only to other states in `S`. -/ def supports (M : Λ → stmt) (S : finset Λ) := default Λ ∈ S ∧ ∀ q ∈ S, supports_stmt S (M q) theorem stmts_supports_stmt {M : Λ → stmt} {S q} (ss : supports M S) : some q ∈ stmts M S → supports_stmt S q := by simp only [stmts, finset.mem_insert_none, finset.mem_bUnion, option.mem_def, forall_eq', exists_imp_distrib]; exact λ l ls h, stmts₁_supports_stmt_mono h (ss.2 _ ls) theorem step_supports (M : Λ → stmt) {S} (ss : supports M S) : ∀ {c c' : cfg}, c' ∈ step M c → c.l ∈ S.insert_none → c'.l ∈ S.insert_none | ⟨some l₁, v, T⟩ c' h₁ h₂ := begin replace h₂ := ss.2 _ (finset.some_mem_insert_none.1 h₂), simp only [step, option.mem_def] at h₁, subst c', revert h₂, induction M l₁ with _ _ q IH _ _ q IH _ _ q IH _ q IH generalizing v T; intro hs, iterate 4 { exact IH _ _ hs }, case TM2.stmt.branch : p q₁' q₂' IH₁ IH₂ { unfold step_aux, cases p v, { exact IH₂ _ _ hs.2 }, { exact IH₁ _ _ hs.1 } }, case TM2.stmt.goto { exact finset.some_mem_insert_none.2 (hs _) }, case TM2.stmt.halt { apply multiset.mem_cons_self } end variable [inhabited σ] /-- The initial state of the TM2 model. The input is provided on a designated stack. -/ def init (k) (L : list (Γ k)) : cfg := ⟨some (default _), default _, update (λ _, []) k L⟩ /-- Evaluates a TM2 program to completion, with the output on the same stack as the input. -/ def eval (M : Λ → stmt) (k) (L : list (Γ k)) : roption (list (Γ k)) := (eval (step M) (init k L)).map $ λ c, c.stk k end end TM2 /-! ## TM2 emulator in TM1 To prove that TM2 computable functions are TM1 computable, we need to reduce each TM2 program to a TM1 program. So suppose a TM2 program is given. This program has to maintain a whole collection of stacks, but we have only one tape, so we must "multiplex" them all together. Pictorially, if stack 1 contains `[a, b]` and stack 2 contains `[c, d, e, f]` then the tape looks like this: ``` bottom: ... | _ | T | _ | _ | _ | _ | ... stack 1: ... | _ | b | a | _ | _ | _ | ... stack 2: ... | _ | f | e | d | c | _ | ... ``` where a tape element is a vertical slice through the diagram. Here the alphabet is `Γ' := bool × ∀ k, option (Γ k)`, where: * `bottom : bool` is marked only in one place, the initial position of the TM, and represents the tail of all stacks. It is never modified. * `stk k : option (Γ k)` is the value of the `k`-th stack, if in range, otherwise `none` (which is the blank value). Note that the head of the stack is at the far end; this is so that push and pop don't have to do any shifting. In "resting" position, the TM is sitting at the position marked `bottom`. For non-stack actions, it operates in place, but for the stack actions `push`, `peek`, and `pop`, it must shuttle to the end of the appropriate stack, make its changes, and then return to the bottom. So the states are: * `normal (l : Λ)`: waiting at `bottom` to execute function `l` * `go k (s : st_act k) (q : stmt₂)`: travelling to the right to get to the end of stack `k` in order to perform stack action `s`, and later continue with executing `q` * `ret (q : stmt₂)`: travelling to the left after having performed a stack action, and executing `q` once we arrive Because of the shuttling, emulation overhead is `O(n)`, where `n` is the current maximum of the length of all stacks. Therefore a program that takes `k` steps to run in TM2 takes `O((m+k)k)` steps to run when emulated in TM1, where `m` is the length of the input. -/ namespace TM2to1 -- A displaced lemma proved in unnecessary generality theorem stk_nth_val {K : Type*} {Γ : K → Type*} {L : list_blank (∀ k, option (Γ k))} {k S} (n) (hL : list_blank.map (proj k) L = list_blank.mk (list.map some S).reverse) : L.nth n k = S.reverse.nth n := begin rw [← proj_map_nth, hL, ← list.map_reverse, list_blank.nth_mk, list.inth, list.nth_map], cases S.reverse.nth n; refl end section parameters {K : Type*} [decidable_eq K] parameters {Γ : K → Type*} parameters {Λ : Type*} [inhabited Λ] parameters {σ : Type*} [inhabited σ] local notation `stmt₂` := TM2.stmt Γ Λ σ local notation `cfg₂` := TM2.cfg Γ Λ σ /-- The alphabet of the TM2 simulator on TM1 is a marker for the stack bottom, plus a vector of stack elements for each stack, or none if the stack does not extend this far. -/ @[nolint unused_arguments] -- [decidable_eq K]: Because K is a parameter, we cannot easily skip -- the decidable_eq assumption, and this is a local definition anyway so it's not important. def Γ' := bool × ∀ k, option (Γ k) instance Γ'.inhabited : inhabited Γ' := ⟨⟨ff, λ _, none⟩⟩ instance Γ'.fintype [fintype K] [∀ k, fintype (Γ k)] : fintype Γ' := prod.fintype _ _ /-- The bottom marker is fixed throughout the calculation, so we use the `add_bottom` function to express the program state in terms of a tape with only the stacks themselves. -/ def add_bottom (L : list_blank (∀ k, option (Γ k))) : list_blank Γ' := list_blank.cons (tt, L.head) (L.tail.map ⟨prod.mk ff, rfl⟩) theorem add_bottom_map (L) : (add_bottom L).map ⟨prod.snd, rfl⟩ = L := begin simp only [add_bottom, list_blank.map_cons]; convert list_blank.cons_head_tail _, generalize : list_blank.tail L = L', refine L'.induction_on _, intro l, simp, rw (_ : _ ∘ _ = id), {simp}, funext a, refl end theorem add_bottom_modify_nth (f : (∀ k, option (Γ k)) → (∀ k, option (Γ k))) (L n) : (add_bottom L).modify_nth (λ a, (a.1, f a.2)) n = add_bottom (L.modify_nth f n) := begin cases n; simp only [add_bottom, list_blank.head_cons, list_blank.modify_nth, list_blank.tail_cons], congr, symmetry, apply list_blank.map_modify_nth, intro, refl end theorem add_bottom_nth_snd (L n) : ((add_bottom L).nth n).2 = L.nth n := by conv {to_rhs, rw [← add_bottom_map L, list_blank.nth_map]}; refl theorem add_bottom_nth_succ_fst (L n) : ((add_bottom L).nth (n+1)).1 = ff := by rw [list_blank.nth_succ, add_bottom, list_blank.tail_cons, list_blank.nth_map]; refl theorem add_bottom_head_fst (L) : (add_bottom L).head.1 = tt := by rw [add_bottom, list_blank.head_cons]; refl /-- A stack action is a command that interacts with the top of a stack. Our default position is at the bottom of all the stacks, so we have to hold on to this action while going to the end to modify the stack. -/ inductive st_act (k : K) | push : (σ → Γ k) → st_act | peek : (σ → option (Γ k) → σ) → st_act | pop : (σ → option (Γ k) → σ) → st_act instance st_act.inhabited {k} : inhabited (st_act k) := ⟨st_act.peek (λ s _, s)⟩ section open st_act /-- The TM2 statement corresponding to a stack action. -/ @[nolint unused_arguments] -- [inhabited Λ]: as this is a local definition it is more trouble than -- it is worth to omit the typeclass assumption without breaking the parameters def st_run {k : K} : st_act k → stmt₂ → stmt₂ | (push f) := TM2.stmt.push k f | (peek f) := TM2.stmt.peek k f | (pop f) := TM2.stmt.pop k f /-- The effect of a stack action on the local variables, given the value of the stack. -/ def st_var {k : K} (v : σ) (l : list (Γ k)) : st_act k → σ | (push f) := v | (peek f) := f v l.head' | (pop f) := f v l.head' /-- The effect of a stack action on the stack. -/ def st_write {k : K} (v : σ) (l : list (Γ k)) : st_act k → list (Γ k) | (push f) := f v :: l | (peek f) := l | (pop f) := l.tail /-- We have partitioned the TM2 statements into "stack actions", which require going to the end of the stack, and all other actions, which do not. This is a modified recursor which lumps the stack actions into one. -/ @[elab_as_eliminator] def {l} stmt_st_rec {C : stmt₂ → Sort l} (H₁ : Π k (s : st_act k) q (IH : C q), C (st_run s q)) (H₂ : Π a q (IH : C q), C (TM2.stmt.load a q)) (H₃ : Π p q₁ q₂ (IH₁ : C q₁) (IH₂ : C q₂), C (TM2.stmt.branch p q₁ q₂)) (H₄ : Π l, C (TM2.stmt.goto l)) (H₅ : C TM2.stmt.halt) : ∀ n, C n | (TM2.stmt.push k f q) := H₁ _ (push f) _ (stmt_st_rec q) | (TM2.stmt.peek k f q) := H₁ _ (peek f) _ (stmt_st_rec q) | (TM2.stmt.pop k f q) := H₁ _ (pop f) _ (stmt_st_rec q) | (TM2.stmt.load a q) := H₂ _ _ (stmt_st_rec q) | (TM2.stmt.branch a q₁ q₂) := H₃ _ _ _ (stmt_st_rec q₁) (stmt_st_rec q₂) | (TM2.stmt.goto l) := H₄ _ | TM2.stmt.halt := H₅ theorem supports_run (S : finset Λ) {k} (s : st_act k) (q) : TM2.supports_stmt S (st_run s q) ↔ TM2.supports_stmt S q := by rcases s with _|_|_; refl end /-- The machine states of the TM2 emulator. We can either be in a normal state when waiting for the next TM2 action, or we can be in the "go" and "return" states to go to the top of the stack and return to the bottom, respectively. -/ inductive Λ' : Type (max u_1 u_2 u_3 u_4) | normal : Λ → Λ' | go (k) : st_act k → stmt₂ → Λ' | ret : stmt₂ → Λ' open Λ' instance Λ'.inhabited : inhabited Λ' := ⟨normal (default _)⟩ local notation `stmt₁` := TM1.stmt Γ' Λ' σ local notation `cfg₁` := TM1.cfg Γ' Λ' σ open TM1.stmt /-- The program corresponding to state transitions at the end of a stack. Here we start out just after the top of the stack, and should end just after the new top of the stack. -/ def tr_st_act {k} (q : stmt₁) : st_act k → stmt₁ | (st_act.push f) := write (λ a s, (a.1, update a.2 k $ some $ f s)) $ move dir.right q | (st_act.peek f) := move dir.left $ load (λ a s, f s (a.2 k)) $ move dir.right q | (st_act.pop f) := branch (λ a _, a.1) ( load (λ a s, f s none) q ) ( move dir.left $ load (λ a s, f s (a.2 k)) $ write (λ a s, (a.1, update a.2 k none)) q ) /-- The initial state for the TM2 emulator, given an initial TM2 state. All stacks start out empty except for the input stack, and the stack bottom mark is set at the head. -/ def tr_init (k) (L : list (Γ k)) : list Γ' := let L' : list Γ' := L.reverse.map (λ a, (ff, update (λ _, none) k a)) in (tt, L'.head.2) :: L'.tail theorem step_run {k : K} (q v S) : ∀ s : st_act k, TM2.step_aux (st_run s q) v S = TM2.step_aux q (st_var v (S k) s) (update S k (st_write v (S k) s)) | (st_act.push f) := rfl | (st_act.peek f) := by unfold st_write; rw function.update_eq_self; refl | (st_act.pop f) := rfl /-- The translation of TM2 statements to TM1 statements. regular actions have direct equivalents, but stack actions are deferred by going to the corresponding `go` state, so that we can find the appropriate stack top. -/ def tr_normal : stmt₂ → stmt₁ | (TM2.stmt.push k f q) := goto (λ _ _, go k (st_act.push f) q) | (TM2.stmt.peek k f q) := goto (λ _ _, go k (st_act.peek f) q) | (TM2.stmt.pop k f q) := goto (λ _ _, go k (st_act.pop f) q) | (TM2.stmt.load a q) := load (λ _, a) (tr_normal q) | (TM2.stmt.branch f q₁ q₂) := branch (λ a, f) (tr_normal q₁) (tr_normal q₂) | (TM2.stmt.goto l) := goto (λ a s, normal (l s)) | TM2.stmt.halt := halt theorem tr_normal_run {k} (s q) : tr_normal (st_run s q) = goto (λ _ _, go k s q) := by rcases s with _|_|_; refl open_locale classical /-- The set of machine states accessible from an initial TM2 statement. -/ noncomputable def tr_stmts₁ : stmt₂ → finset Λ' | Q@(TM2.stmt.push k f q) := {go k (st_act.push f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.peek k f q) := {go k (st_act.peek f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.pop k f q) := {go k (st_act.pop f) q, ret q} ∪ tr_stmts₁ q | Q@(TM2.stmt.load a q) := tr_stmts₁ q | Q@(TM2.stmt.branch f q₁ q₂) := tr_stmts₁ q₁ ∪ tr_stmts₁ q₂ | _ := ∅ theorem tr_stmts₁_run {k s q} : tr_stmts₁ (st_run s q) = {go k s q, ret q} ∪ tr_stmts₁ q := by rcases s with _|_|_; unfold tr_stmts₁ st_run theorem tr_respects_aux₂ {k q v} {S : Π k, list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : ∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) (o) : let v' := st_var v (S k) o, Sk' := st_write v (S k) o, S' := update S k Sk' in ∃ (L' : list_blank (∀ k, option (Γ k))), (∀ k, L'.map (proj k) = list_blank.mk ((S' k).map some).reverse) ∧ TM1.step_aux (tr_st_act q o) v ((tape.move dir.right)^[(S k).length] (tape.mk' ∅ (add_bottom L))) = TM1.step_aux q v' ((tape.move dir.right)^[(S' k).length] (tape.mk' ∅ (add_bottom L'))) := begin dsimp only, simp, cases o; simp only [st_write, st_var, tr_st_act, TM1.step_aux], case TM2to1.st_act.push : f { have := tape.write_move_right_n (λ a : Γ', (a.1, update a.2 k (some (f v)))), dsimp only at this, refine ⟨_, λ k', _, by rw [ tape.move_right_n_head, list.length, tape.mk'_nth_nat, this, add_bottom_modify_nth (λ a, update a k (some (f v))), nat.add_one, iterate_succ']⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [list.reverse_cons, function.update_same, list_blank.nth_mk, list.inth, list.map], { rw [list.nth_le_nth, list.nth_le_append_right]; simp only [h, list.nth_le_singleton, list.length_map, list.length_reverse, nat.succ_pos', list.length_append, lt_add_iff_pos_right, list.length] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth], cases decidable.lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } }, case TM2to1.st_act.peek : f { rw function.update_eq_self, use [L, hL], rw [tape.move_left_right], congr, cases e : S k, {refl}, rw [list.length_cons, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hL k), e, list.reverse_cons, ← list.length_reverse, list.nth_concat_length], refl }, case TM2to1.st_act.pop : f { cases e : S k, { simp only [tape.mk'_head, list_blank.head_cons, tape.move_left_mk', list.length, tape.write_mk', list.head', iterate_zero_apply, list.tail_nil], rw [← e, function.update_eq_self], exact ⟨L, hL, by rw [add_bottom_head_fst, cond]⟩ }, { refine ⟨_, λ k', _, by rw [ list.length_cons, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, cond, iterate_succ', tape.move_right_left, tape.move_right_n_head, tape.mk'_nth_nat, tape.write_move_right_n (λ a:Γ', (a.1, update a.2 k none)), add_bottom_modify_nth (λ a, update a k none), add_bottom_nth_snd, stk_nth_val _ (hL k), e, show (list.cons hd tl).reverse.nth tl.length = some hd, by rw [list.reverse_cons, ← list.length_reverse, list.nth_concat_length]; refl, list.head', list.tail]⟩, refine list_blank.ext (λ i, _), rw [list_blank.nth_map, list_blank.nth_modify_nth, proj, pointed_map.mk_val], by_cases h' : k' = k, { subst k', split_ifs; simp only [ function.update_same, list_blank.nth_mk, list.tail, list.inth], { rw [list.nth_len_le], {refl}, rw [h, list.length_reverse, list.length_map] }, rw [← proj_map_nth, hL, list_blank.nth_mk, list.inth, e, list.map, list.reverse_cons], cases decidable.lt_or_gt_of_ne h with h h, { rw list.nth_append, simpa only [list.length_map, list.length_reverse] using h }, { rw [list.nth_len_le, list.nth_len_le]; simp only [nat.add_one_le_iff, h, list.length, le_of_lt, list.length_reverse, list.length_append, list.length_map] } }, { split_ifs; rw [function.update_noteq h', ← proj_map_nth, hL], rw function.update_noteq h' } } }, end parameters (M : Λ → stmt₂) include M /-- The TM2 emulator machine states written as a TM1 program. This handles the `go` and `ret` states, which shuttle to and from a stack top. -/ def tr : Λ' → stmt₁ | (normal q) := tr_normal (M q) | (go k s q) := branch (λ a s, (a.2 k).is_none) (tr_st_act (goto (λ _ _, ret q)) s) (move dir.right $ goto (λ _ _, go k s q)) | (ret q) := branch (λ a s, a.1) (tr_normal q) (move dir.left $ goto (λ _ _, ret q)) local attribute [pp_using_anonymous_constructor] turing.TM1.cfg /-- The relation between TM2 configurations and TM1 configurations of the TM2 emulator. -/ inductive tr_cfg : cfg₂ → cfg₁ → Prop | mk {q v} {S : ∀ k, list (Γ k)} (L : list_blank (∀ k, option (Γ k))) : (∀ k, L.map (proj k) = list_blank.mk ((S k).map some).reverse) → tr_cfg ⟨q, v, S⟩ ⟨q.map normal, v, tape.mk' ∅ (add_bottom L)⟩ theorem tr_respects_aux₁ {k} (o q v) {S : list (Γ k)} {L : list_blank (∀ k, option (Γ k))} (hL : L.map (proj k) = list_blank.mk (S.map some).reverse) (n ≤ S.length) : reaches₀ (TM1.step tr) ⟨some (go k o q), v, (tape.mk' ∅ (add_bottom L))⟩ ⟨some (go k o q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, apply (IH (le_of_lt H)).tail, rw iterate_succ_apply', simp only [TM1.step, TM1.step_aux, tr, tape.mk'_nth_nat, tape.move_right_n_head, add_bottom_nth_snd, option.mem_def], rw [stk_nth_val _ hL, list.nth_le_nth], refl, rwa list.length_reverse end theorem tr_respects_aux₃ {q v} {L : list_blank (∀ k, option (Γ k))} (n) : reaches₀ (TM1.step tr) ⟨some (ret q), v, (tape.move dir.right)^[n] (tape.mk' ∅ (add_bottom L))⟩ ⟨some (ret q), v, (tape.mk' ∅ (add_bottom L))⟩ := begin induction n with n IH, {refl}, refine reaches₀.head _ IH, rw [option.mem_def, TM1.step, tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_succ_fst, TM1.step_aux, iterate_succ', tape.move_right_left], refl, end theorem tr_respects_aux {q v T k} {S : Π k, list (Γ k)} (hT : ∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) (o : st_act k) (IH : ∀ {v : σ} {S : Π (k : K), list (Γ k)} {T : list_blank (∀ k, option (Γ k))}, (∀ k, list_blank.map (proj k) T = list_blank.mk ((S k).map some).reverse) → (∃ b, tr_cfg (TM2.step_aux q v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal q) v (tape.mk' ∅ (add_bottom T))) b)) : ∃ b, tr_cfg (TM2.step_aux (st_run o q) v S) b ∧ reaches (TM1.step tr) (TM1.step_aux (tr_normal (st_run o q)) v (tape.mk' ∅ (add_bottom T))) b := begin simp only [tr_normal_run, step_run], have hgo := tr_respects_aux₁ M o q v (hT k) _ (le_refl _), obtain ⟨T', hT', hrun⟩ := tr_respects_aux₂ hT o, have hret := tr_respects_aux₃ M _, have := hgo.tail' rfl, rw [tr, TM1.step_aux, tape.move_right_n_head, tape.mk'_nth_nat, add_bottom_nth_snd, stk_nth_val _ (hT k), list.nth_len_le (le_of_eq (list.length_reverse _)), option.is_none, cond, hrun, TM1.step_aux] at this, obtain ⟨c, gc, rc⟩ := IH hT', refine ⟨c, gc, (this.to₀.trans hret c (trans_gen.head' rfl _)).to_refl⟩, rw [tr, TM1.step_aux, tape.mk'_head, add_bottom_head_fst], exact rc, end local attribute [simp] respects TM2.step TM2.step_aux tr_normal theorem tr_respects : respects (TM2.step M) (TM1.step tr) tr_cfg := λ c₁ c₂ h, begin cases h with l v S L hT, clear h, cases l, {constructor}, simp only [TM2.step, respects, option.map_some'], suffices : ∃ b, _ ∧ reaches (TM1.step (tr M)) _ _, from let ⟨b, c, r⟩ := this in ⟨b, c, trans_gen.head' rfl r⟩, rw [tr], revert v S L hT, refine stmt_st_rec _ _ _ _ _ (M l); intros, { exact tr_respects_aux M hT s @IH }, { exact IH _ hT }, { unfold TM2.step_aux tr_normal TM1.step_aux, cases p v; [exact IH₂ _ hT, exact IH₁ _ hT] }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ }, { exact ⟨_, ⟨_, hT⟩, refl_trans_gen.refl⟩ } end theorem tr_cfg_init (k) (L : list (Γ k)) : tr_cfg (TM2.init k L) (TM1.init (tr_init k L)) := begin rw (_ : TM1.init _ = _), { refine ⟨list_blank.mk (L.reverse.map $ λ a, update (default _) k (some a)), λ k', _⟩, refine list_blank.ext (λ i, _), rw [list_blank.map_mk, list_blank.nth_mk, list.inth, list.map_map, (∘), list.nth_map, proj, pointed_map.mk_val], by_cases k' = k, { subst k', simp only [function.update_same], rw [list_blank.nth_mk, list.inth, ← list.map_reverse, list.nth_map] }, { simp only [function.update_noteq h], rw [list_blank.nth_mk, list.inth, list.map, list.reverse_nil, list.nth], cases L.reverse.nth i; refl } }, { rw [tr_init, TM1.init], dsimp only, congr; cases L.reverse; try {refl}, simp only [list.map_map, list.tail_cons, list.map], refl } end theorem tr_eval_dom (k) (L : list (Γ k)) : (TM1.eval tr (tr_init k L)).dom ↔ (TM2.eval M k L).dom := tr_eval_dom tr_respects (tr_cfg_init _ _) theorem tr_eval (k) (L : list (Γ k)) {L₁ L₂} (H₁ : L₁ ∈ TM1.eval tr (tr_init k L)) (H₂ : L₂ ∈ TM2.eval M k L) : ∃ (S : ∀ k, list (Γ k)) (L' : list_blank (∀ k, option (Γ k))), add_bottom L' = L₁ ∧ (∀ k, L'.map (proj k) = list_blank.mk ((S k).map some).reverse) ∧ S k = L₂ := begin obtain ⟨c₁, h₁, rfl⟩ := (roption.mem_map_iff _).1 H₁, obtain ⟨c₂, h₂, rfl⟩ := (roption.mem_map_iff _).1 H₂, obtain ⟨_, ⟨q, v, S, L', hT⟩, h₃⟩ := tr_eval (tr_respects M) (tr_cfg_init M k L) h₂, cases roption.mem_unique h₁ h₃, exact ⟨S, L', by simp only [tape.mk'_right₀], hT, rfl⟩ end /-- The support of a set of TM2 states in the TM2 emulator. -/ noncomputable def tr_supp (S : finset Λ) : finset Λ' := S.bUnion (λ l, insert (normal l) (tr_stmts₁ (M l))) theorem tr_supports {S} (ss : TM2.supports M S) : TM1.supports tr (tr_supp S) := ⟨finset.mem_bUnion.2 ⟨_, ss.1, finset.mem_insert.2 $ or.inl rfl⟩, λ l' h, begin suffices : ∀ q (ss' : TM2.supports_stmt S q) (sub : ∀ x ∈ tr_stmts₁ q, x ∈ tr_supp M S), TM1.supports_stmt (tr_supp M S) (tr_normal q) ∧ (∀ l' ∈ tr_stmts₁ q, TM1.supports_stmt (tr_supp M S) (tr M l')), { rcases finset.mem_bUnion.1 h with ⟨l, lS, h⟩, have := this _ (ss.2 l lS) (λ x hx, finset.mem_bUnion.2 ⟨_, lS, finset.mem_insert_of_mem hx⟩), rcases finset.mem_insert.1 h with rfl | h; [exact this.1, exact this.2 _ h] }, clear h l', refine stmt_st_rec _ _ _ _ _; intros, { -- stack op rw TM2to1.supports_run at ss', simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at sub, have hgo := sub _ (or.inl $ or.inl rfl), have hret := sub _ (or.inl $ or.inr rfl), cases IH ss' (λ x hx, sub x $ or.inr hx) with IH₁ IH₂, refine ⟨by simp only [tr_normal_run, TM1.supports_stmt]; intros; exact hgo, λ l h, _⟩, rw [tr_stmts₁_run] at h, simp only [TM2to1.tr_stmts₁_run, finset.mem_union, finset.mem_insert, finset.mem_singleton] at h, rcases h with ⟨rfl | rfl⟩ | h, { unfold TM1.supports_stmt TM2to1.tr, rcases s with _|_|_, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨λ _ _, hret, λ _ _, hgo⟩ }, { exact ⟨⟨λ _ _, hret, λ _ _, hret⟩, λ _ _, hgo⟩ } }, { unfold TM1.supports_stmt TM2to1.tr, exact ⟨IH₁, λ _ _, hret⟩ }, { exact IH₂ _ h } }, { -- load unfold TM2to1.tr_stmts₁ at ss' sub ⊢, exact IH ss' sub }, { -- branch unfold TM2to1.tr_stmts₁ at sub, cases IH₁ ss'.1 (λ x hx, sub x $ finset.mem_union_left _ hx) with IH₁₁ IH₁₂, cases IH₂ ss'.2 (λ x hx, sub x $ finset.mem_union_right _ hx) with IH₂₁ IH₂₂, refine ⟨⟨IH₁₁, IH₂₁⟩, λ l h, _⟩, rw [tr_stmts₁] at h, rcases finset.mem_union.1 h with h | h; [exact IH₁₂ _ h, exact IH₂₂ _ h] }, { -- goto rw tr_stmts₁, unfold TM2to1.tr_normal TM1.supports_stmt, unfold TM2.supports_stmt at ss', exact ⟨λ _ v, finset.mem_bUnion.2 ⟨_, ss' v, finset.mem_insert_self _ _⟩, λ _, false.elim⟩ }, { exact ⟨trivial, λ _, false.elim⟩ } -- halt end⟩ end end TM2to1 end turing
b1e44f10cb236aa31ec1d073f18ca93687d2f9b0
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/exam_2/satisfiability/exam2_test.lean
a5dcabad9c48694dae88d959bfee6dd0d8e56e5c
[]
no_license
jngo13/Discrete-Mathematics
8671540ef2da7c75915d32332dd20c02f001474e
bf674a866e61f60e6e6d128df85fa73819091787
refs/heads/master
1,675,615,657,924
1,609,142,011,000
1,609,142,011,000
267,190,341
0
0
null
null
null
null
UTF-8
Lean
false
false
1,962
lean
import .exam2 --import .satisfiability #eval is_satisfiable true_intro #eval is_satisfiable false_elim #eval is_satisfiable true_imp #eval is_satisfiable true_intro #eval is_satisfiable false_elim #eval is_satisfiable and_intro #eval is_satisfiable and_elim_left #eval is_satisfiable and_elim_right #eval is_satisfiable or_intro_left #eval is_satisfiable or_intro_right #eval is_satisfiable or_elim #eval is_satisfiable iff_intro #eval is_satisfiable iff_intro' #eval is_satisfiable iff_elim_left #eval is_satisfiable iff_elim_right #eval is_satisfiable arrow_elim #eval is_satisfiable resolution #eval is_satisfiable unit_resolution #eval is_satisfiable syllogism #eval is_satisfiable modus_tollens #eval is_satisfiable neg_elim #eval is_satisfiable excluded_middle #eval is_satisfiable neg_intro #eval is_satisfiable affirm_consequence #eval is_satisfiable affirm_disjunct #eval is_satisfiable deny_antecedent #eval is_unsatisfiable true_intro #eval is_unsatisfiable false_elim #eval is_unsatisfiable true_imp #eval is_unsatisfiable true_intro #eval is_unsatisfiable false_elim #eval is_unsatisfiable and_intro #eval is_unsatisfiable and_elim_left #eval is_unsatisfiable and_elim_right #eval is_unsatisfiable or_intro_left #eval is_unsatisfiable or_intro_right #eval is_unsatisfiable or_elim #eval is_unsatisfiable iff_intro #eval is_unsatisfiable iff_intro' #eval is_unsatisfiable iff_elim_left #eval is_unsatisfiable iff_elim_right #eval is_unsatisfiable arrow_elim #eval is_unsatisfiable resolution #eval is_unsatisfiable unit_resolution #eval is_unsatisfiable syllogism #eval is_unsatisfiable modus_tollens #eval is_unsatisfiable neg_elim #eval is_unsatisfiable excluded_middle #eval is_unsatisfiable neg_intro #eval is_unsatisfiable affirm_consequence #eval is_unsatisfiable affirm_disjunct #eval is_unsatisfiable deny_antecedent #eval is_unsatisfiable (P ∧ ¬ P)
a943908a8d6aa470e57bdf762d7d4caac0e519f9
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebraic_geometry/pullbacks.lean
d3fbcd6d6fb5a84c950d03f25d5e9071157d8aa4
[ "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
27,450
lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import algebraic_geometry.gluing import category_theory.limits.opposites import algebraic_geometry.Gamma_Spec_adjunction /-! # Fibred products of schemes In this file we construct the fibred product of schemes via gluing. We roughly follow [har77] Theorem 3.3. In particular, the main construction is to show that for an open cover `{ Uᵢ }` of `X`, if there exist fibred products `Uᵢ ×[Z] Y` for each `i`, then there exists a fibred product `X ×[Z] Y`. Then, for constructing the fibred product for arbitrary schemes `X, Y, Z`, we can use the construction to reduce to the case where `X, Y, Z` are all affine, where fibred products are constructed via tensor products. -/ universes v u noncomputable theory open category_theory category_theory.limits algebraic_geometry namespace algebraic_geometry.Scheme namespace pullback variables {C : Type u} [category.{v} C] variables {X Y Z : Scheme.{u}} (𝒰 : open_cover.{u} X) (f : X ⟶ Z) (g : Y ⟶ Z) variables [∀ i, has_pullback (𝒰.map i ≫ f) g] /-- The intersection of `Uᵢ ×[Z] Y` and `Uⱼ ×[Z] Y` is given by (Uᵢ ×[Z] Y) ×[X] Uⱼ -/ def V (i j : 𝒰.J) : Scheme := pullback ((pullback.fst : pullback ((𝒰.map i) ≫ f) g ⟶ _) ≫ (𝒰.map i)) (𝒰.map j) /-- The canonical transition map `(Uᵢ ×[Z] Y) ×[X] Uⱼ ⟶ (Uⱼ ×[Z] Y) ×[X] Uᵢ` given by the fact that pullbacks are associative and symmetric. -/ def t (i j : 𝒰.J) : V 𝒰 f g i j ⟶ V 𝒰 f g j i := begin haveI : has_pullback (pullback.snd ≫ 𝒰.map i ≫ f) g := has_pullback_assoc_symm (𝒰.map j) (𝒰.map i) (𝒰.map i ≫ f) g, haveI : has_pullback (pullback.snd ≫ 𝒰.map j ≫ f) g := has_pullback_assoc_symm (𝒰.map i) (𝒰.map j) (𝒰.map j ≫ f) g, refine (pullback_symmetry _ _).hom ≫ _, refine (pullback_assoc _ _ _ _).inv ≫ _, change pullback _ _ ⟶ pullback _ _, refine _ ≫ (pullback_symmetry _ _).hom, refine _ ≫ (pullback_assoc _ _ _ _).hom, refine pullback.map _ _ _ _ (pullback_symmetry _ _).hom (𝟙 _) (𝟙 _) _ _, rw [pullback_symmetry_hom_comp_snd_assoc, pullback.condition_assoc, category.comp_id], rw [category.comp_id, category.id_comp] end @[simp, reassoc] lemma t_fst_fst (i j : 𝒰.J) : t 𝒰 f g i j ≫ pullback.fst ≫ pullback.fst = pullback.snd := begin delta t, simp only [category.assoc, id.def, pullback_symmetry_hom_comp_fst_assoc, pullback_assoc_hom_snd_fst, pullback.lift_fst_assoc, pullback_symmetry_hom_comp_snd, pullback_assoc_inv_fst_fst, pullback_symmetry_hom_comp_fst], end @[simp, reassoc] lemma t_fst_snd (i j : 𝒰.J) : t 𝒰 f g i j ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.snd := begin delta t, simp only [pullback_symmetry_hom_comp_snd_assoc, category.comp_id, category.assoc, id.def, pullback_symmetry_hom_comp_fst_assoc, pullback_assoc_hom_snd_snd, pullback.lift_snd, pullback_assoc_inv_snd], end @[simp, reassoc] lemma t_snd (i j : 𝒰.J) : t 𝒰 f g i j ≫ pullback.snd = pullback.fst ≫ pullback.fst := begin delta t, simp only [pullback_symmetry_hom_comp_snd_assoc, category.assoc, id.def, pullback_symmetry_hom_comp_snd, pullback_assoc_hom_fst, pullback.lift_fst_assoc, pullback_symmetry_hom_comp_fst, pullback_assoc_inv_fst_snd], end lemma t_id (i : 𝒰.J) : t 𝒰 f g i i = 𝟙 _ := begin apply pullback.hom_ext; rw category.id_comp, apply pullback.hom_ext, { rw ← cancel_mono (𝒰.map i), simp only [pullback.condition, category.assoc, t_fst_fst] }, { simp only [category.assoc, t_fst_snd]}, { rw ← cancel_mono (𝒰.map i),simp only [pullback.condition, t_snd, category.assoc] } end /-- The inclusion map of `V i j = (Uᵢ ×[Z] Y) ×[X] Uⱼ ⟶ Uᵢ ×[Z] Y`-/ abbreviation fV (i j : 𝒰.J) : V 𝒰 f g i j ⟶ pullback ((𝒰.map i) ≫ f) g := pullback.fst /-- The map `((Xᵢ ×[Z] Y) ×[X] Xⱼ) ×[Xᵢ ×[Z] Y] ((Xᵢ ×[Z] Y) ×[X] Xₖ)` ⟶ `((Xⱼ ×[Z] Y) ×[X] Xₖ) ×[Xⱼ ×[Z] Y] ((Xⱼ ×[Z] Y) ×[X] Xᵢ)` needed for gluing -/ def t' (i j k : 𝒰.J) : pullback (fV 𝒰 f g i j) (fV 𝒰 f g i k) ⟶ pullback (fV 𝒰 f g j k) (fV 𝒰 f g j i) := begin refine (pullback_right_pullback_fst_iso _ _ _).hom ≫ _, refine _ ≫ (pullback_symmetry _ _).hom, refine _ ≫ (pullback_right_pullback_fst_iso _ _ _).inv, refine pullback.map _ _ _ _ (t 𝒰 f g i j) (𝟙 _) (𝟙 _) _ _, { simp only [←pullback.condition, category.comp_id, t_fst_fst_assoc] }, { simp only [category.comp_id, category.id_comp]} end section end @[simp, reassoc] lemma t'_fst_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.fst ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.snd := begin delta t', simp only [category.assoc, pullback_symmetry_hom_comp_fst_assoc, pullback_right_pullback_fst_iso_inv_snd_fst_assoc, pullback.lift_fst_assoc, t_fst_fst, pullback_right_pullback_fst_iso_hom_fst_assoc], end @[simp, reassoc] lemma t'_fst_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.fst ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.snd := begin delta t', simp only [category.assoc, pullback_symmetry_hom_comp_fst_assoc, pullback_right_pullback_fst_iso_inv_snd_fst_assoc, pullback.lift_fst_assoc, t_fst_snd, pullback_right_pullback_fst_iso_hom_fst_assoc], end @[simp, reassoc] lemma t'_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.fst ≫ pullback.snd = pullback.snd ≫ pullback.snd := begin delta t', simp only [category.comp_id, category.assoc, pullback_symmetry_hom_comp_fst_assoc, pullback_right_pullback_fst_iso_inv_snd_snd, pullback.lift_snd, pullback_right_pullback_fst_iso_hom_snd], end @[simp, reassoc] lemma t'_snd_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.snd ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.snd := begin delta t', simp only [category.assoc, pullback_symmetry_hom_comp_snd_assoc, pullback_right_pullback_fst_iso_inv_fst_assoc, pullback.lift_fst_assoc, t_fst_fst, pullback_right_pullback_fst_iso_hom_fst_assoc], end @[simp, reassoc] lemma t'_snd_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.snd ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.snd := begin delta t', simp only [category.assoc, pullback_symmetry_hom_comp_snd_assoc, pullback_right_pullback_fst_iso_inv_fst_assoc, pullback.lift_fst_assoc, t_fst_snd, pullback_right_pullback_fst_iso_hom_fst_assoc], end @[simp, reassoc] lemma t'_snd_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ pullback.snd ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.fst := begin delta t', simp only [category.assoc, pullback_symmetry_hom_comp_snd_assoc, pullback_right_pullback_fst_iso_inv_fst_assoc, pullback.lift_fst_assoc, t_snd, pullback_right_pullback_fst_iso_hom_fst_assoc], end lemma cocycle_fst_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.fst ≫ pullback.fst ≫ pullback.fst = pullback.fst ≫ pullback.fst ≫ pullback.fst := by simp only [t'_fst_fst_fst, t'_fst_snd, t'_snd_snd] lemma cocycle_fst_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.fst ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.fst ≫ pullback.snd := by simp only [t'_fst_fst_snd] lemma cocycle_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.fst ≫ pullback.snd = pullback.fst ≫ pullback.snd := by simp only [t'_fst_snd, t'_snd_snd, t'_fst_fst_fst] lemma cocycle_snd_fst_fst (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.snd ≫ pullback.fst ≫ pullback.fst = pullback.snd ≫ pullback.fst ≫ pullback.fst := begin rw ← cancel_mono (𝒰.map i), simp only [pullback.condition_assoc, t'_snd_fst_fst, t'_fst_snd, t'_snd_snd] end lemma cocycle_snd_fst_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.snd ≫ pullback.fst ≫ pullback.snd = pullback.snd ≫ pullback.fst ≫ pullback.snd := by simp only [pullback.condition_assoc, t'_snd_fst_snd] lemma cocycle_snd_snd (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j ≫ pullback.snd ≫ pullback.snd = pullback.snd ≫ pullback.snd := by simp only [t'_snd_snd, t'_fst_fst_fst, t'_fst_snd] -- `by tidy` should solve it, but it times out. lemma cocycle (i j k : 𝒰.J) : t' 𝒰 f g i j k ≫ t' 𝒰 f g j k i ≫ t' 𝒰 f g k i j = 𝟙 _ := begin apply pullback.hom_ext; rw category.id_comp, { apply pullback.hom_ext, { apply pullback.hom_ext, { simp_rw category.assoc, exact cocycle_fst_fst_fst 𝒰 f g i j k }, { simp_rw category.assoc, exact cocycle_fst_fst_snd 𝒰 f g i j k } }, { simp_rw category.assoc, exact cocycle_fst_snd 𝒰 f g i j k } }, { apply pullback.hom_ext, { apply pullback.hom_ext, { simp_rw category.assoc, exact cocycle_snd_fst_fst 𝒰 f g i j k }, { simp_rw category.assoc, exact cocycle_snd_fst_snd 𝒰 f g i j k } }, { simp_rw category.assoc, exact cocycle_snd_snd 𝒰 f g i j k } } end /-- Given `Uᵢ ×[Z] Y`, this is the glued fibered product `X ×[Z] Y`. -/ @[simps] def gluing : Scheme.glue_data.{u} := { J := 𝒰.J, U := λ i, pullback ((𝒰.map i) ≫ f) g, V := λ ⟨i, j⟩, V 𝒰 f g i j, -- `p⁻¹(Uᵢ ∩ Uⱼ)` where `p : Uᵢ ×[Z] Y ⟶ Uᵢ ⟶ X`. f := λ i j, pullback.fst, f_id := λ i, infer_instance, f_open := infer_instance, t := λ i j, t 𝒰 f g i j, t_id := λ i, t_id 𝒰 f g i, t' := λ i j k, t' 𝒰 f g i j k, t_fac := λ i j k, begin apply pullback.hom_ext, apply pullback.hom_ext, all_goals { simp } end, cocycle := λ i j k, cocycle 𝒰 f g i j k } /-- The first projection from the glued scheme into `X`. -/ def p1 : (gluing 𝒰 f g).glued ⟶ X := begin fapply multicoequalizer.desc, exact λ i, pullback.fst ≫ 𝒰.map i, rintro ⟨i, j⟩, change pullback.fst ≫ _ ≫ 𝒰.map i = (_ ≫ _) ≫ _ ≫ 𝒰.map j, rw pullback.condition, rw ← category.assoc, congr' 1, rw category.assoc, exact (t_fst_fst _ _ _ _ _).symm end /-- The second projection from the glued scheme into `Y`. -/ def p2 : (gluing 𝒰 f g).glued ⟶ Y := begin fapply multicoequalizer.desc, exact λ i, pullback.snd, rintro ⟨i, j⟩, change pullback.fst ≫ _ = (_ ≫ _) ≫ _, rw category.assoc, exact (t_fst_snd _ _ _ _ _).symm end lemma p_comm : p1 𝒰 f g ≫ f = p2 𝒰 f g ≫ g := begin apply multicoequalizer.hom_ext, intro i, erw [multicoequalizer.π_desc_assoc, multicoequalizer.π_desc_assoc], rw [category.assoc, pullback.condition] end variable (s : pullback_cone f g) /-- (Implementation) The canonical map `(s.X ×[X] Uᵢ) ×[s.X] (s.X ×[X] Uⱼ) ⟶ (Uᵢ ×[Z] Y) ×[X] Uⱼ` This is used in `glued_lift`. -/ def glued_lift_pullback_map (i j : 𝒰.J) : pullback ((𝒰.pullback_cover s.fst).map i) ((𝒰.pullback_cover s.fst).map j) ⟶ (gluing 𝒰 f g).V ⟨i, j⟩ := begin change pullback pullback.fst pullback.fst ⟶ pullback _ _, refine (pullback_right_pullback_fst_iso _ _ _).hom ≫ _, refine pullback.map _ _ _ _ _ (𝟙 _) (𝟙 _) _ _, { exact (pullback_symmetry _ _).hom ≫ pullback.map _ _ _ _ (𝟙 _) s.snd f (category.id_comp _).symm s.condition }, { simpa using pullback.condition }, { simp only [category.comp_id, category.id_comp] } end @[reassoc] lemma glued_lift_pullback_map_fst (i j : 𝒰.J) : glued_lift_pullback_map 𝒰 f g s i j ≫ pullback.fst = pullback.fst ≫ (pullback_symmetry _ _).hom ≫ pullback.map _ _ _ _ (𝟙 _) s.snd f (category.id_comp _).symm s.condition := begin delta glued_lift_pullback_map, simp only [category.assoc, id.def, pullback.lift_fst, pullback_right_pullback_fst_iso_hom_fst_assoc], end @[reassoc] lemma glued_lift_pullback_map_snd (i j : 𝒰.J) : glued_lift_pullback_map 𝒰 f g s i j ≫ pullback.snd = pullback.snd ≫ pullback.snd := begin delta glued_lift_pullback_map, simp only [category.assoc, category.comp_id, id.def, pullback.lift_snd, pullback_right_pullback_fst_iso_hom_snd], end /-- The lifted map `s.X ⟶ (gluing 𝒰 f g).glued` in order to show that `(gluing 𝒰 f g).glued` is indeed the pullback. Given a pullback cone `s`, we have the maps `s.fst ⁻¹' Uᵢ ⟶ Uᵢ` and `s.fst ⁻¹' Uᵢ ⟶ s.X ⟶ Y` that we may lift to a map `s.fst ⁻¹' Uᵢ ⟶ Uᵢ ×[Z] Y`. to glue these into a map `s.X ⟶ Uᵢ ×[Z] Y`, we need to show that the maps agree on `(s.fst ⁻¹' Uᵢ) ×[s.X] (s.fst ⁻¹' Uⱼ) ⟶ Uᵢ ×[Z] Y`. This is achieved by showing that both of these maps factors through `glued_lift_pullback_map`. -/ def glued_lift : s.X ⟶ (gluing 𝒰 f g).glued := begin fapply (𝒰.pullback_cover s.fst).glue_morphisms, { exact λ i, (pullback_symmetry _ _).hom ≫ pullback.map _ _ _ _ (𝟙 _) s.snd f (category.id_comp _).symm s.condition ≫ (gluing 𝒰 f g).ι i }, intros i j, rw ← glued_lift_pullback_map_fst_assoc, have : _ = pullback.fst ≫ _ := (gluing 𝒰 f g).glue_condition i j, rw [← this, gluing_to_glue_data_t, gluing_to_glue_data_f], simp_rw ← category.assoc, congr' 1, apply pullback.hom_ext; simp_rw category.assoc, { rw [t_fst_fst, glued_lift_pullback_map_snd], congr' 1, rw [← iso.inv_comp_eq, pullback_symmetry_inv_comp_snd], erw pullback.lift_fst, rw category.comp_id }, { rw [t_fst_snd, glued_lift_pullback_map_fst_assoc], erw [pullback.lift_snd, pullback.lift_snd], rw [pullback_symmetry_hom_comp_snd_assoc, pullback_symmetry_hom_comp_snd_assoc], exact pullback.condition_assoc _ } end lemma glued_lift_p1 : glued_lift 𝒰 f g s ≫ p1 𝒰 f g = s.fst := begin rw ← cancel_epi (𝒰.pullback_cover s.fst).from_glued, apply multicoequalizer.hom_ext, intro b, erw [multicoequalizer.π_desc_assoc, multicoequalizer.π_desc_assoc], delta glued_lift, simp_rw ← category.assoc, rw (𝒰.pullback_cover s.fst).ι_glue_morphisms, simp_rw category.assoc, erw [multicoequalizer.π_desc, pullback.lift_fst_assoc, pullback.condition, category.comp_id], rw pullback_symmetry_hom_comp_fst_assoc, end lemma glued_lift_p2 : glued_lift 𝒰 f g s ≫ p2 𝒰 f g = s.snd := begin rw ← cancel_epi (𝒰.pullback_cover s.fst).from_glued, apply multicoequalizer.hom_ext, intro b, erw [multicoequalizer.π_desc_assoc, multicoequalizer.π_desc_assoc], delta glued_lift, simp_rw ← category.assoc, rw (𝒰.pullback_cover s.fst).ι_glue_morphisms, simp_rw category.assoc, erw [multicoequalizer.π_desc, pullback.lift_snd], rw pullback_symmetry_hom_comp_snd_assoc, refl end /-- (Implementation) The canonical map `(W ×[X] Uᵢ) ×[W] (Uⱼ ×[Z] Y) ⟶ (Uⱼ ×[Z] Y) ×[X] Uᵢ = V j i` where `W` is the glued fibred product. This is used in `lift_comp_ι`. -/ def pullback_fst_ι_to_V (i j : 𝒰.J) : pullback (pullback.fst : pullback (p1 𝒰 f g) (𝒰.map i) ⟶ _) ((gluing 𝒰 f g).ι j) ⟶ V 𝒰 f g j i := (pullback_symmetry _ _ ≪≫ (pullback_right_pullback_fst_iso (p1 𝒰 f g) (𝒰.map i) _)).hom ≫ (pullback.congr_hom (multicoequalizer.π_desc _ _ _ _ _) rfl).hom @[simp, reassoc] lemma pullback_fst_ι_to_V_fst (i j : 𝒰.J) : pullback_fst_ι_to_V 𝒰 f g i j ≫ pullback.fst = pullback.snd := begin delta pullback_fst_ι_to_V, simp only [iso.trans_hom, pullback.congr_hom_hom, category.assoc, pullback.lift_fst, category.comp_id, pullback_right_pullback_fst_iso_hom_fst, pullback_symmetry_hom_comp_fst], end @[simp, reassoc] lemma pullback_fst_ι_to_V_snd (i j : 𝒰.J) : pullback_fst_ι_to_V 𝒰 f g i j ≫ pullback.snd = pullback.fst ≫ pullback.snd := begin delta pullback_fst_ι_to_V, simp only [iso.trans_hom, pullback.congr_hom_hom, category.assoc, pullback.lift_snd, category.comp_id, pullback_right_pullback_fst_iso_hom_snd, pullback_symmetry_hom_comp_snd_assoc] end /-- We show that the map `W ×[X] Uᵢ ⟶ Uᵢ ×[Z] Y ⟶ W` is the first projection, where the first map is given by the lift of `W ×[X] Uᵢ ⟶ Uᵢ` and `W ×[X] Uᵢ ⟶ W ⟶ Y`. It suffices to show that the two map agrees when restricted onto `Uⱼ ×[Z] Y`. In this case, both maps factor through `V j i` via `pullback_fst_ι_to_V` -/ lemma lift_comp_ι (i : 𝒰.J) : pullback.lift pullback.snd (pullback.fst ≫ p2 𝒰 f g) (by rw [← pullback.condition_assoc, category.assoc, p_comm]) ≫ (gluing 𝒰 f g).ι i = (pullback.fst : pullback (p1 𝒰 f g) (𝒰.map i) ⟶ _) := begin apply ((gluing 𝒰 f g).open_cover.pullback_cover pullback.fst).hom_ext, intro j, dsimp only [open_cover.pullback_cover], transitivity pullback_fst_ι_to_V 𝒰 f g i j ≫ fV 𝒰 f g j i ≫ (gluing 𝒰 f g).ι _, { rw ← (show _ = fV 𝒰 f g j i ≫ _, from (gluing 𝒰 f g).glue_condition j i), simp_rw ← category.assoc, congr' 1, rw [gluing_to_glue_data_f, gluing_to_glue_data_t], apply pullback.hom_ext; simp_rw category.assoc, { rw [t_fst_fst, pullback.lift_fst, pullback_fst_ι_to_V_snd] }, { rw [t_fst_snd, pullback.lift_snd, pullback_fst_ι_to_V_fst_assoc, pullback.condition_assoc], erw multicoequalizer.π_desc } }, { rw [pullback.condition, ← category.assoc], congr' 1, apply pullback.hom_ext, { simp only [pullback_fst_ι_to_V_fst] }, { simp only [pullback_fst_ι_to_V_fst] } } end /-- The canonical isomorphism between `W ×[X] Uᵢ` and `Uᵢ ×[X] Y`. That is, the preimage of `Uᵢ` in `W` along `p1` is indeed `Uᵢ ×[X] Y`. -/ def pullback_p1_iso (i : 𝒰.J) : pullback (p1 𝒰 f g) (𝒰.map i) ≅ pullback (𝒰.map i ≫ f) g := begin fsplit, exact pullback.lift pullback.snd (pullback.fst ≫ p2 𝒰 f g) (by rw [← pullback.condition_assoc, category.assoc, p_comm]), refine pullback.lift ((gluing 𝒰 f g).ι i) pullback.fst (by erw multicoequalizer.π_desc), { apply pullback.hom_ext, { simpa using lift_comp_ι 𝒰 f g i }, { simp only [category.assoc, pullback.lift_snd, pullback.lift_fst, category.id_comp] } }, { apply pullback.hom_ext, { simp only [category.assoc, pullback.lift_fst, pullback.lift_snd, category.id_comp] }, { simp only [category.assoc, pullback.lift_snd, pullback.lift_fst_assoc, category.id_comp], erw multicoequalizer.π_desc } }, end @[simp, reassoc] lemma pullback_p1_iso_hom_fst (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).hom ≫ pullback.fst = pullback.snd := by { delta pullback_p1_iso, simp only [pullback.lift_fst] } @[simp, reassoc] lemma pullback_p1_iso_hom_snd (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).hom ≫ pullback.snd = pullback.fst ≫ p2 𝒰 f g := by { delta pullback_p1_iso, simp only [pullback.lift_snd] } @[simp, reassoc] lemma pullback_p1_iso_inv_fst (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).inv ≫ pullback.fst = (gluing 𝒰 f g).ι i := by { delta pullback_p1_iso, simp only [pullback.lift_fst] } @[simp, reassoc] lemma pullback_p1_iso_inv_snd (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).inv ≫ pullback.snd = pullback.fst := by { delta pullback_p1_iso, simp only [pullback.lift_snd] } @[simp, reassoc] lemma pullback_p1_iso_hom_ι (i : 𝒰.J) : (pullback_p1_iso 𝒰 f g i).hom ≫ (gluing 𝒰 f g).ι i = pullback.fst := by rw [← pullback_p1_iso_inv_fst, iso.hom_inv_id_assoc] /-- The glued scheme (`(gluing 𝒰 f g).glued`) is indeed the pullback of `f` and `g`. -/ def glued_is_limit : is_limit (pullback_cone.mk _ _ (p_comm 𝒰 f g)) := begin apply pullback_cone.is_limit_aux', intro s, refine ⟨glued_lift 𝒰 f g s, glued_lift_p1 𝒰 f g s, glued_lift_p2 𝒰 f g s, _⟩, intros m h₁ h₂, change m ≫ p1 𝒰 f g = _ at h₁, change m ≫ p2 𝒰 f g = _ at h₂, apply (𝒰.pullback_cover s.fst).hom_ext, intro i, rw open_cover.pullback_cover_map, have := pullback_right_pullback_fst_iso (p1 𝒰 f g) (𝒰.map i) m ≪≫ pullback.congr_hom h₁ rfl, erw (𝒰.pullback_cover s.fst).ι_glue_morphisms, rw [← cancel_epi (pullback_right_pullback_fst_iso (p1 𝒰 f g) (𝒰.map i) m ≪≫ pullback.congr_hom h₁ rfl).hom, iso.trans_hom, category.assoc, pullback.congr_hom_hom, pullback.lift_fst_assoc, category.comp_id, pullback_right_pullback_fst_iso_hom_fst_assoc, pullback.condition], transitivity pullback.snd ≫ (pullback_p1_iso 𝒰 f g _).hom ≫ (gluing 𝒰 f g).ι _, { congr' 1, rw ← pullback_p1_iso_hom_ι }, simp_rw ← category.assoc, congr' 1, apply pullback.hom_ext, { simp only [category.comp_id, pullback_right_pullback_fst_iso_hom_snd, category.assoc, pullback_p1_iso_hom_fst, pullback.lift_snd, pullback.lift_fst, pullback_symmetry_hom_comp_fst] }, { simp only [category.comp_id, pullback_right_pullback_fst_iso_hom_fst_assoc, pullback_p1_iso_hom_snd, category.assoc, pullback.lift_fst_assoc, pullback_symmetry_hom_comp_snd_assoc, pullback.lift_snd], rw [← pullback.condition_assoc, h₂] } end lemma has_pullback_of_cover : has_pullback f g := ⟨⟨⟨_, glued_is_limit 𝒰 f g⟩⟩⟩ instance affine_has_pullback {A B C : CommRing} (f : Spec.obj (opposite.op A) ⟶ Spec.obj (opposite.op C)) (g : Spec.obj (opposite.op B) ⟶ Spec.obj (opposite.op C)) : has_pullback f g := begin rw [← Spec.image_preimage f, ← Spec.image_preimage g], exact ⟨⟨⟨_,is_limit_of_has_pullback_of_preserves_limit Spec (Spec.preimage f) (Spec.preimage g)⟩⟩⟩ end lemma affine_affine_has_pullback {B C : CommRing} {X : Scheme} (f : X ⟶ Spec.obj (opposite.op C)) (g : Spec.obj (opposite.op B) ⟶ Spec.obj (opposite.op C)) : has_pullback f g := has_pullback_of_cover X.affine_cover f g instance base_affine_has_pullback {C : CommRing} {X Y : Scheme} (f : X ⟶ Spec.obj (opposite.op C)) (g : Y ⟶ Spec.obj (opposite.op C)) : has_pullback f g := @@has_pullback_symmetry _ _ _ (@@has_pullback_of_cover Y.affine_cover g f (λ i, @@has_pullback_symmetry _ _ _ $ affine_affine_has_pullback _ _)) instance left_affine_comp_pullback_has_pullback {X Y Z : Scheme} (f : X ⟶ Z) (g : Y ⟶ Z) (i : Z.affine_cover.J) : has_pullback ((Z.affine_cover.pullback_cover f).map i ≫ f) g := begin let Xᵢ := pullback f (Z.affine_cover.map i), let Yᵢ := pullback g (Z.affine_cover.map i), let W := pullback (pullback.snd : Yᵢ ⟶ _) (pullback.snd : Xᵢ ⟶ _), have := big_square_is_pullback (pullback.fst : W ⟶ _) (pullback.fst : Yᵢ ⟶ _) (pullback.snd : Xᵢ ⟶ _) (Z.affine_cover.map i) pullback.snd pullback.snd g pullback.condition.symm pullback.condition.symm (pullback_cone.flip_is_limit $ pullback_is_pullback _ _) (pullback_cone.flip_is_limit $ pullback_is_pullback _ _), have : has_pullback (pullback.snd ≫ Z.affine_cover.map i : Xᵢ ⟶ _) g := ⟨⟨⟨_,this⟩⟩⟩, rw ← pullback.condition at this, exact this, end instance {X Y Z : Scheme} (f : X ⟶ Z) (g : Y ⟶ Z) : has_pullback f g := has_pullback_of_cover (Z.affine_cover.pullback_cover f) f g instance : has_pullbacks Scheme := has_pullbacks_of_has_limit_cospan _ /-- Given an open cover `{ Xᵢ }` of `X`, then `X ×[Z] Y` is covered by `Xᵢ ×[Z] Y`. -/ @[simps J obj map] def open_cover_of_left (𝒰 : open_cover X) (f : X ⟶ Z) (g : Y ⟶ Z) : open_cover (pullback f g) := begin fapply ((gluing 𝒰 f g).open_cover.pushforward_iso (limit.iso_limit_cone ⟨_, glued_is_limit 𝒰 f g⟩).inv).copy 𝒰.J (λ i, pullback (𝒰.map i ≫ f) g) (λ i, pullback.map _ _ _ _ (𝒰.map i) (𝟙 _) (𝟙 _) (category.comp_id _) (by simp)) (equiv.refl 𝒰.J) (λ _, iso.refl _), rintro (i : 𝒰.J), change pullback.map _ _ _ _ _ _ _ _ _ = 𝟙 _ ≫ (gluing 𝒰 f g).ι i ≫ _, refine eq.trans _ (category.id_comp _).symm, apply pullback.hom_ext, all_goals { dsimp, simp only [limit.iso_limit_cone_inv_π, pullback_cone.mk_π_app_left, category.comp_id, pullback_cone.mk_π_app_right, category.assoc, pullback.lift_fst, pullback.lift_snd], symmetry, exact multicoequalizer.π_desc _ _ _ _ _ }, end /-- Given an open cover `{ Yᵢ }` of `Y`, then `X ×[Z] Y` is covered by `X ×[Z] Yᵢ`. -/ @[simps J obj map] def open_cover_of_right (𝒰 : open_cover Y) (f : X ⟶ Z) (g : Y ⟶ Z) : open_cover (pullback f g) := begin fapply ((open_cover_of_left 𝒰 g f).pushforward_iso (pullback_symmetry _ _).hom).copy 𝒰.J (λ i, pullback f (𝒰.map i ≫ g)) (λ i, pullback.map _ _ _ _ (𝟙 _) (𝒰.map i) (𝟙 _) (by simp) (category.comp_id _)) (equiv.refl _) (λ i, pullback_symmetry _ _), intro i, dsimp [open_cover.bind], apply pullback.hom_ext; simp, end /-- (Implementation). Use `open_cover_of_base` instead. -/ def open_cover_of_base' (𝒰 : open_cover Z) (f : X ⟶ Z) (g : Y ⟶ Z) : open_cover (pullback f g) := begin apply (open_cover_of_left (𝒰.pullback_cover f) f g).bind, intro i, let Xᵢ := pullback f (𝒰.map i), let Yᵢ := pullback g (𝒰.map i), let W := pullback (pullback.snd : Yᵢ ⟶ _) (pullback.snd : Xᵢ ⟶ _), have := big_square_is_pullback (pullback.fst : W ⟶ _) (pullback.fst : Yᵢ ⟶ _) (pullback.snd : Xᵢ ⟶ _) (𝒰.map i) pullback.snd pullback.snd g pullback.condition.symm pullback.condition.symm (pullback_cone.flip_is_limit $ pullback_is_pullback _ _) (pullback_cone.flip_is_limit $ pullback_is_pullback _ _), refine open_cover_of_is_iso ((pullback_symmetry _ _).hom ≫ (limit.iso_limit_cone ⟨_, this⟩).inv ≫ pullback.map _ _ _ _ (𝟙 _) (𝟙 _) (𝟙 _) _ _), { simpa only [category.comp_id, category.id_comp, ← pullback.condition] }, { simp only [category.comp_id, category.id_comp] }, apply_instance end /-- Given an open cover `{ Zᵢ }` of `Z`, then `X ×[Z] Y` is covered by `Xᵢ ×[Zᵢ] Yᵢ`, where `Xᵢ = X ×[Z] Zᵢ` and `Yᵢ = Y ×[Z] Zᵢ` is the preimage of `Zᵢ` in `X` and `Y`. -/ @[simps J obj map] def open_cover_of_base (𝒰 : open_cover Z) (f : X ⟶ Z) (g : Y ⟶ Z) : open_cover (pullback f g) := begin apply (open_cover_of_base' 𝒰 f g).copy 𝒰.J (λ i, pullback (pullback.snd : pullback f (𝒰.map i) ⟶ _) (pullback.snd : pullback g (𝒰.map i) ⟶ _)) (λ i, pullback.map _ _ _ _ pullback.fst pullback.fst (𝒰.map i) pullback.condition.symm pullback.condition.symm) ((equiv.prod_punit 𝒰.J).symm.trans (equiv.sigma_equiv_prod 𝒰.J punit).symm) (λ _, iso.refl _), intro i, change _ = _ ≫ _ ≫ _, refine eq.trans _ (category.id_comp _).symm, apply pullback.hom_ext; simp only [category.comp_id, open_cover_of_left_map, open_cover.pullback_cover_map, pullback_cone.mk_π_app_left, open_cover_of_is_iso_map, limit.iso_limit_cone_inv_π_assoc, category.assoc, pullback.lift_fst_assoc, pullback_symmetry_hom_comp_snd_assoc, pullback.lift_fst, limit.iso_limit_cone_inv_π, pullback_cone.mk_π_app_right, pullback_symmetry_hom_comp_fst_assoc, pullback.lift_snd], end end pullback end algebraic_geometry.Scheme