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
bcb382412963de0b1210db6ad54406e1c158a842
1437b3495ef9020d5413178aa33c0a625f15f15f
/analysis/measure_theory/integration.lean
732cdd3cd68574f8a754ef8fd7ec2ec66c49a72b
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,137
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl Lebesgue integral on `ennreal`. We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. -/ import algebra.pi_instances analysis.measure_theory.measure_space analysis.measure_theory.borel_space noncomputable theory open lattice set filter local attribute [instance] classical.prop_decidable lemma supr_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [orderable_topology α] {f : ℕ → α} {a : α} (hf : monotone f) (h : tendsto f at_top (nhds a)) : supr f = a := le_antisymm (supr_le $ assume i, le_of_not_gt $ assume hi, have {n | i ≤ n} ∈ (at_top : filter ℕ).sets, from mem_at_top _, let ⟨n, h₁, h₂⟩ := inhabited_of_mem_sets at_top_ne_bot (inter_mem_sets this ((tendsto_orderable.1 h).2 _ hi)) in not_lt_of_ge (hf h₁) h₂) (le_of_not_gt $ assume ha, let ⟨n, hn⟩ := inhabited_of_mem_sets at_top_ne_bot ((tendsto_orderable.1 h).1 _ ha) in not_lt_of_ge (le_supr _ _) hn) namespace measure_theory variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (measurable_sn : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩ @[extensionality] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := by cases f; cases g; congr; exact funext H protected def range (f : α →ₛ β) := f.finite.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ ∃ a, f a = b := finite.mem_to_finset def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_subset (set.finite_singleton b) $ by rintro _ ⟨a, rfl⟩; simp⟩ @[simp] theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl lemma range_const (α) [measure_space α] [ne : nonempty α] (b : β) : (const α b).range = {b} := begin ext b', simp [mem_range], exact ⟨assume ⟨_, h⟩, h.symm, assume h, ne.elim $ λa, ⟨a, h.symm⟩⟩ end lemma is_measurable_cut (p : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | p a b}) : is_measurable {a | p a (f a)} := begin rw (_ : {a | p a (f a)} = ⋃ b ∈ set.range f, {a | p a b} ∩ f ⁻¹' {b}), { exact is_measurable.bUnion (countable_finite f.finite) (λ b _, is_measurable.inter (h b) (f.measurable_sn _)) }, ext a, simp, exact ⟨λ h, ⟨_, ⟨a, rfl⟩, h, rfl⟩, λ ⟨_, ⟨a', rfl⟩, h', e⟩, e.symm ▸ h'⟩ end theorem preimage_measurable (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, by simp [is_measurable.const]) theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, preimage_measurable f s def ite {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨λ a, if a ∈ s then f a else g a, λ x, by letI : measurable_space β := ⊤; exact measurable.if hs f.measurable g.measurable _ trivial, finite_subset (finite_union f.finite g.finite) begin rintro _ ⟨a, rfl⟩, by_cases a ∈ s; simp [h], exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩] end⟩ @[simp] theorem ite_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : ite hs f g a = if a ∈ s then f a else g a := rfl def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, is_measurable_cut (λa b, g b a ∈ ({c} : set γ)) f (λ b, (g b).measurable_sn c), finite_subset (finite_bUnion f.finite (λ b, (g b).finite)) $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨_, ⟨a, rfl⟩, _, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl def restrict [has_zero β] (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then ite hs f (const α 0) else const α 0 @[simp] theorem restrict_apply [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by unfold_coes; simp [restrict, hs]; apply ite_apply hs theorem restrict_preimage [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by ext a; dsimp; rw [restrict_apply]; by_cases a ∈ s; simp [h, hs, ht] def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) @[simp] theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := begin ext c, simp [mem_range], split, { rintros ⟨a, rfl⟩, exact ⟨f a, ⟨_, rfl⟩, rfl⟩ }, { rintros ⟨_, ⟨a, rfl⟩, rfl⟩, exact ⟨_, rfl⟩ } end def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp] lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl instance [add_monoid β] : add_monoid (α →ₛ β) := { add := (+), zero := 0, add_assoc := assume f g h, ext (assume a, add_assoc _ _ _), zero_add := assume f, ext (assume a, zero_add _), add_zero := assume f, ext (assume a, add_zero _) } instance [semiring β] [add_monoid β] : has_scalar β (α →ₛ β) := ⟨λb f, f.map (λa, b * a)⟩ instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_refl _, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order } instance [order_top β] : order_top (α →ₛ β) := { top := const α⊤, le_top := λf a, le_top, .. simple_func.partial_order } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) := { .. simple_func.lattice.semilattice_sup,.. simple_func.lattice.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.lattice.semilattice_sup,.. simple_func.lattice.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice.lattice, .. simple_func.lattice.order_bot, .. simple_func.lattice.order_top } lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section approx section variables [topological_space β] [semilattice_sup_bot β] [has_zero β] def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α(i k)) {a:α | i k ≤ f a}) lemma approx_apply [ordered_topology β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : _root_.measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf.preimage $ is_measurable_of_is_closed $ is_closed_ge' _) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h end lemma supr_approx_apply [topological_space β] [complete_lattice β] [ordered_topology β] [has_zero β] (i : ℕ → β) (f : α → β) (a : α) (hf : _root_.measurable f) (h_zero : (0 : β) = ⊥): (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox def ennreal_rat_embed (n : ℕ) : ennreal := nnreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) (hq : 0 ≤ q) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal := approx ennreal_rat_embed lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ennreal) (hf : _root_.measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q hq], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end end eapprox end measurable section measure variables [measure_space α] def integral (f : α →ₛ ennreal) : ennreal := f.range.sum (λ x, x * volume (f ⁻¹' {x})) -- TODO: slow simp proofs lemma map_integral (g : β → ennreal) (f : α →ₛ β) : (f.map g).integral = f.range.sum (λ x, g x * volume (f ⁻¹' {x})) := begin simp only [integral, coe_map, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, let s' := f.range.filter (λb, g b = g (f a)), have : g ∘ ⇑f ⁻¹' {g (f a)} = (⋃b∈s', ⇑f ⁻¹' {b}), { ext a', simp, split, { assume eq, exact ⟨⟨_, rfl⟩, eq⟩ }, { rintros ⟨_, eq⟩, exact eq } }, calc g (f a) * volume (g ∘ ⇑f ⁻¹' {g (f a)}) = g (f a) * volume (⋃b∈s', ⇑f ⁻¹' {b}) : by rw [this] ... = g (f a) * s'.sum (λb, volume (f ⁻¹' {b})) : begin rw [volume_bUnion_finset], { simp [pairwise_on, (on)], rintros b a₀ rfl eq₀ b a₁ rfl eq₁ ne a ⟨h₁, h₂⟩, simp at h₁ h₂, rw [← h₁, h₂] at ne, exact ne rfl }, exact assume a ha, preimage_measurable _ _ end ... = s'.sum (λb, g (f a) * volume (f ⁻¹' {b})) : by rw [finset.mul_sum] ... = s'.sum (λb, g b * volume (f ⁻¹' {b})) : finset.sum_congr rfl $ by simp {contextual := tt} end lemma zero_integral : (0 : α →ₛ ennreal).integral = 0 := begin refine (finset.sum_eq_zero_iff_of_nonneg $ assume _ _, zero_le _).2 _, assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, exact zero_mul _ end lemma add_integral (f g : α →ₛ ennreal) : (f + g).integral = f.integral + g.integral := calc (f + g).integral = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x}) + x.2 * volume (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_integral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x})) + (pair f g).range.sum (λx, x.2 * volume (pair f g ⁻¹' {x})) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).integral + ((pair f g).map prod.snd).integral : by rw [map_integral, map_integral] ... = integral f + integral g : rfl lemma const_mul_integral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).integral = x * f.integral := calc (f.map (λa, x * a)).integral = f.range.sum (λr, x * r * volume (f ⁻¹' {r})) : by rw [map_integral] ... = f.range.sum (λr, x * (r * volume (f ⁻¹' {r}))) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.integral : finset.mul_sum.symm lemma mem_restrict_range [has_zero β] {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (∃a∈s, f a = r) := begin simp only [mem_range, restrict_apply, hs], split, { rintros ⟨a, ha⟩, split_ifs at ha, { exact or.inr ⟨a, h, ha⟩ }, { exact or.inl ⟨ha.symm, assume eq, h $ eq.symm ▸ trivial⟩ } }, { rintros (⟨rfl, h⟩ | ⟨a, ha, rfl⟩), { have : ¬ ∀a, a ∈ s := assume this, h $ eq_univ_of_forall this, rcases not_forall.1 this with ⟨a, ha⟩, refine ⟨a, _⟩, rw [if_neg ha] }, { refine ⟨a, _⟩, rw [if_pos ha] } } end lemma restrict_preimage' {r : ennreal} {s : set α} (f : α →ₛ ennreal) (hs : is_measurable s) (hr : r ≠ 0): (restrict f s) ⁻¹' {r} = (f ⁻¹' {r} ∩ s) := begin ext a, by_cases a ∈ s; simp [hs, h, hr.symm] end lemma restrict_integral (f : α →ₛ ennreal) (s : set α) (hs : is_measurable s) : (restrict f s).integral = f.range.sum (λr, r * volume (f ⁻¹' {r} ∩ s)) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { assume r hr, rcases (mem_restrict_range hs).1 hr with ⟨rfl, h⟩ | ⟨a, ha, rfl⟩, { simp }, { assume _, exact mem_range.2 ⟨a, rfl⟩ } }, { assume a b _ _ _ _ h, exact h }, { assume r hr, by_cases r0 : r = 0, { simp [r0] }, assume h0, rcases mem_range.1 hr with ⟨a, rfl⟩, have : f ⁻¹' {f a} ∩ s ≠ ∅, { assume h, simpa [h] using h0 }, rcases ne_empty_iff_exists_mem.1 this with ⟨a', eq', ha'⟩, refine ⟨_, (mem_restrict_range hs).2 (or.inr ⟨a', ha', _⟩), _, rfl⟩, { simpa using eq' }, { rwa [restrict_preimage' _ hs r0] } }, { assume r hr ne, by_cases r = 0, { simp [h] }, rw [restrict_preimage' _ hs h] } end lemma restrict_const_integral (c : ennreal) (s : set α) (hs : is_measurable s) : (restrict (const α c) s).integral = c * volume s := have (@const α ennreal _ c) ⁻¹' {c} = univ, begin refine eq_univ_of_forall (assume a, _), simp, end, calc (restrict (const α c) s).integral = c * volume ((const α c) ⁻¹' {c} ∩ s) : begin rw [restrict_integral (const α c) s hs], refine finset.sum_eq_single c _ _, { assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, contradiction }, { by_cases nonempty α, { assume ne, rcases h with ⟨a⟩, exfalso, exact ne (mem_range.2 ⟨a, rfl⟩) }, { assume empty, have : (@const α ennreal _ c) ⁻¹' {c} ∩ s = ∅, { ext a, exfalso, exact h ⟨a⟩ }, simp only [this, volume_empty, mul_zero] } } end ... = c * volume s : by rw [this, univ_inter] lemma integral_sup_le (f g : α →ₛ ennreal) : f.integral ⊔ g.integral ≤ (f ⊔ g).integral := calc f.integral ⊔ g.integral = ((pair f g).map prod.fst).integral ⊔ ((pair f g).map prod.snd).integral : rfl ... ≤ (pair f g).range.sum (λx, (x.1 ⊔ x.2) * volume (pair f g ⁻¹' {x})) : begin rw [map_integral, map_integral], refine sup_le _ _; refine finset.sum_le_sum' (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).integral : by rw [sup_eq_map₂, map_integral] lemma integral_le_integral (f g : α →ₛ ennreal) (h : f ≤ g) : f.integral ≤ g.integral := calc f.integral ≤ f.integral ⊔ g.integral : le_sup_left ... ≤ (f ⊔ g).integral : integral_sup_le _ _ ... = g.integral : by rw [sup_of_le_right h] lemma integral_congr (f g : α →ₛ ennreal) (h : {a | f a = g a} ∈ (@measure_space.μ α _).a_e.sets) : f.integral = g.integral := show ((pair f g).map prod.fst).integral = ((pair f g).map prod.snd).integral, from begin rw [map_integral, map_integral], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine volume_mono_null (assume a' ha', _) h, simp at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp [this] } end end measure end simple_func section lintegral open simple_func variable [measure_space α] /-- The lower Lebesgue integral -/ def lintegral (f : α → ennreal) : ennreal := ⨆ (s : α →ₛ ennreal) (hf : f ≥ s), s.integral notation `∫⁻` binders `, ` r:(scoped f, lintegral f) := r theorem simple_func.lintegral_eq_integral (f : α →ₛ ennreal) : (∫⁻ a, f a) = f.integral := le_antisymm (supr_le $ assume s, supr_le $ assume hs, integral_le_integral _ _ hs) (le_supr_of_le f $ le_supr_of_le (le_refl f) $ le_refl _) lemma lintegral_le_lintegral (f g : α → ennreal) (h : f ≤ g) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) := supr_le_supr $ assume s, supr_le $ assume hs, le_supr_of_le (le_trans hs h) (le_refl _) lemma lintegral_eq_nnreal (f : α → ennreal) : (∫⁻ a, f a) = (⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map (coe : nnreal → ennreal)), (s.map (coe : nnreal → ennreal)).integral) := begin let c : nnreal → ennreal := coe, refine le_antisymm (supr_le $ assume s, supr_le $ assume hs, _) (supr_le $ assume s, supr_le $ assume hs, le_supr_of_le (s.map c) $ le_supr _ hs), by_cases {a | s a ≠ ⊤} ∈ ((@measure_space.μ α _).a_e).sets, { have : f ≥ (s.map ennreal.to_nnreal).map c := le_trans (assume a, ennreal.coe_to_nnreal_le_self) hs, refine le_supr_of_le (s.map ennreal.to_nnreal) (le_supr_of_le this (le_of_eq $ integral_congr _ _ _)), exact filter.mem_sets_of_superset h (assume a ha, (ennreal.coe_to_nnreal ha).symm) }, { have h_vol_s : volume {a : α | s a = ⊤} ≠ 0, { simp [measure.a_e, set.compl_set_of] at h, assumption }, let n : ℕ → (α →ₛ nnreal) := λn, restrict (const α (n : nnreal)) (s ⁻¹' {⊤}), have n_le_s : ∀i, (n i).map c ≤ s, { assume i a, dsimp [n, c], rw [restrict_apply _ (s.preimage_measurable _)], split_ifs with ha, { simp at ha, exact ha.symm ▸ le_top }, { exact zero_le _ } }, have approx_s : ∀ (i : ℕ), ↑i * volume {a : α | s a = ⊤} ≤ integral (map c (n i)), { assume i, have : {a : α | s a = ⊤} = s ⁻¹' {⊤}, { ext a, simp }, rw [this, ← restrict_const_integral _ _ (s.preimage_measurable _)], { refine integral_le_integral _ _ (assume a, le_of_eq _), simp [n, c, restrict_apply, s.preimage_measurable], split_ifs; simp [ennreal.coe_nat] }, }, calc s.integral ≤ ⊤ : le_top ... = (⨆i:ℕ, (i : ennreal) * volume {a | s a = ⊤}) : by rw [← ennreal.supr_mul, ennreal.supr_coe_nat, ennreal.top_mul, if_neg h_vol_s] ... ≤ (⨆i, ((n i).map c).integral) : supr_le_supr approx_s ... ≤ ⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map c), (s.map c).integral : have ∀i, ((n i).map c : α → ennreal) ≤ f := assume i, le_trans (n_le_s i) hs, (supr_le $ assume i, le_supr_of_le (n i) (le_supr (λh, ((n i).map c).integral) (this i))) } end /-- Monotone convergence theorem -- somtimes called Beppo-Levi convergence -/ theorem lintegral_supr {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) := let c : nnreal → ennreal := coe in let F (a:α) := ⨆n, f n a in have hF : measurable F := measurable.supr hf, show (∫⁻ a, F a) = (⨆n, ∫⁻ a, f n a), begin refine le_antisymm _ _, { rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union_left, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} := assume n, measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * integral (s.map c) = (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r})) : by rw [← const_mul_integral, integral, eq_rs] ... ≤ (rs.map c).range.sum (λr, r * volume (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ (rs.map c).range.sum (λr, (⨆n, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}))) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [volume, measure_Union_eq_supr_nat _ (mono x), ennreal.mul_supr], { assume i, refine is_measurable.inter ((rs.map c).preimage_measurable _) _, refine (hf i).preimage _, exact is_measurable_of_is_closed (is_closed_ge' _) } end) ... ≤ ⨆n, (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (volume_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).integral) : begin refine supr_le_supr (assume n, _), rw [restrict_integral _ _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2, ext a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_integral], refine lintegral_le_lintegral _ _ (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end }, { exact supr_le (assume n, lintegral_le_lintegral _ _ $ assume a, le_supr _ n) } end lemma lintegral_eq_supr_eapprox_integral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a) = (⨆n, (eapprox f n).integral) := calc (∫⁻ a, f a) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).integral) : by congr; ext n; rw [(eapprox f n).lintegral_eq_integral] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a) = (∫⁻ a, f a) + (∫⁻ a, g a) := calc (∫⁻ a, f a + g a) = (∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a)) : by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a)) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).integral + (eapprox g n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_integral, ← simple_func.lintegral_eq_integral], refl }, { assume n, exact measurable_add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add' (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).integral) + (⨆n, (eapprox g n).integral) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.integral_le_integral _ _ (monotone_eapprox _ h) } ... = (∫⁻ a, f a) + (∫⁻ a, g a) : by rw [lintegral_eq_supr_eapprox_integral hf, lintegral_eq_supr_eapprox_integral hg] @[simp] lemma lintegral_zero : (∫⁻ a:α, 0) = 0 := show (∫⁻ a:α, (0 : α →ₛ ennreal) a) = 0, by rw [simple_func.lintegral_eq_integral, zero_integral] lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) : (∫⁻ a, r * f a) = r * (∫⁻ a, f a) := calc (∫⁻ a, r * f a) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a)) : by congr; funext a; rw [← supr_eapprox_apply f hf, ennreal.mul_supr]; refl ... = (⨆n, r * (eapprox f n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_integral, ← simple_func.lintegral_eq_integral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_integral hf] lemma lintegral_supr_const (r : ennreal) {s : set α} (hs : is_measurable s) : (∫⁻ a, ⨆(h : a ∈ s), r) = r * volume s := begin rw [← restrict_const_integral r s hs, ← (restrict (const α r) s).lintegral_eq_integral], congr; ext a; by_cases a ∈ s; simp [h, hs], end end lintegral /- namespace measure def integral [measurable_space α] (m : measure α) (f : α → ennreal) : ennreal := @lintegral α { μ := m } f def measure.with_density [measurable_space α] (m : measure α) (f : α → ennreal) : measure α := if measurable f then measure.of_measurable (λs hs, m.integral (λa, ⨆(h : a ∈ s), f a)) _ _ else m end measure -/ end measure_theory
9af6f8beb3e1cb1f5a8c8fc4d844520abef3b573
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.21.lean
d06f962773f40c553ff742e979fc7229da0f8ebb
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
52
lean
import standard set_option unifier.max_steps 100000
9f169b5dceb41dcbe8af288385e3d0de361056ba
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/run/dunfold3.lean
c7699e2700bf469472b57574ce44a2269c0d8a35
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
883
lean
open tactic def g : nat → nat := λ x, x + 5 example (a b : nat) (p : nat → Prop) (h : p (g (nat.succ (nat.succ a)))) : p (g (a + 2)) := begin unfold g at h, do { h ← get_local `h >>= infer_type, t ← to_expr `(p (nat.succ (nat.succ a) + 5)), guard (h = t) }, unfold add has_add.add bit0 one nat.add, unfold g, do { t ← target, h ← get_local `h >>= infer_type, guard (t = h) }, assumption end meta def check_expected (p : pexpr) : tactic unit := do t ← target, ex ← to_expr p, guard (t = ex) example (a b c : nat) (f : nat → nat → nat) (h : false) : f (g a) (g b) = (g c) := begin unfold_occs g [2], check_expected `(f (g a) (b + 5) = g c), contradiction end example (a b c : nat) (f : nat → nat → nat) (h : false) : f (g a) (g b) = (g c) := begin unfold_occs g [1, 3], check_expected `(f (a + 5) (g b) = c + 5), contradiction end
faaf1f6915d36735d4a1274465e51cf6d3e0c0f4
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/category/state.lean
42cb19c5335fb288d4a4f48e8edd06a6bc30d643
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,441
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.category.monad init.category.alternative def state (σ : Type) (α : Type) : Type := σ → α × σ section variables {σ : Type} {α β : Type} @[inline] def state_return (a : α) : state σ α := λ s, (a, s) @[inline] def state_bind (a : state σ α) (b : α → state σ β) : state σ β := λ s, match (a s) with (a', s') := b a' s' end instance (σ : Type) : monad (state σ) := {pure := @state_return σ, bind := @state_bind σ} end namespace state @[inline] def read {σ : Type} : state σ σ := λ s, (s, s) @[inline] def write {σ : Type} : σ → state σ unit := λ s' s, ((), s') end state def state_t (σ : Type) (m : Type → Type) [monad m] (α : Type) : Type := σ → m (α × σ) section variable {σ : Type} variable {m : Type → Type} variable [monad m] variables {α β : Type} def state_t_return (a : α) : state_t σ m α := λ s, show m (α × σ), from return (a, s) def state_t_bind (act₁ : state_t σ m α) (act₂ : α → state_t σ m β) : state_t σ m β := λ s, show m (β × σ), from do (a, new_s) ← act₁ s, act₂ a new_s end instance (σ : Type) (m : Type → Type) [monad m] : monad (state_t σ m) := {pure := @state_t_return σ m _, bind := @state_t_bind σ m _} section variable {σ : Type} variable {m : Type → Type} variable [monad m] variable [alternative m] variable {α : Type} def state_t_orelse (act₁ act₂ : state_t σ m α) : state_t σ m α := λ s, act₁ s <|> act₂ s def state_t_failure : state_t σ m α := λ s, failure end instance (σ : Type) (m : Type → Type) [alternative m] [monad m] : alternative (state_t σ m) := { state_t.monad σ m with failure := @state_t_failure σ m _ _, orelse := @state_t_orelse σ m _ _ } namespace state_t def read {σ : Type} {m : Type → Type} [monad m] : state_t σ m σ := λ s, return (s, s) def write {σ : Type} {m : Type → Type} [monad m] : σ → state_t σ m unit := λ s' s, return ((), s') def modify {σ : Type} {m : Type → Type} [monad m] (f : σ → σ) : state_t σ m unit := do s ← read, write (f s) def lift {α σ : Type} {m : Type → Type} [monad m] (t : m α) : state_t σ m α := λ s, do a ← t, return (a, s) end state_t
a08a485cda2c1b25e7d6b4b810d9b76f35752a3e
969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb
/src/topology/separation.lean
9494e67abe65b2a023b3d9356ce5847515676647
[ "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
43,204
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 Separation properties of topological spaces. -/ import topology.subset_properties import topology.connected open set filter open_locale topological_space filter local attribute [instance] classical.prop_decidable -- TODO: use "open_locale classical" universes u v variables {α : Type u} {β : Type v} [topological_space α] section separation /-- `separated` is a predicate on pairs of sub`set`s of a topological space. It holds if the two sub`set`s are contained in disjoint open sets. -/ def separated : set α → set α → Prop := λ (s t : set α), ∃ U V : (set α), (is_open U) ∧ is_open V ∧ (s ⊆ U) ∧ (t ⊆ V) ∧ disjoint U V namespace separated open separated @[symm] lemma symm {s t : set α} : separated s t → separated t s := λ ⟨U, V, oU, oV, aU, bV, UV⟩, ⟨V, U, oV, oU, bV, aU, disjoint.symm UV⟩ lemma comm (s t : set α) : separated s t ↔ separated t s := ⟨symm, symm⟩ lemma empty_right (a : set α) : separated a ∅ := ⟨_, _, is_open_univ, is_open_empty, λ a h, mem_univ a, λ a h, by cases h, disjoint_empty _⟩ lemma empty_left (a : set α) : separated ∅ a := (empty_right _).symm lemma union_left {a b c : set α} : separated a c → separated b c → separated (a ∪ b) c := λ ⟨U, V, oU, oV, aU, bV, UV⟩ ⟨W, X, oW, oX, aW, bX, WX⟩, ⟨U ∪ W, V ∩ X, is_open_union oU oW, is_open_inter oV oX, union_subset_union aU aW, subset_inter bV bX, set.disjoint_union_left.mpr ⟨disjoint_of_subset_right (inter_subset_left _ _) UV, disjoint_of_subset_right (inter_subset_right _ _) WX⟩⟩ lemma union_right {a b c : set α} (ab : separated a b) (ac : separated a c) : separated a (b ∪ c) := (ab.symm.union_left ac.symm).symm end separated /-- A T₀ space, also known as a Kolmogorov space, is a topological space where for every pair `x ≠ y`, there is an open set containing one but not the other. -/ class t0_space (α : Type u) [topological_space α] : Prop := (t0 : ∀ x y, x ≠ y → ∃ U:set α, is_open U ∧ (xor (x ∈ U) (y ∈ U))) theorem is_closed.exists_closed_singleton {α : Type*} [topological_space α] [t0_space α] [compact_space α] {S : set α} (hS : is_closed S) (hne : S.nonempty) : ∃ (x : α), x ∈ S ∧ is_closed ({x} : set α) := begin obtain ⟨V, Vsub, Vne, Vcls, hV⟩ := hS.exists_minimal_nonempty_closed_subset hne, by_cases hnt : ∃ (x y : α) (hx : x ∈ V) (hy : y ∈ V), x ≠ y, { exfalso, obtain ⟨x, y, hx, hy, hne⟩ := hnt, obtain ⟨U, hU, hsep⟩ := t0_space.t0 _ _ hne, have : ∀ (z w : α) (hz : z ∈ V) (hw : w ∈ V) (hz' : z ∈ U) (hw' : ¬ w ∈ U), false, { intros z w hz hw hz' hw', have uvne : (V ∩ Uᶜ).nonempty, { use w, simp only [hw, hw', set.mem_inter_eq, not_false_iff, and_self, set.mem_compl_eq], }, specialize hV (V ∩ Uᶜ) (set.inter_subset_left _ _) uvne (is_closed_inter Vcls (is_closed_compl_iff.mpr hU)), have : V ⊆ Uᶜ, { rw ←hV, exact set.inter_subset_right _ _ }, exact this hz hz', }, cases hsep, { exact this x y hx hy hsep.1 hsep.2 }, { exact this y x hy hx hsep.1 hsep.2 } }, { push_neg at hnt, obtain ⟨z, hz⟩ := Vne, refine ⟨z, Vsub hz, _⟩, convert Vcls, ext, simp only [set.mem_singleton_iff, set.mem_compl_eq], split, { rintro rfl, exact hz, }, { exact λ hx, hnt x z hx hz, }, }, end theorem exists_open_singleton_of_open_finset [t0_space α] (s : finset α) (sne : s.nonempty) (hso : is_open (↑s : set α)) : ∃ x ∈ s, is_open ({x} : set α):= begin induction s using finset.strong_induction_on with s ihs, by_cases hs : set.subsingleton (↑s : set α), { rcases sne with ⟨x, hx⟩, refine ⟨x, hx, _⟩, have : (↑s : set α) = {x}, from hs.eq_singleton_of_mem hx, rwa this at hso }, { dunfold set.subsingleton at hs, push_neg at hs, rcases hs with ⟨x, hx, y, hy, hxy⟩, rcases t0_space.t0 x y hxy with ⟨U, hU, hxyU⟩, wlog H : x ∈ U ∧ y ∉ U := hxyU using [x y, y x], obtain ⟨z, hzs, hz⟩ : ∃ z ∈ s.filter (λ z, z ∈ U), is_open ({z} : set α), { refine ihs _ (finset.filter_ssubset.2 ⟨y, hy, H.2⟩) ⟨x, finset.mem_filter.2 ⟨hx, H.1⟩⟩ _, rw [finset.coe_filter], exact is_open_inter hso hU }, exact ⟨z, (finset.mem_filter.1 hzs).1, hz⟩ } end theorem exists_open_singleton_of_fintype [t0_space α] [f : fintype α] [ha : nonempty α] : ∃ x:α, is_open ({x}:set α) := begin refine ha.elim (λ x, _), have : is_open (↑(finset.univ : finset α) : set α), { simp }, rcases exists_open_singleton_of_open_finset _ ⟨x, finset.mem_univ x⟩ this with ⟨x, _, hx⟩, exact ⟨x, hx⟩ end instance subtype.t0_space [t0_space α] {p : α → Prop} : t0_space (subtype p) := ⟨λ x y hxy, let ⟨U, hU, hxyU⟩ := t0_space.t0 (x:α) y ((not_congr subtype.ext_iff_val).1 hxy) in ⟨(coe : subtype p → α) ⁻¹' U, is_open_induced hU, hxyU⟩⟩ /-- A T₁ space, also known as a Fréchet space, is a topological space where every singleton set is closed. Equivalently, for every pair `x ≠ y`, there is an open set containing `x` and not `y`. -/ class t1_space (α : Type u) [topological_space α] : Prop := (t1 : ∀x, is_closed ({x} : set α)) lemma is_closed_singleton [t1_space α] {x : α} : is_closed ({x} : set α) := t1_space.t1 x lemma is_open_compl_singleton [t1_space α] {x : α} : is_open ({x}ᶜ : set α) := is_closed_singleton.is_open_compl lemma is_open_ne [t1_space α] {x : α} : is_open {y | y ≠ x} := is_open_compl_singleton instance subtype.t1_space {α : Type u} [topological_space α] [t1_space α] {p : α → Prop} : t1_space (subtype p) := ⟨λ ⟨x, hx⟩, is_closed_induced_iff.2 $ ⟨{x}, is_closed_singleton, set.ext $ λ y, by simp [subtype.ext_iff_val]⟩⟩ @[priority 100] -- see Note [lower instance priority] instance t1_space.t0_space [t1_space α] : t0_space α := ⟨λ x y h, ⟨{z | z ≠ y}, is_open_ne, or.inl ⟨h, not_not_intro rfl⟩⟩⟩ lemma compl_singleton_mem_nhds [t1_space α] {x y : α} (h : y ≠ x) : {x}ᶜ ∈ 𝓝 y := mem_nhds_sets is_open_compl_singleton $ by rwa [mem_compl_eq, mem_singleton_iff] @[simp] lemma closure_singleton [t1_space α] {a : α} : closure ({a} : set α) = {a} := is_closed_singleton.closure_eq lemma set.subsingleton.closure [t1_space α] {s : set α} (hs : s.subsingleton) : (closure s).subsingleton := hs.induction_on (by simp) $ λ x, by simp @[simp] lemma subsingleton_closure [t1_space α] {s : set α} : (closure s).subsingleton ↔ s.subsingleton := ⟨λ h, h.mono subset_closure, λ h, h.closure⟩ lemma is_closed_map_const {α β} [topological_space α] [topological_space β] [t1_space β] {y : β} : is_closed_map (function.const α y) := begin apply is_closed_map.of_nonempty, intros s hs h2s, simp_rw [h2s.image_const, is_closed_singleton] end lemma discrete_of_t1_of_finite {X : Type*} [topological_space X] [t1_space X] [fintype X] : discrete_topology X := begin apply singletons_open_iff_discrete.mp, intros x, rw [← is_closed_compl_iff, ← bUnion_of_singleton ({x} : set X)ᶜ], exact is_closed_bUnion (finite.of_fintype _) (λ y _, is_closed_singleton) end lemma singleton_mem_nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : {x} ∈ 𝓝[s] x := begin have : ({⟨x, hx⟩} : set s) ∈ 𝓝 (⟨x, hx⟩ : s), by simp [nhds_discrete], simpa only [nhds_within_eq_map_subtype_coe hx, image_singleton] using @image_mem_map _ _ _ (coe : s → α) _ this end lemma nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : 𝓝[s] x = pure x := le_antisymm (le_pure_iff.2 $ singleton_mem_nhds_within_of_mem_discrete hx) (pure_le_nhds_within hx) lemma filter.has_basis.exists_inter_eq_singleton_of_mem_discrete {ι : Type*} {p : ι → Prop} {t : ι → set α} {s : set α} [discrete_topology s] {x : α} (hb : (𝓝 x).has_basis p t) (hx : x ∈ s) : ∃ i (hi : p i), t i ∩ s = {x} := begin rcases (nhds_within_has_basis hb s).mem_iff.1 (singleton_mem_nhds_within_of_mem_discrete hx) with ⟨i, hi, hix⟩, exact ⟨i, hi, subset.antisymm hix $ singleton_subset_iff.2 ⟨mem_of_nhds $ hb.mem_of_mem hi, hx⟩⟩ end /-- A point `x` in a discrete subset `s` of a topological space admits a neighbourhood that only meets `s` at `x`. -/ lemma nhds_inter_eq_singleton_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ U ∈ 𝓝 x, U ∩ s = {x} := by simpa using (𝓝 x).basis_sets.exists_inter_eq_singleton_of_mem_discrete hx /-- For point `x` in a discrete subset `s` of a topological space, there is a set `U` such that 1. `U` is a punctured neighborhood of `x` (ie. `U ∪ {x}` is a neighbourhood of `x`), 2. `U` is disjoint from `s`. -/ lemma disjoint_nhds_within_of_mem_discrete {s : set α} [discrete_topology s] {x : α} (hx : x ∈ s) : ∃ U ∈ 𝓝[{x}ᶜ] x, disjoint U s := let ⟨V, h, h'⟩ := nhds_inter_eq_singleton_of_mem_discrete hx in ⟨{x}ᶜ ∩ V, inter_mem_nhds_within _ h, (disjoint_iff_inter_eq_empty.mpr (by { rw [inter_assoc, h', compl_inter_self] }))⟩ /-- Let `X` be a topological space and let `s, t ⊆ X` be two subsets. If there is an inclusion `t ⊆ s`, then the topological space structure on `t` induced by `X` is the same as the one obtained by the induced topological space structure on `s`. -/ lemma topological_space.subset_trans {X : Type*} [tX : topological_space X] {s t : set X} (ts : t ⊆ s) : (subtype.topological_space : topological_space t) = (subtype.topological_space : topological_space s).induced (set.inclusion ts) := begin change tX.induced ((coe : s → X) ∘ (set.inclusion ts)) = topological_space.induced (set.inclusion ts) (tX.induced _), rw ← induced_compose, end /-- This lemma characterizes discrete topological spaces as those whose singletons are neighbourhoods. -/ lemma discrete_topology_iff_nhds {X : Type*} [topological_space X] : discrete_topology X ↔ (nhds : X → filter X) = pure := begin split, { introI hX, exact nhds_discrete X }, { intro h, constructor, apply eq_of_nhds_eq_nhds, simp [h, nhds_bot] } end /-- The topology pulled-back under an inclusion `f : X → Y` from the discrete topology (`⊥`) is the discrete topology. This version does not assume the choice of a topology on either the source `X` nor the target `Y` of the inclusion `f`. -/ lemma induced_bot {X Y : Type*} {f : X → Y} (hf : function.injective f) : topological_space.induced f ⊥ = ⊥ := eq_of_nhds_eq_nhds (by simp [nhds_induced, ← set.image_singleton, hf.preimage_image, nhds_bot]) /-- The topology induced under an inclusion `f : X → Y` from the discrete topological space `Y` is the discrete topology on `X`. -/ lemma discrete_topology_induced {X Y : Type*} [tY : topological_space Y] [discrete_topology Y] {f : X → Y} (hf : function.injective f) : @discrete_topology X (topological_space.induced f tY) := begin constructor, rw discrete_topology.eq_bot Y, exact induced_bot hf end /-- Let `s, t ⊆ X` be two subsets of a topological space `X`. If `t ⊆ s` and the topology induced by `X`on `s` is discrete, then also the topology induces on `t` is discrete. -/ lemma discrete_topology.of_subset {X : Type*} [topological_space X] {s t : set X} (ds : discrete_topology s) (ts : t ⊆ s) : discrete_topology t := begin rw [topological_space.subset_trans ts, ds.eq_bot], exact {eq_bot := induced_bot (set.inclusion_injective ts)} end /-- A T₂ space, also known as a Hausdorff space, is one in which for every `x ≠ y` there exists disjoint open sets around `x` and `y`. This is the most widely used of the separation axioms. -/ class t2_space (α : Type u) [topological_space α] : Prop := (t2 : ∀x y, x ≠ y → ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅) lemma t2_separation [t2_space α] {x y : α} (h : x ≠ y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := t2_space.t2 x y h @[priority 100] -- see Note [lower instance priority] instance t2_space.t1_space [t2_space α] : t1_space α := ⟨λ x, is_open_compl_iff.1 $ is_open_iff_forall_mem_open.2 $ λ y hxy, let ⟨u, v, hu, hv, hyu, hxv, huv⟩ := t2_separation (mt mem_singleton_of_eq hxy) in ⟨u, λ z hz1 hz2, (ext_iff.1 huv x).1 ⟨mem_singleton_iff.1 hz2 ▸ hz1, hxv⟩, hu, hyu⟩⟩ lemma eq_of_nhds_ne_bot [ht : t2_space α] {x y : α} (h : ne_bot (𝓝 x ⊓ 𝓝 y)) : x = y := classical.by_contradiction $ assume : x ≠ y, let ⟨u, v, hu, hv, hx, hy, huv⟩ := t2_space.t2 x y this in absurd huv $ (inf_ne_bot_iff.1 h (mem_nhds_sets hu hx) (mem_nhds_sets hv hy)).ne_empty lemma t2_iff_nhds : t2_space α ↔ ∀ {x y : α}, ne_bot (𝓝 x ⊓ 𝓝 y) → x = y := ⟨assume h, by exactI λ x y, eq_of_nhds_ne_bot, assume h, ⟨assume x y xy, have 𝓝 x ⊓ 𝓝 y = ⊥ := not_ne_bot.1 $ mt h xy, let ⟨u', hu', v', hv', u'v'⟩ := empty_in_sets_eq_bot.mpr this, ⟨u, uu', uo, hu⟩ := mem_nhds_sets_iff.mp hu', ⟨v, vv', vo, hv⟩ := mem_nhds_sets_iff.mp hv' in ⟨u, v, uo, vo, hu, hv, disjoint.eq_bot $ disjoint.mono uu' vv' u'v'⟩⟩⟩ lemma t2_iff_ultrafilter : t2_space α ↔ ∀ {x y : α} (f : ultrafilter α), ↑f ≤ 𝓝 x → ↑f ≤ 𝓝 y → x = y := t2_iff_nhds.trans $ by simp only [←exists_ultrafilter_iff, and_imp, le_inf_iff, exists_imp_distrib] lemma is_closed_diagonal [t2_space α] : is_closed (diagonal α) := begin refine is_closed_iff_cluster_pt.mpr _, rintro ⟨a₁, a₂⟩ h, refine eq_of_nhds_ne_bot ⟨λ this : 𝓝 a₁ ⊓ 𝓝 a₂ = ⊥, h.ne _⟩, obtain ⟨t₁, (ht₁ : t₁ ∈ 𝓝 a₁), t₂, (ht₂ : t₂ ∈ 𝓝 a₂), (h' : t₁ ∩ t₂ ⊆ ∅)⟩ := by rw [←empty_in_sets_eq_bot, mem_inf_sets] at this; exact this, rw [nhds_prod_eq, ←empty_in_sets_eq_bot], apply filter.sets_of_superset, apply inter_mem_inf_sets (prod_mem_prod ht₁ ht₂) (mem_principal_sets.mpr (subset.refl _)), exact assume ⟨x₁, x₂⟩ ⟨⟨hx₁, hx₂⟩, (heq : x₁ = x₂)⟩, show false, from @h' x₁ ⟨hx₁, heq.symm ▸ hx₂⟩ end lemma t2_iff_is_closed_diagonal : t2_space α ↔ is_closed (diagonal α) := begin split, { introI h, exact is_closed_diagonal }, { intro h, constructor, intros x y hxy, have : (x, y) ∈ (diagonal α)ᶜ, by rwa [mem_compl_iff], obtain ⟨t, t_sub, t_op, xyt⟩ : ∃ t ⊆ (diagonal α)ᶜ, is_open t ∧ (x, y) ∈ t := is_open_iff_forall_mem_open.mp h.is_open_compl _ this, rcases is_open_prod_iff.mp t_op x y xyt with ⟨U, V, U_op, V_op, xU, yV, H⟩, use [U, V, U_op, V_op, xU, yV], have := subset.trans H t_sub, rw eq_empty_iff_forall_not_mem, rintros z ⟨zU, zV⟩, have : ¬ (z, z) ∈ diagonal α := this (mk_mem_prod zU zV), exact this rfl }, end section separated open separated finset lemma finset_disjoint_finset_opens_of_t2 [t2_space α] : ∀ (s t : finset α), disjoint s t → separated (s : set α) t := begin refine induction_on_union _ (λ a b hi d, (hi d.symm).symm) (λ a d, empty_right a) (λ a b ab, _) _, { obtain ⟨U, V, oU, oV, aU, bV, UV⟩ := t2_separation (by { rw [ne.def, ← finset.mem_singleton], exact (disjoint_singleton.mp ab.symm) }), refine ⟨U, V, oU, oV, _, _, set.disjoint_iff_inter_eq_empty.mpr UV⟩; exact singleton_subset_set_iff.mpr ‹_› }, { intros a b c ac bc d, apply_mod_cast union_left (ac (disjoint_of_subset_left (a.subset_union_left b) d)) (bc _), exact disjoint_of_subset_left (a.subset_union_right b) d }, end lemma point_disjoint_finset_opens_of_t2 [t2_space α] {x : α} {s : finset α} (h : x ∉ s) : separated ({x} : set α) ↑s := by exact_mod_cast finset_disjoint_finset_opens_of_t2 {x} s (singleton_disjoint.mpr h) end separated @[simp] lemma nhds_eq_nhds_iff {a b : α} [t2_space α] : 𝓝 a = 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [h, inf_idem]; exact nhds_ne_bot, assume h, h ▸ rfl⟩ @[simp] lemma nhds_le_nhds_iff {a b : α} [t2_space α] : 𝓝 a ≤ 𝓝 b ↔ a = b := ⟨assume h, eq_of_nhds_ne_bot $ by rw [inf_of_le_left h]; exact nhds_ne_bot, assume h, h ▸ le_refl _⟩ lemma tendsto_nhds_unique [t2_space α] {f : β → α} {l : filter β} {a b : α} [ne_bot l] (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb lemma tendsto_nhds_unique' [t2_space α] {f : β → α} {l : filter β} {a b : α} (hl : ne_bot l) (ha : tendsto f l (𝓝 a)) (hb : tendsto f l (𝓝 b)) : a = b := eq_of_nhds_ne_bot $ ne_bot_of_le $ le_inf ha hb section lim variables [t2_space α] {f : filter α} /-! ### Properties of `Lim` and `lim` In this section we use explicit `nonempty α` instances for `Lim` and `lim`. This way the lemmas are useful without a `nonempty α` instance. -/ lemma Lim_eq {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : @Lim _ _ ⟨a⟩ f = a := tendsto_nhds_unique (le_nhds_Lim ⟨a, h⟩) h lemma Lim_eq_iff [ne_bot f] (h : ∃ (a : α), f ≤ nhds a) {a} : @Lim _ _ ⟨a⟩ f = a ↔ f ≤ 𝓝 a := ⟨λ c, c ▸ le_nhds_Lim h, Lim_eq⟩ lemma ultrafilter.Lim_eq_iff_le_nhds [compact_space α] {x : α} {F : ultrafilter α} : F.Lim = x ↔ ↑F ≤ 𝓝 x := ⟨λ h, h ▸ F.le_nhds_Lim, Lim_eq⟩ lemma is_open_iff_ultrafilter' [compact_space α] (U : set α) : is_open U ↔ (∀ F : ultrafilter α, F.Lim ∈ U → U ∈ F.1) := begin rw is_open_iff_ultrafilter, refine ⟨λ h F hF, h F.Lim hF F F.le_nhds_Lim, _⟩, intros cond x hx f h, rw [← (ultrafilter.Lim_eq_iff_le_nhds.2 h)] at hx, exact cond _ hx end lemma filter.tendsto.lim_eq {a : α} {f : filter β} [ne_bot f] {g : β → α} (h : tendsto g f (𝓝 a)) : @lim _ _ _ ⟨a⟩ f g = a := Lim_eq h lemma filter.lim_eq_iff {f : filter β} [ne_bot f] {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) {a} : @lim _ _ _ ⟨a⟩ f g = a ↔ tendsto g f (𝓝 a) := ⟨λ c, c ▸ tendsto_nhds_lim h, filter.tendsto.lim_eq⟩ lemma continuous.lim_eq [topological_space β] {f : β → α} (h : continuous f) (a : β) : @lim _ _ _ ⟨f a⟩ (𝓝 a) f = f a := (h.tendsto a).lim_eq @[simp] lemma Lim_nhds (a : α) : @Lim _ _ ⟨a⟩ (𝓝 a) = a := Lim_eq (le_refl _) @[simp] lemma lim_nhds_id (a : α) : @lim _ _ _ ⟨a⟩ (𝓝 a) id = a := Lim_nhds a @[simp] lemma Lim_nhds_within {a : α} {s : set α} (h : a ∈ closure s) : @Lim _ _ ⟨a⟩ (𝓝[s] a) = a := by haveI : ne_bot (𝓝[s] a) := mem_closure_iff_cluster_pt.1 h; exact Lim_eq inf_le_left @[simp] lemma lim_nhds_within_id {a : α} {s : set α} (h : a ∈ closure s) : @lim _ _ _ ⟨a⟩ (𝓝[s] a) id = a := Lim_nhds_within h end lim /-! ### Instances of `t2_space` typeclass We use two lemmas to prove that various standard constructions generate Hausdorff spaces from Hausdorff spaces: * `separated_by_continuous` says that two points `x y : α` can be separated by open neighborhoods provided that there exists a continuous map `f`: α → β` with a Hausdorff codomain such that `f x ≠ f y`. We use this lemma to prove that topological spaces defined using `induced` are Hausdorff spaces. * `separated_by_open_embedding` says that for an open embedding `f : α → β` of a Hausdorff space `α`, the images of two distinct points `x y : α`, `x ≠ y` can be separated by open neighborhoods. We use this lemma to prove that topological spaces defined using `coinduced` are Hausdorff spaces. -/ @[priority 100] -- see Note [lower instance priority] instance t2_space_discrete {α : Type*} [topological_space α] [discrete_topology α] : t2_space α := { t2 := assume x y hxy, ⟨{x}, {y}, is_open_discrete _, is_open_discrete _, rfl, rfl, eq_empty_iff_forall_not_mem.2 $ by intros z hz; cases eq_of_mem_singleton hz.1; cases eq_of_mem_singleton hz.2; cc⟩ } lemma separated_by_continuous {α : Type*} {β : Type*} [topological_space α] [topological_space β] [t2_space β] {f : α → β} (hf : continuous f) {x y : α} (h : f x ≠ f y) : ∃u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f ⁻¹' u, f ⁻¹' v, uo.preimage hf, vo.preimage hf, xu, yv, by rw [←preimage_inter, uv, preimage_empty]⟩ lemma separated_by_open_embedding {α β : Type*} [topological_space α] [topological_space β] [t2_space α] {f : α → β} (hf : open_embedding f) {x y : α} (h : x ≠ y) : ∃ u v : set β, is_open u ∧ is_open v ∧ f x ∈ u ∧ f y ∈ v ∧ u ∩ v = ∅ := let ⟨u, v, uo, vo, xu, yv, uv⟩ := t2_separation h in ⟨f '' u, f '' v, hf.is_open_map _ uo, hf.is_open_map _ vo, mem_image_of_mem _ xu, mem_image_of_mem _ yv, by rw [image_inter hf.inj, uv, image_empty]⟩ instance {α : Type*} {p : α → Prop} [t : topological_space α] [t2_space α] : t2_space (subtype p) := ⟨assume x y h, separated_by_continuous continuous_subtype_val (mt subtype.eq h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α × β) := ⟨assume ⟨x₁,x₂⟩ ⟨y₁,y₂⟩ h, or.elim (not_and_distrib.mp (mt prod.ext_iff.mpr h)) (λ h₁, separated_by_continuous continuous_fst h₁) (λ h₂, separated_by_continuous continuous_snd h₂)⟩ lemma embedding.t2_space [topological_space β] [t2_space β] {f : α → β} (hf : embedding f) : t2_space α := ⟨λ x y h, separated_by_continuous hf.continuous (hf.inj.ne h)⟩ instance {α : Type*} {β : Type*} [t₁ : topological_space α] [t2_space α] [t₂ : topological_space β] [t2_space β] : t2_space (α ⊕ β) := begin constructor, rintros (x|x) (y|y) h, { replace h : x ≠ y := λ c, (c.subst h) rfl, exact separated_by_open_embedding open_embedding_inl h }, { exact ⟨_, _, is_open_range_inl, is_open_range_inr, ⟨x, rfl⟩, ⟨y, rfl⟩, range_inl_inter_range_inr⟩ }, { exact ⟨_, _, is_open_range_inr, is_open_range_inl, ⟨x, rfl⟩, ⟨y, rfl⟩, range_inr_inter_range_inl⟩ }, { replace h : x ≠ y := λ c, (c.subst h) rfl, exact separated_by_open_embedding open_embedding_inr h } end instance Pi.t2_space {α : Type*} {β : α → Type v} [t₂ : Πa, topological_space (β a)] [∀a, t2_space (β a)] : t2_space (Πa, β a) := ⟨assume x y h, let ⟨i, hi⟩ := not_forall.mp (mt funext h) in separated_by_continuous (continuous_apply i) hi⟩ instance sigma.t2_space {ι : Type*} {α : ι → Type*} [Πi, topological_space (α i)] [∀a, t2_space (α a)] : t2_space (Σi, α i) := begin constructor, rintros ⟨i, x⟩ ⟨j, y⟩ neq, rcases em (i = j) with (rfl|h), { replace neq : x ≠ y := λ c, (c.subst neq) rfl, exact separated_by_open_embedding open_embedding_sigma_mk neq }, { exact ⟨_, _, is_open_range_sigma_mk, is_open_range_sigma_mk, ⟨x, rfl⟩, ⟨y, rfl⟩, by tidy⟩ } end variables [topological_space β] lemma is_closed_eq [t2_space α] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {x:β | f x = g x} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_diagonal /-- If two continuous maps are equal on `s`, then they are equal on the closure of `s`. -/ lemma set.eq_on.closure [t2_space α] {s : set β} {f g : β → α} (h : eq_on f g s) (hf : continuous f) (hg : continuous g) : eq_on f g (closure s) := closure_minimal h (is_closed_eq hf hg) /-- If two continuous functions are equal on a dense set, then they are equal. -/ lemma continuous.ext_on [t2_space α] {s : set β} (hs : dense s) {f g : β → α} (hf : continuous f) (hg : continuous g) (h : eq_on f g s) : f = g := funext $ λ x, h.closure hf hg (hs x) lemma function.left_inverse.closed_range [t2_space α] {f : α → β} {g : β → α} (h : function.left_inverse f g) (hf : continuous f) (hg : continuous g) : is_closed (range g) := have eq_on (g ∘ f) id (closure $ range g), from h.right_inv_on_range.eq_on.closure (hg.comp hf) continuous_id, is_closed_of_closure_subset $ λ x hx, calc x = g (f x) : (this hx).symm ... ∈ _ : mem_range_self _ lemma function.left_inverse.closed_embedding [t2_space α] {f : α → β} {g : β → α} (h : function.left_inverse f g) (hf : continuous f) (hg : continuous g) : closed_embedding g := ⟨h.embedding hf hg, h.closed_range hf hg⟩ lemma diagonal_eq_range_diagonal_map {α : Type*} : {p:α×α | p.1 = p.2} = range (λx, (x,x)) := ext $ assume p, iff.intro (assume h, ⟨p.1, prod.ext_iff.2 ⟨rfl, h⟩⟩) (assume ⟨x, hx⟩, show p.1 = p.2, by rw ←hx) lemma prod_subset_compl_diagonal_iff_disjoint {α : Type*} {s t : set α} : set.prod s t ⊆ {p:α×α | p.1 = p.2}ᶜ ↔ s ∩ t = ∅ := by rw [eq_empty_iff_forall_not_mem, subset_compl_comm, diagonal_eq_range_diagonal_map, range_subset_iff]; simp lemma compact_compact_separated [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) (hst : s ∩ t = ∅) : ∃u v : set α, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ u ∩ v = ∅ := by simp only [prod_subset_compl_diagonal_iff_disjoint.symm] at ⊢ hst; exact generalized_tube_lemma hs ht is_closed_diagonal.is_open_compl hst /-- In a `t2_space`, every compact set is closed. -/ lemma is_compact.is_closed [t2_space α] {s : set α} (hs : is_compact s) : is_closed s := is_open_compl_iff.1 $ is_open_iff_forall_mem_open.mpr $ assume x hx, let ⟨u, v, uo, vo, su, xv, uv⟩ := compact_compact_separated hs (compact_singleton : is_compact {x}) (by rwa [inter_comm, ←subset_compl_iff_disjoint, singleton_subset_iff]) in have v ⊆ sᶜ, from subset_compl_comm.mp (subset.trans su (subset_compl_iff_disjoint.mpr uv)), ⟨v, this, vo, by simpa using xv⟩ lemma compact_exhaustion.is_closed [t2_space α] (K : compact_exhaustion α) (n : ℕ) : is_closed (K n) := (K.is_compact n).is_closed lemma is_compact.inter [t2_space α] {s t : set α} (hs : is_compact s) (ht : is_compact t) : is_compact (s ∩ t) := hs.inter_right $ ht.is_closed lemma compact_closure_of_subset_compact [t2_space α] {s t : set α} (ht : is_compact t) (h : s ⊆ t) : is_compact (closure s) := compact_of_is_closed_subset ht is_closed_closure (closure_minimal h ht.is_closed) lemma image_closure_of_compact [t2_space β] {s : set α} (hs : is_compact (closure s)) {f : α → β} (hf : continuous_on f (closure s)) : f '' closure s = closure (f '' s) := subset.antisymm hf.image_closure $ closure_minimal (image_subset f subset_closure) (hs.image_of_continuous_on hf).is_closed /-- If a compact set is covered by two open sets, then we can cover it by two compact subsets. -/ lemma is_compact.binary_compact_cover [t2_space α] {K U V : set α} (hK : is_compact K) (hU : is_open U) (hV : is_open V) (h2K : K ⊆ U ∪ V) : ∃ K₁ K₂ : set α, is_compact K₁ ∧ is_compact K₂ ∧ K₁ ⊆ U ∧ K₂ ⊆ V ∧ K = K₁ ∪ K₂ := begin rcases compact_compact_separated (compact_diff hK hU) (compact_diff hK hV) (by rwa [diff_inter_diff, diff_eq_empty]) with ⟨O₁, O₂, h1O₁, h1O₂, h2O₁, h2O₂, hO⟩, refine ⟨_, _, compact_diff hK h1O₁, compact_diff hK h1O₂, by rwa [diff_subset_comm], by rwa [diff_subset_comm], by rw [← diff_inter, hO, diff_empty]⟩ end lemma continuous.is_closed_map [compact_space α] [t2_space β] {f : α → β} (h : continuous f) : is_closed_map f := λ s hs, (hs.compact.image h).is_closed lemma continuous.closed_embedding [compact_space α] [t2_space β] {f : α → β} (h : continuous f) (hf : function.injective f) : closed_embedding f := closed_embedding_of_continuous_injective_closed h hf h.is_closed_map section open finset function /-- For every finite open cover `Uᵢ` of a compact set, there exists a compact cover `Kᵢ ⊆ Uᵢ`. -/ lemma is_compact.finite_compact_cover [t2_space α] {s : set α} (hs : is_compact s) {ι} (t : finset ι) (U : ι → set α) (hU : ∀ i ∈ t, is_open (U i)) (hsC : s ⊆ ⋃ i ∈ t, U i) : ∃ K : ι → set α, (∀ i, is_compact (K i)) ∧ (∀i, K i ⊆ U i) ∧ s = ⋃ i ∈ t, K i := begin classical, induction t using finset.induction with x t hx ih generalizing U hU s hs hsC, { refine ⟨λ _, ∅, λ i, compact_empty, λ i, empty_subset _, _⟩, simpa only [subset_empty_iff, finset.not_mem_empty, Union_neg, Union_empty, not_false_iff] using hsC }, simp only [finset.set_bUnion_insert] at hsC, simp only [finset.mem_insert] at hU, have hU' : ∀ i ∈ t, is_open (U i) := λ i hi, hU i (or.inr hi), rcases hs.binary_compact_cover (hU x (or.inl rfl)) (is_open_bUnion hU') hsC with ⟨K₁, K₂, h1K₁, h1K₂, h2K₁, h2K₂, hK⟩, rcases ih U hU' h1K₂ h2K₂ with ⟨K, h1K, h2K, h3K⟩, refine ⟨update K x K₁, _, _, _⟩, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h1K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h1K] }}, { intros i, by_cases hi : i = x, { simp only [update_same, hi, h2K₁] }, { rw [← ne.def] at hi, simp only [update_noteq hi, h2K] }}, { simp only [set_bUnion_insert_update _ hx, hK, h3K] } end end lemma locally_compact_of_compact_nhds [t2_space α] (h : ∀ x : α, ∃ s, s ∈ 𝓝 x ∧ is_compact s) : locally_compact_space α := ⟨assume x n hn, let ⟨u, un, uo, xu⟩ := mem_nhds_sets_iff.mp hn in let ⟨k, kx, kc⟩ := h x in -- K is compact but not necessarily contained in N. -- K \ U is again compact and doesn't contain x, so -- we may find open sets V, W separating x from K \ U. -- Then K \ W is a compact neighborhood of x contained in U. let ⟨v, w, vo, wo, xv, kuw, vw⟩ := compact_compact_separated compact_singleton (compact_diff kc uo) (by rw [singleton_inter_eq_empty]; exact λ h, h.2 xu) in have wn : wᶜ ∈ 𝓝 x, from mem_nhds_sets_iff.mpr ⟨v, subset_compl_iff_disjoint.mpr vw, vo, singleton_subset_iff.mp xv⟩, ⟨k \ w, filter.inter_mem_sets kx wn, subset.trans (diff_subset_comm.mp kuw) un, compact_diff kc wo⟩⟩ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_compact [t2_space α] [compact_space α] : locally_compact_space α := locally_compact_of_compact_nhds (assume x, ⟨univ, mem_nhds_sets is_open_univ trivial, compact_univ⟩) /-- In a locally compact T₂ space, every point has an open neighborhood with compact closure -/ lemma exists_open_with_compact_closure [locally_compact_space α] [t2_space α] (x : α) : ∃ (U : set α), is_open U ∧ x ∈ U ∧ is_compact (closure U) := begin rcases exists_compact_mem_nhds x with ⟨K, hKc, hxK⟩, rcases mem_nhds_sets_iff.1 hxK with ⟨t, h1t, h2t, h3t⟩, exact ⟨t, h2t, h3t, compact_closure_of_subset_compact hKc h1t⟩ end end separation section regularity /-- A T₃ space, also known as a regular space (although this condition sometimes omits T₂), is one in which for every closed `C` and `x ∉ C`, there exist disjoint open sets containing `x` and `C` respectively. -/ class regular_space (α : Type u) [topological_space α] extends t1_space α : Prop := (regular : ∀{s:set α} {a}, is_closed s → a ∉ s → ∃t, is_open t ∧ s ⊆ t ∧ 𝓝[t] a = ⊥) lemma nhds_is_closed [regular_space α] {a : α} {s : set α} (h : s ∈ 𝓝 a) : ∃ t ∈ 𝓝 a, t ⊆ s ∧ is_closed t := let ⟨s', h₁, h₂, h₃⟩ := mem_nhds_sets_iff.mp h in have ∃t, is_open t ∧ s'ᶜ ⊆ t ∧ 𝓝[t] a = ⊥, from regular_space.regular (is_closed_compl_iff.mpr h₂) (not_not_intro h₃), let ⟨t, ht₁, ht₂, ht₃⟩ := this in ⟨tᶜ, mem_sets_of_eq_bot $ by rwa [compl_compl], subset.trans (compl_subset_comm.1 ht₂) h₁, is_closed_compl_iff.mpr ht₁⟩ lemma closed_nhds_basis [regular_space α] (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_closed s) id := ⟨λ t, ⟨λ t_in, let ⟨s, s_in, h_st, h⟩ := nhds_is_closed t_in in ⟨s, ⟨s_in, h⟩, h_st⟩, λ ⟨s, ⟨s_in, hs⟩, hst⟩, mem_sets_of_superset s_in hst⟩⟩ instance subtype.regular_space [regular_space α] {p : α → Prop} : regular_space (subtype p) := ⟨begin intros s a hs ha, rcases is_closed_induced_iff.1 hs with ⟨s, hs', rfl⟩, rcases regular_space.regular hs' ha with ⟨t, ht, hst, hat⟩, refine ⟨coe ⁻¹' t, is_open_induced ht, preimage_mono hst, _⟩, rw [nhds_within, nhds_induced, ← comap_principal, ← comap_inf, ← nhds_within, hat, comap_bot] end⟩ variable (α) @[priority 100] -- see Note [lower instance priority] instance regular_space.t2_space [regular_space α] : t2_space α := ⟨λ x y hxy, let ⟨s, hs, hys, hxs⟩ := regular_space.regular is_closed_singleton (mt mem_singleton_iff.1 hxy), ⟨t, hxt, u, hsu, htu⟩ := empty_in_sets_eq_bot.2 hxs, ⟨v, hvt, hv, hxv⟩ := mem_nhds_sets_iff.1 hxt in ⟨v, s, hv, hs, hxv, singleton_subset_iff.1 hys, eq_empty_of_subset_empty $ λ z ⟨hzv, hzs⟩, htu ⟨hvt hzv, hsu hzs⟩⟩⟩ variable {α} lemma disjoint_nested_nhds [regular_space α] {x y : α} (h : x ≠ y) : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ U₁ ∩ U₂ = ∅ := begin rcases t2_separation h with ⟨U₁, U₂, U₁_op, U₂_op, x_in, y_in, H⟩, rcases nhds_is_closed (mem_nhds_sets U₁_op x_in) with ⟨V₁, V₁_in, h₁, V₁_closed⟩, rcases nhds_is_closed (mem_nhds_sets U₂_op y_in) with ⟨V₂, V₂_in, h₂, V₂_closed⟩, use [U₁, V₁, mem_sets_of_superset V₁_in h₁, V₁_in, U₂, V₂, mem_sets_of_superset V₂_in h₂, V₂_in], tauto end end regularity section normality /-- A T₄ space, also known as a normal space (although this condition sometimes omits T₂), is one in which for every pair of disjoint closed sets `C` and `D`, there exist disjoint open sets containing `C` and `D` respectively. -/ class normal_space (α : Type u) [topological_space α] extends t1_space α : Prop := (normal : ∀ s t : set α, is_closed s → is_closed t → disjoint s t → ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v) theorem normal_separation [normal_space α] {s t : set α} (H1 : is_closed s) (H2 : is_closed t) (H3 : disjoint s t) : ∃ u v, is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v := normal_space.normal s t H1 H2 H3 theorem normal_exists_closure_subset [normal_space α] {s t : set α} (hs : is_closed s) (ht : is_open t) (hst : s ⊆ t) : ∃ u, is_open u ∧ s ⊆ u ∧ closure u ⊆ t := begin have : disjoint s tᶜ, from λ x ⟨hxs, hxt⟩, hxt (hst hxs), rcases normal_separation hs (is_closed_compl_iff.2 ht) this with ⟨s', t', hs', ht', hss', htt', hs't'⟩, refine ⟨s', hs', hss', subset.trans (closure_minimal _ (is_closed_compl_iff.2 ht')) (compl_subset_comm.1 htt')⟩, exact λ x hxs hxt, hs't' ⟨hxs, hxt⟩ end @[priority 100] -- see Note [lower instance priority] instance normal_space.regular_space [normal_space α] : regular_space α := { regular := λ s x hs hxs, let ⟨u, v, hu, hv, hsu, hxv, huv⟩ := normal_separation hs is_closed_singleton (λ _ ⟨hx, hy⟩, hxs $ mem_of_eq_of_mem (eq_of_mem_singleton hy).symm hx) in ⟨u, hu, hsu, filter.empty_in_sets_eq_bot.1 $ filter.mem_inf_sets.2 ⟨v, mem_nhds_sets hv (singleton_subset_iff.1 hxv), u, filter.mem_principal_self u, inter_comm u v ▸ huv⟩⟩ } -- We can't make this an instance because it could cause an instance loop. lemma normal_of_compact_t2 [compact_space α] [t2_space α] : normal_space α := begin refine ⟨assume s t hs ht st, _⟩, simp only [disjoint_iff], exact compact_compact_separated hs.compact ht.compact st.eq_bot end end normality /-- In a compact t2 space, the connected component of a point equals the intersection of all its clopen neighbourhoods. -/ lemma connected_component_eq_Inter_clopen [t2_space α] [compact_space α] {x : α} : connected_component x = ⋂ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z := begin apply eq_of_subset_of_subset connected_component_subset_Inter_clopen, -- Reduce to showing that the clopen intersection is connected. refine is_preconnected.subset_connected_component _ (mem_Inter.2 (λ Z, Z.2.2)), -- We do this by showing that any disjoint cover by two closed sets implies -- that one of these closed sets must contain our whole thing. -- To reduce to the case where the cover is disjoint on all of `α` we need that `s` is closed have hs : @is_closed _ _inst_1 (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) := is_closed_Inter (λ Z, Z.2.1.2), rw (is_preconnected_iff_subset_of_fully_disjoint_closed hs), intros a b ha hb hab ab_empty, haveI := @normal_of_compact_t2 α _ _ _, -- Since our space is normal, we get two larger disjoint open sets containing the disjoint -- closed sets. If we can show that our intersection is a subset of any of these we can then -- "descend" this to show that it is a subset of either a or b. rcases normal_separation ha hb (disjoint_iff.2 ab_empty) with ⟨u, v, hu, hv, hau, hbv, huv⟩, -- If we can find a clopen set around x, contained in u ∪ v, we get a disjoint decomposition -- Z = Z ∩ u ∪ Z ∩ v of clopen sets. The intersection of all clopen neighbourhoods will then lie -- in whichever of u or v x lies in and hence will be a subset of either a or b. suffices : ∃ (Z : set α), is_clopen Z ∧ x ∈ Z ∧ Z ⊆ u ∪ v, { cases this with Z H, rw [disjoint_iff_inter_eq_empty] at huv, have H1 := is_clopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hu hv huv, rw [union_comm] at H, have H2 := is_clopen_inter_of_disjoint_cover_clopen H.1 H.2.2 hv hu (inter_comm u v ▸ huv), by_cases (x ∈ u), -- The x ∈ u case. { left, suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ u, { rw ←set.disjoint_iff_inter_eq_empty at huv, replace hab : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ a ∪ b := hab, replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ u := this, exact disjoint.left_le_of_le_sup_right hab (huv.mono this hbv) }, { apply subset.trans _ (inter_subset_right Z u), apply Inter_subset (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, ↑Z) ⟨Z ∩ u, H1, mem_inter H.2.1 h⟩ } }, -- If x ∉ u, we get x ∈ v since x ∈ u ∪ v. The rest is then like the x ∈ u case. have h1 : x ∈ v, { cases (mem_union x u v).1 (mem_of_subset_of_mem (subset.trans hab (union_subset_union hau hbv)) (mem_Inter.2 (λ i, i.2.2))) with h1 h1, { exfalso, exact h h1}, { exact h1} }, right, suffices : (⋂ (Z : {Z : set α // is_clopen Z ∧ x ∈ Z}), ↑Z) ⊆ v, { rw [inter_comm, ←set.disjoint_iff_inter_eq_empty] at huv, replace hab : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ a ∪ b := hab, replace this : (⋂ (Z : {Z // is_clopen Z ∧ x ∈ Z}), ↑Z) ≤ v := this, exact disjoint.left_le_of_le_sup_left hab (huv.mono this hau) }, { apply subset.trans _ (inter_subset_right Z v), apply Inter_subset (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, ↑Z) ⟨Z ∩ v, H2, mem_inter H.2.1 h1⟩ } }, -- Now we find the required Z. We utilize the fact that X \ u ∪ v will be compact, -- so there must be some finite intersection of clopen neighbourhoods of X disjoint to it, -- but a finite intersection of clopen sets is clopen so we let this be our Z. have H1 := ((is_closed_compl_iff.2 (is_open_union hu hv)).compact.inter_Inter_nonempty (λ Z : {Z : set α // is_clopen Z ∧ x ∈ Z}, Z) (λ Z, Z.2.1.2)), rw [←not_imp_not, not_forall, not_nonempty_iff_eq_empty, inter_comm] at H1, have huv_union := subset.trans hab (union_subset_union hau hbv), rw [← compl_compl (u ∪ v), subset_compl_iff_disjoint] at huv_union, cases H1 huv_union with Zi H2, refine ⟨(⋂ (U ∈ Zi), subtype.val U), _, _, _⟩, { exact is_clopen_bInter (λ Z hZ, Z.2.1) }, { exact mem_bInter_iff.2 (λ Z hZ, Z.2.2) }, { rwa [not_nonempty_iff_eq_empty, inter_comm, ←subset_compl_iff_disjoint, compl_compl] at H2 } end section connected_component_setoid local attribute [instance] connected_component_setoid /-- `connected_components α` is Hausdorff when `α` is Hausdorff and compact -/ instance connected_components.t2 [t2_space α] [compact_space α] : t2_space (connected_components α) := begin -- Proof follows that of: https://stacks.math.columbia.edu/tag/0900 -- Fix 2 distinct connected components, with points a and b refine ⟨λ x y, quotient.induction_on x (quotient.induction_on y (λ a b ne, _))⟩, rw connected_component_nrel_iff at ne, have h := connected_component_disjoint ne, -- write ⟦b⟧ as the intersection of all clopen subsets containing it rw [connected_component_eq_Inter_clopen, disjoint_iff_inter_eq_empty, inter_comm] at h, -- Now we show that this can be reduced to some clopen containing ⟦b⟧ being disjoint to ⟦a⟧ cases is_closed_connected_component.compact.elim_finite_subfamily_closed _ _ h with fin_a ha, swap, { exact λ Z, Z.2.1.2 }, set U : set α := (⋂ (i : {Z // is_clopen Z ∧ b ∈ Z}) (H : i ∈ fin_a), ↑i) with hU, rw ←hU at ha, have hu_clopen : is_clopen U := is_clopen_bInter (λ i j, i.2.1), -- This clopen and its complement will separate the points corresponding to ⟦a⟧ and ⟦b⟧ use [quotient.mk '' U, quotient.mk '' Uᶜ], -- Using the fact that clopens are unions of connected components, we show that -- U and Uᶜ is the preimage of a clopen set in the quotient have hu : quotient.mk ⁻¹' (quotient.mk '' U) = U := (connected_components_preimage_image U ▸ eq.symm) hu_clopen.eq_union_connected_components, have huc : quotient.mk ⁻¹' (quotient.mk '' Uᶜ) = Uᶜ := (connected_components_preimage_image Uᶜ ▸ eq.symm) (is_clopen_compl hu_clopen).eq_union_connected_components, -- showing that U and Uᶜ are open and separates ⟦a⟧ and ⟦b⟧ refine ⟨_,_,_,_,_⟩, { rw [(quotient_map_iff.1 quotient_map_quotient_mk).2 _, hu], exact hu_clopen.1 }, { rw [(quotient_map_iff.1 quotient_map_quotient_mk).2 _, huc], exact is_open_compl_iff.2 hu_clopen.2 }, { exact mem_image_of_mem _ (mem_Inter.2 (λ Z, mem_Inter.2 (λ Zmem, Z.2.2))) }, { apply mem_image_of_mem, exact mem_of_subset_of_mem (subset_compl_iff_disjoint.2 ha) (@mem_connected_component _ _ a) }, apply preimage_injective.2 (@surjective_quotient_mk _ _), rw [preimage_inter, preimage_empty, hu, huc, inter_compl_self _], end end connected_component_setoid
ec9668ae4dfbb1955fda5946ffb7ce5a26bf8e24
7b02c598aa57070b4cf4fbfe2416d0479220187f
/homotopy/cohomology.hlean
38a7e4ccd68e07fa2a6156e270298f3ca31d4510
[ "Apache-2.0" ]
permissive
jdchristensen/Spectral
50d4f0ddaea1484d215ef74be951da6549de221d
6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8
refs/heads/master
1,611,555,010,649
1,496,724,191,000
1,496,724,191,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,138
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Reduced cohomology of spectra and cohomology theories -/ import .spectrum ..algebra.arrow_group .fwedge ..choice .pushout ..algebra.product_group open eq spectrum int trunc pointed EM group algebra circle sphere nat EM.ops equiv susp is_trunc function fwedge cofiber bool lift sigma is_equiv choice pushout algebra unit pi namespace cohomology /- The cohomology of X with coefficients in Y is trunc 0 (A →* Ω[2] (Y (n+2))) In the file arrow_group (in algebra) we construct the group structure on this type. -/ definition cohomology (X : Type*) (Y : spectrum) (n : ℤ) : AbGroup := AbGroup_trunc_pmap X (Y (n+2)) definition parametrized_cohomology {X : Type*} (Y : X → spectrum) (n : ℤ) : AbGroup := AbGroup_trunc_ppi (λx, Y x (n+2)) definition ordinary_cohomology [reducible] (X : Type*) (G : AbGroup) (n : ℤ) : AbGroup := cohomology X (EM_spectrum G) n definition ordinary_cohomology_Z [reducible] (X : Type*) (n : ℤ) : AbGroup := ordinary_cohomology X agℤ n notation `H^` n `[`:0 X:0 `, ` Y:0 `]`:0 := cohomology X Y n notation `H^` n `[`:0 X:0 `]`:0 := ordinary_cohomology_Z X n notation `pH^` n `[`:0 binders `, ` r:(scoped Y, parametrized_cohomology Y n) `]`:0 := r -- check H^3[S¹*,EM_spectrum agℤ] -- check H^3[S¹*] -- check pH^3[(x : S¹*), EM_spectrum agℤ] /- an alternate definition of cohomology -/ definition cohomology_equiv_shomotopy_group_cotensor (X : Type*) (Y : spectrum) (n : ℤ) : H^n[X, Y] ≃ πₛ[-n] (sp_cotensor X Y) := trunc_equiv_trunc 0 (!pfunext ⬝e loop_pequiv_loop !pfunext ⬝e loopn_pequiv_loopn 2 (pequiv_of_eq (ap (λn, ppmap X (Y n)) (add.comm n 2 ⬝ ap (add 2) !neg_neg⁻¹)))) definition unpointed_cohomology (X : Type) (Y : spectrum) (n : ℤ) : AbGroup := cohomology X₊ Y n /- functoriality -/ definition cohomology_functor [constructor] {X X' : Type*} (f : X' →* X) (Y : spectrum) (n : ℤ) : cohomology X Y n →g cohomology X' Y n := Group_trunc_pmap_homomorphism f definition cohomology_functor_pid (X : Type*) (Y : spectrum) (n : ℤ) (f : H^n[X, Y]) : cohomology_functor (pid X) Y n f = f := !Group_trunc_pmap_pid definition cohomology_functor_pcompose {X X' X'' : Type*} (f : X' →* X) (g : X'' →* X') (Y : spectrum) (n : ℤ) (h : H^n[X, Y]) : cohomology_functor (f ∘* g) Y n h = cohomology_functor g Y n (cohomology_functor f Y n h) := !Group_trunc_pmap_pcompose definition cohomology_functor_phomotopy {X X' : Type*} {f g : X' →* X} (p : f ~* g) (Y : spectrum) (n : ℤ) : cohomology_functor f Y n ~ cohomology_functor g Y n := Group_trunc_pmap_phomotopy p definition cohomology_functor_phomotopy_refl {X X' : Type*} (f : X' →* X) (Y : spectrum) (n : ℤ) (x : H^n[X, Y]) : cohomology_functor_phomotopy (phomotopy.refl f) Y n x = idp := Group_trunc_pmap_phomotopy_refl f x definition cohomology_functor_pconst {X X' : Type*} (Y : spectrum) (n : ℤ) (f : H^n[X, Y]) : cohomology_functor (pconst X' X) Y n f = 1 := !Group_trunc_pmap_pconst definition cohomology_isomorphism {X X' : Type*} (f : X' ≃* X) (Y : spectrum) (n : ℤ) : H^n[X, Y] ≃g H^n[X', Y] := Group_trunc_pmap_isomorphism f definition cohomology_isomorphism_refl (X : Type*) (Y : spectrum) (n : ℤ) (x : H^n[X,Y]) : cohomology_isomorphism (pequiv.refl X) Y n x = x := !Group_trunc_pmap_isomorphism_refl /- suspension axiom -/ definition cohomology_psusp_2 (Y : spectrum) (n : ℤ) : Ω (Ω[2] (Y ((n+1)+2))) ≃* Ω[2] (Y (n+2)) := begin apply loopn_pequiv_loopn 2, exact loop_pequiv_loop (pequiv_of_eq (ap Y (add.right_comm n 1 2))) ⬝e* !equiv_glue⁻¹ᵉ* end definition cohomology_psusp_1 (X : Type*) (Y : spectrum) (n : ℤ) : psusp X →* Ω (Ω (Y (n + 1 + 2))) ≃ X →* Ω (Ω (Y (n+2))) := calc psusp X →* Ω[2] (Y (n + 1 + 2)) ≃ X →* Ω (Ω[2] (Y (n + 1 + 2))) : psusp_adjoint_loop_unpointed ... ≃ X →* Ω[2] (Y (n+2)) : equiv_of_pequiv (pequiv_ppcompose_left (cohomology_psusp_2 Y n)) definition cohomology_psusp_1_pmap_mul {X : Type*} {Y : spectrum} {n : ℤ} (f g : psusp X →* Ω (Ω (Y (n + 1 + 2)))) : cohomology_psusp_1 X Y n (pmap_mul f g) ~* pmap_mul (cohomology_psusp_1 X Y n f) (cohomology_psusp_1 X Y n g) := begin unfold [cohomology_psusp_1], refine pwhisker_left _ !loop_psusp_intro_pmap_mul ⬝* _, apply pcompose_pmap_mul end definition cohomology_psusp_equiv (X : Type*) (Y : spectrum) (n : ℤ) : H^n+1[psusp X, Y] ≃ H^n[X, Y] := trunc_equiv_trunc _ (cohomology_psusp_1 X Y n) definition cohomology_psusp (X : Type*) (Y : spectrum) (n : ℤ) : H^n+1[psusp X, Y] ≃g H^n[X, Y] := isomorphism_of_equiv (cohomology_psusp_equiv X Y n) begin intro f₁ f₂, induction f₁ with f₁, induction f₂ with f₂, apply ap tr, apply eq_of_phomotopy, exact cohomology_psusp_1_pmap_mul f₁ f₂ end definition cohomology_psusp_natural {X X' : Type*} (f : X →* X') (Y : spectrum) (n : ℤ) : cohomology_psusp X Y n ∘ cohomology_functor (psusp_functor f) Y (n+1) ~ cohomology_functor f Y n ∘ cohomology_psusp X' Y n := begin refine (trunc_functor_compose _ _ _)⁻¹ʰᵗʸ ⬝hty _ ⬝hty trunc_functor_compose _ _ _, apply trunc_functor_homotopy, intro g, apply eq_of_phomotopy, refine _ ⬝* !passoc⁻¹*, apply pwhisker_left, apply loop_psusp_intro_natural end /- exactness -/ definition cohomology_exact {X X' : Type*} (f : X →* X') (Y : spectrum) (n : ℤ) : is_exact_g (cohomology_functor (pcod f) Y n) (cohomology_functor f Y n) := is_exact_trunc_functor (cofiber_exact f) /- additivity -/ definition additive_hom [constructor] {I : Type} (X : I → Type*) (Y : spectrum) (n : ℤ) : H^n[⋁X, Y] →g Πᵍ i, H^n[X i, Y] := Group_pi_intro (λi, cohomology_functor (pinl i) Y n) definition additive_equiv.{u} {I : Type.{u}} (H : has_choice 0 I) (X : I → Type*) (Y : spectrum) (n : ℤ) : H^n[⋁X, Y] ≃ Πᵍ i, H^n[X i, Y] := trunc_fwedge_pmap_equiv H X (Ω[2] (Y (n+2))) definition spectrum_additive {I : Type} (H : has_choice 0 I) (X : I → Type*) (Y : spectrum) (n : ℤ) : is_equiv (additive_hom X Y n) := is_equiv_of_equiv_of_homotopy (additive_equiv H X Y n) begin intro f, induction f, reflexivity end /- dimension axiom for ordinary cohomology -/ open is_conn trunc_index theorem EM_dimension' (G : AbGroup) (n : ℤ) (H : n ≠ 0) : is_contr (ordinary_cohomology pbool G n) := begin apply is_conn_equiv_closed 0 !pmap_pbool_equiv⁻¹ᵉ, apply is_conn_equiv_closed 0 !equiv_glue2⁻¹ᵉ, cases n with n n, { cases n with n, { exfalso, apply H, reflexivity }, { apply is_conn_of_le, apply zero_le_of_nat n, exact is_conn_EMadd1 G n, }}, { apply is_trunc_trunc_of_is_trunc, apply @is_contr_loop_of_is_trunc (n+1) (K G 0), apply is_trunc_of_le _ (zero_le_of_nat n) } end theorem EM_dimension (G : AbGroup) (n : ℤ) (H : n ≠ 0) : is_contr (ordinary_cohomology (plift pbool) G n) := @(is_trunc_equiv_closed_rev -2 (equiv_of_isomorphism (cohomology_isomorphism (pequiv_plift pbool) _ _))) (EM_dimension' G n H) /- cohomology theory -/ structure cohomology_theory.{u} : Type.{u+1} := (HH : ℤ → pType.{u} → AbGroup.{u}) (Hiso : Π(n : ℤ) {X Y : Type*} (f : X ≃* Y), HH n Y ≃g HH n X) (Hiso_refl : Π(n : ℤ) (X : Type*) (x : HH n X), Hiso n pequiv.rfl x = x) (Hh : Π(n : ℤ) {X Y : Type*} (f : X →* Y), HH n Y →g HH n X) (Hhomotopy : Π(n : ℤ) {X Y : Type*} {f g : X →* Y} (p : f ~* g), Hh n f ~ Hh n g) (Hhomotopy_refl : Π(n : ℤ) {X Y : Type*} (f : X →* Y) (x : HH n Y), Hhomotopy n (phomotopy.refl f) x = idp) (Hid : Π(n : ℤ) {X : Type*} (x : HH n X), Hh n (pid X) x = x) (Hcompose : Π(n : ℤ) {X Y Z : Type*} (g : Y →* Z) (f : X →* Y) (z : HH n Z), Hh n (g ∘* f) z = Hh n f (Hh n g z)) (Hsusp : Π(n : ℤ) (X : Type*), HH (succ n) (psusp X) ≃g HH n X) (Hsusp_natural : Π(n : ℤ) {X Y : Type*} (f : X →* Y), Hsusp n X ∘ Hh (succ n) (psusp_functor f) ~ Hh n f ∘ Hsusp n Y) (Hexact : Π(n : ℤ) {X Y : Type*} (f : X →* Y), is_exact_g (Hh n (pcod f)) (Hh n f)) (Hadditive : Π(n : ℤ) {I : Type.{u}} (X : I → Type*), has_choice 0 I → is_equiv (Group_pi_intro (λi, Hh n (pinl i)) : HH n (⋁ X) → Πᵍ i, HH n (X i))) structure ordinary_theory.{u} extends cohomology_theory.{u} : Type.{u+1} := (Hdimension : Π(n : ℤ), n ≠ 0 → is_contr (HH n (plift pbool))) attribute cohomology_theory.HH [coercion] postfix `^→`:90 := cohomology_theory.Hh open cohomology_theory definition Hequiv (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X ≃* Y) : H n Y ≃ H n X := equiv_of_isomorphism (Hiso H n f) definition Hsusp_neg (H : cohomology_theory) (n : ℤ) (X : Type*) : H n (psusp X) ≃g H (pred n) X := isomorphism_of_eq (ap (λn, H n _) proof (sub_add_cancel n 1)⁻¹ qed) ⬝g cohomology_theory.Hsusp H (pred n) X definition Hsusp_neg_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) : Hsusp_neg H n X ∘ H ^→ n (psusp_functor f) ~ H ^→ (pred n) f ∘ Hsusp_neg H n Y := sorry definition Hsusp_inv_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) : H ^→ (succ n) (psusp_functor f) ∘g (Hsusp H n Y)⁻¹ᵍ ~ (Hsusp H n X)⁻¹ᵍ ∘ H ^→ n f := sorry definition Hsusp_neg_inv_natural (H : cohomology_theory) (n : ℤ) {X Y : Type*} (f : X →* Y) : H ^→ n (psusp_functor f) ∘g (Hsusp_neg H n Y)⁻¹ᵍ ~ (Hsusp_neg H n X)⁻¹ᵍ ∘ H ^→ (pred n) f := sorry definition Hadditive_equiv (H : cohomology_theory) (n : ℤ) {I : Type} (X : I → Type*) (H2 : has_choice 0 I) : H n (⋁ X) ≃g Πᵍ i, H n (X i) := isomorphism.mk _ (Hadditive H n X H2) definition Hlift_empty.{u} (H : cohomology_theory.{u}) (n : ℤ) : is_contr (H n (plift punit)) := let P : lift empty → Type* := lift.rec empty.elim in let x := Hadditive H n P _ in begin note z := equiv.mk _ x, refine @(is_trunc_equiv_closed_rev -2 (_ ⬝e z ⬝e _)) !is_contr_unit, refine Hequiv H n (pequiv_punit_of_is_contr _ _ ⬝e* !pequiv_plift), apply is_contr_fwedge_of_neg, intro y, induction y with y, exact y, apply equiv_unit_of_is_contr, apply is_contr_pi_of_neg, intro y, induction y with y, exact y end definition Hempty (H : cohomology_theory.{0}) (n : ℤ) : is_contr (H n punit) := @(is_trunc_equiv_closed _ (Hequiv H n !pequiv_plift)) (Hlift_empty H n) definition Hconst (H : cohomology_theory) (n : ℤ) {X Y : Type*} (y : H n Y) : H ^→ n (pconst X Y) y = 1 := begin refine Hhomotopy H n (pconst_pcompose (pconst X (plift punit)))⁻¹* y ⬝ _, refine Hcompose H n _ _ y ⬝ _, refine ap (H ^→ n _) (@eq_of_is_contr _ (Hlift_empty H n) _ 1) ⬝ _, apply respect_one end -- definition Hwedge (H : cohomology_theory) (n : ℤ) (A B : Type*) : H n (A ∨ B) ≃g H n A ×ag H n B := -- begin -- refine Hiso H n (pwedge_pequiv_fwedge A B)⁻¹ᵉ* ⬝g _, -- refine Hadditive_equiv H n _ _ ⬝g _ -- end definition cohomology_theory_spectrum.{u} [constructor] (Y : spectrum.{u}) : cohomology_theory.{u} := cohomology_theory.mk (λn A, H^n[A, Y]) (λn A B f, cohomology_isomorphism f Y n) (λn A, cohomology_isomorphism_refl A Y n) (λn A B f, cohomology_functor f Y n) (λn A B f g p, cohomology_functor_phomotopy p Y n) (λn A B f x, cohomology_functor_phomotopy_refl f Y n x) (λn A x, cohomology_functor_pid A Y n x) (λn A B C g f x, cohomology_functor_pcompose g f Y n x) (λn A, cohomology_psusp A Y n) (λn A B f, cohomology_psusp_natural f Y n) (λn A B f, cohomology_exact f Y n) (λn I A H, spectrum_additive H A Y n) -- set_option pp.universes true -- set_option pp.abbreviations false -- print cohomology_theory_spectrum -- print EM_spectrum -- print has_choice_lift -- print equiv_lift -- print has_choice_equiv_closed definition ordinary_theory_EM [constructor] (G : AbGroup) : ordinary_theory := ⦃ordinary_theory, cohomology_theory_spectrum (EM_spectrum G), Hdimension := EM_dimension G ⦄ end cohomology
923e7536d0013e4b734a0ad09c472b98825423df
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/measure_theory/ae_eq_fun.lean
e6ba384cf90ac3449013b7e3279d91bfccc26a60
[ "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
22,605
lean
/- Copyright (c) 2019 Johannes Hölzl, Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Zhouhang Zhou -/ import measure_theory.integration /-! # Almost everywhere equal functions Two measurable functions are treated as identical if they are almost everywhere equal. We form the set of equivalence classes under the relation of being almost everywhere equal, which is sometimes known as the `L⁰` space. See `l1_space.lean` for `L¹` space. ## Notation * `α →ₘ β` is the type of `L⁰` space, where `α` is a measure space and `β` is a measurable space. `f : α →ₘ β` is a "function" in `L⁰`. In comments, `[f]` is also used to denote an `L⁰` function. `ₘ` can be typed as `\_m`. Sometimes it is shown as a box if font is missing. ## Main statements * The linear structure of `L⁰` : Addition and scalar multiplication are defined on `L⁰` in the natural way, i.e., `[f] + [g] := [f + g]`, `c • [f] := [c • f]`. So defined, `α →ₘ β` inherits the linear structure of `β`. For example, if `β` is a module, then `α →ₘ β` is a module over the same ring. See `mk_add_mk`, `neg_mk`, `mk_sub_mk`, `smul_mk`, `add_to_fun`, `neg_to_fun`, `sub_to_fun`, `smul_to_fun` * The order structure of `L⁰` : `≤` can be defined in a similar way: `[f] ≤ [g]` if `f a ≤ g a` for almost all `a` in domain. And `α →ₘ β` inherits the preorder and partial order of `β`. TODO: Define `sup` and `inf` on `L⁰` so that it forms a lattice. It seems that `β` must be a linear order, since otherwise `f ⊔ g` may not be a measurable function. * Emetric on `L⁰` : If `β` is an `emetric_space`, then `L⁰` can be made into an `emetric_space`, where `edist [f] [g]` is defined to be `∫⁻ a, edist (f a) (g a)`. The integral used here is `lintegral : (α → ennreal) → ennreal`, which is defined in the file `integration.lean`. See `edist_mk_mk` and `edist_to_fun`. ## Implementation notes * `f.to_fun` : To find a representative of `f : α →ₘ β`, use `f.to_fun`. For each operation `op` in `L⁰`, there is a lemma called `op_to_fun`, characterizing, say, `(f op g).to_fun`. * `ae_eq_fun.mk` : To constructs an `L⁰` function `α →ₘ β` from a measurable function `f : α → β`, use `ae_eq_fun.mk` * `comp` : Use `comp g f` to get `[g ∘ f]` from `g : β → γ` and `[f] : α →ₘ γ` * `comp₂` : Use `comp₂ g f₁ f₂ to get `[λa, g (f₁ a) (f₂ a)]`. For example, `[f + g]` is `comp₂ (+)` ## Tags function space, almost everywhere equal, `L⁰`, ae_eq_fun -/ noncomputable theory open_locale classical namespace measure_theory open set filter topological_space universes u v variables {α : Type u} {β : Type v} [measure_space α] section measurable_space variables [measurable_space β] variables (α β) /-- The equivalence relation of being almost everywhere equal -/ instance ae_eq_fun.setoid : setoid { f : α → β // measurable f } := ⟨ λf g, ∀ₘ a, f.1 a = g.1 a, assume ⟨f, hf⟩, by filter_upwards [] assume a, rfl, assume ⟨f, hf⟩ ⟨g, hg⟩ hfg, by filter_upwards [hfg] assume a, eq.symm, assume ⟨f, hf⟩ ⟨g, hg⟩ ⟨h, hh⟩ hfg hgh, by filter_upwards [hfg, hgh] assume a, eq.trans ⟩ /-- The space of equivalence classes of measurable functions, where two measurable functions are equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/ def ae_eq_fun : Type (max u v) := quotient (ae_eq_fun.setoid α β) variables {α β} infixr ` →ₘ `:25 := ae_eq_fun end measurable_space namespace ae_eq_fun variables [measurable_space β] /-- Construct the equivalence class `[f]` of a measurable function `f`, based on the equivalence relation of being almost everywhere equal. -/ def mk (f : α → β) (hf : measurable f) : α →ₘ β := quotient.mk ⟨f, hf⟩ /-- A representative of an `ae_eq_fun` [f] -/ protected def to_fun (f : α →ₘ β) : α → β := @quotient.out _ (ae_eq_fun.setoid α β) f protected lemma measurable (f : α →ₘ β) : measurable f.to_fun := (@quotient.out _ (ae_eq_fun.setoid α β) f).2 instance : has_coe (α →ₘ β) (α → β) := ⟨λf, f.to_fun⟩ @[simp] lemma quot_mk_eq_mk (f : {f : α → β // measurable f}) : quot.mk setoid.r f = mk f.1 f.2 := by cases f; refl @[simp] lemma mk_eq_mk (f g : α → β) (hf hg) : mk f hf = mk g hg ↔ (∀ₘ a, f a = g a) := ⟨quotient.exact, assume h, quotient.sound h⟩ @[ext] lemma ext (f g : α →ₘ β) (f' g' : α → β) (hf' hg') (hf : mk f' hf' = f) (hg : mk g' hg' = g) (h : ∀ₘ a, f' a = g' a) : f = g := by { rw [← hf, ← hg], rw mk_eq_mk, assumption } lemma self_eq_mk (f : α →ₘ β) : f = mk (f.to_fun) f.measurable := by simp [mk, ae_eq_fun.to_fun] lemma all_ae_mk_to_fun (f : α → β) (hf) : ∀ₘ a, (mk f hf).to_fun a = f a := by rw [← mk_eq_mk _ f _ hf, ← self_eq_mk (mk f hf)] /-- Given a measurable function `g : β → γ`, and an almost everywhere equal function `[f] : α →ₘ β`, return the equivalence class of `g ∘ f`, i.e., the almost everywhere equal function `[g ∘ f] : α →ₘ γ`. -/ def comp {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g) (f : α →ₘ β) : α →ₘ γ := quotient.lift_on f (λf, mk (g ∘ f.1) (measurable.comp hg f.2)) $ assume f₁ f₂ eq, by refine quotient.sound _; filter_upwards [eq] assume a, congr_arg g @[simp] lemma comp_mk {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g) (f : α → β) (hf) : comp g hg (mk f hf) = mk (g ∘ f) (measurable.comp hg hf) := rfl lemma comp_eq_mk_to_fun {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g) (f : α →ₘ β) : comp g hg f = mk (g ∘ f.to_fun) (hg.comp f.measurable) := by conv_lhs { rw [self_eq_mk f, comp_mk] } lemma comp_to_fun {γ : Type*} [measurable_space γ] (g : β → γ) (hg : measurable g) (f : α →ₘ β) : ∀ₘ a, (comp g hg f).to_fun a = (g ∘ f.to_fun) a := by { rw comp_eq_mk_to_fun, apply all_ae_mk_to_fun } /-- Given a measurable function `g : β → γ → δ`, and almost everywhere equal functions `[f₁] : α →ₘ β` and `[f₂] : α →ₘ γ`, return the equivalence class of the function `λa, g (f₁ a) (f₂ a)`, i.e., the almost everywhere equal function `[λa, g (f₁ a) (f₂ a)] : α →ₘ γ` -/ def comp₂ {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α →ₘ β) (f₂ : α →ₘ γ) : α →ₘ δ := begin refine quotient.lift_on₂ f₁ f₂ (λf₁ f₂, mk (λa, g (f₁.1 a) (f₂.1 a)) $ _) _, { exact measurable.comp hg (measurable.prod_mk f₁.2 f₂.2) }, { rintros ⟨f₁, hf₁⟩ ⟨f₂, hf₂⟩ ⟨g₁, hg₁⟩ ⟨g₂, hg₂⟩ h₁ h₂, refine quotient.sound _, filter_upwards [h₁, h₂], simp {contextual := tt} } end @[simp] lemma comp₂_mk_mk {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α → β) (f₂ : α → γ) (hf₁ hf₂) : comp₂ g hg (mk f₁ hf₁) (mk f₂ hf₂) = mk (λa, g (f₁ a) (f₂ a)) (measurable.comp hg (measurable.prod_mk hf₁ hf₂)) := rfl lemma comp₂_eq_mk_to_fun {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α →ₘ β) (f₂ : α →ₘ γ) : comp₂ g hg f₁ f₂ = mk (λa, g (f₁.to_fun a) (f₂.to_fun a)) (hg.comp (measurable.prod_mk f₁.measurable f₂.measurable)) := by conv_lhs { rw [self_eq_mk f₁, self_eq_mk f₂, comp₂_mk_mk] } lemma comp₂_to_fun {γ δ : Type*} [measurable_space γ] [measurable_space δ] (g : β → γ → δ) (hg : measurable (λp:β×γ, g p.1 p.2)) (f₁ : α →ₘ β) (f₂ : α →ₘ γ) : ∀ₘ a, (comp₂ g hg f₁ f₂).to_fun a = g (f₁.to_fun a) (f₂.to_fun a) := by { rw comp₂_eq_mk_to_fun, apply all_ae_mk_to_fun } /-- Given a predicate `p` and an equivalence class `[f]`, return true if `p` holds of `f a` for almost all `a` -/ def lift_pred (p : β → Prop) (f : α →ₘ β) : Prop := quotient.lift_on f (λf, ∀ₘ a, p (f.1 a)) begin assume f g h, dsimp, refine propext (all_ae_congr _), filter_upwards [h], simp {contextual := tt} end /-- Given a relation `r` and equivalence class `[f]` and `[g]`, return true if `r` holds of `(f a, g a)` for almost all `a` -/ def lift_rel {γ : Type*} [measurable_space γ] (r : β → γ → Prop) (f : α →ₘ β) (g : α →ₘ γ) : Prop := lift_pred (λp:β×γ, r p.1 p.2) (comp₂ prod.mk (measurable.prod_mk (measurable.fst measurable_id) (measurable.snd measurable_id)) f g) lemma lift_rel_mk_mk {γ : Type*} [measurable_space γ] (r : β → γ → Prop) (f : α → β) (g : α → γ) (hf hg) : lift_rel r (mk f hf) (mk g hg) ↔ ∀ₘ a, r (f a) (g a) := iff.rfl lemma lift_rel_iff_to_fun {γ : Type*} [measurable_space γ] (r : β → γ → Prop) (f : α →ₘ β) (g : α →ₘ γ) : lift_rel r f g ↔ ∀ₘ a, r (f.to_fun a) (g.to_fun a) := by conv_lhs { rw [self_eq_mk f, self_eq_mk g, lift_rel_mk_mk] } section order instance [preorder β] : preorder (α →ₘ β) := { le := lift_rel (≤), le_refl := by rintros ⟨⟨f, hf⟩⟩; exact univ_mem_sets' (assume a, le_refl _), le_trans := begin rintros ⟨⟨f, hf⟩⟩ ⟨⟨g, hg⟩⟩ ⟨⟨h, hh⟩⟩ hfg hgh, filter_upwards [hfg, hgh] assume a, le_trans end } lemma mk_le_mk [preorder β] {f g : α → β} (hf hg) : mk f hf ≤ mk g hg ↔ ∀ₘ a, f a ≤ g a := iff.rfl lemma le_iff_to_fun_le [preorder β] {f g : α →ₘ β} : f ≤ g ↔ ∀ₘ a, f.to_fun a ≤ g.to_fun a := lift_rel_iff_to_fun _ _ _ instance [partial_order β] : partial_order (α →ₘ β) := { le_antisymm := begin rintros ⟨⟨f, hf⟩⟩ ⟨⟨g, hg⟩⟩ hfg hgf, refine quotient.sound _, filter_upwards [hfg, hgf] assume a, le_antisymm end, .. ae_eq_fun.preorder } /- TODO: Prove `L⁰` space is a lattice if β is linear order. What if β is only a lattice? -/ -- instance [linear_order β] : semilattice_sup (α →ₘ β) := -- { sup := comp₂ (⊔) (_), -- .. ae_eq_fun.partial_order } end order variable (α) /-- The equivalence class of a constant function: `[λa:α, b]`, based on the equivalence relation of being almost everywhere equal -/ def const (b : β) : α →ₘ β := mk (λa:α, b) measurable_const lemma const_to_fun (b : β) : ∀ₘ a, (const α b).to_fun a = b := all_ae_mk_to_fun _ _ variable {α} instance [inhabited β] : inhabited (α →ₘ β) := ⟨const _ (default _)⟩ instance [has_zero β] : has_zero (α →ₘ β) := ⟨const α 0⟩ lemma zero_def [has_zero β] : (0 : α →ₘ β) = mk (λa:α, 0) measurable_const := rfl lemma zero_to_fun [has_zero β] : ∀ₘ a, (0 : α →ₘ β).to_fun a = 0 := const_to_fun _ _ instance [has_one β] : has_one (α →ₘ β) := ⟨const α 1⟩ lemma one_def [has_one β] : (1 : α →ₘ β) = mk (λa:α, 1) measurable_const := rfl lemma one_to_fun [has_one β] : ∀ₘ a, (1 : α →ₘ β).to_fun a = 1 := const_to_fun _ _ section add_monoid variables {γ : Type*} [topological_space γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ] [add_monoid γ] [topological_add_monoid γ] instance : has_add (α →ₘ γ) := ⟨comp₂ (+) measurable_add⟩ @[simp] lemma mk_add_mk (f g : α → γ) (hf hg) : (mk f hf) + (mk g hg) = mk (f + g) (measurable.add hf hg) := rfl lemma add_to_fun (f g : α →ₘ γ) : ∀ₘ a, (f + g).to_fun a = f.to_fun a + g.to_fun a := comp₂_to_fun _ _ _ _ instance : add_monoid (α →ₘ γ) := { zero := 0, add := (+), add_zero := by rintros ⟨a⟩; exact quotient.sound (all_ae_of_all $ assume a, add_zero _), zero_add := by rintros ⟨a⟩; exact quotient.sound (all_ae_of_all $ assume a, zero_add _), add_assoc := by rintros ⟨a⟩ ⟨b⟩ ⟨c⟩; exact quotient.sound (all_ae_of_all $ assume a, add_assoc _ _ _) } end add_monoid section add_comm_monoid variables {γ : Type*} [topological_space γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ] [add_comm_monoid γ] [topological_add_monoid γ] instance add_comm_monoid : add_comm_monoid (α →ₘ γ) := { add_comm := by rintros ⟨a⟩ ⟨b⟩; exact quotient.sound (univ_mem_sets' $ assume a, add_comm _ _), .. ae_eq_fun.add_monoid } end add_comm_monoid section add_group variables {γ : Type*} [topological_space γ] [measurable_space γ] [borel_space γ] [add_group γ] [topological_add_group γ] instance : has_neg (α →ₘ γ) := ⟨comp has_neg.neg measurable_id.neg⟩ @[simp] lemma neg_mk (f : α → γ) (hf) : -(mk f hf) = mk (-f) (measurable.neg hf) := rfl lemma neg_to_fun (f : α →ₘ γ) : ∀ₘ a, (-f).to_fun a = - f.to_fun a := comp_to_fun _ _ _ variables [second_countable_topology γ] instance : add_group (α →ₘ γ) := { neg := has_neg.neg, add_left_neg := by rintros ⟨a⟩; exact quotient.sound (all_ae_of_all $ assume a, add_left_neg _), .. ae_eq_fun.add_monoid } @[simp] lemma mk_sub_mk (f g : α → γ) (hf hg) : (mk f hf) - (mk g hg) = mk (λa, (f a) - (g a)) (measurable.sub hf hg) := rfl lemma sub_to_fun (f g : α →ₘ γ) : ∀ₘ a, (f - g).to_fun a = f.to_fun a - g.to_fun a := begin rw sub_eq_add_neg, filter_upwards [add_to_fun f (-g), neg_to_fun g], assume a, simp only [mem_set_of_eq], repeat {assume h, rw h}, refl end end add_group section add_comm_group variables {γ : Type*} [topological_space γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ] [add_comm_group γ] [topological_add_group γ] instance : add_comm_group (α →ₘ γ) := { .. ae_eq_fun.add_group, .. ae_eq_fun.add_comm_monoid } end add_comm_group section semimodule variables {𝕜 : Type*} [semiring 𝕜] [topological_space 𝕜] variables {γ : Type*} [topological_space γ] [measurable_space γ] [borel_space γ] [add_comm_monoid γ] [semimodule 𝕜 γ] [topological_semimodule 𝕜 γ] instance : has_scalar 𝕜 (α →ₘ γ) := ⟨λ c f, comp (has_scalar.smul c) (measurable_id.const_smul _) f⟩ @[simp] lemma smul_mk (c : 𝕜) (f : α → γ) (hf) : c • (mk f hf) = mk (c • f) (hf.const_smul _) := rfl lemma smul_to_fun (c : 𝕜) (f : α →ₘ γ) : ∀ₘ a, (c • f).to_fun a = c • f.to_fun a := comp_to_fun _ _ _ variables [second_countable_topology γ] [topological_add_monoid γ] instance : semimodule 𝕜 (α →ₘ γ) := { one_smul := by { rintros ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, one_smul] }, mul_smul := by { rintros x y ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, mul_action.mul_smul x y f], refl }, smul_add := begin rintros x ⟨f, hf⟩ ⟨g, hg⟩, simp only [quot_mk_eq_mk, smul_mk, mk_add_mk], congr, exact smul_add x f g end, smul_zero := by { intro x, simp only [zero_def, smul_mk], congr, exact smul_zero x }, add_smul := begin intros x y, rintro ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, mk_add_mk], congr, exact add_smul x y f end, zero_smul := by { rintro ⟨f, hf⟩, simp only [quot_mk_eq_mk, smul_mk, zero_def], congr, exact zero_smul 𝕜 f }} instance : mul_action 𝕜 (α →ₘ γ) := by apply_instance end semimodule section module variables {𝕜 : Type*} [ring 𝕜] [topological_space 𝕜] variables {γ : Type*} [topological_space γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ] [add_comm_group γ] [topological_add_group γ] [module 𝕜 γ] [topological_semimodule 𝕜 γ] instance : module 𝕜 (α →ₘ γ) := { .. ae_eq_fun.semimodule } end module section vector_space variables {𝕜 : Type*} [field 𝕜] [topological_space 𝕜] variables {γ : Type*} [topological_space γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ] [add_comm_group γ] [topological_add_group γ] [vector_space 𝕜 γ] [topological_semimodule 𝕜 γ] instance : vector_space 𝕜 (α →ₘ γ) := { .. ae_eq_fun.semimodule } end vector_space /- TODO : Prove that `L⁰` is a complete space if the codomain is complete. -/ /- TODO : Multiplicative structure of `L⁰` if useful -/ open ennreal /-- For `f : α → ennreal`, Define `∫ [f]` to be `∫ f` -/ def eintegral (f : α →ₘ ennreal) : ennreal := quotient.lift_on f (λf, lintegral f.1) (assume ⟨f, hf⟩ ⟨g, hg⟩ eq, lintegral_congr_ae eq) @[simp] lemma eintegral_mk (f : α → ennreal) (hf) : eintegral (mk f hf) = lintegral f := rfl lemma eintegral_to_fun (f : α →ₘ ennreal) : eintegral f = lintegral (f.to_fun) := by conv_lhs { rw [self_eq_mk f, eintegral_mk] } @[simp] lemma eintegral_zero : eintegral (0 : α →ₘ ennreal) = 0 := lintegral_zero @[simp] lemma eintegral_eq_zero_iff (f : α →ₘ ennreal) : eintegral f = 0 ↔ f = 0 := begin rcases f with ⟨f, hf⟩, refine iff.trans (lintegral_eq_zero_iff hf) ⟨_, _⟩, { assume h, exact quotient.sound h }, { assume h, exact quotient.exact h } end lemma eintegral_add : ∀(f g : α →ₘ ennreal), eintegral (f + g) = eintegral f + eintegral g := by { rintros ⟨f⟩ ⟨g⟩, simp only [quot_mk_eq_mk, mk_add_mk, eintegral_mk], exact lintegral_add f.2 g.2 } lemma eintegral_le_eintegral {f g : α →ₘ ennreal} (h : f ≤ g) : eintegral f ≤ eintegral g := begin rcases f with ⟨f, hf⟩, rcases g with ⟨g, hg⟩, simp only [quot_mk_eq_mk, eintegral_mk, mk_le_mk] at *, refine lintegral_le_lintegral_ae _, filter_upwards [h], simp end section variables {γ : Type*} [emetric_space γ] [second_countable_topology γ] [measurable_space γ] [opens_measurable_space γ] /-- `comp_edist [f] [g] a` will return `edist (f a) (g a) -/ def comp_edist (f g : α →ₘ γ) : α →ₘ ennreal := comp₂ edist measurable_edist f g lemma comp_edist_to_fun (f g : α →ₘ γ) : ∀ₘ a, (comp_edist f g).to_fun a = edist (f.to_fun a) (g.to_fun a) := comp₂_to_fun _ _ _ _ lemma comp_edist_self : ∀ (f : α →ₘ γ), comp_edist f f = 0 := by rintro ⟨f⟩; refine quotient.sound _; simp only [edist_self] /-- Almost everywhere equal functions form an `emetric_space`, with the emetric defined as `edist f g = ∫⁻ a, edist (f a) (g a)`. -/ instance : emetric_space (α →ₘ γ) := { edist := λf g, eintegral (comp_edist f g), edist_self := assume f, (eintegral_eq_zero_iff _).2 (comp_edist_self _), edist_comm := by rintros ⟨f⟩ ⟨g⟩; simp only [comp_edist, quot_mk_eq_mk, comp₂_mk_mk, edist_comm], edist_triangle := begin rintros ⟨f⟩ ⟨g⟩ ⟨h⟩, simp only [comp_edist, quot_mk_eq_mk, comp₂_mk_mk, (eintegral_add _ _).symm], exact lintegral_mono (assume a, edist_triangle _ _ _) end, eq_of_edist_eq_zero := begin rintros ⟨f⟩ ⟨g⟩, simp only [edist, comp_edist, quot_mk_eq_mk, comp₂_mk_mk, eintegral_eq_zero_iff], simp only [zero_def, mk_eq_mk, edist_eq_zero], assume h, assumption end } lemma edist_mk_mk {f g : α → γ} (hf hg) : edist (mk f hf) (mk g hg) = ∫⁻ x, edist (f x) (g x) := rfl lemma edist_to_fun (f g : α →ₘ γ) : edist f g = ∫⁻ x, edist (f.to_fun x) (g.to_fun x) := by conv_lhs { rw [self_eq_mk f, self_eq_mk g, edist_mk_mk] } lemma edist_zero_to_fun [has_zero γ] (f : α →ₘ γ) : edist f 0 = ∫⁻ x, edist (f.to_fun x) 0 := begin rw edist_to_fun, apply lintegral_congr_ae, have : ∀ₘ a:α, (0 : α →ₘ γ).to_fun a = 0 := zero_to_fun, filter_upwards [this], assume a h, simp only [mem_set_of_eq] at *, rw h end end section metric variables {γ : Type*} [metric_space γ] [second_countable_topology γ] [measurable_space γ] [opens_measurable_space γ] lemma edist_mk_mk' {f g : α → γ} (hf hg) : edist (mk f hf) (mk g hg) = ∫⁻ x, nndist (f x) (g x) := show (∫⁻ x, edist (f x) (g x)) = ∫⁻ x, nndist (f x) (g x), from lintegral_congr_ae $all_ae_of_all $ assume a, edist_nndist _ _ lemma edist_to_fun' (f g : α →ₘ γ) : edist f g = ∫⁻ x, nndist (f.to_fun x) (g.to_fun x) := by conv_lhs { rw [self_eq_mk f, self_eq_mk g, edist_mk_mk'] } end metric section normed_group variables {γ : Type*} [normed_group γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ] lemma edist_eq_add_add : ∀ {f g h : α →ₘ γ}, edist f g = edist (f + h) (g + h) := begin rintros ⟨f⟩ ⟨g⟩ ⟨h⟩, simp only [quot_mk_eq_mk, mk_add_mk, edist_mk_mk'], apply lintegral_congr_ae, filter_upwards [], simp [nndist_eq_nnnorm] end end normed_group section normed_space set_option class.instance_max_depth 100 variables {𝕜 : Type*} [normed_field 𝕜] variables {γ : Type*} [normed_group γ] [second_countable_topology γ] [normed_space 𝕜 γ] [measurable_space γ] [borel_space γ] lemma edist_smul (x : 𝕜) : ∀ f : α →ₘ γ, edist (x • f) 0 = (ennreal.of_real ∥x∥) * edist f 0 := begin rintros ⟨f, hf⟩, simp only [zero_def, edist_mk_mk', quot_mk_eq_mk, smul_mk], exact calc (∫⁻ (a : α), nndist (x • f a) 0) = (∫⁻ (a : α), (nnnorm x) * nnnorm (f a)) : lintegral_congr_ae $ by { filter_upwards [], assume a, simp [nndist_eq_nnnorm, nnnorm_smul] } ... = _ : lintegral_const_mul _ hf.ennnorm ... = _ : begin convert rfl, { rw ← coe_nnnorm, rw [ennreal.of_real], congr, exact nnreal.of_real_coe }, { funext, simp [nndist_eq_nnnorm] } end, end end normed_space section pos_part variables {γ : Type*} [topological_space γ] [decidable_linear_order γ] [order_closed_topology γ] [second_countable_topology γ] [has_zero γ] [measurable_space γ] [opens_measurable_space γ] /-- Positive part of an `ae_eq_fun`. -/ def pos_part (f : α →ₘ γ) : α →ₘ γ := comp₂ max (measurable_id.fst.max measurable_id.snd) f 0 lemma pos_part_to_fun (f : α →ₘ γ) : ∀ₘ a, (pos_part f).to_fun a = max (f.to_fun a) (0:γ) := begin filter_upwards [comp₂_to_fun max (measurable_id.fst.max measurable_id.snd) f 0, @ae_eq_fun.zero_to_fun α γ], simp only [mem_set_of_eq], assume a h₁ h₂, rw [pos_part, h₁, h₂] end end pos_part end ae_eq_fun end measure_theory
746c5fd6770aaaad489bb7c9175e7204e1831f50
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/real/irrational.lean
5fbe72943cd594d3a089b87e21ed250fda7fd858
[ "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
9,562
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Yury Kudryashov -/ import data.real.sqrt import data.rat.sqrt import ring_theory.int.basic import data.polynomial.eval import data.polynomial.degree import tactic.interval_cases import ring_theory.algebraic /-! # Irrational real numbers In this file we define a predicate `irrational` on `ℝ`, prove that the `n`-th root of an integer number is irrational if it is not integer, and that `sqrt q` is irrational if and only if `rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q`. We also provide dot-style constructors like `irrational.add_rat`, `irrational.rat_sub` etc. -/ open rat real multiplicity /-- A real number is irrational if it is not equal to any rational number. -/ def irrational (x : ℝ) := x ∉ set.range (coe : ℚ → ℝ) lemma irrational_iff_ne_rational (x : ℝ) : irrational x ↔ ∀ a b : ℤ, x ≠ a / b := by simp only [irrational, rat.forall, cast_mk, not_exists, set.mem_range, cast_coe_int, cast_div, eq_comm] /-- A transcendental real number is irrational. -/ lemma transcendental.irrational {r : ℝ} (tr : transcendental ℚ r) : irrational r := by { rintro ⟨a, rfl⟩, exact tr (is_algebraic_algebra_map a) } /-! ### Irrationality of roots of integer and rational numbers -/ /-- If `x^n`, `n > 0`, is integer and is not the `n`-th power of an integer, then `x` is irrational. -/ theorem irrational_nrt_of_notint_nrt {x : ℝ} (n : ℕ) (m : ℤ) (hxr : x ^ n = m) (hv : ¬ ∃ y : ℤ, x = y) (hnpos : 0 < n) : irrational x := begin rintros ⟨⟨N, D, P, C⟩, rfl⟩, rw [← cast_pow] at hxr, have c1 : ((D : ℤ) : ℝ) ≠ 0, { rw [int.cast_ne_zero, int.coe_nat_ne_zero], exact ne_of_gt P }, have c2 : ((D : ℤ) : ℝ) ^ n ≠ 0 := pow_ne_zero _ c1, rw [num_denom', cast_pow, cast_mk, div_pow, div_eq_iff_mul_eq c2, ← int.cast_pow, ← int.cast_pow, ← int.cast_mul, int.cast_inj] at hxr, have hdivn : ↑D ^ n ∣ N ^ n := dvd.intro_left m hxr, rw [← int.dvd_nat_abs, ← int.coe_nat_pow, int.coe_nat_dvd, int.nat_abs_pow, nat.pow_dvd_pow_iff hnpos] at hdivn, have hD : D = 1 := by rw [← nat.gcd_eq_right hdivn, C.gcd_eq_one], subst D, refine hv ⟨N, _⟩, rw [num_denom', int.coe_nat_one, mk_eq_div, int.cast_one, div_one, cast_coe_int] end /-- If `x^n = m` is an integer and `n` does not divide the `multiplicity p m`, then `x` is irrational. -/ theorem irrational_nrt_of_n_not_dvd_multiplicity {x : ℝ} (n : ℕ) {m : ℤ} (hm : m ≠ 0) (p : ℕ) [hp : fact p.prime] (hxr : x ^ n = m) (hv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.1.ne_one, hm⟩) % n ≠ 0) : irrational x := begin rcases nat.eq_zero_or_pos n with rfl | hnpos, { rw [eq_comm, pow_zero, ← int.cast_one, int.cast_inj] at hxr, simpa [hxr, multiplicity.one_right (mt is_unit_iff_dvd_one.1 (mt int.coe_nat_dvd.1 hp.1.not_dvd_one)), nat.zero_mod] using hv }, refine irrational_nrt_of_notint_nrt _ _ hxr _ hnpos, rintro ⟨y, rfl⟩, rw [← int.cast_pow, int.cast_inj] at hxr, subst m, have : y ≠ 0, { rintro rfl, rw zero_pow hnpos at hm, exact hm rfl }, erw [multiplicity.pow' (nat.prime_iff_prime_int.1 hp.1) (finite_int_iff.2 ⟨hp.1.ne_one, this⟩), nat.mul_mod_right] at hv, exact hv rfl end theorem irrational_sqrt_of_multiplicity_odd (m : ℤ) (hm : 0 < m) (p : ℕ) [hp : fact p.prime] (Hpv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.1.ne_one, (ne_of_lt hm).symm⟩) % 2 = 1) : irrational (sqrt m) := @irrational_nrt_of_n_not_dvd_multiplicity _ 2 _ (ne.symm (ne_of_lt hm)) p hp (sqr_sqrt (int.cast_nonneg.2 $ le_of_lt hm)) (by rw Hpv; exact one_ne_zero) theorem nat.prime.irrational_sqrt {p : ℕ} (hp : nat.prime p) : irrational (sqrt p) := @irrational_sqrt_of_multiplicity_odd p (int.coe_nat_pos.2 hp.pos) p ⟨hp⟩ $ by simp [multiplicity_self (mt is_unit_iff_dvd_one.1 (mt int.coe_nat_dvd.1 hp.not_dvd_one) : _)]; refl theorem irrational_sqrt_two : irrational (sqrt 2) := by simpa using nat.prime_two.irrational_sqrt theorem irrational_sqrt_rat_iff (q : ℚ) : irrational (sqrt q) ↔ rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q := if H1 : rat.sqrt q * rat.sqrt q = q then iff_of_false (not_not_intro ⟨rat.sqrt q, by rw [← H1, cast_mul, sqrt_mul_self (cast_nonneg.2 $ rat.sqrt_nonneg q), sqrt_eq, abs_of_nonneg (rat.sqrt_nonneg q)]⟩) (λ h, h.1 H1) else if H2 : 0 ≤ q then iff_of_true (λ ⟨r, hr⟩, H1 $ (exists_mul_self _).1 ⟨r, by rwa [eq_comm, sqrt_eq_iff_mul_self_eq (cast_nonneg.2 H2), ← cast_mul, rat.cast_inj] at hr; rw [← hr]; exact real.sqrt_nonneg _⟩) ⟨H1, H2⟩ else iff_of_false (not_not_intro ⟨0, by rw cast_zero; exact (sqrt_eq_zero_of_nonpos (rat.cast_nonpos.2 $ le_of_not_le H2)).symm⟩) (λ h, H2 h.2) instance (q : ℚ) : decidable (irrational (sqrt q)) := decidable_of_iff' _ (irrational_sqrt_rat_iff q) /-! ### Adding/subtracting/multiplying by rational numbers -/ lemma rat.not_irrational (q : ℚ) : ¬irrational q := λ h, h ⟨q, rfl⟩ namespace irrational variables (q : ℚ) {x y : ℝ} open_locale classical theorem add_cases : irrational (x + y) → irrational x ∨ irrational y := begin delta irrational, contrapose!, rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩, exact ⟨rx + ry, cast_add rx ry⟩ end theorem of_rat_add (h : irrational (q + x)) : irrational x := h.add_cases.elim (λ h, absurd h q.not_irrational) id theorem rat_add (h : irrational x) : irrational (q + x) := of_rat_add (-q) $ by rwa [cast_neg, neg_add_cancel_left] theorem of_add_rat : irrational (x + q) → irrational x := add_comm ↑q x ▸ of_rat_add q theorem add_rat (h : irrational x) : irrational (x + q) := add_comm ↑q x ▸ h.rat_add q theorem of_neg (h : irrational (-x)) : irrational x := λ ⟨q, hx⟩, h ⟨-q, by rw [cast_neg, hx]⟩ protected theorem neg (h : irrational x) : irrational (-x) := of_neg $ by rwa neg_neg theorem sub_rat (h : irrational x) : irrational (x - q) := by simpa only [sub_eq_add_neg, cast_neg] using h.add_rat (-q) theorem rat_sub (h : irrational x) : irrational (q - x) := by simpa only [sub_eq_add_neg] using h.neg.rat_add q theorem of_sub_rat (h : irrational (x - q)) : irrational x := (of_add_rat (-q) $ by simpa only [cast_neg, sub_eq_add_neg] using h) theorem of_rat_sub (h : irrational (q - x)) : irrational x := of_neg (of_rat_add q (by simpa only [sub_eq_add_neg] using h)) theorem mul_cases : irrational (x * y) → irrational x ∨ irrational y := begin delta irrational, contrapose!, rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩, exact ⟨rx * ry, cast_mul rx ry⟩ end theorem of_mul_rat (h : irrational (x * q)) : irrational x := h.mul_cases.elim id (λ h, absurd h q.not_irrational) theorem mul_rat (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (x * q) := of_mul_rat q⁻¹ $ by rwa [mul_assoc, ← cast_mul, mul_inv_cancel hq, cast_one, mul_one] theorem of_rat_mul : irrational (q * x) → irrational x := mul_comm x q ▸ of_mul_rat q theorem rat_mul (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (q * x) := mul_comm x q ▸ h.mul_rat hq theorem of_mul_self (h : irrational (x * x)) : irrational x := h.mul_cases.elim id id theorem of_inv (h : irrational x⁻¹) : irrational x := λ ⟨q, hq⟩, h $ hq ▸ ⟨q⁻¹, q.cast_inv⟩ protected theorem inv (h : irrational x) : irrational x⁻¹ := of_inv $ by rwa inv_inv' theorem div_cases (h : irrational (x / y)) : irrational x ∨ irrational y := h.mul_cases.imp id of_inv theorem of_rat_div (h : irrational (q / x)) : irrational x := (h.of_rat_mul q).of_inv theorem of_one_div (h : irrational (1 / x)) : irrational x := of_rat_div 1 $ by rwa [cast_one] theorem of_pow : ∀ n : ℕ, irrational (x^n) → irrational x | 0 := λ h, (h ⟨1, cast_one⟩).elim | (n+1) := λ h, h.mul_cases.elim id (of_pow n) theorem of_fpow : ∀ m : ℤ, irrational (x^m) → irrational x | (n:ℕ) := of_pow n | -[1+n] := λ h, by { rw fpow_neg_succ_of_nat at h, exact h.of_inv.of_pow _ } end irrational section polynomial open polynomial variables (x : ℝ) (p : polynomial ℤ) lemma one_lt_nat_degree_of_irrational_root (hx : irrational x) (p_nonzero : p ≠ 0) (x_is_root : aeval x p = 0) : 1 < p.nat_degree := begin by_contra rid, rcases exists_eq_X_add_C_of_nat_degree_le_one (not_lt.1 rid) with ⟨a, b, rfl⟩, clear rid, have : (a : ℝ) * x = -b, by simpa [eq_neg_iff_add_eq_zero] using x_is_root, rcases em (a = 0) with (rfl|ha), { obtain rfl : b = 0, by simpa, simpa using p_nonzero }, { rw [mul_comm, ← eq_div_iff_mul_eq, eq_comm] at this, refine hx ⟨-b / a, _⟩, assumption_mod_cast, assumption_mod_cast } end end polynomial section variables {q : ℚ} {x : ℝ} open irrational @[simp] theorem irrational_rat_add_iff : irrational (q + x) ↔ irrational x := ⟨of_rat_add q, rat_add q⟩ @[simp] theorem irrational_add_rat_iff : irrational (x + q) ↔ irrational x := ⟨of_add_rat q, add_rat q⟩ @[simp] theorem irrational_rat_sub_iff : irrational (q - x) ↔ irrational x := ⟨of_rat_sub q, rat_sub q⟩ @[simp] theorem irrational_sub_rat_iff : irrational (x - q) ↔ irrational x := ⟨of_sub_rat q, sub_rat q⟩ @[simp] theorem irrational_neg_iff : irrational (-x) ↔ irrational x := ⟨of_neg, irrational.neg⟩ @[simp] theorem irrational_inv_iff : irrational x⁻¹ ↔ irrational x := ⟨of_inv, irrational.inv⟩ end
dcf697bb63617344cb447d63c6915e241c686157
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/analysis/calculus/fderiv.lean
9dc5e2e36fdea9a757f4703df8957135f92806f0
[ "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
80,385
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Sébastien Gouëzel, Yury Kudryashov -/ import analysis.asymptotics analysis.calculus.tangent_cone /-! # The Fréchet derivative Let `E` and `F` be normed spaces, `f : E → F`, and `f' : E →L[𝕜] F` a continuous 𝕜-linear map, where `𝕜` is a non-discrete normed field. Then `has_fderiv_within_at f f' s x` says that `f` has derivative `f'` at `x`, where the domain of interest is restricted to `s`. We also have `has_fderiv_at f f' x := has_fderiv_within_at f f' x univ` ## Main results In addition to the definition and basic properties of the derivative, this file contains the usual formulas (and existence assertions) for the derivative of * constants * the identity * bounded linear maps * bounded bilinear maps * sum of two functions * multiplication of a function by a scalar constant * negative of a function * subtraction of two functions * multiplication of a function by a scalar function * multiplication of two scalar functions * composition of functions (the chain rule) For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. One can also interpret the derivative of a function `f : 𝕜 → E` as an element of `E` (by identifying a linear function from `𝕜` to `E` with its value at `1`). Results on the Fréchet derivative are translated to this more elementary point of view on the derivative in the file `deriv.lean`. The derivative of polynomials is handled there, as it is naturally one-dimensional. ## Implementation details The derivative is defined in terms of the `is_o` relation, but also characterized in terms of the `tendsto` relation. We also introduce predicates `differentiable_within_at 𝕜 f s x` (where `𝕜` is the base field, `f` the function to be differentiated, `x` the point at which the derivative is asserted to exist, and `s` the set along which the derivative is defined), as well as `differentiable_at 𝕜 f x`, `differentiable_on 𝕜 f s` and `differentiable 𝕜 f` to express the existence of a derivative. To be able to compute with derivatives, we write `fderiv_within 𝕜 f s x` and `fderiv 𝕜 f x` for some choice of a derivative if it exists, and the zero function otherwise. This choice only behaves well along sets for which the derivative is unique, i.e., those for which the tangent directions span a dense subset of the whole space. The predicates `unique_diff_within_at s x` and `unique_diff_on s`, defined in `tangent_cone.lean` express this property. We prove that indeed they imply the uniqueness of the derivative. This is satisfied for open subsets, and in particular for `univ`. This uniqueness only holds when the field is non-discrete, which we request at the very beginning: otherwise, a derivative can be defined, but it has no interesting properties whatsoever. ## Tags derivative, differentiable, Fréchet, calculus -/ open filter asymptotics continuous_linear_map set open_locale topological_space classical noncomputable theory set_option class.instance_max_depth 90 section variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space 𝕜 G] /-- A function `f` has the continuous linear map `f'` as derivative along the filter `L` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` converges along the filter `L`. This definition is designed to be specialized for `L = 𝓝 x` (in `has_fderiv_at`), giving rise to the usual notion of Fréchet derivative, and for `L = nhds_within x s` (in `has_fderiv_within_at`), giving rise to the notion of Fréchet derivative along the set `s`. -/ def has_fderiv_at_filter (f : E → F) (f' : E →L[𝕜] F) (x : E) (L : filter E) := is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L /-- A function `f` has the continuous linear map `f'` as derivative at `x` within a set `s` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x` inside `s`. -/ def has_fderiv_within_at (f : E → F) (f' : E →L[𝕜] F) (s : set E) (x : E) := has_fderiv_at_filter f f' x (nhds_within x s) /-- A function `f` has the continuous linear map `f'` as derivative at `x` if `f x' = f x + f' (x' - x) + o (x' - x)` when `x'` tends to `x`. -/ def has_fderiv_at (f : E → F) (f' : E →L[𝕜] F) (x : E) := has_fderiv_at_filter f f' x (𝓝 x) variables (𝕜) /-- A function `f` is differentiable at a point `x` within a set `s` if it admits a derivative there (possibly non-unique). -/ def differentiable_within_at (f : E → F) (s : set E) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_within_at f f' s x /-- A function `f` is differentiable at a point `x` if it admits a derivative there (possibly non-unique). -/ def differentiable_at (f : E → F) (x : E) := ∃f' : E →L[𝕜] F, has_fderiv_at f f' x /-- If `f` has a derivative at `x` within `s`, then `fderiv_within 𝕜 f s x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv_within (f : E → F) (s : set E) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_within_at f f' s x then classical.some h else 0 /-- If `f` has a derivative at `x`, then `fderiv 𝕜 f x` is such a derivative. Otherwise, it is set to `0`. -/ def fderiv (f : E → F) (x : E) : E →L[𝕜] F := if h : ∃f', has_fderiv_at f f' x then classical.some h else 0 /-- `differentiable_on 𝕜 f s` means that `f` is differentiable within `s` at any point of `s`. -/ def differentiable_on (f : E → F) (s : set E) := ∀x ∈ s, differentiable_within_at 𝕜 f s x /-- `differentiable 𝕜 f` means that `f` is differentiable at any point. -/ def differentiable (f : E → F) := ∀x, differentiable_at 𝕜 f x variables {𝕜} variables {f f₀ f₁ g : E → F} variables {f' f₀' f₁' g' : E →L[𝕜] F} variables (e : E →L[𝕜] F) variables {x : E} variables {s t : set E} variables {L L₁ L₂ : filter E} lemma fderiv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 f s x = 0 := have ¬ ∃ f', has_fderiv_within_at f f' s x, from h, by simp [fderiv_within, this] lemma fderiv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : fderiv 𝕜 f x = 0 := have ¬ ∃ f', has_fderiv_at f f' x, from h, by simp [fderiv, this] section derivative_uniqueness /- In this section, we discuss the uniqueness of the derivative. We prove that the definitions `unique_diff_within_at` and `unique_diff_on` indeed imply the uniqueness of the derivative. -/ /-- If a function f has a derivative f' at x, a rescaled version of f around x converges to f', i.e., `n (f (x + (1/n) v) - f x)` converges to `f' v`. More generally, if `c n` tends to infinity and `c n * d n` tends to `v`, then `c n * (f (x + d n) - f x)` tends to `f' v`. This lemma expresses this fact, for functions having a derivative within a set. Its specific formulation is useful for tangent cone related discussions. -/ theorem has_fderiv_within_at.lim (h : has_fderiv_within_at f f' s x) {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} {v : E} (dtop : ∀ᶠ n in l, x + d n ∈ s) (clim : tendsto (λ n, ∥c n∥) l at_top) (cdlim : tendsto (λ n, c n • d n) l (𝓝 v)) : tendsto (λn, c n • (f (x + d n) - f x)) l (𝓝 (f' v)) := begin have tendsto_arg : tendsto (λ n, x + d n) l (nhds_within x s), { conv in (nhds_within x s) { rw ← add_zero x }, rw [nhds_within, tendsto_inf], split, { apply tendsto_const_nhds.add (tangent_cone_at.lim_zero l clim cdlim) }, { rwa tendsto_principal } }, have : is_o (λ y, f y - f x - f' (y - x)) (λ y, y - x) (nhds_within x s) := h, have : is_o (λ n, f (x + d n) - f x - f' ((x + d n) - x)) (λ n, (x + d n) - x) l := this.comp_tendsto tendsto_arg, have : is_o (λ n, f (x + d n) - f x - f' (d n)) d l := by simpa only [add_sub_cancel'], have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, c n • d n) l := (is_O_refl c l).smul_is_o this, have : is_o (λn, c n • (f (x + d n) - f x - f' (d n))) (λn, (1:ℝ)) l := this.trans_is_O (is_O_one_of_tendsto ℝ cdlim), have L1 : tendsto (λn, c n • (f (x + d n) - f x - f' (d n))) l (𝓝 0) := (is_o_one_iff ℝ).1 this, have L2 : tendsto (λn, f' (c n • d n)) l (𝓝 (f' v)) := tendsto.comp f'.cont.continuous_at cdlim, have L3 : tendsto (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) l (𝓝 (0 + f' v)) := L1.add L2, have : (λn, (c n • (f (x + d n) - f x - f' (d n)) + f' (c n • d n))) = (λn, c n • (f (x + d n) - f x)), by { ext n, simp [smul_add, smul_sub] }, rwa [this, zero_add] at L3 end /-- `unique_diff_within_at` achieves its goal: it implies the uniqueness of the derivative. -/ theorem unique_diff_within_at.eq (H : unique_diff_within_at 𝕜 s x) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := begin have A : ∀y ∈ tangent_cone_at 𝕜 s x, f' y = f₁' y, { rintros y ⟨c, d, dtop, clim, cdlim⟩, exact tendsto_nhds_unique (by simp) (h.lim at_top dtop clim cdlim) (h₁.lim at_top dtop clim cdlim) }, have B : ∀y ∈ submodule.span 𝕜 (tangent_cone_at 𝕜 s x), f' y = f₁' y, { assume y hy, apply submodule.span_induction hy, { exact λy hy, A y hy }, { simp only [continuous_linear_map.map_zero] }, { simp {contextual := tt} }, { simp {contextual := tt} } }, have C : ∀y ∈ closure ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E), f' y = f₁' y, { assume y hy, let K := {y | f' y = f₁' y}, have : (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ K := B, have : closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E) ⊆ closure K := closure_mono this, have : y ∈ closure K := this hy, rwa closure_eq_of_is_closed (is_closed_eq f'.continuous f₁'.continuous) at this }, rw H.1 at C, ext y, exact C y (mem_univ _) end theorem unique_diff_on.eq (H : unique_diff_on 𝕜 s) (hx : x ∈ s) (h : has_fderiv_within_at f f' s x) (h₁ : has_fderiv_within_at f f₁' s x) : f' = f₁' := unique_diff_within_at.eq (H x hx) h h₁ end derivative_uniqueness section fderiv_properties /-! ### Basic properties of the derivative -/ theorem has_fderiv_at_filter_iff_tendsto : has_fderiv_at_filter f f' x L ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) := have h : ∀ x', ∥x' - x∥ = 0 → ∥f x' - f x - f' (x' - x)∥ = 0, from λ x' hx', by { rw [sub_eq_zero.1 (norm_eq_zero.1 hx')], simp }, begin unfold has_fderiv_at_filter, rw [←is_o_norm_left, ←is_o_norm_right, is_o_iff_tendsto h], exact tendsto_congr (λ _, div_eq_inv_mul), end theorem has_fderiv_within_at_iff_tendsto : has_fderiv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_tendsto : has_fderiv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_fderiv_at_iff_is_o_nhds_zero : has_fderiv_at f f' x ↔ is_o (λh, f (x + h) - f x - f' h) (λh, h) (𝓝 0) := begin split, { assume H, have : tendsto (λ (z : E), z + x) (𝓝 0) (𝓝 (0 + x)), from tendsto_id.add tendsto_const_nhds, rw [zero_add] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel', add_comm z] }, { assume H, have : tendsto (λ (z : E), z - x) (𝓝 x) (𝓝 (x - x)), from tendsto_id.sub tendsto_const_nhds, rw [sub_self] at this, refine (H.comp_tendsto this).congr _ _; intro z; simp only [function.comp, add_sub_cancel'_right] } end theorem has_fderiv_at_filter.mono (h : has_fderiv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_fderiv_at_filter f f' x L₁ := h.mono hst theorem has_fderiv_within_at.mono (h : has_fderiv_within_at f f' t x) (hst : s ⊆ t) : has_fderiv_within_at f f' s x := h.mono (nhds_within_mono _ hst) theorem has_fderiv_at.has_fderiv_at_filter (h : has_fderiv_at f f' x) (hL : L ≤ 𝓝 x) : has_fderiv_at_filter f f' x L := h.mono hL theorem has_fderiv_at.has_fderiv_within_at (h : has_fderiv_at f f' x) : has_fderiv_within_at f f' s x := h.has_fderiv_at_filter inf_le_left lemma has_fderiv_within_at.differentiable_within_at (h : has_fderiv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := ⟨f', h⟩ lemma has_fderiv_at.differentiable_at (h : has_fderiv_at f f' x) : differentiable_at 𝕜 f x := ⟨f', h⟩ @[simp] lemma has_fderiv_within_at_univ : has_fderiv_within_at f f' univ x ↔ has_fderiv_at f f' x := by { simp only [has_fderiv_within_at, nhds_within_univ], refl } /-- Directional derivative agrees with `has_fderiv`. -/ lemma has_fderiv_at.lim (hf : has_fderiv_at f f' x) (v : E) {α : Type*} {c : α → 𝕜} {l : filter α} (hc : tendsto (λ n, ∥c n∥) l at_top) : tendsto (λ n, (c n) • (f (x + (c n)⁻¹ • v) - f x)) l (𝓝 (f' v)) := begin refine (has_fderiv_within_at_univ.2 hf).lim _ (univ_mem_sets' (λ _, trivial)) hc _, assume U hU, refine (eventually_ne_of_tendsto_norm_at_top hc (0:𝕜)).mono (λ y hy, _), convert mem_of_nhds hU, dsimp only [], rw [← mul_smul, mul_inv_cancel hy, one_smul] end theorem has_fderiv_at_unique (h₀ : has_fderiv_at f f₀' x) (h₁ : has_fderiv_at f f₁' x) : f₀' = f₁' := begin rw ← has_fderiv_within_at_univ at h₀ h₁, exact unique_diff_within_at_univ.eq h₀ h₁ end lemma has_fderiv_within_at_inter' (h : t ∈ nhds_within x s) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict'' s h] lemma has_fderiv_within_at_inter (h : t ∈ 𝓝 x) : has_fderiv_within_at f f' (s ∩ t) x ↔ has_fderiv_within_at f f' s x := by simp [has_fderiv_within_at, nhds_within_restrict' s h] lemma has_fderiv_within_at.union (hs : has_fderiv_within_at f f' s x) (ht : has_fderiv_within_at f f' t x) : has_fderiv_within_at f f' (s ∪ t) x := begin simp only [has_fderiv_within_at, nhds_within_union], exact hs.join ht, end lemma has_fderiv_within_at.nhds_within (h : has_fderiv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_fderiv_within_at f f' t x := (has_fderiv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_fderiv_within_at.has_fderiv_at (h : has_fderiv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_fderiv_at f f' x := by rwa [← univ_inter s, has_fderiv_within_at_inter hs, has_fderiv_within_at_univ] at h lemma differentiable_within_at.has_fderiv_within_at (h : differentiable_within_at 𝕜 f s x) : has_fderiv_within_at f (fderiv_within 𝕜 f s x) s x := begin dunfold fderiv_within, dunfold differentiable_within_at at h, rw dif_pos h, exact classical.some_spec h end lemma differentiable_at.has_fderiv_at (h : differentiable_at 𝕜 f x) : has_fderiv_at f (fderiv 𝕜 f x) x := begin dunfold fderiv, dunfold differentiable_at at h, rw dif_pos h, exact classical.some_spec h end lemma has_fderiv_at.fderiv (h : has_fderiv_at f f' x) : fderiv 𝕜 f x = f' := by { ext, rw has_fderiv_at_unique h h.differentiable_at.has_fderiv_at } lemma has_fderiv_within_at.fderiv_within (h : has_fderiv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = f' := (hxs.eq h h.differentiable_within_at.has_fderiv_within_at).symm /-- If `x` is not in the closure of `s`, then `f` has any derivative at `x` within `s`, as this statement is empty. -/ lemma has_fderiv_within_at_of_not_mem_closure (h : x ∉ closure s) : has_fderiv_within_at f f' s x := begin simp [mem_closure_iff_nhds_within_ne_bot] at h, simp [has_fderiv_within_at, has_fderiv_at_filter, h, is_o, is_O_with], end lemma differentiable_within_at.mono (h : differentiable_within_at 𝕜 f t x) (st : s ⊆ t) : differentiable_within_at 𝕜 f s x := begin rcases h with ⟨f', hf'⟩, exact ⟨f', hf'.mono st⟩ end lemma differentiable_within_at_univ : differentiable_within_at 𝕜 f univ x ↔ differentiable_at 𝕜 f x := by simp only [differentiable_within_at, has_fderiv_within_at_univ, differentiable_at] lemma differentiable_within_at_inter (ht : t ∈ 𝓝 x) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict' s ht] lemma differentiable_within_at_inter' (ht : t ∈ nhds_within x s) : differentiable_within_at 𝕜 f (s ∩ t) x ↔ differentiable_within_at 𝕜 f s x := by simp only [differentiable_within_at, has_fderiv_within_at, has_fderiv_at_filter, nhds_within_restrict'' s ht] lemma differentiable_at.differentiable_within_at (h : differentiable_at 𝕜 f x) : differentiable_within_at 𝕜 f s x := (differentiable_within_at_univ.2 h).mono (subset_univ _) lemma differentiable.differentiable_at (h : differentiable 𝕜 f) : differentiable_at 𝕜 f x := h x lemma differentiable_within_at.differentiable_at (h : differentiable_within_at 𝕜 f s x) (hs : s ∈ 𝓝 x) : differentiable_at 𝕜 f x := h.imp (λ f' hf', hf'.has_fderiv_at hs) lemma differentiable_at.fderiv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = fderiv 𝕜 f x := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact h.has_fderiv_at.has_fderiv_within_at end lemma differentiable_on.mono (h : differentiable_on 𝕜 f t) (st : s ⊆ t) : differentiable_on 𝕜 f s := λx hx, (h x (st hx)).mono st lemma differentiable_on_univ : differentiable_on 𝕜 f univ ↔ differentiable 𝕜 f := by { simp [differentiable_on, differentiable_within_at_univ], refl } lemma differentiable.differentiable_on (h : differentiable 𝕜 f) : differentiable_on 𝕜 f s := (differentiable_on_univ.2 h).mono (subset_univ _) lemma differentiable_on_of_locally_differentiable_on (h : ∀x∈s, ∃u, is_open u ∧ x ∈ u ∧ differentiable_on 𝕜 f (s ∩ u)) : differentiable_on 𝕜 f s := begin assume x xs, rcases h x xs with ⟨t, t_open, xt, ht⟩, exact (differentiable_within_at_inter (mem_nhds_sets t_open xt)).1 (ht x ⟨xs, xt⟩) end lemma fderiv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : fderiv_within 𝕜 f s x = fderiv_within 𝕜 f t x := ((differentiable_within_at.has_fderiv_within_at h).mono st).fderiv_within ht @[simp] lemma fderiv_within_univ : fderiv_within 𝕜 f univ = fderiv 𝕜 f := begin ext x : 1, by_cases h : differentiable_at 𝕜 f x, { apply has_fderiv_within_at.fderiv_within _ unique_diff_within_at_univ, rw has_fderiv_within_at_univ, apply h.has_fderiv_at }, { have : ¬ differentiable_within_at 𝕜 f univ x, by contrapose! h; rwa ← differentiable_within_at_univ, rw [fderiv_zero_of_not_differentiable_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end lemma fderiv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f (s ∩ t) x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f (s ∩ t) x, { apply fderiv_within_subset (inter_subset_left _ _) _ ((differentiable_within_at_inter ht).1 h), apply hs.inter ht }, { have : ¬ differentiable_within_at 𝕜 f s x, by contrapose! h; rw differentiable_within_at_inter; assumption, rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this] } end end fderiv_properties section congr /-! ### congr properties of the derivative -/ theorem has_fderiv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, f₀ x = f₁ x) (h₁ : ∀ x, f₀' x = f₁' x) : has_fderiv_at_filter f₀ f₀' x L ↔ has_fderiv_at_filter f₁ f₁' x L := by { rw (ext h₁), exact is_o_congr (by filter_upwards [h₀] λ x (h : _ = _), by simp [h, hx]) (univ_mem_sets' $ λ _, rfl) } lemma has_fderiv_at_filter.congr_of_mem_sets (h : has_fderiv_at_filter f f' x L) (hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_at_filter f₁ f' x L := begin apply (has_fderiv_at_filter_congr_of_mem_sets hx hL _).2 h, exact λx, rfl end lemma has_fderiv_within_at.congr_mono (h : has_fderiv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_fderiv_within_at f₁ f' t x := has_fderiv_at_filter.congr_of_mem_sets (h.mono h₁) (filter.mem_inf_sets_of_right ht) hx lemma has_fderiv_within_at.congr (h : has_fderiv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_fderiv_within_at.congr_of_mem_nhds_within (h : has_fderiv_within_at f f' s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_fderiv_within_at f₁ f' s x := has_fderiv_at_filter.congr_of_mem_sets h h₁ hx lemma has_fderiv_at.congr_of_mem_nhds (h : has_fderiv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_fderiv_at f₁ f' x := has_fderiv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma differentiable_within_at.congr_mono (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : differentiable_within_at 𝕜 f₁ t x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at ht hx h₁).differentiable_within_at lemma differentiable_within_at.congr (h : differentiable_within_at 𝕜 f s x) (ht : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := differentiable_within_at.congr_mono h ht hx (subset.refl _) lemma differentiable_within_at.congr_of_mem_nhds_within (h : differentiable_within_at 𝕜 f s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : differentiable_within_at 𝕜 f₁ s x := (h.has_fderiv_within_at.congr_of_mem_nhds_within h₁ hx).differentiable_within_at lemma differentiable_on.congr_mono (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ t, f₁ x = f x) (h₁ : t ⊆ s) : differentiable_on 𝕜 f₁ t := λ x hx, (h x (h₁ hx)).congr_mono h' (h' x hx) h₁ lemma differentiable_on.congr (h : differentiable_on 𝕜 f s) (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s := λ x hx, (h x hx).congr h' (h' x hx) lemma differentiable_on_congr (h' : ∀x ∈ s, f₁ x = f x) : differentiable_on 𝕜 f₁ s ↔ differentiable_on 𝕜 f s := ⟨λ h, differentiable_on.congr h (λy hy, (h' y hy).symm), λ h, differentiable_on.congr h h'⟩ lemma differentiable_at.congr_of_mem_nhds (h : differentiable_at 𝕜 f x) (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : differentiable_at 𝕜 f₁ x := has_fderiv_at.differentiable_at (has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_at hL (mem_of_nhds hL : _)) lemma differentiable_within_at.fderiv_within_congr_mono (h : differentiable_within_at 𝕜 f s x) (hs : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (hxt : unique_diff_within_at 𝕜 t x) (h₁ : t ⊆ s) : fderiv_within 𝕜 f₁ t x = fderiv_within 𝕜 f s x := (has_fderiv_within_at.congr_mono h.has_fderiv_within_at hs hx h₁).fderiv_within hxt lemma fderiv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin by_cases h : differentiable_within_at 𝕜 f s x ∨ differentiable_within_at 𝕜 f₁ s x, { cases h, { apply has_fderiv_within_at.fderiv_within _ hs, exact has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_within_at hL hx }, { symmetry, apply has_fderiv_within_at.fderiv_within _ hs, apply has_fderiv_at_filter.congr_of_mem_sets h.has_fderiv_within_at _ hx.symm, convert hL, ext y, exact eq_comm } }, { push_neg at h, have A : fderiv_within 𝕜 f s x = 0, by { unfold differentiable_within_at at h, simp [fderiv_within, h] }, have A₁ : fderiv_within 𝕜 f₁ s x = 0, by { unfold differentiable_within_at at h, simp [fderiv_within, h] }, rw [A, A₁] } end lemma fderiv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : fderiv_within 𝕜 f₁ s x = fderiv_within 𝕜 f s x := begin apply fderiv_within_congr_of_mem_nhds_within hs _ hx, apply mem_sets_of_superset self_mem_nhds_within, exact hL end lemma fderiv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : fderiv 𝕜 f₁ x = fderiv 𝕜 f x := begin have A : f₁ x = f x := (mem_of_nhds hL : _), rw [← fderiv_within_univ, ← fderiv_within_univ], rw ← nhds_within_univ at hL, exact fderiv_within_congr_of_mem_nhds_within unique_diff_within_at_univ hL A end end congr section id /-! ### Derivative of the identity -/ theorem has_fderiv_at_filter_id (x : E) (L : filter E) : has_fderiv_at_filter id (id : E →L[𝕜] E) x L := (is_o_zero _ _).congr_left $ by simp theorem has_fderiv_within_at_id (x : E) (s : set E) : has_fderiv_within_at id (id : E →L[𝕜] E) s x := has_fderiv_at_filter_id _ _ theorem has_fderiv_at_id (x : E) : has_fderiv_at id (id : E →L[𝕜] E) x := has_fderiv_at_filter_id _ _ lemma differentiable_at_id : differentiable_at 𝕜 id x := (has_fderiv_at_id x).differentiable_at lemma differentiable_within_at_id : differentiable_within_at 𝕜 id s x := differentiable_at_id.differentiable_within_at lemma differentiable_id : differentiable 𝕜 (id : E → E) := λx, differentiable_at_id lemma differentiable_on_id : differentiable_on 𝕜 id s := differentiable_id.differentiable_on lemma fderiv_id : fderiv 𝕜 id x = id := has_fderiv_at.fderiv (has_fderiv_at_id x) lemma fderiv_within_id (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 id s x = id := begin rw differentiable_at.fderiv_within (differentiable_at_id) hxs, exact fderiv_id end end id section const /-! ### derivative of a constant function -/ theorem has_fderiv_at_filter_const (c : F) (x : E) (L : filter E) : has_fderiv_at_filter (λ x, c) (0 : E →L[𝕜] F) x L := (is_o_zero _ _).congr_left $ λ _, by simp only [zero_apply, sub_self] theorem has_fderiv_within_at_const (c : F) (x : E) (s : set E) : has_fderiv_within_at (λ x, c) (0 : E →L[𝕜] F) s x := has_fderiv_at_filter_const _ _ _ theorem has_fderiv_at_const (c : F) (x : E) : has_fderiv_at (λ x, c) (0 : E →L[𝕜] F) x := has_fderiv_at_filter_const _ _ _ lemma differentiable_at_const (c : F) : differentiable_at 𝕜 (λx, c) x := ⟨0, has_fderiv_at_const c x⟩ lemma differentiable_within_at_const (c : F) : differentiable_within_at 𝕜 (λx, c) s x := differentiable_at.differentiable_within_at (differentiable_at_const _) lemma fderiv_const_apply (c : F) : fderiv 𝕜 (λy, c) x = 0 := has_fderiv_at.fderiv (has_fderiv_at_const c x) lemma fderiv_const (c : F) : fderiv 𝕜 (λ (y : E), c) = 0 := by { ext m, rw fderiv_const_apply, refl } lemma fderiv_within_const_apply (c : F) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λy, c) s x = 0 := begin rw differentiable_at.fderiv_within (differentiable_at_const _) hxs, exact fderiv_const_apply _ end lemma differentiable_const (c : F) : differentiable 𝕜 (λx : E, c) := λx, differentiable_at_const _ lemma differentiable_on_const (c : F) : differentiable_on 𝕜 (λx, c) s := (differentiable_const _).differentiable_on end const section continuous_linear_map /-! ### Continuous linear maps There are currently two variants of these in mathlib, the bundled version (named `continuous_linear_map`, and denoted `E →L[𝕜] F`), and the unbundled version (with a predicate `is_bounded_linear_map`). We give statements for both versions. -/ lemma is_bounded_linear_map.has_fderiv_at_filter (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at_filter f h.to_continuous_linear_map x L := begin have : (λ (x' : E), f x' - f x - h.to_continuous_linear_map (x' - x)) = λx', 0, { ext, have : ∀a, h.to_continuous_linear_map a = f a := λa, rfl, simp, simp [this] }, rw [has_fderiv_at_filter, this], exact asymptotics.is_o_zero _ _ end lemma is_bounded_linear_map.has_fderiv_within_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_within_at f h.to_continuous_linear_map s x := h.has_fderiv_at_filter lemma is_bounded_linear_map.has_fderiv_at (h : is_bounded_linear_map 𝕜 f) : has_fderiv_at f h.to_continuous_linear_map x := h.has_fderiv_at_filter lemma is_bounded_linear_map.differentiable_at (h : is_bounded_linear_map 𝕜 f) : differentiable_at 𝕜 f x := h.has_fderiv_at.differentiable_at lemma is_bounded_linear_map.differentiable_within_at (h : is_bounded_linear_map 𝕜 f) : differentiable_within_at 𝕜 f s x := h.differentiable_at.differentiable_within_at lemma is_bounded_linear_map.fderiv (h : is_bounded_linear_map 𝕜 f) : fderiv 𝕜 f x = h.to_continuous_linear_map := has_fderiv_at.fderiv (h.has_fderiv_at) lemma is_bounded_linear_map.fderiv_within (h : is_bounded_linear_map 𝕜 f) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 f s x = h.to_continuous_linear_map := begin rw differentiable_at.fderiv_within h.differentiable_at hxs, exact h.fderiv end lemma is_bounded_linear_map.differentiable (h : is_bounded_linear_map 𝕜 f) : differentiable 𝕜 f := λx, h.differentiable_at lemma is_bounded_linear_map.differentiable_on (h : is_bounded_linear_map 𝕜 f) : differentiable_on 𝕜 f s := h.differentiable.differentiable_on lemma continuous_linear_map.has_fderiv_at_filter : has_fderiv_at_filter e e x L := begin have : (λ (x' : E), e x' - e x - e (x' - x)) = λx', 0, by { ext, simp }, rw [has_fderiv_at_filter, this], exact asymptotics.is_o_zero _ _ end protected lemma continuous_linear_map.has_fderiv_within_at : has_fderiv_within_at e e s x := e.has_fderiv_at_filter protected lemma continuous_linear_map.has_fderiv_at : has_fderiv_at e e x := e.has_fderiv_at_filter protected lemma continuous_linear_map.differentiable_at : differentiable_at 𝕜 e x := e.has_fderiv_at.differentiable_at protected lemma continuous_linear_map.differentiable_within_at : differentiable_within_at 𝕜 e s x := e.differentiable_at.differentiable_within_at protected lemma continuous_linear_map.fderiv : fderiv 𝕜 e x = e := e.has_fderiv_at.fderiv protected lemma continuous_linear_map.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 e s x = e := begin rw differentiable_at.fderiv_within e.differentiable_at hxs, exact e.fderiv end protected lemma continuous_linear_map.differentiable : differentiable 𝕜 e := λx, e.differentiable_at protected lemma continuous_linear_map.differentiable_on : differentiable_on 𝕜 e s := e.differentiable.differentiable_on end continuous_linear_map section const_smul /-! ### Derivative of a function multiplied by a constant -/ theorem has_fderiv_at_filter.const_smul (h : has_fderiv_at_filter f f' x L) (c : 𝕜) : has_fderiv_at_filter (λ x, c • f x) (c • f') x L := (is_o_const_smul_left h c).congr_left $ λ x, by simp [smul_sub] theorem has_fderiv_within_at.const_smul (h : has_fderiv_within_at f f' s x) (c : 𝕜) : has_fderiv_within_at (λ x, c • f x) (c • f') s x := h.const_smul c theorem has_fderiv_at.const_smul (h : has_fderiv_at f f' x) (c : 𝕜) : has_fderiv_at (λ x, c • f x) (c • f') x := h.const_smul c lemma differentiable_within_at.const_smul (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : differentiable_within_at 𝕜 (λy, c • f y) s x := (h.has_fderiv_within_at.const_smul c).differentiable_within_at lemma differentiable_at.const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : differentiable_at 𝕜 (λy, c • f y) x := (h.has_fderiv_at.const_smul c).differentiable_at lemma differentiable_on.const_smul (h : differentiable_on 𝕜 f s) (c : 𝕜) : differentiable_on 𝕜 (λy, c • f y) s := λx hx, (h x hx).const_smul c lemma differentiable.const_smul (h : differentiable 𝕜 f) (c : 𝕜) : differentiable 𝕜 (λy, c • f y) := λx, (h x).const_smul c lemma fderiv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) (c : 𝕜) : fderiv_within 𝕜 (λy, c • f y) s x = c • fderiv_within 𝕜 f s x := (h.has_fderiv_within_at.const_smul c).fderiv_within hxs lemma fderiv_const_smul (h : differentiable_at 𝕜 f x) (c : 𝕜) : fderiv 𝕜 (λy, c • f y) x = c • fderiv 𝕜 f x := (h.has_fderiv_at.const_smul c).fderiv end const_smul section add /-! ### Derivative of the sum of two functions -/ theorem has_fderiv_at_filter.add (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ λ _, by simp [sub_eq_add_neg]; abel theorem has_fderiv_within_at.add (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_fderiv_at.add (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma differentiable_within_at.add (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y + g y) s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y + g y) x := (hf.has_fderiv_at.add hg.has_fderiv_at).differentiable_at lemma differentiable_on.add (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y + g y) s := λx hx, (hf x hx).add (hg x hx) lemma differentiable.add (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y + g y) := λx, (hf x).add (hg x) lemma fderiv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y + g y) s x = fderiv_within 𝕜 f s x + fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.add hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y + g y) x = fderiv 𝕜 f x + fderiv 𝕜 g x := (hf.has_fderiv_at.add hg.has_fderiv_at).fderiv theorem has_fderiv_at_filter.add_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_fderiv_at_filter_const _ _ _) theorem has_fderiv_within_at.add_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_fderiv_at.add_const (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, f x + c) f' x := hf.add_const c lemma differentiable_within_at.add_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y + c) s x := (hf.has_fderiv_within_at.add_const c).differentiable_within_at lemma differentiable_at.add_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y + c) x := (hf.has_fderiv_at.add_const c).differentiable_at lemma differentiable_on.add_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y + c) s := λx hx, (hf x hx).add_const c lemma differentiable.add_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y + c) := λx, (hf x).add_const c lemma fderiv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y + c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.add_const c).fderiv_within hxs lemma fderiv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y + c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.add_const c).fderiv theorem has_fderiv_at_filter.const_add (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_fderiv_at_filter_const _ _ _).add hf theorem has_fderiv_within_at.const_add (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_fderiv_at.const_add (hf : has_fderiv_at f f' x) (c : F): has_fderiv_at (λ x, c + f x) f' x := hf.const_add c lemma differentiable_within_at.const_add (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c + f y) s x := (hf.has_fderiv_within_at.const_add c).differentiable_within_at lemma differentiable_at.const_add (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c + f y) x := (hf.has_fderiv_at.const_add c).differentiable_at lemma differentiable_on.const_add (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c + f y) s := λx hx, (hf x hx).const_add c lemma differentiable.const_add (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c + f y) := λx, (hf x).const_add c lemma fderiv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c + f y) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_add c).fderiv_within hxs lemma fderiv_const_add (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c + f y) x = fderiv 𝕜 f x := (hf.has_fderiv_at.const_add c).fderiv end add section neg /-! ### Derivative of the negative of a function -/ theorem has_fderiv_at_filter.neg (h : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (λ x, -f x) (-f') x L := (h.const_smul (-1:𝕜)).congr (by simp) (by simp) theorem has_fderiv_within_at.neg (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_fderiv_at.neg (h : has_fderiv_at f f' x) : has_fderiv_at (λ x, -f x) (-f') x := h.neg lemma differentiable_within_at.neg (h : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λy, -f y) s x := h.has_fderiv_within_at.neg.differentiable_within_at lemma differentiable_at.neg (h : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λy, -f y) x := h.has_fderiv_at.neg.differentiable_at lemma differentiable_on.neg (h : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λy, -f y) s := λx hx, (h x hx).neg lemma differentiable.neg (h : differentiable 𝕜 f) : differentiable 𝕜 (λy, -f y) := λx, (h x).neg lemma fderiv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λy, -f y) s x = - fderiv_within 𝕜 f s x := h.has_fderiv_within_at.neg.fderiv_within hxs lemma fderiv_neg (h : differentiable_at 𝕜 f x) : fderiv 𝕜 (λy, -f y) x = - fderiv 𝕜 f x := h.has_fderiv_at.neg.fderiv end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_fderiv_at_filter.sub (hf : has_fderiv_at_filter f f' x L) (hg : has_fderiv_at_filter g g' x L) : has_fderiv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_fderiv_within_at.sub (hf : has_fderiv_within_at f f' s x) (hg : has_fderiv_within_at g g' s x) : has_fderiv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_fderiv_at.sub (hf : has_fderiv_at f f' x) (hg : has_fderiv_at g g' x) : has_fderiv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma differentiable_within_at.sub (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : differentiable_within_at 𝕜 (λ y, f y - g y) s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : differentiable_at 𝕜 (λ y, f y - g y) x := (hf.has_fderiv_at.sub hg.has_fderiv_at).differentiable_at lemma differentiable_on.sub (hf : differentiable_on 𝕜 f s) (hg : differentiable_on 𝕜 g s) : differentiable_on 𝕜 (λy, f y - g y) s := λx hx, (hf x hx).sub (hg x hx) lemma differentiable.sub (hf : differentiable 𝕜 f) (hg : differentiable 𝕜 g) : differentiable 𝕜 (λy, f y - g y) := λx, (hf x).sub (hg x) lemma fderiv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : fderiv_within 𝕜 (λy, f y - g y) s x = fderiv_within 𝕜 f s x - fderiv_within 𝕜 g s x := (hf.has_fderiv_within_at.sub hg.has_fderiv_within_at).fderiv_within hxs lemma fderiv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : fderiv 𝕜 (λy, f y - g y) x = fderiv 𝕜 f x - fderiv 𝕜 g x := (hf.has_fderiv_at.sub hg.has_fderiv_at).fderiv theorem has_fderiv_at_filter.is_O_sub (h : has_fderiv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := h.is_O.congr_of_sub.2 (f'.is_O_sub _ _) theorem has_fderiv_at_filter.sub_const (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_fderiv_within_at.sub_const (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_fderiv_at.sub_const (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, f x - c) f' x := hf.sub_const c lemma differentiable_within_at.sub_const (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, f y - c) s x := (hf.has_fderiv_within_at.sub_const c).differentiable_within_at lemma differentiable_at.sub_const (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, f y - c) x := (hf.has_fderiv_at.sub_const c).differentiable_at lemma differentiable_on.sub_const (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, f y - c) s := λx hx, (hf x hx).sub_const c lemma differentiable.sub_const (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, f y - c) := λx, (hf x).sub_const c lemma fderiv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, f y - c) s x = fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.sub_const c).fderiv_within hxs lemma fderiv_sub_const (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, f y - c) x = fderiv 𝕜 f x := (hf.has_fderiv_at.sub_const c).fderiv theorem has_fderiv_at_filter.const_sub (hf : has_fderiv_at_filter f f' x L) (c : F) : has_fderiv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_fderiv_within_at.const_sub (hf : has_fderiv_within_at f f' s x) (c : F) : has_fderiv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_fderiv_at.const_sub (hf : has_fderiv_at f f' x) (c : F) : has_fderiv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma differentiable_within_at.const_sub (hf : differentiable_within_at 𝕜 f s x) (c : F) : differentiable_within_at 𝕜 (λ y, c - f y) s x := (hf.has_fderiv_within_at.const_sub c).differentiable_within_at lemma differentiable_at.const_sub (hf : differentiable_at 𝕜 f x) (c : F) : differentiable_at 𝕜 (λ y, c - f y) x := (hf.has_fderiv_at.const_sub c).differentiable_at lemma differentiable_on.const_sub (hf : differentiable_on 𝕜 f s) (c : F) : differentiable_on 𝕜 (λy, c - f y) s := λx hx, (hf x hx).const_sub c lemma differentiable.const_sub (hf : differentiable 𝕜 f) (c : F) : differentiable 𝕜 (λy, c - f y) := λx, (hf x).const_sub c lemma fderiv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : fderiv_within 𝕜 (λy, c - f y) s x = -fderiv_within 𝕜 f s x := (hf.has_fderiv_within_at.const_sub c).fderiv_within hxs lemma fderiv_const_sub (hf : differentiable_at 𝕜 f x) (c : F) : fderiv 𝕜 (λy, c - f y) x = -fderiv 𝕜 f x := (hf.has_fderiv_at.const_sub c).fderiv end sub section continuous /-! ### Deducing continuity from differentiability -/ theorem has_fderiv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_fderiv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := begin have : tendsto (λ x', f x' - f x) L (𝓝 0), { refine h.is_O_sub.trans_tendsto (tendsto_le_left hL _), rw ← sub_self x, exact tendsto_id.sub tendsto_const_nhds }, have := tendsto.add this tendsto_const_nhds, rw zero_add (f x) at this, exact this.congr (by simp) end theorem has_fderiv_within_at.continuous_within_at (h : has_fderiv_within_at f f' s x) : continuous_within_at f s x := has_fderiv_at_filter.tendsto_nhds inf_le_left h theorem has_fderiv_at.continuous_at (h : has_fderiv_at f f' x) : continuous_at f x := has_fderiv_at_filter.tendsto_nhds (le_refl _) h lemma differentiable_within_at.continuous_within_at (h : differentiable_within_at 𝕜 f s x) : continuous_within_at f s x := let ⟨f', hf'⟩ := h in hf'.continuous_within_at lemma differentiable_at.continuous_at (h : differentiable_at 𝕜 f x) : continuous_at f x := let ⟨f', hf'⟩ := h in hf'.continuous_at lemma differentiable_on.continuous_on (h : differentiable_on 𝕜 f s) : continuous_on f s := λx hx, (h x hx).continuous_within_at lemma differentiable.continuous (h : differentiable 𝕜 f) : continuous f := continuous_iff_continuous_at.2 $ λx, (h x).continuous_at end continuous section bilinear_map /-! ### Derivative of a bounded bilinear map -/ variables {b : E × F → G} {u : set (E × F) } open normed_field lemma is_bounded_bilinear_map.has_fderiv_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_at b (h.deriv p) p := begin have : (λ (x : E × F), b x - b p - (h.deriv p) (x - p)) = (λx, b (x.1 - p.1, x.2 - p.2)), { ext x, delta is_bounded_bilinear_map.deriv, change b x - b p - (b (p.1, x.2-p.2) + b (x.1-p.1, p.2)) = b (x.1 - p.1, x.2 - p.2), have : b x = b (x.1, x.2), by { cases x, refl }, rw this, have : b p = b (p.1, p.2), by { cases p, refl }, rw this, simp only [h.map_sub_left, h.map_sub_right], abel }, rw [has_fderiv_at, has_fderiv_at_filter, this], rcases h.bound with ⟨C, Cpos, hC⟩, have A : asymptotics.is_O (λx : E × F, b (x.1 - p.1, x.2 - p.2)) (λx, ∥x - p∥ * ∥x - p∥) (𝓝 p) := ⟨C, filter.univ_mem_sets' (λx, begin simp only [mem_set_of_eq, norm_mul, norm_norm], calc ∥b (x.1 - p.1, x.2 - p.2)∥ ≤ C * ∥x.1 - p.1∥ * ∥x.2 - p.2∥ : hC _ _ ... ≤ C * ∥x-p∥ * ∥x-p∥ : by apply_rules [mul_le_mul, le_max_left, le_max_right, norm_nonneg, le_of_lt Cpos, le_refl, mul_nonneg, norm_nonneg, norm_nonneg] ... = C * (∥x-p∥ * ∥x-p∥) : mul_assoc _ _ _ end)⟩, have B : asymptotics.is_o (λ (x : E × F), ∥x - p∥ * ∥x - p∥) (λx, 1 * ∥x - p∥) (𝓝 p), { refine asymptotics.is_o.mul_is_O (asymptotics.is_o.norm_left _) (asymptotics.is_O_refl _ _), apply (asymptotics.is_o_one_iff ℝ).2, rw [← sub_self p], exact tendsto_id.sub tendsto_const_nhds }, simp only [one_mul, asymptotics.is_o_norm_right] at B, exact A.trans_is_o B end lemma is_bounded_bilinear_map.has_fderiv_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : has_fderiv_within_at b (h.deriv p) u p := (h.has_fderiv_at p).has_fderiv_within_at lemma is_bounded_bilinear_map.differentiable_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_at 𝕜 b p := (h.has_fderiv_at p).differentiable_at lemma is_bounded_bilinear_map.differentiable_within_at (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : differentiable_within_at 𝕜 b u p := (h.differentiable_at p).differentiable_within_at lemma is_bounded_bilinear_map.fderiv (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) : fderiv 𝕜 b p = h.deriv p := has_fderiv_at.fderiv (h.has_fderiv_at p) lemma is_bounded_bilinear_map.fderiv_within (h : is_bounded_bilinear_map 𝕜 b) (p : E × F) (hxs : unique_diff_within_at 𝕜 u p) : fderiv_within 𝕜 b u p = h.deriv p := begin rw differentiable_at.fderiv_within (h.differentiable_at p) hxs, exact h.fderiv p end lemma is_bounded_bilinear_map.differentiable (h : is_bounded_bilinear_map 𝕜 b) : differentiable 𝕜 b := λx, h.differentiable_at x lemma is_bounded_bilinear_map.differentiable_on (h : is_bounded_bilinear_map 𝕜 b) : differentiable_on 𝕜 b u := h.differentiable.differentiable_on lemma is_bounded_bilinear_map.continuous (h : is_bounded_bilinear_map 𝕜 b) : continuous b := h.differentiable.continuous lemma is_bounded_bilinear_map.continuous_left (h : is_bounded_bilinear_map 𝕜 b) {f : F} : continuous (λe, b (e, f)) := h.continuous.comp (continuous_id.prod_mk continuous_const) lemma is_bounded_bilinear_map.continuous_right (h : is_bounded_bilinear_map 𝕜 b) {e : E} : continuous (λf, b (e, f)) := h.continuous.comp (continuous_const.prod_mk continuous_id) end bilinear_map section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {f₂ : E → G} {f₂' : E →L[𝕜] G} lemma has_fderiv_at_filter.prod (hf₁ : has_fderiv_at_filter f₁ f₁' x L) (hf₂ : has_fderiv_at_filter f₂ f₂' x L) : has_fderiv_at_filter (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x L := begin have : (λ (x' : E), (f₁ x', f₂ x') - (f₁ x, f₂ x) - (continuous_linear_map.prod f₁' f₂') (x' -x)) = (λ (x' : E), (f₁ x' - f₁ x - f₁' (x' - x), f₂ x' - f₂ x - f₂' (x' - x))) := rfl, rw [has_fderiv_at_filter, this], rw [asymptotics.is_o_prod_left], exact ⟨hf₁, hf₂⟩ end lemma has_fderiv_within_at.prod (hf₁ : has_fderiv_within_at f₁ f₁' s x) (hf₂ : has_fderiv_within_at f₂ f₂' s x) : has_fderiv_within_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') s x := hf₁.prod hf₂ lemma has_fderiv_at.prod (hf₁ : has_fderiv_at f₁ f₁' x) (hf₂ : has_fderiv_at f₂ f₂' x) : has_fderiv_at (λx, (f₁ x, f₂ x)) (continuous_linear_map.prod f₁' f₂') x := hf₁.prod hf₂ lemma differentiable_within_at.prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) : differentiable_within_at 𝕜 (λx:E, (f₁ x, f₂ x)) s x := (hf₁.has_fderiv_within_at.prod hf₂.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : differentiable_at 𝕜 (λx:E, (f₁ x, f₂ x)) x := (hf₁.has_fderiv_at.prod hf₂.has_fderiv_at).differentiable_at lemma differentiable_on.prod (hf₁ : differentiable_on 𝕜 f₁ s) (hf₂ : differentiable_on 𝕜 f₂ s) : differentiable_on 𝕜 (λx:E, (f₁ x, f₂ x)) s := λx hx, differentiable_within_at.prod (hf₁ x hx) (hf₂ x hx) lemma differentiable.prod (hf₁ : differentiable 𝕜 f₁) (hf₂ : differentiable 𝕜 f₂) : differentiable 𝕜 (λx:E, (f₁ x, f₂ x)) := λ x, differentiable_at.prod (hf₁ x) (hf₂ x) lemma differentiable_at.fderiv_prod (hf₁ : differentiable_at 𝕜 f₁ x) (hf₂ : differentiable_at 𝕜 f₂ x) : fderiv 𝕜 (λx:E, (f₁ x, f₂ x)) x = continuous_linear_map.prod (fderiv 𝕜 f₁ x) (fderiv 𝕜 f₂ x) := has_fderiv_at.fderiv (has_fderiv_at.prod hf₁.has_fderiv_at hf₂.has_fderiv_at) lemma differentiable_at.fderiv_within_prod (hf₁ : differentiable_within_at 𝕜 f₁ s x) (hf₂ : differentiable_within_at 𝕜 f₂ s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx:E, (f₁ x, f₂ x)) s x = continuous_linear_map.prod (fderiv_within 𝕜 f₁ s x) (fderiv_within 𝕜 f₂ s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.prod hf₁.has_fderiv_within_at hf₂.has_fderiv_within_at end end cartesian_product section composition /-! ### Derivative of the composition of two functions For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_fderiv_at_filter.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := let eq₁ := (g'.is_O_comp _ _).trans_is_o hf in let eq₂ := (hg.comp_tendsto tendsto_map).trans_is_O hf.is_O_sub in by { refine eq₂.triangle (eq₁.congr_left (λ x', _)), simp } /- A readable version of the previous theorem, a general form of the chain rule. -/ example {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at_filter g g' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (g ∘ f) (g'.comp f') x L := begin unfold has_fderiv_at_filter at hg, have : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', f x' - f x) L, from hg.comp_tendsto (le_refl _), have eq₁ : is_o (λ x', g (f x') - g (f x) - g' (f x' - f x)) (λ x', x' - x) L, from this.trans_is_O hf.is_O_sub, have eq₂ : is_o (λ x', f x' - f x - f' (x' - x)) (λ x', x' - x) L, from hf, have : is_O (λ x', g' (f x' - f x - f' (x' - x))) (λ x', f x' - f x - f' (x' - x)) L, from g'.is_O_comp _ _, have : is_o (λ x', g' (f x' - f x - f' (x' - x))) (λ x', x' - x) L, from this.trans_is_o eq₂, have eq₃ : is_o (λ x', g' (f x' - f x) - (g' (f' (x' - x)))) (λ x', x' - x) L, by { refine this.congr_left _, simp}, exact eq₁.triangle eq₃ end theorem has_fderiv_within_at.comp {g : F → G} {g' : F →L[𝕜] G} {t : set F} (hg : has_fderiv_within_at g g' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin apply has_fderiv_at_filter.comp _ (has_fderiv_at_filter.mono hg _) hf, calc map f (nhds_within x s) ≤ nhds_within (f x) (f '' s) : hf.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (f x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_fderiv_at.comp {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (g ∘ f) (g'.comp f') x := (hg.mono hf.continuous_at).comp x hf theorem has_fderiv_at.comp_has_fderiv_within_at {g : F → G} {g' : F →L[𝕜] G} (hg : has_fderiv_at g g' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (g ∘ f) (g'.comp f') s x := begin rw ← has_fderiv_within_at_univ at hg, exact has_fderiv_within_at.comp x hg hf subset_preimage_univ end lemma differentiable_within_at.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) : differentiable_within_at 𝕜 (g ∘ f) s x := begin rcases hf with ⟨f', hf'⟩, rcases hg with ⟨g', hg'⟩, exact ⟨continuous_linear_map.comp g' f', hg'.comp x hf' h⟩ end lemma differentiable_at.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (g ∘ f) x := (hg.has_fderiv_at.comp x hf.has_fderiv_at).differentiable_at lemma differentiable_at.comp_differentiable_within_at {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (g ∘ f) s x := (differentiable_within_at_univ.2 hg).comp x hf (by simp) lemma fderiv_within.comp {g : F → G} {t : set F} (hg : differentiable_within_at 𝕜 g t (f x)) (hf : differentiable_within_at 𝕜 f s x) (h : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv_within 𝕜 g t (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_within_at.comp x (hg.has_fderiv_within_at) (hf.has_fderiv_within_at) h end lemma fderiv.comp {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (g ∘ f) x = (fderiv 𝕜 g (f x)).comp (fderiv 𝕜 f x) := begin apply has_fderiv_at.fderiv, exact has_fderiv_at.comp x hg.has_fderiv_at hf.has_fderiv_at end lemma fderiv.comp_fderiv_within {g : F → G} (hg : differentiable_at 𝕜 g (f x)) (hf : differentiable_within_at 𝕜 f s x) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (g ∘ f) s x = (fderiv 𝕜 g (f x)).comp (fderiv_within 𝕜 f s x) := begin apply has_fderiv_within_at.fderiv_within _ hxs, exact has_fderiv_at.comp_has_fderiv_within_at x (hg.has_fderiv_at) (hf.has_fderiv_within_at) end lemma differentiable_on.comp {g : F → G} {t : set F} (hg : differentiable_on 𝕜 g t) (hf : differentiable_on 𝕜 f s) (st : s ⊆ f ⁻¹' t) : differentiable_on 𝕜 (g ∘ f) s := λx hx, differentiable_within_at.comp x (hg (f x) (st hx)) (hf x hx) st lemma differentiable.comp {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable 𝕜 f) : differentiable 𝕜 (g ∘ f) := λx, differentiable_at.comp x (hg (f x)) (hf x) lemma differentiable.comp_differentiable_on {g : F → G} (hg : differentiable 𝕜 g) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (g ∘ f) s := (differentiable_on_univ.2 hg).comp hf (by simp) end composition section smul /-! ### Derivative of the product of a scalar-valued function and a vector-valued function -/ variables {c : E → 𝕜} {c' : E →L[𝕜] 𝕜} theorem has_fderiv_within_at.smul (hc : has_fderiv_within_at c c' s x) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) s x := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × F), p.1 • p.2) := is_bounded_bilinear_map_smul, exact has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, f x)) (hc.prod hf) end theorem has_fderiv_at.smul (hc : has_fderiv_at c c' x) (hf : has_fderiv_at f f' x) : has_fderiv_at (λ y, c y • f y) (c x • f' + c'.smul_right (f x)) x := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × F), p.1 • p.2) := is_bounded_bilinear_map_smul, exact has_fderiv_at.comp x (this.has_fderiv_at (c x, f x)) (hc.prod hf) end lemma differentiable_within_at.smul (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : differentiable_within_at 𝕜 (λ y, c y • f y) s x := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : differentiable_at 𝕜 (λ y, c y • f y) x := (hc.has_fderiv_at.smul hf.has_fderiv_at).differentiable_at lemma differentiable_on.smul (hc : differentiable_on 𝕜 c s) (hf : differentiable_on 𝕜 f s) : differentiable_on 𝕜 (λ y, c y • f y) s := λx hx, (hc x hx).smul (hf x hx) lemma differentiable.smul (hc : differentiable 𝕜 c) (hf : differentiable 𝕜 f) : differentiable 𝕜 (λ y, c y • f y) := λx, (hc x).smul (hf x) lemma fderiv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : fderiv_within 𝕜 (λ y, c y • f y) s x = c x • fderiv_within 𝕜 f s x + (fderiv_within 𝕜 c s x).smul_right (f x) := (hc.has_fderiv_within_at.smul hf.has_fderiv_within_at).fderiv_within hxs lemma fderiv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : fderiv 𝕜 (λ y, c y • f y) x = c x • fderiv 𝕜 f x + (fderiv 𝕜 c x).smul_right (f x) := (hc.has_fderiv_at.smul hf.has_fderiv_at).fderiv theorem has_fderiv_within_at.smul_const (hc : has_fderiv_within_at c c' s x) (f : F) : has_fderiv_within_at (λ y, c y • f) (c'.smul_right f) s x := begin convert hc.smul (has_fderiv_within_at_const f x s), -- Help Lean find an instance letI : distrib_mul_action 𝕜 (E →L[𝕜] F) := continuous_linear_map.module.to_distrib_mul_action, rw [smul_zero, zero_add] end theorem has_fderiv_at.smul_const (hc : has_fderiv_at c c' x) (f : F) : has_fderiv_at (λ y, c y • f) (c'.smul_right f) x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.smul_const f end lemma differentiable_within_at.smul_const (hc : differentiable_within_at 𝕜 c s x) (f : F) : differentiable_within_at 𝕜 (λ y, c y • f) s x := (hc.has_fderiv_within_at.smul_const f).differentiable_within_at lemma differentiable_at.smul_const (hc : differentiable_at 𝕜 c x) (f : F) : differentiable_at 𝕜 (λ y, c y • f) x := (hc.has_fderiv_at.smul_const f).differentiable_at lemma differentiable_on.smul_const (hc : differentiable_on 𝕜 c s) (f : F) : differentiable_on 𝕜 (λ y, c y • f) s := λx hx, (hc x hx).smul_const f lemma differentiable.smul_const (hc : differentiable 𝕜 c) (f : F) : differentiable 𝕜 (λ y, c y • f) := λx, (hc x).smul_const f lemma fderiv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : fderiv_within 𝕜 (λ y, c y • f) s x = (fderiv_within 𝕜 c s x).smul_right f := (hc.has_fderiv_within_at.smul_const f).fderiv_within hxs lemma fderiv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : fderiv 𝕜 (λ y, c y • f) x = (fderiv 𝕜 c x).smul_right f := (hc.has_fderiv_at.smul_const f).fderiv end smul section mul /-! ### Derivative of the product of two scalar-valued functions -/ set_option class.instance_max_depth 120 variables {c d : E → 𝕜} {c' d' : E →L[𝕜] 𝕜} theorem has_fderiv_within_at.mul (hc : has_fderiv_within_at c c' s x) (hd : has_fderiv_within_at d d' s x) : has_fderiv_within_at (λ y, c y * d y) (c x • d' + d x • c') s x := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_mul, convert has_fderiv_at.comp_has_fderiv_within_at x (this.has_fderiv_at (c x, d x)) (hc.prod hd), ext z, change c x * d' z + d x * c' z = c x * d' z + c' z * d x, ring end theorem has_fderiv_at.mul (hc : has_fderiv_at c c' x) (hd : has_fderiv_at d d' x) : has_fderiv_at (λ y, c y * d y) (c x • d' + d x • c') x := begin have : is_bounded_bilinear_map 𝕜 (λ (p : 𝕜 × 𝕜), p.1 * p.2) := is_bounded_bilinear_map_mul, convert has_fderiv_at.comp x (this.has_fderiv_at (c x, d x)) (hc.prod hd), ext z, change c x * d' z + d x * c' z = c x * d' z + c' z * d x, ring end lemma differentiable_within_at.mul (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : differentiable_within_at 𝕜 (λ y, c y * d y) s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).differentiable_within_at lemma differentiable_at.mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : differentiable_at 𝕜 (λ y, c y * d y) x := (hc.has_fderiv_at.mul hd.has_fderiv_at).differentiable_at lemma differentiable_on.mul (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) : differentiable_on 𝕜 (λ y, c y * d y) s := λx hx, (hc x hx).mul (hd x hx) lemma differentiable.mul (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) : differentiable 𝕜 (λ y, c y * d y) := λx, (hc x).mul (hd x) lemma fderiv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : fderiv_within 𝕜 (λ y, c y * d y) s x = c x • fderiv_within 𝕜 d s x + d x • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul hd.has_fderiv_within_at).fderiv_within hxs lemma fderiv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : fderiv 𝕜 (λ y, c y * d y) x = c x • fderiv 𝕜 d x + d x • fderiv 𝕜 c x := (hc.has_fderiv_at.mul hd.has_fderiv_at).fderiv theorem has_fderiv_within_at.mul_const (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, c y * d) (d • c') s x := begin have := hc.mul (has_fderiv_within_at_const d x s), letI : distrib_mul_action 𝕜 (E →L[𝕜] 𝕜) := continuous_linear_map.module.to_distrib_mul_action, rwa [smul_zero, zero_add] at this end theorem has_fderiv_at.mul_const (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, c y * d) (d • c') x := begin rw [← has_fderiv_within_at_univ] at *, exact hc.mul_const d end lemma differentiable_within_at.mul_const (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, c y * d) s x := (hc.has_fderiv_within_at.mul_const d).differentiable_within_at lemma differentiable_at.mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, c y * d) x := (hc.has_fderiv_at.mul_const d).differentiable_at lemma differentiable_on.mul_const (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, c y * d) s := λx hx, (hc x hx).mul_const d lemma differentiable.mul_const (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, c y * d) := λx, (hc x).mul_const d lemma fderiv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, c y * d) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.mul_const d).fderiv_within hxs lemma fderiv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, c y * d) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.mul_const d).fderiv theorem has_fderiv_within_at.const_mul (hc : has_fderiv_within_at c c' s x) (d : 𝕜) : has_fderiv_within_at (λ y, d * c y) (d • c') s x := begin simp only [mul_comm d], exact hc.mul_const d, end theorem has_fderiv_at.const_mul (hc : has_fderiv_at c c' x) (d : 𝕜) : has_fderiv_at (λ y, d * c y) (d • c') x := begin simp only [mul_comm d], exact hc.mul_const d, end lemma differentiable_within_at.const_mul (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : differentiable_within_at 𝕜 (λ y, d * c y) s x := (hc.has_fderiv_within_at.const_mul d).differentiable_within_at lemma differentiable_at.const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : differentiable_at 𝕜 (λ y, d * c y) x := (hc.has_fderiv_at.const_mul d).differentiable_at lemma differentiable_on.const_mul (hc : differentiable_on 𝕜 c s) (d : 𝕜) : differentiable_on 𝕜 (λ y, d * c y) s := λx hx, (hc x hx).const_mul d lemma differentiable.const_mul (hc : differentiable 𝕜 c) (d : 𝕜) : differentiable 𝕜 (λ y, d * c y) := λx, (hc x).const_mul d lemma fderiv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : fderiv_within 𝕜 (λ y, d * c y) s x = d • fderiv_within 𝕜 c s x := (hc.has_fderiv_within_at.const_mul d).fderiv_within hxs lemma fderiv_const_mul (hc : differentiable_at 𝕜 c x) (d : 𝕜) : fderiv 𝕜 (λ y, d * c y) x = d • fderiv 𝕜 c x := (hc.has_fderiv_at.const_mul d).fderiv end mul section continuous_linear_equiv /-! ### Differentiability of linear equivs, and invariance of differentiability -/ variable (iso : E ≃L[𝕜] F) protected lemma continuous_linear_equiv.has_fderiv_within_at : has_fderiv_within_at iso (iso : E →L[𝕜] F) s x := iso.to_continuous_linear_map.has_fderiv_within_at protected lemma continuous_linear_equiv.has_fderiv_at : has_fderiv_at iso (iso : E →L[𝕜] F) x := iso.to_continuous_linear_map.has_fderiv_at_filter protected lemma continuous_linear_equiv.differentiable_at : differentiable_at 𝕜 iso x := iso.has_fderiv_at.differentiable_at protected lemma continuous_linear_equiv.differentiable_within_at : differentiable_within_at 𝕜 iso s x := iso.differentiable_at.differentiable_within_at protected lemma continuous_linear_equiv.fderiv : fderiv 𝕜 iso x = iso := iso.has_fderiv_at.fderiv protected lemma continuous_linear_equiv.fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 iso s x = iso := iso.to_continuous_linear_map.fderiv_within hxs protected lemma continuous_linear_equiv.differentiable : differentiable 𝕜 iso := λx, iso.differentiable_at protected lemma continuous_linear_equiv.differentiable_on : differentiable_on 𝕜 iso s := iso.differentiable.differentiable_on lemma continuous_linear_equiv.comp_differentiable_within_at_iff {f : G → E} {s : set G} {x : G} : differentiable_within_at 𝕜 (iso ∘ f) s x ↔ differentiable_within_at 𝕜 f s x := begin refine ⟨λ H, _, λ H, iso.differentiable.differentiable_at.comp_differentiable_within_at x H⟩, have : differentiable_within_at 𝕜 (iso.symm ∘ (iso ∘ f)) s x := iso.symm.differentiable.differentiable_at.comp_differentiable_within_at x H, rwa [← function.comp.assoc iso.symm iso f, iso.symm_comp_self] at this, end lemma continuous_linear_equiv.comp_differentiable_at_iff {f : G → E} {x : G} : differentiable_at 𝕜 (iso ∘ f) x ↔ differentiable_at 𝕜 f x := by rw [← differentiable_within_at_univ, ← differentiable_within_at_univ, iso.comp_differentiable_within_at_iff] lemma continuous_linear_equiv.comp_differentiable_on_iff {f : G → E} {s : set G} : differentiable_on 𝕜 (iso ∘ f) s ↔ differentiable_on 𝕜 f s := begin rw [differentiable_on, differentiable_on], simp only [iso.comp_differentiable_within_at_iff], end lemma continuous_linear_equiv.comp_differentiable_iff {f : G → E} : differentiable 𝕜 (iso ∘ f) ↔ differentiable 𝕜 f := begin rw [← differentiable_on_univ, ← differentiable_on_univ], exact iso.comp_differentiable_on_iff end lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] E} : has_fderiv_within_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') s x ↔ has_fderiv_within_at f f' s x := begin refine ⟨λ H, _, λ H, iso.has_fderiv_at.comp_has_fderiv_within_at x H⟩, have A : f = iso.symm ∘ (iso ∘ f), by { rw [← function.comp.assoc, iso.symm_comp_self], refl }, have B : f' = (iso.symm : F →L[𝕜] E).comp ((iso : E →L[𝕜] F).comp f'), by rw [← continuous_linear_map.comp_assoc, iso.coe_symm_comp_coe, continuous_linear_map.id_comp], rw [A, B], exact iso.symm.has_fderiv_at.comp_has_fderiv_within_at x H end lemma continuous_linear_equiv.comp_has_fderiv_at_iff {f : G → E} {x : G} {f' : G →L[𝕜] E} : has_fderiv_at (iso ∘ f) ((iso : E →L[𝕜] F).comp f') x ↔ has_fderiv_at f f' x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff] lemma continuous_linear_equiv.comp_has_fderiv_within_at_iff' {f : G → E} {s : set G} {x : G} {f' : G →L[𝕜] F} : has_fderiv_within_at (iso ∘ f) f' s x ↔ has_fderiv_within_at f ((iso.symm : F →L[𝕜] E).comp f') s x := begin set g := (iso.symm : F →L[𝕜] E).comp f' with h, have : f' = (iso : E →L[𝕜] F).comp g, by rw [h, ← continuous_linear_map.comp_assoc, iso.coe_comp_coe_symm, continuous_linear_map.id_comp], rw this, exact iso.comp_has_fderiv_within_at_iff end lemma continuous_linear_equiv.comp_has_fderiv_at_iff' {f : G → E} {x : G} {f' : G →L[𝕜] F} : has_fderiv_at (iso ∘ f) f' x ↔ has_fderiv_at f ((iso.symm : F →L[𝕜] E).comp f') x := by rw [← has_fderiv_within_at_univ, ← has_fderiv_within_at_univ, iso.comp_has_fderiv_within_at_iff'] lemma continuous_linear_equiv.comp_fderiv_within {f : G → E} {s : set G} {x : G} (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (iso ∘ f) s x = (iso : E →L[𝕜] F).comp (fderiv_within 𝕜 f s x) := begin by_cases h : differentiable_within_at 𝕜 f s x, { rw [fderiv.comp_fderiv_within x iso.differentiable_at h hxs, iso.fderiv] }, { have : ¬differentiable_within_at 𝕜 (iso ∘ f) s x, by simp [-coe_fn_coe_base, iso.comp_differentiable_within_at_iff, h], rw [fderiv_within_zero_of_not_differentiable_within_at h, fderiv_within_zero_of_not_differentiable_within_at this], ext y, simp [-coe_fn_coe_base] } end lemma continuous_linear_equiv.comp_fderiv {f : G → E} {x : G} : fderiv 𝕜 (iso ∘ f) x = (iso : E →L[𝕜] F).comp (fderiv 𝕜 f x) := begin rw [← fderiv_within_univ, ← fderiv_within_univ], exact iso.comp_fderiv_within unique_diff_within_at_univ, end end continuous_linear_equiv end section /- In the special case of a normed space over the reals, we can use scalar multiplication in the `tendsto` characterization of the Fréchet derivative. -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] variables {F : Type*} [normed_group F] [normed_space ℝ F] variables {f : E → F} {f' : E →L[ℝ] F} {x : E} theorem has_fderiv_at_filter_real_equiv {L : filter E} : tendsto (λ x' : E, ∥x' - x∥⁻¹ * ∥f x' - f x - f' (x' - x)∥) L (𝓝 0) ↔ tendsto (λ x' : E, ∥x' - x∥⁻¹ • (f x' - f x - f' (x' - x))) L (𝓝 0) := begin symmetry, rw [tendsto_iff_norm_tendsto_zero], refine tendsto_congr (λ x', _), have : ∥x' - x∥⁻¹ ≥ 0, from inv_nonneg.mpr (norm_nonneg _), simp [norm_smul, real.norm_eq_abs, abs_of_nonneg this] end lemma has_fderiv_at.lim_real (hf : has_fderiv_at f f' x) (v : E) : tendsto (λ (c:ℝ), c • (f (x + c⁻¹ • v) - f x)) at_top (𝓝 (f' v)) := begin apply hf.lim v, rw tendsto_at_top_at_top, exact λ b, ⟨b, λ a ha, le_trans ha (le_abs_self _)⟩ end end section tangent_cone variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {f : E → F} {s : set E} {f' : E →L[𝕜] F} /-- The image of a tangent cone under the differential of a map is included in the tangent cone to the image. -/ lemma has_fderiv_within_at.image_tangent_cone_subset {x : E} (h : has_fderiv_within_at f f' s x) : f' '' (tangent_cone_at 𝕜 s x) ⊆ tangent_cone_at 𝕜 (f '' s) (f x) := begin rw image_subset_iff, rintros v ⟨c, d, dtop, clim, cdlim⟩, refine ⟨c, (λn, f (x + d n) - f x), mem_sets_of_superset dtop _, clim, h.lim at_top dtop clim cdlim⟩, simp [-mem_image, mem_image_of_mem] {contextual := tt} end /-- If a set has the unique differentiability property at a point x, then the image of this set under a map with onto derivative has also the unique differentiability property at the image point. -/ lemma has_fderiv_within_at.unique_diff_within_at {x : E} (h : has_fderiv_within_at f f' s x) (hs : unique_diff_within_at 𝕜 s x) (h' : closure (range f') = univ) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin have A : ∀v ∈ tangent_cone_at 𝕜 s x, f' v ∈ tangent_cone_at 𝕜 (f '' s) (f x), { assume v hv, have := h.image_tangent_cone_subset, rw image_subset_iff at this, exact this hv }, have B : ∀v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E), f' v ∈ (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F), { assume v hv, apply submodule.span_induction hv, { exact λ w hw, submodule.subset_span (A w hw) }, { simp }, { assume w₁ w₂ hw₁ hw₂, rw continuous_linear_map.map_add, exact submodule.add_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) hw₁ hw₂ }, { assume a w hw, rw continuous_linear_map.map_smul, exact submodule.smul_mem (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))) _ hw } }, rw [unique_diff_within_at, ← univ_subset_iff], split, show f x ∈ closure (f '' s), from h.continuous_within_at.mem_closure_image hs.2, show univ ⊆ closure ↑(submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x))), from calc univ ⊆ closure (range f') : univ_subset_iff.2 h' ... = closure (f' '' univ) : by rw image_univ ... = closure (f' '' (closure (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : by rw hs.1 ... ⊆ closure (closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E))) : closure_mono (image_closure_subset_closure_image f'.cont) ... = closure (f' '' (submodule.span 𝕜 (tangent_cone_at 𝕜 s x) : set E)) : closure_closure ... ⊆ closure (submodule.span 𝕜 (tangent_cone_at 𝕜 (f '' s) (f x)) : set F) : closure_mono (image_subset_iff.mpr B) end lemma has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv {x : E} (e' : E ≃L[𝕜] F) (h : has_fderiv_within_at f (e' : E →L[𝕜] F) s x) (hs : unique_diff_within_at 𝕜 s x) : unique_diff_within_at 𝕜 (f '' s) (f x) := begin apply h.unique_diff_within_at hs, have : range (e' : E →L[𝕜] F) = univ := e'.to_linear_equiv.to_equiv.range_eq_univ, rw [this, closure_univ] end lemma continuous_linear_equiv.unique_diff_on_preimage_iff (e : F ≃L[𝕜] E) : unique_diff_on 𝕜 (e ⁻¹' s) ↔ unique_diff_on 𝕜 s := begin split, { assume hs x hx, have A : s = e '' (e.symm '' s) := (equiv.symm_image_image (e.symm.to_linear_equiv.to_equiv) s).symm, have B : e.symm '' s = e⁻¹' s := equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s, rw [A, B, (e.apply_symm_apply x).symm], refine has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e e.has_fderiv_within_at (hs _ _), rwa [mem_preimage, e.apply_symm_apply x] }, { assume hs x hx, have : e ⁻¹' s = e.symm '' s := (equiv.image_eq_preimage e.symm.to_linear_equiv.to_equiv s).symm, rw [this, (e.symm_apply_apply x).symm], exact has_fderiv_within_at.unique_diff_within_at_of_continuous_linear_equiv e.symm e.symm.has_fderiv_within_at (hs _ hx) }, end end tangent_cone section restrict_scalars /-! ### Restricting from `ℂ` to `ℝ`, or generally from `𝕜'` to `𝕜` If a function is differentiable over `ℂ`, then it is differentiable over `ℝ`. In this paragraph, we give variants of this statement, in the general situation where `ℂ` and `ℝ` are replaced respectively by `𝕜'` and `𝕜` where `𝕜'` is a normed algebra over `𝕜`. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {E : Type*} [normed_group E] [normed_space 𝕜' E] {F : Type*} [normed_group F] [normed_space 𝕜' F] {f : E → F} {f' : E →L[𝕜'] F} {s : set E} {x : E} local attribute [instance] normed_space.restrict_scalars lemma has_fderiv_at.restrict_scalars (h : has_fderiv_at f f' x) : has_fderiv_at f (f'.restrict_scalars 𝕜) x := h lemma has_fderiv_within_at.restrict_scalars (h : has_fderiv_within_at f f' s x) : has_fderiv_within_at f (f'.restrict_scalars 𝕜) s x := h lemma differentiable_at.restrict_scalars (h : differentiable_at 𝕜' f x) : differentiable_at 𝕜 f x := (h.has_fderiv_at.restrict_scalars 𝕜).differentiable_at lemma differentiable_within_at.restrict_scalars (h : differentiable_within_at 𝕜' f s x) : differentiable_within_at 𝕜 f s x := (h.has_fderiv_within_at.restrict_scalars 𝕜).differentiable_within_at lemma differentiable_on.restrict_scalars (h : differentiable_on 𝕜' f s) : differentiable_on 𝕜 f s := λx hx, (h x hx).restrict_scalars 𝕜 lemma differentiable.restrict_scalars (h : differentiable 𝕜' f) : differentiable 𝕜 f := λx, (h x).restrict_scalars 𝕜 end restrict_scalars
8b127b0b72cae0bc6c44f91cee11ec7270c9ed78
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/polynomial/field_division.lean
b1a6db3f07905a0f3b359bc771cbf3fadd041ceb
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
19,401
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.derivative import data.polynomial.ring_division import ring_theory.euclidean_domain /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical big_operators polynomial namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : ℕ} section is_domain variables [comm_ring R] [is_domain R] lemma derivative_root_multiplicity_of_root [char_zero R] {p : R[X]} {t : R} (hpt : p.is_root t) : p.derivative.root_multiplicity t = p.root_multiplicity t - 1 := begin rcases eq_or_ne p 0 with rfl | hp, { simp }, nth_rewrite 0 [←p.div_by_monic_mul_pow_root_multiplicity_eq t], simp only [derivative_pow, derivative_mul, derivative_sub, derivative_X, derivative_C, sub_zero, mul_one], set n := p.root_multiplicity t - 1, have hn : n + 1 = _ := tsub_add_cancel_of_le ((root_multiplicity_pos hp).mpr hpt), rw ←hn, set q := p /ₘ (X - C t) ^ (n + 1) with hq, convert_to root_multiplicity t ((X - C t) ^ n * (derivative q * (X - C t) + q * C ↑(n + 1))) = n, { congr, rw [mul_add, mul_left_comm $ (X - C t) ^ n, ←pow_succ'], congr' 1, rw [mul_left_comm $ (X - C t) ^ n, mul_comm $ (X - C t) ^ n] }, have h : (derivative q * (X - C t) + q * C ↑(n + 1)).eval t ≠ 0, { suffices : eval t q * ↑(n + 1) ≠ 0, { simpa }, refine mul_ne_zero _ (nat.cast_ne_zero.mpr n.succ_ne_zero), convert eval_div_by_monic_pow_root_multiplicity_ne_zero t hp, exact hn ▸ hq }, rw [root_multiplicity_mul, root_multiplicity_X_sub_C_pow, root_multiplicity_eq_zero h, add_zero], refine mul_ne_zero (pow_ne_zero n $ X_sub_C_ne_zero t) _, contrapose! h, rw [h, eval_zero] end lemma root_multiplicity_sub_one_le_derivative_root_multiplicity [char_zero R] (p : R[X]) (t : R) : p.root_multiplicity t - 1 ≤ p.derivative.root_multiplicity t := begin by_cases p.is_root t, { exact (derivative_root_multiplicity_of_root h).symm.le }, { rw [root_multiplicity_eq_zero h, zero_tsub], exact zero_le _ } end section normalization_monoid variables [normalization_monoid R] instance : normalization_monoid R[X] := { norm_unit := λ p, ⟨C ↑(norm_unit (p.leading_coeff)), C ↑(norm_unit (p.leading_coeff))⁻¹, by rw [← ring_hom.map_mul, units.mul_inv, C_1], by rw [← ring_hom.map_mul, units.inv_mul, C_1]⟩, norm_unit_zero := units.ext (by simp), norm_unit_mul := λ p q hp0 hq0, units.ext (begin dsimp, rw [ne.def, ← leading_coeff_eq_zero] at *, rw [leading_coeff_mul, norm_unit_mul hp0 hq0, units.coe_mul, C_mul], end), norm_unit_coe_units := λ u, units.ext begin rw [← mul_one u⁻¹, units.coe_mul, units.eq_inv_mul_iff_mul_eq], dsimp, rcases polynomial.is_unit_iff.1 ⟨u, rfl⟩ with ⟨_, ⟨w, rfl⟩, h2⟩, rw [← h2, leading_coeff_C, norm_unit_coe_units, ← C_mul, units.mul_inv, C_1], end } @[simp] lemma coe_norm_unit {p : R[X]} : (norm_unit p : R[X]) = C ↑(norm_unit p.leading_coeff) := by simp [norm_unit] lemma leading_coeff_normalize (p : R[X]) : leading_coeff (normalize p) = normalize (leading_coeff p) := by simp lemma monic.normalize_eq_self {p : R[X]} (hp : p.monic) : normalize p = p := by simp only [polynomial.coe_norm_unit, normalize_apply, hp.leading_coeff, norm_unit_one, units.coe_one, polynomial.C.map_one, mul_one] lemma roots_normalize {p : R[X]} : (normalize p).roots = p.roots := by rw [normalize_apply, mul_comm, coe_norm_unit, roots_C_mul _ (norm_unit (leading_coeff p)).ne_zero] end normalization_monoid end is_domain section division_ring variables [division_ring R] {p q : R[X]} lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, begin rw [eq_C_of_degree_le_zero h] at hp0 hp, exact hp (is_unit.map C (is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))), end) lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : R[X]) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul, degree_C h₁, add_zero] @[simp] lemma map_eq_zero [semiring S] [nontrivial S] (f : R →+* S) : p.map f = 0 ↔ p = 0 := by simp only [polynomial.ext_iff, map_eq_zero, coeff_map, coeff_zero] lemma map_ne_zero [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : p.map f ≠ 0 := mt (map_eq_zero f).1 hp end division_ring section field variables [field R] {p q : R[X]} lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ /-- Division of polynomials. See `polynomial.div_by_monic` for more details.-/ def div (p q : R[X]) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) /-- Remainder of polynomial division. See `polynomial.mod_by_monic` for more details. -/ def mod (p q : R[X]) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : R[X]) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : R[X]) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) instance : has_div R[X] := ⟨div⟩ instance : has_mod R[X] := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : R[X]) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : R[X]) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : R[X]) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain R[X] := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq), .. polynomial.comm_ring, .. polynomial.nontrivial } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv_rhs { rw [← euclidean_domain.div_add_mod p q, degree_add_eq_left_of_degree_lt this, degree_mul] } lemma degree_div_le (p q : R[X]) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [division_ring k] (p : R[X]) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective f.injective @[simp] lemma nat_degree_map [division_ring k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [division_ring k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp only [← coeff_nat_degree, coeff_map f, nat_degree_map] theorem monic_map_iff [division_ring k] {f : R →+* k} {p : R[X]} : (p.map f).monic ↔ p.monic := by rw [monic, leading_coeff_map, ← f.map_one, function.injective.eq_iff f.injective, monic] theorem is_unit_map [field k] (f : R →+* k) : is_unit (p.map f) ↔ is_unit p := by simp_rw [is_unit_iff_degree_eq_zero, degree_map] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, polynomial.map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← map_inv₀ f, ← map_C f, ← polynomial.map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] section open euclidean_domain theorem gcd_map [field k] (f : R →+* k) : gcd (p.map f) (q.map f) = (gcd p q).map f := gcd.induction p q (λ x, by simp_rw [polynomial.map_zero, euclidean_domain.gcd_zero_left]) $ λ x y hx ih, by rw [gcd_val, ← map_mod, ih, ← gcd_val] end lemma eval₂_gcd_eq_zero [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} (hf : f.eval₂ ϕ α = 0) (hg : g.eval₂ ϕ α = 0) : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 := by rw [euclidean_domain.gcd_eq_gcd_ab f g, polynomial.eval₂_add, polynomial.eval₂_mul, polynomial.eval₂_mul, hf, hg, zero_mul, zero_mul, zero_add] lemma eval_gcd_eq_zero {f g : R[X]} {α : R} (hf : f.eval α = 0) (hg : g.eval α = 0) : (euclidean_domain.gcd f g).eval α = 0 := eval₂_gcd_eq_zero hf hg lemma root_left_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : f.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_left f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_right_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : g.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_right f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_gcd_iff_root_left_right [comm_semiring k] {ϕ : R →+* k} {f g : R[X]} {α : k} : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 ↔ (f.eval₂ ϕ α = 0) ∧ (g.eval₂ ϕ α = 0) := ⟨λ h, ⟨root_left_of_root_gcd h, root_right_of_root_gcd h⟩, λ h, eval₂_gcd_eq_zero h.1 h.2⟩ lemma is_root_gcd_iff_is_root_left_right {f g : R[X]} {α : R} : (euclidean_domain.gcd f g).is_root α ↔ f.is_root α ∧ g.is_root α := root_gcd_iff_root_left_right theorem is_coprime_map [field k] (f : R →+* k) : is_coprime (p.map f) (q.map f) ↔ is_coprime p q := by rw [← euclidean_domain.gcd_is_unit_iff, ← euclidean_domain.gcd_is_unit_iff, gcd_map, is_unit_map] lemma mem_roots_map [comm_ring k] [is_domain k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ (p.map f).roots ↔ p.eval₂ f x = 0 := by rw [mem_roots (map_ne_zero hp), is_root, polynomial.eval_map]; apply_instance lemma root_set_monomial [comm_ring S] [is_domain S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (monomial n a).root_set S = {0} := by rw [root_set, map_monomial, roots_monomial ((_root_.map_ne_zero (algebra_map R S)).2 ha), multiset.to_finset_nsmul _ _ hn, multiset.to_finset_singleton, finset.coe_singleton] lemma root_set_C_mul_X_pow [comm_ring S] [is_domain S] [algebra R S] {n : ℕ} (hn : n ≠ 0) {a : R} (ha : a ≠ 0) : (C a * X ^ n).root_set S = {0} := by rw [C_mul_X_pow_eq_monomial, root_set_monomial hn ha] lemma root_set_X_pow [comm_ring S] [is_domain S] [algebra R S] {n : ℕ} (hn : n ≠ 0) : (X ^ n : R[X]).root_set S = {0} := by { rw [←one_mul (X ^ n : R[X]), ←C_1, root_set_C_mul_X_pow hn], exact one_ne_zero } lemma root_set_prod [comm_ring S] [is_domain S] [algebra R S] {ι : Type*} (f : ι → R[X]) (s : finset ι) (h : s.prod f ≠ 0) : (s.prod f).root_set S = ⋃ (i ∈ s), (f i).root_set S := begin simp only [root_set, ←finset.mem_coe], rw [polynomial.map_prod, roots_prod, finset.bind_to_finset, s.val_to_finset, finset.coe_bUnion], rwa [←polynomial.map_prod, ne, map_eq_zero], end lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_rfl)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : R[X]ˣ) (n : ℕ) : ((↑u : R[X]).coeff n)⁻¹ = ((↑u⁻¹ : R[X]).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := begin rw [ne.def, ← leading_coeff_eq_zero, ← ne.def, ← is_unit_iff_ne_zero] at hp0, rw [monic, leading_coeff_normalize, normalize_eq_one], apply hp0, end lemma leading_coeff_div (hpq : q.degree ≤ p.degree) : (p / q).leading_coeff = p.leading_coeff / q.leading_coeff := begin by_cases hq : q = 0, { simp [hq] }, rw [div_def, leading_coeff_mul, leading_coeff_C, leading_coeff_div_by_monic_of_monic (monic_mul_leading_coeff_inv hq) _, mul_comm, div_eq_mul_inv], rwa [degree_mul_leading_coeff_inv q hq] end lemma div_C_mul : p / (C a * q) = C a⁻¹ * (p / q) := begin by_cases ha : a = 0, { simp [ha] }, simp only [div_def, leading_coeff_mul, mul_inv, leading_coeff_C, C.map_mul, mul_assoc], congr' 3, rw [mul_left_comm q, ← mul_assoc, ← C.map_mul, mul_inv_cancel ha, C.map_one, one_mul] end lemma C_mul_dvd (ha : a ≠ 0) : C a * p ∣ q ↔ p ∣ q := ⟨λ h, dvd_trans (dvd_mul_left _ _) h, λ ⟨r, hr⟩, ⟨C a⁻¹ * r, by rw [mul_assoc, mul_left_comm p, ← mul_assoc, ← C.map_mul, _root_.mul_inv_cancel ha, C.map_one, one_mul, hr]⟩⟩ lemma dvd_C_mul (ha : a ≠ 0) : p ∣ polynomial.C a * q ↔ p ∣ q := ⟨λ ⟨r, hr⟩, ⟨C a⁻¹ * r, by rw [mul_left_comm p, ← hr, ← mul_assoc, ← C.map_mul, _root_.inv_mul_cancel ha, C.map_one, one_mul]⟩, λ h, dvd_trans h (dvd_mul_left _ _)⟩ lemma coe_norm_unit_of_ne_zero (hp : p ≠ 0) : (norm_unit p : R[X]) = C p.leading_coeff⁻¹ := have p.leading_coeff ≠ 0 := mt leading_coeff_eq_zero.mp hp, by simp [comm_group_with_zero.coe_norm_unit _ this] lemma normalize_monic (h : monic p) : normalize p = p := by simp [h] theorem map_dvd_map' [field k] (f : R →+* k) {x y : R[X]} : x.map f ∣ y.map f ↔ x ∣ y := if H : x = 0 then by rw [H, polynomial.map_zero, zero_dvd_iff, zero_dvd_iff, map_eq_zero] else by rw [← normalize_dvd_iff, ← @normalize_dvd_iff R[X], normalize_apply, normalize_apply, coe_norm_unit_of_ne_zero H, coe_norm_unit_of_ne_zero (mt (map_eq_zero f).1 H), leading_coeff_map, ← map_inv₀ f, ← map_C, ← polynomial.map_mul, map_dvd_map _ f.injective (monic_mul_leading_coeff_inv H)] lemma degree_normalize : degree (normalize p) = degree p := by simp lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p := have prime (normalize p), from monic.prime_of_degree_eq_one (hp1 ▸ degree_normalize) (monic_normalize (λ hp0, absurd hp1 (hp0.symm ▸ by simp; exact dec_trivial))), (normalize_associated _).prime this lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := (prime_of_degree_eq_one hp1).irreducible theorem not_irreducible_C (x : R) : ¬irreducible (C x) := if H : x = 0 then by { rw [H, C_0], exact not_irreducible_zero } else λ hx, irreducible.not_unit hx $ is_unit_C.2 $ is_unit_iff_ne_zero.2 H theorem degree_pos_of_irreducible (hp : irreducible p) : 0 < p.degree := lt_of_not_ge $ λ hp0, have _ := eq_C_of_degree_le_zero hp0, not_irreducible_C (p.coeff 0) $ this ▸ hp /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : K[X]) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : K[X]) (f /ₘ (X - C a)) := begin refine or.resolve_left (euclidean_domain.dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end end field end polynomial
4f4b56b6e775fe732f6fbc9fe170cf9e7cf3ccac
f7315930643edc12e76c229a742d5446dad77097
/tests/lean/run/466.lean
6716d61fc4f00427209c761d5c370024206886ba
[ "Apache-2.0" ]
permissive
bmalehorn/lean
8f77b762a76c59afff7b7403f9eb5fc2c3ce70c1
53653c352643751c4b62ff63ec5e555f11dae8eb
refs/heads/master
1,610,945,684,489
1,429,681,220,000
1,429,681,449,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
179
lean
open eq section parameter (A : Type) definition foo (a : A) : a = a := refl a definition bar (a : A) : foo a = refl a := begin unfold foo, apply rfl end end
867cc123743a22815534767055edfa36c58826fd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/int/nat_prime.lean
c49b3c290572401e0824e312a9180a635325ac3b
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,610
lean
/- Copyright (c) 2020 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker, Bryan Gin-ge Chen -/ import data.nat.prime /-! # Lemmas about nat.prime using `int`s > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open nat namespace int lemma not_prime_of_int_mul {a b : ℤ} {c : ℕ} (ha : 1 < a.nat_abs) (hb : 1 < b.nat_abs) (hc : a*b = (c : ℤ)) : ¬ nat.prime c := not_prime_mul' (nat_abs_mul_nat_abs_eq hc) ha hb lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : nat.prime p) {m n : ℤ} {k l : ℕ} (hpm : ↑(p ^ k) ∣ m) (hpn : ↑(p ^ l) ∣ n) (hpmn : ↑(p ^ (k+l+1)) ∣ m*n) : ↑(p ^ (k+1)) ∣ m ∨ ↑(p ^ (l+1)) ∣ n := have hpm' : p ^ k ∣ m.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpm, have hpn' : p ^ l ∣ n.nat_abs, from int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpn, have hpmn' : (p ^ (k+l+1)) ∣ m.nat_abs*n.nat_abs, by rw ←int.nat_abs_mul; apply (int.coe_nat_dvd.1 $ int.dvd_nat_abs.2 hpmn), let hsd := nat.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul p_prime hpm' hpn' hpmn' in hsd.elim (λ hsd1, or.inl begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd1 end) (λ hsd2, or.inr begin apply int.dvd_nat_abs.1, apply int.coe_nat_dvd.2 hsd2 end) lemma prime.dvd_nat_abs_of_coe_dvd_sq {p : ℕ} (hp : p.prime) (k : ℤ) (h : ↑p ∣ k ^ 2) : p ∣ k.nat_abs := begin apply @nat.prime.dvd_of_dvd_pow _ _ 2 hp, rwa [sq, ← nat_abs_mul, ← coe_nat_dvd_left, ← sq] end end int
e3e729e831055b842cba22609fef1817bf4c2070
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Compiler/LCNF/ElimDead.lean
156004bcc23269c9d86cd0d953def3b64f1ebd1e
[ "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
2,407
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.CompilerM namespace Lean.Compiler.LCNF abbrev UsedLocalDecls := FVarIdHashSet /-- Collect set of (let) free variables in a LCNF value. This code exploits the LCNF property that local declarations do not occur in types. -/ def collectLocalDecls (s : UsedLocalDecls) (e : Expr) : UsedLocalDecls := go s e where go (s : UsedLocalDecls) (e : Expr) : UsedLocalDecls := match e with | .proj _ _ e => go s e | .forallE .. => s | .lam _ _ b _ => go s b | .letE .. => unreachable! -- Valid LCNF does not contain `let`-declarations | .app f a => go (go s a) f | .mdata _ b => go s b | .fvar fvarId => s.insert fvarId | _ => s namespace ElimDead abbrev M := StateRefT UsedLocalDecls CompilerM private abbrev collectExprM (e : Expr) : M Unit := modify (collectLocalDecls · e) private abbrev collectFVarM (fvarId : FVarId) : M Unit := modify (·.insert fvarId) mutual partial def visitFunDecl (funDecl : FunDecl) : M FunDecl := do let value ← elimDead funDecl.value funDecl.updateValue value partial def elimDead (code : Code) : M Code := do match code with | .let decl k => let k ← elimDead k if (← get).contains decl.fvarId then /- Remark: we don't need to collect `decl.type` because LCNF local declarations do not occur in types. -/ collectExprM decl.value return code.updateCont! k else eraseLetDecl decl return k | .fun decl k | .jp decl k => let k ← elimDead k if (← get).contains decl.fvarId then let decl ← visitFunDecl decl return code.updateFun! decl k else eraseFunDecl decl return k | .cases c => let alts ← c.alts.mapMonoM fun alt => return alt.updateCode (← elimDead alt.getCode) collectFVarM c.discr return code.updateAlts! alts | .return fvarId => collectFVarM fvarId; return code | .jmp fvarId args => collectFVarM fvarId; args.forM collectExprM; return code | .unreach .. => return code end end ElimDead def Code.elimDead (code : Code) : CompilerM Code := ElimDead.elimDead code |>.run' {} def Decl.elimDead (decl : Decl) : CompilerM Decl := do return { decl with value := (← decl.value.elimDead) } end Lean.Compiler.LCNF
1fb6ff2f33d670eb6e27d80877891a4226933d2a
7282d49021d38dacd06c4ce45a48d09627687fe0
/tests/lean/simp17.lean
facb8e33caea68b5fc0d8473cad87eb3ca4389bb
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
343
lean
rewrite_set simple add_rewrite and_truer and_truel and_falser and_falsel or_falsel Nat::add_zeror : simple (* add_congr_theorem("simple", "and_congrr") *) variables a b c : Nat (* local t = parse_lean([[c + 0 ≠ b + 1 ∧ b = 0 ∧ c = 1]]) local s, pr = simplify(t, "simple") print(s) print(pr) print(get_environment():type_check(pr)) *)
6b3e1027035e8e41098da36c0ae6053c992083a3
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Meta/Basic.lean
c41eed377fee9a5c3a6d2fe7af2bfa2069d80ad3
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
49,864
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.LOption import Lean.Environment import Lean.Class import Lean.ReducibilityAttrs import Lean.Util.Trace import Lean.Util.RecDepth import Lean.Util.PPExt import Lean.Util.OccursCheck import Lean.Util.MonadBacktrack import Lean.Compiler.InlineAttrs import Lean.Meta.TransparencyMode import Lean.Meta.DiscrTreeTypes import Lean.Eval import Lean.CoreM /- This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean.Meta builtin_initialize isDefEqStuckExceptionId : InternalExceptionId ← registerInternalExceptionId `isDefEqStuck structure Config where foApprox : Bool := false ctxApprox : Bool := false quasiPatternApprox : Bool := false /-- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ constApprox : Bool := false /-- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. -/ isDefEqStuckEx : Bool := false transparency : TransparencyMode := TransparencyMode.default /-- If zetaNonDep == false, then non dependent let-decls are not zeta expanded. -/ zetaNonDep : Bool := true /-- When `trackZeta == true`, we store zetaFVarIds all free variables that have been zeta-expanded. -/ trackZeta : Bool := false unificationHints : Bool := true /-- Enables proof irrelevance at `isDefEq` -/ proofIrrelevance : Bool := true /-- By default synthetic opaque metavariables are not assigned by `isDefEq`. Motivation: we want to make sure typing constraints resolved during elaboration should not "fill" holes that are supposed to be filled using tactics. However, this restriction is too restrictive for tactics such as `exact t`. When elaborating `t`, we dot not fill named holes when solving typing constraints or TC resolution. But, we ignore the restriction when we try to unify the type of `t` with the goal target type. We claim this is not a hack and is defensible behavior because this last unification step is not really part of the term elaboration. -/ assignSyntheticOpaque : Bool := false /-- When `ignoreLevelDepth` is `false`, only universe level metavariables with depth == metavariable context depth can be assigned. We used to have `ignoreLevelDepth == false` always, but this setting produced counterintuitive behavior in a few cases. Recall that universe levels are often ignored by users, they may not even be aware they exist. We still use this restriction for regular metavariables. See discussion at the beginning of `MetavarContext.lean`. We claim it is reasonable to ignore this restriction for universe metavariables because their values are often contrained by the terms is instances and simp theorems. TODO: we should delete this configuration option and the method `isReadOnlyLevelMVar` after we have more tests. -/ ignoreLevelMVarDepth : Bool := true /-- Enable/Disable support for offset constraints such as `?x + 1 =?= e` -/ offsetCnstrs : Bool := true structure ParamInfo where binderInfo : BinderInfo := BinderInfo.default hasFwdDeps : Bool := false backDeps : Array Nat := #[] deriving Inhabited def ParamInfo.isImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.implicit def ParamInfo.isInstImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.instImplicit def ParamInfo.isStrictImplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.strictImplicit def ParamInfo.isExplicit (p : ParamInfo) : Bool := p.binderInfo == BinderInfo.default || p.binderInfo == BinderInfo.auxDecl structure FunInfo where paramInfo : Array ParamInfo := #[] resultDeps : Array Nat := #[] structure InfoCacheKey where transparency : TransparencyMode expr : Expr nargs? : Option Nat deriving Inhabited, BEq namespace InfoCacheKey instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) <| mixHash (hash expr) (hash nargs)⟩ end InfoCacheKey open Std (PersistentArray PersistentHashMap) abbrev SynthInstanceCache := PersistentHashMap Expr (Option Expr) abbrev InferTypeCache := PersistentExprStructMap Expr abbrev FunInfoCache := PersistentHashMap InfoCacheKey FunInfo abbrev WhnfCache := PersistentExprStructMap Expr /- A set of pairs. TODO: consider more efficient representations (e.g., a proper set) and caching policies (e.g., imperfect cache). We should also investigate the impact on memory consumption. -/ abbrev DefEqCache := PersistentHashMap (Expr × Expr) Unit structure Cache where inferType : InferTypeCache := {} funInfo : FunInfoCache := {} synthInstance : SynthInstanceCache := {} whnfDefault : WhnfCache := {} -- cache for closed terms and `TransparencyMode.default` whnfAll : WhnfCache := {} -- cache for closed terms and `TransparencyMode.all` defEqDefault : DefEqCache := {} defEqAll : DefEqCache := {} deriving Inhabited /-- "Context" for a postponed universe constraint. `lhs` and `rhs` are the surrounding `isDefEq` call when the postponed constraint was created. -/ structure DefEqContext where lhs : Expr rhs : Expr lctx : LocalContext localInstances : LocalInstances /-- Auxiliary structure for representing postponed universe constraints. Remark: the fields `ref` and `rootDefEq?` are used for error message generation only. Remark: we may consider improving the error message generation in the future. -/ structure PostponedEntry where ref : Syntax -- We save the `ref` at entry creation time lhs : Level rhs : Level ctx? : Option DefEqContext -- Context for the surrounding `isDefEq` call when entry was created deriving Inhabited structure State where mctx : MetavarContext := {} cache : Cache := {} /- When `trackZeta == true`, then any let-decl free variable that is zeta expansion performed by `MetaM` is stored in `zetaFVarIds`. -/ zetaFVarIds : FVarIdSet := {} postponed : PersistentArray PostponedEntry := {} deriving Inhabited structure SavedState where core : Core.State meta : State deriving Inhabited structure Context where config : Config := {} lctx : LocalContext := {} localInstances : LocalInstances := #[] /-- Not `none` when inside of an `isDefEq` test. See `PostponedEntry`. -/ defEqCtx? : Option DefEqContext := none /-- Track the number of nested `synthPending` invocations. Nested invocations can happen when the type class resolution invokes `synthPending`. Remark: in the current implementation, `synthPending` fails if `synthPendingDepth > 0`. We will add a configuration option if necessary. -/ synthPendingDepth : Nat := 0 abbrev MetaM := ReaderT Context $ StateRefT State CoreM -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. instance : Monad MetaM := let i := inferInstanceAs (Monad MetaM); { pure := i.pure, bind := i.bind } instance : Inhabited (MetaM α) where default := fun _ _ => arbitrary instance : MonadLCtx MetaM where getLCtx := return (← read).lctx instance : MonadMCtx MetaM where getMCtx := return (← get).mctx modifyMCtx f := modify fun s => { s with mctx := f s.mctx } instance : AddMessageContext MetaM where addMessageContext := addMessageContextFull protected def saveState : MetaM SavedState := return { core := (← getThe Core.State), meta := (← get) } /-- Restore backtrackable parts of the state. -/ def SavedState.restore (b : SavedState) : MetaM Unit := do Core.restore b.core modify fun s => { s with mctx := b.meta.mctx, zetaFVarIds := b.meta.zetaFVarIds, postponed := b.meta.postponed } instance : MonadBacktrack SavedState MetaM where saveState := Meta.saveState restoreState s := s.restore @[inline] def MetaM.run (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM (α × State) := x ctx |>.run s @[inline] def MetaM.run' (x : MetaM α) (ctx : Context := {}) (s : State := {}) : CoreM α := Prod.fst <$> x.run ctx s @[inline] def MetaM.toIO (x : MetaM α) (ctxCore : Core.Context) (sCore : Core.State) (ctx : Context := {}) (s : State := {}) : IO (α × Core.State × State) := do let ((a, s), sCore) ← (x.run ctx s).toIO ctxCore sCore pure (a, sCore, s) instance [MetaEval α] : MetaEval (MetaM α) := ⟨fun env opts x _ => MetaEval.eval env opts x.run' true⟩ protected def throwIsDefEqStuck : MetaM α := throw <| Exception.internal isDefEqStuckExceptionId builtin_initialize registerTraceClass `Meta registerTraceClass `Meta.debug @[inline] def liftMetaM [MonadLiftT MetaM m] (x : MetaM α) : m α := liftM x @[inline] def mapMetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, MetaM α → MetaM α) {α} (x : m α) : m α := controlAt MetaM fun runInBase => f <| runInBase x @[inline] def map1MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → MetaM α) → MetaM α) {α} (k : β → m α) : m α := controlAt MetaM fun runInBase => f fun b => runInBase <| k b @[inline] def map2MetaM [MonadControlT MetaM m] [Monad m] (f : forall {α}, (β → γ → MetaM α) → MetaM α) {α} (k : β → γ → m α) : m α := controlAt MetaM fun runInBase => f fun b c => runInBase <| k b c section Methods variable [MonadControlT MetaM n] [Monad n] @[inline] def modifyCache (f : Cache → Cache) : MetaM Unit := modify fun ⟨mctx, cache, zetaFVarIds, postponed⟩ => ⟨mctx, f cache, zetaFVarIds, postponed⟩ @[inline] def modifyInferTypeCache (f : InferTypeCache → InferTypeCache) : MetaM Unit := modifyCache fun ⟨ic, c1, c2, c3, c4, c5, c6⟩ => ⟨f ic, c1, c2, c3, c4, c5, c6⟩ def getLocalInstances : MetaM LocalInstances := return (← read).localInstances def getConfig : MetaM Config := return (← read).config def setMCtx (mctx : MetavarContext) : MetaM Unit := modify fun s => { s with mctx := mctx } def resetZetaFVarIds : MetaM Unit := modify fun s => { s with zetaFVarIds := {} } def getZetaFVarIds : MetaM FVarIdSet := return (← get).zetaFVarIds def getPostponed : MetaM (PersistentArray PostponedEntry) := return (← get).postponed def setPostponed (postponed : PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := postponed } @[inline] def modifyPostponed (f : PersistentArray PostponedEntry → PersistentArray PostponedEntry) : MetaM Unit := modify fun s => { s with postponed := f s.postponed } /- WARNING: The following 4 constants are a hack for simulating forward declarations. They are defined later using the `export` attribute. This is hackish because we have to hard-code the true arity of these definitions here, and make sure the C names match. We have used another hack based on `IO.Ref`s in the past, it was safer but less efficient. -/ @[extern 6 "lean_whnf"] constant whnf : Expr → MetaM Expr @[extern 6 "lean_infer_type"] constant inferType : Expr → MetaM Expr @[extern 7 "lean_is_expr_def_eq"] constant isExprDefEqAux : Expr → Expr → MetaM Bool @[extern 6 "lean_synth_pending"] protected constant synthPending : MVarId → MetaM Bool def whnfForall (e : Expr) : MetaM Expr := do let e' ← whnf e if e'.isForall then pure e' else pure e -- withIncRecDepth for a monad `n` such that `[MonadControlT MetaM n]` protected def withIncRecDepth (x : n α) : n α := mapMetaM (withIncRecDepth (m := MetaM)) x private def mkFreshExprMVarAtCore (mvarId : MVarId) (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind) (userName : Name) (numScopeArgs : Nat) : MetaM Expr := do modifyMCtx fun mctx => mctx.addExprMVarDecl mvarId userName lctx localInsts type kind numScopeArgs; return mkMVar mvarId def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore (← mkFreshMVarId) lctx localInsts type kind userName numScopeArgs def mkFreshLevelMVar : MetaM Level := do let mvarId ← mkFreshMVarId modifyMCtx fun mctx => mctx.addLevelMVarDecl mvarId; return mkLevelMVar mvarId private def mkFreshExprMVarCore (type : Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := do mkFreshExprMVarAt (← getLCtx) (← getLocalInstances) type kind userName private def mkFreshExprMVarImpl (type? : Option Expr) (kind : MetavarKind) (userName : Name) : MetaM Expr := match type? with | some type => mkFreshExprMVarCore type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVarCore (mkSort u) MetavarKind.natural Name.anonymous mkFreshExprMVarCore type kind userName def mkFreshExprMVar (type? : Option Expr) (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := mkFreshExprMVarImpl type? kind userName def mkFreshTypeMVar (kind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := do let u ← mkFreshLevelMVar mkFreshExprMVar (mkSort u) kind userName /- Low-level version of `MkFreshExprMVar` which allows users to create/reserve a `mvarId` using `mkFreshId`, and then later create the metavar using this method. -/ private def mkFreshExprMVarWithIdCore (mvarId : MVarId) (type : Expr) (kind : MetavarKind := MetavarKind.natural) (userName : Name := Name.anonymous) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAtCore mvarId (← getLCtx) (← getLocalInstances) type kind userName numScopeArgs def mkFreshExprMVarWithId (mvarId : MVarId) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName := Name.anonymous) : MetaM Expr := match type? with | some type => mkFreshExprMVarWithIdCore mvarId type kind userName | none => do let u ← mkFreshLevelMVar let type ← mkFreshExprMVar (mkSort u) mkFreshExprMVarWithIdCore mvarId type kind userName def mkFreshLevelMVars (num : Nat) : MetaM (List Level) := num.foldM (init := []) fun _ us => return (← mkFreshLevelMVar)::us def mkFreshLevelMVarsFor (info : ConstantInfo) : MetaM (List Level) := mkFreshLevelMVars info.numLevelParams def mkConstWithFreshMVarLevels (declName : Name) : MetaM Expr := do let info ← getConstInfo declName return mkConst declName (← mkFreshLevelMVarsFor info) def getTransparency : MetaM TransparencyMode := return (← getConfig).transparency def shouldReduceAll : MetaM Bool := return (← getTransparency) == TransparencyMode.all def shouldReduceReducibleOnly : MetaM Bool := return (← getTransparency) == TransparencyMode.reducible def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do match (← getMCtx).findDecl? mvarId with | some d => pure d | none => throwError "unknown metavariable '?{mvarId.name}'" def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := modifyMCtx fun mctx => mctx.setMVarKind mvarId kind /- Update the type of the given metavariable. This function assumes the new type is definitionally equal to the current one -/ def setMVarType (mvarId : MVarId) (type : Expr) : MetaM Unit := do modifyMCtx fun mctx => mctx.setMVarType mvarId type def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do return (← getMVarDecl mvarId).depth != (← getMCtx).depth def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.syntheticOpaque => return !(← getConfig).assignSyntheticOpaque | _ => return mvarDecl.depth != (← getMCtx).depth def getLevelMVarDepth (mvarId : MVarId) : MetaM Nat := do match (← getMCtx).findLevelDepth? mvarId with | some depth => return depth | _ => throwError "unknown universe metavariable '?{mvarId.name}'" def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do if (← getConfig).ignoreLevelMVarDepth then return false else return (← getLevelMVarDepth mvarId) != (← getMCtx).depth def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit := modifyMCtx fun mctx => mctx.renameMVar mvarId newUserName def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool := return (← getMCtx).isExprAssigned mvarId def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) := return (← getMCtx).getExprAssignment? mvarId /-- Return true if `e` contains `mvarId` directly or indirectly -/ def occursCheck (mvarId : MVarId) (e : Expr) : MetaM Bool := return (← getMCtx).occursCheck mvarId e def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit := modifyMCtx fun mctx => mctx.assignExpr mvarId val def isDelayedAssigned (mvarId : MVarId) : MetaM Bool := return (← getMCtx).isDelayedAssigned mvarId def getDelayedAssignment? (mvarId : MVarId) : MetaM (Option DelayedMetavarAssignment) := return (← getMCtx).getDelayedAssignment? mvarId def hasAssignableMVar (e : Expr) : MetaM Bool := return (← getMCtx).hasAssignableMVar e def throwUnknownFVar (fvarId : FVarId) : MetaM α := throwError "unknown free variable '{mkFVar fvarId}'" def findLocalDecl? (fvarId : FVarId) : MetaM (Option LocalDecl) := return (← getLCtx).find? fvarId def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do match (← getLCtx).find? fvarId with | some d => pure d | none => throwUnknownFVar fvarId def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl := getLocalDecl fvar.fvarId! def getLocalDeclFromUserName (userName : Name) : MetaM LocalDecl := do match (← getLCtx).findFromUserName? userName with | some d => pure d | none => throwError "unknown local declaration '{userName}'" def instantiateLevelMVars (u : Level) : MetaM Level := MetavarContext.instantiateLevelMVars u def instantiateMVars (e : Expr) : MetaM Expr := (MetavarContext.instantiateExprMVars e).run def instantiateLocalDeclMVars (localDecl : LocalDecl) : MetaM LocalDecl := match localDecl with | LocalDecl.cdecl idx id n type bi => return LocalDecl.cdecl idx id n (← instantiateMVars type) bi | LocalDecl.ldecl idx id n type val nonDep => return LocalDecl.ldecl idx id n (← instantiateMVars type) (← instantiateMVars val) nonDep @[inline] def liftMkBindingM (x : MetavarContext.MkBindingM α) : MetaM α := do match x (← getLCtx) { mctx := (← getMCtx), ngen := (← getNGen) } with | EStateM.Result.ok e newS => do setNGen newS.ngen; setMCtx newS.mctx; pure e | EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => do setMCtx newS.mctx; setNGen newS.ngen; throwError "failed to create binder due to failure when reverting variable dependencies" def abstractRange (e : Expr) (n : Nat) (xs : Array Expr) : MetaM Expr := liftMkBindingM <| MetavarContext.abstractRange e n xs def abstract (e : Expr) (xs : Array Expr) : MetaM Expr := abstractRange e xs.size xs def mkForallFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkForall xs e usedOnly usedLetOnly def mkLambdaFVars (xs : Array Expr) (e : Expr) (usedOnly : Bool := false) (usedLetOnly : Bool := true) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.mkLambda xs e usedOnly usedLetOnly def mkLetFVars (xs : Array Expr) (e : Expr) (usedLetOnly := true) : MetaM Expr := mkLambdaFVars xs e (usedLetOnly := usedLetOnly) def mkArrow (d b : Expr) : MetaM Expr := return Lean.mkForall (← mkFreshUserName `x) BinderInfo.default d b /-- `fun _ : Unit => a` -/ def mkFunUnit (a : Expr) : MetaM Expr := return Lean.mkLambda (← mkFreshUserName `x) BinderInfo.default (mkConst ``Unit) a def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM <| MetavarContext.elimMVarDeps xs e preserveOrder @[inline] def withConfig (f : Config → Config) : n α → n α := mapMetaM <| withReader (fun ctx => { ctx with config := f ctx.config }) @[inline] def withTrackingZeta (x : n α) : n α := withConfig (fun cfg => { cfg with trackZeta := true }) x @[inline] def withoutProofIrrelevance (x : n α) : n α := withConfig (fun cfg => { cfg with proofIrrelevance := false }) x @[inline] def withTransparency (mode : TransparencyMode) : n α → n α := mapMetaM <| withConfig (fun config => { config with transparency := mode }) @[inline] def withDefault (x : n α) : n α := withTransparency TransparencyMode.default x @[inline] def withReducible (x : n α) : n α := withTransparency TransparencyMode.reducible x @[inline] def withReducibleAndInstances (x : n α) : n α := withTransparency TransparencyMode.instances x @[inline] def withAtLeastTransparency (mode : TransparencyMode) (x : n α) : n α := withConfig (fun config => let oldMode := config.transparency let mode := if oldMode.lt mode then mode else oldMode { config with transparency := mode }) x /-- Execute `x` allowing `isDefEq` to assign synthetic opaque metavariables. -/ @[inline] def withAssignableSyntheticOpaque (x : n α) : n α := withConfig (fun config => { config with assignSyntheticOpaque := true }) x /-- Save cache, execute `x`, restore cache -/ @[inline] private def savingCacheImpl (x : MetaM α) : MetaM α := do let savedCache := (← get).cache try x finally modify fun s => { s with cache := savedCache } @[inline] def savingCache : n α → n α := mapMetaM savingCacheImpl def getTheoremInfo (info : ConstantInfo) : MetaM (Option ConstantInfo) := do if (← shouldReduceAll) then return some info else return none private def getDefInfoTemp (info : ConstantInfo) : MetaM (Option ConstantInfo) := do match (← getTransparency) with | TransparencyMode.all => return some info | TransparencyMode.default => return some info | _ => if (← isReducible info.name) then return some info else return none /- Remark: we later define `getConst?` at `GetConst.lean` after we define `Instances.lean`. This method is only used to implement `isClassQuickConst?`. It is very similar to `getConst?`, but it returns none when `TransparencyMode.instances` and `constName` is an instance. This difference should be irrelevant for `isClassQuickConst?`. -/ private def getConstTemp? (constName : Name) : MetaM (Option ConstantInfo) := do match (← getEnv).find? constName with | some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info | some (info@(ConstantInfo.defnInfo _)) => getDefInfoTemp info | some info => pure (some info) | none => throwUnknownConstant constName private def isClassQuickConst? (constName : Name) : MetaM (LOption Name) := do if isClass (← getEnv) constName then pure (LOption.some constName) else match (← getConstTemp? constName) with | some _ => pure LOption.undef | none => pure LOption.none private partial def isClassQuick? : Expr → MetaM (LOption Name) | Expr.bvar .. => pure LOption.none | Expr.lit .. => pure LOption.none | Expr.fvar .. => pure LOption.none | Expr.sort .. => pure LOption.none | Expr.lam .. => pure LOption.none | Expr.letE .. => pure LOption.undef | Expr.proj .. => pure LOption.undef | Expr.forallE _ _ b _ => isClassQuick? b | Expr.mdata _ e _ => isClassQuick? e | Expr.const n _ _ => isClassQuickConst? n | Expr.mvar mvarId _ => do match (← getExprMVarAssignment? mvarId) with | some val => isClassQuick? val | none => pure LOption.none | Expr.app f _ _ => match f.getAppFn with | Expr.const n .. => isClassQuickConst? n | Expr.lam .. => pure LOption.undef | _ => pure LOption.none def saveAndResetSynthInstanceCache : MetaM SynthInstanceCache := do let savedSythInstance := (← get).cache.synthInstance modifyCache fun c => { c with synthInstance := {} } pure savedSythInstance def restoreSynthInstanceCache (cache : SynthInstanceCache) : MetaM Unit := modifyCache fun c => { c with synthInstance := cache } @[inline] private def resettingSynthInstanceCacheImpl (x : MetaM α) : MetaM α := do let savedSythInstance ← saveAndResetSynthInstanceCache try x finally restoreSynthInstanceCache savedSythInstance /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache : n α → n α := mapMetaM resettingSynthInstanceCacheImpl @[inline] def resettingSynthInstanceCacheWhen (b : Bool) (x : n α) : n α := if b then resettingSynthInstanceCache x else x private def withNewLocalInstanceImp (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := do let localDecl ← getFVarLocalDecl fvar /- Recall that we use `auxDecl` binderInfo when compiling recursive declarations. -/ match localDecl.binderInfo with | BinderInfo.auxDecl => k | _ => resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ def withNewLocalInstance (className : Name) (fvar : Expr) : n α → n α := mapMetaM <| withNewLocalInstanceImp className fvar private def fvarsSizeLtMaxFVars (fvars : Array Expr) (maxFVars? : Option Nat) : Bool := match maxFVars? with | some maxFVars => fvars.size < maxFVars | none => true mutual /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ private partial def withNewLocalInstancesImp (fvars : Array Expr) (i : Nat) (k : MetaM α) : MetaM α := do if h : i < fvars.size then let fvar := fvars.get ⟨i, h⟩ let decl ← getFVarLocalDecl fvar match (← isClassQuick? decl.type) with | LOption.none => withNewLocalInstancesImp fvars (i+1) k | LOption.undef => match (← isClassExpensive? decl.type) with | none => withNewLocalInstancesImp fvars (i+1) k | some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k | LOption.some c => withNewLocalInstance c fvar <| withNewLocalInstancesImp fvars (i+1) k else k /-- `forallTelescopeAuxAux lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context extended with declarations for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ private partial def forallTelescopeReducingAuxAux (reducing : Bool) (maxFVars? : Option Nat) (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do let rec process (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (type : Expr) : MetaM α := do match type with | Expr.forallE n d b c => if fvarsSizeLtMaxFVars fvars maxFVars? then let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId let fvars := fvars.push fvar process lctx fvars j b else let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars type | _ => let type := type.instantiateRevRange j fvars.size fvars; withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do if reducing && fvarsSizeLtMaxFVars fvars maxFVars? then let newType ← whnf type if newType.isForall then process lctx fvars fvars.size newType else k fvars type else k fvars type process (← getLCtx) #[] 0 type private partial def forallTelescopeReducingAux (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do match maxFVars? with | some 0 => k #[] type | _ => do let newType ← whnf type if newType.isForall then forallTelescopeReducingAuxAux true maxFVars? newType k else k #[] type private partial def isClassExpensive? : Expr → MetaM (Option Name) | type => withReducible <| -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux type none fun xs type => do let env ← getEnv match type.getAppFn with | Expr.const c _ _ => do if isClass env c then return some c else -- make sure abbreviations are unfolded match (← whnf type).getAppFn with | Expr.const c _ _ => return if isClass env c then some c else none | _ => return none | _ => return none private partial def isClassImp? (type : Expr) : MetaM (Option Name) := do match (← isClassQuick? type) with | LOption.none => pure none | LOption.some c => pure (some c) | LOption.undef => isClassExpensive? type end def isClass? (type : Expr) : MetaM (Option Name) := try isClassImp? type catch _ => pure none private def withNewLocalInstancesImpAux (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImp fvars j partial def withNewLocalInstances (fvars : Array Expr) (j : Nat) : n α → n α := mapMetaM <| withNewLocalInstancesImpAux fvars j @[inline] private def forallTelescopeImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do forallTelescopeReducingAuxAux (reducing := false) (maxFVars? := none) type k /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeImp type k) k private def forallTelescopeReducingImp (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type (maxFVars? := none) k /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallTelescopeReducingImp type k) k private def forallBoundedTelescopeImp (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux type maxFVars? k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => forallBoundedTelescopeImp type maxFVars? k) k private partial def lambdaTelescopeImp (e : Expr) (consumeLet : Bool) (k : Array Expr → Expr → MetaM α) : MetaM α := do process consumeLet (← getLCtx) #[] 0 e where process (consumeLet : Bool) (lctx : LocalContext) (fvars : Array Expr) (j : Nat) (e : Expr) : MetaM α := do match consumeLet, e with | _, Expr.lam n d b c => let d := d.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo let fvar := mkFVar fvarId process consumeLet lctx (fvars.push fvar) j b | true, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars let v := v.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLetDecl fvarId n t v let fvar := mkFVar fvarId process true lctx (fvars.push fvar) j b | _, e => let e := e.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstancesImp fvars j do k fvars e /-- Similar to `forallTelescope` but for lambda and let expressions. -/ def lambdaLetTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp type true k) k /-- Similar to `forallTelescope` but for lambda expressions. -/ def lambdaTelescope (type : Expr) (k : Array Expr → Expr → n α) : n α := map2MetaM (fun k => lambdaTelescopeImp type false k) k /-- Return the parameter names for the givel global declaration. -/ def getParamNames (declName : Name) : MetaM (Array Name) := do forallTelescopeReducing (← getConstInfo declName).type fun xs _ => do xs.mapM fun x => do let localDecl ← getLocalDecl x.fvarId! pure localDecl.userName -- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments. private partial def forallMetaTelescopeReducingAux (e : Expr) (reducing : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do if maxMVars?.isEqSome mvars.size then let type := type.instantiateRevRange j mvars.size mvars; return (mvars, bis, type) else match type with | Expr.forallE n d b c => let d := d.instantiateRevRange j mvars.size mvars let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind let mvar ← mkFreshExprMVar d k n let mvars := mvars.push mvar let bis := bis.push c.binderInfo process mvars bis j b | _ => let type := type.instantiateRevRange j mvars.size mvars; if reducing then do let newType ← whnf type; if newType.isForall then process mvars bis mvars.size newType else return (mvars, bis, type) else return (mvars, bis, type) /-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/ def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := false) (maxMVars? := none) kind /-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) maxMVars? kind /-- Similar to `forallMetaTelescopeReducing`, stops constructing the telescope when it reaches size `maxMVars`. -/ def forallMetaBoundedTelescope (e : Expr) (maxMVars : Nat) (kind : MetavarKind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux e (reducing := true) (maxMVars? := some maxMVars) (kind := kind) /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ partial def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := process #[] #[] 0 e where process (mvars : Array Expr) (bis : Array BinderInfo) (j : Nat) (type : Expr) : MetaM (Array Expr × Array BinderInfo × Expr) := do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do let type := type.instantiateRevRange j mvars.size mvars pure (mvars, bis, type) if maxMVars?.isEqSome mvars.size then finalize () else match type with | Expr.lam n d b c => let d := d.instantiateRevRange j mvars.size mvars let mvar ← mkFreshExprMVar d let mvars := mvars.push mvar let bis := bis.push c.binderInfo process mvars bis j b | _ => finalize () private def withNewFVar (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do match (← isClass? fvarType) with | none => k fvar | some c => withNewLocalInstance c fvar <| k fvar private def withLocalDeclImp (n : Name) (bi : BinderInfo) (type : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLocalDecl fvarId n type bi let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k def withLocalDecl (name : Name) (bi : BinderInfo) (type : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLocalDeclImp name bi type k) k def withLocalDeclD (name : Name) (type : Expr) (k : Expr → n α) : n α := withLocalDecl name BinderInfo.default type k partial def withLocalDecls [Inhabited α] (declInfos : Array (Name × BinderInfo × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := loop #[] where loop [Inhabited α] (acc : Array Expr) : n α := do if acc.size < declInfos.size then let (name, bi, typeCtor) := declInfos[acc.size] withLocalDecl name bi (←typeCtor acc) fun x => loop (acc.push x) else k acc def withLocalDeclsD [Inhabited α] (declInfos : Array (Name × (Array Expr → n Expr))) (k : (xs : Array Expr) → n α) : n α := withLocalDecls (declInfos.map (fun (name, typeCtor) => (name, BinderInfo.default, typeCtor))) k private def withNewBinderInfosImp (bs : Array (FVarId × BinderInfo)) (k : MetaM α) : MetaM α := do let lctx := bs.foldl (init := (← getLCtx)) fun lctx (fvarId, bi) => lctx.setBinderInfo fvarId bi withReader (fun ctx => { ctx with lctx := lctx }) k def withNewBinderInfos (bs : Array (FVarId × BinderInfo)) (k : n α) : n α := mapMetaM (fun k => withNewBinderInfosImp bs k) k private def withLetDeclImp (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do let fvarId ← mkFreshFVarId let ctx ← read let lctx := ctx.lctx.mkLetDecl fvarId n type val let fvar := mkFVar fvarId withReader (fun ctx => { ctx with lctx := lctx }) do withNewFVar fvar type k def withLetDecl (name : Name) (type : Expr) (val : Expr) (k : Expr → n α) : n α := map1MetaM (fun k => withLetDeclImp name type val k) k private def withExistingLocalDeclsImp (decls : List LocalDecl) (k : MetaM α) : MetaM α := do let ctx ← read let numLocalInstances := ctx.localInstances.size let lctx := decls.foldl (fun (lctx : LocalContext) decl => lctx.addDecl decl) ctx.lctx withReader (fun ctx => { ctx with lctx := lctx }) do let newLocalInsts ← decls.foldlM (fun (newlocalInsts : Array LocalInstance) (decl : LocalDecl) => (do { match (← isClass? decl.type) with | none => pure newlocalInsts | some c => pure <| newlocalInsts.push { className := c, fvar := decl.toExpr } } : MetaM _)) ctx.localInstances; if newLocalInsts.size == numLocalInstances then k else resettingSynthInstanceCache <| withReader (fun ctx => { ctx with localInstances := newLocalInsts }) k def withExistingLocalDecls (decls : List LocalDecl) : n α → n α := mapMetaM <| withExistingLocalDeclsImp decls private def withNewMCtxDepthImp (x : MetaM α) : MetaM α := do let saved ← get modify fun s => { s with mctx := s.mctx.incDepth, postponed := {} } try x finally modify fun s => { s with mctx := saved.mctx, postponed := saved.postponed } /-- Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`, and restore saved data. -/ def withNewMCtxDepth : n α → n α := mapMetaM withNewMCtxDepthImp private def withLocalContextImp (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do let localInstsCurr ← getLocalInstances withReader (fun ctx => { ctx with lctx := lctx, localInstances := localInsts }) do if localInsts == localInstsCurr then x else resettingSynthInstanceCache x def withLCtx (lctx : LocalContext) (localInsts : LocalInstances) : n α → n α := mapMetaM <| withLocalContextImp lctx localInsts private def withMVarContextImp (mvarId : MVarId) (x : MetaM α) : MetaM α := do let mvarDecl ← getMVarDecl mvarId withLocalContextImp mvarDecl.lctx mvarDecl.localInstances x /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def withMVarContext (mvarId : MVarId) : n α → n α := mapMetaM <| withMVarContextImp mvarId private def withMCtxImp (mctx : MetavarContext) (x : MetaM α) : MetaM α := do let mctx' ← getMCtx setMCtx mctx try x finally setMCtx mctx' def withMCtx (mctx : MetavarContext) : n α → n α := mapMetaM <| withMCtxImp mctx @[inline] private def approxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true}) x /-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/ @[inline] def approxDefEq : n α → n α := mapMetaM approxDefEqImp @[inline] private def fullApproxDefEqImp (x : MetaM α) : MetaM α := withConfig (fun config => { config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true }) x /-- Similar to `approxDefEq`, but uses all available approximations. We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code. For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[Pure ?m]`. Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to solve `[Pure (fun _ => IO Bool)]` -/ @[inline] def fullApproxDefEq : n α → n α := mapMetaM fullApproxDefEqImp def normalizeLevel (u : Level) : MetaM Level := do let u ← instantiateLevelMVars u pure u.normalize def assignLevelMVar (mvarId : MVarId) (u : Level) : MetaM Unit := do modifyMCtx fun mctx => mctx.assignLevel mvarId u def whnfR (e : Expr) : MetaM Expr := withTransparency TransparencyMode.reducible <| whnf e def whnfD (e : Expr) : MetaM Expr := withTransparency TransparencyMode.default <| whnf e def whnfI (e : Expr) : MetaM Expr := withTransparency TransparencyMode.instances <| whnf e def setInlineAttribute (declName : Name) (kind := Compiler.InlineAttributeKind.inline): MetaM Unit := do let env ← getEnv match Compiler.setInlineAttribute env declName kind with | Except.ok env => setEnv env | Except.error msg => throwError msg private partial def instantiateForallAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | Expr.forallE _ _ b _ => instantiateForallAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateForall, too many parameters" else pure e /- Given `e` of the form `forall (a_1 : A_1) ... (a_n : A_n), B[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `B[p_1, ..., p_n]`. -/ def instantiateForall (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateForallAux ps 0 e private partial def instantiateLambdaAux (ps : Array Expr) (i : Nat) (e : Expr) : MetaM Expr := do if h : i < ps.size then let p := ps.get ⟨i, h⟩ match (← whnf e) with | Expr.lam _ _ b _ => instantiateLambdaAux ps (i+1) (b.instantiate1 p) | _ => throwError "invalid instantiateLambda, too many parameters" else pure e /- Given `e` of the form `fun (a_1 : A_1) ... (a_n : A_n) => t[a_1, ..., a_n]` and `p_1 : A_1, ... p_n : A_n`, return `t[p_1, ..., p_n]`. It uses `whnf` to reduce `e` if it is not a lambda -/ def instantiateLambda (e : Expr) (ps : Array Expr) : MetaM Expr := instantiateLambdaAux ps 0 e /-- Return true iff `e` depends on the free variable `fvarId` -/ def dependsOn (e : Expr) (fvarId : FVarId) : MetaM Bool := return (← getMCtx).exprDependsOn e fvarId def ppExpr (e : Expr) : MetaM Format := do let ctxCore ← readThe Core.Context Lean.ppExpr { env := (← getEnv), mctx := (← getMCtx), lctx := (← getLCtx), opts := (← getOptions), currNamespace := ctxCore.currNamespace, openDecls := ctxCore.openDecls } e @[inline] protected def orElse (x : MetaM α) (y : Unit → MetaM α) : MetaM α := do let s ← saveState try x catch _ => s.restore; y () instance : OrElse (MetaM α) := ⟨Meta.orElse⟩ instance : Alternative MetaM where failure := fun {α} => throwError "failed" orElse := Meta.orElse @[inline] private def orelseMergeErrorsImp (x y : MetaM α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ m₂) : MetaM α := do let env ← getEnv let mctx ← getMCtx try x catch ex => setEnv env setMCtx mctx match ex with | Exception.error ref₁ m₁ => try y catch | Exception.error ref₂ m₂ => throw <| Exception.error (mergeRef ref₁ ref₂) (mergeMsg m₁ m₂) | ex => throw ex | ex => throw ex /-- Similar to `orelse`, but merge errors. Note that internal errors are not caught. The default `mergeRef` uses the `ref` (position information) for the first message. The default `mergeMsg` combines error messages using `Format.line ++ Format.line` as a separator. -/ @[inline] def orelseMergeErrors [MonadControlT MetaM m] [Monad m] (x y : m α) (mergeRef : Syntax → Syntax → Syntax := fun r₁ r₂ => r₁) (mergeMsg : MessageData → MessageData → MessageData := fun m₁ m₂ => m₁ ++ Format.line ++ Format.line ++ m₂) : m α := do controlAt MetaM fun runInBase => orelseMergeErrorsImp (runInBase x) (runInBase y) mergeRef mergeMsg /-- Execute `x`, and apply `f` to the produced error message -/ def mapErrorImp (x : MetaM α) (f : MessageData → MessageData) : MetaM α := do try x catch | Exception.error ref msg => throw <| Exception.error ref <| f msg | ex => throw ex @[inline] def mapError [MonadControlT MetaM m] [Monad m] (x : m α) (f : MessageData → MessageData) : m α := controlAt MetaM fun runInBase => mapErrorImp (runInBase x) f /-- Sort free variables using an order `x < y` iff `x` was defined before `y`. If a free variable is not in the local context, we use their id. -/ def sortFVarIds (fvarIds : Array FVarId) : MetaM (Array FVarId) := do let lctx ← getLCtx return fvarIds.qsort fun fvarId₁ fvarId₂ => match lctx.find? fvarId₁, lctx.find? fvarId₂ with | some d₁, some d₂ => d₁.index < d₂.index | some _, none => false | none, some _ => true | none, none => Name.quickLt fvarId₁.name fvarId₂.name end Methods end Meta export Meta (MetaM) end Lean
9394e2b658e090370961f0ab8ec968c86b2eb7a3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/sqrt_norm_num.lean
4ae37dded19f09aac9904f42f6a12983d053a29c
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,469
lean
/- Copyright (c) 2022 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.norm_num import data.nat.sqrt /-! ### `norm_num` plugin for `sqrt` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The `norm_num` plugin evaluates `sqrt` by bounding it between consecutive integers. -/ namespace norm_num open tactic nat lemma is_sqrt {n a a2 b : ℕ} (ha2 : a * a = a2) (hb : a2 + b = n) (hle : b ≤ bit0 a) : sqrt n = a := by { rw [← hb, ← ha2, ← pow_two], exact sqrt_add_eq' _ hle } /-- Given `n` provides `(a, ⊢ nat.sqrt n = a)`. -/ meta def prove_sqrt (ic : instance_cache) (n : expr) : tactic (instance_cache × expr × expr) := do nn ← n.to_nat, let na := nn.sqrt, (ic, a) ← ic.of_nat na, (ic, a2, ha2) ← prove_mul_nat ic a a, (ic, b) ← ic.of_nat (nn - na*na), (ic, hb) ← prove_add_nat ic a2 b n, (ic, hle) ← prove_le_nat ic b (`(bit0:ℕ→ℕ).mk_app [a]), pure (ic, a, `(@is_sqrt).mk_app [n, a, a2, b, ha2, hb, hle]) /-- A `norm_num` plugin for `sqrt n` when `n` is a numeral. -/ @[norm_num] meta def eval_sqrt : expr → tactic (expr × expr) | `(sqrt %%en) := do n ← en.to_nat, match n with | 0 := pure (`(0:ℕ), `(sqrt_zero)) | _ := do c ← mk_instance_cache `(ℕ), prod.snd <$> prove_sqrt c en end | _ := failed end norm_num
ee08a1b2cc79d8e9b2e802205809479a2daf6e6e
4727251e0cd73359b15b664c3170e5d754078599
/test/calc.lean
a527971d154fdc34806d6ff08b16d7eee725162c
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
1,056
lean
import analysis.asymptotics.asymptotic_equivalent import measure_theory.integral.interval_integral import measure_theory.measure.vector_measure variables {α β γ δ : Type*} section is_equivalent open_locale asymptotics example {l : filter α} {u v w : α → β} [normed_group β] (huv : u ~[l] v) (hvw : v ~[l] w) : u ~[l] w := calc u ~[l] v : huv ... ~[l] w : hvw end is_equivalent section interval_integral variables {f : ℝ → ℝ} {μ : measure_theory.measure ℝ} local notation u ` ~[`:50 a:50`-`:40 b `] `:0 v:50 := interval_integrable a b u v example {a b c : ℝ} (hab : a ~[f-μ] b) (hbc : b ~[f-μ] c) : interval_integrable f μ a c := calc a ~[f-μ] b : hab ... ~[f-μ] c : hbc end interval_integral section vector_measure open measure_theory measure_theory.vector_measure open_locale measure_theory example {u : vector_measure ℝ ℝ} {v : vector_measure ℝ ℝ} {w : vector_measure ℝ ℝ} (huv : u ≪ᵥ v) (hvw : v ≪ᵥ w) : u ≪ᵥ w := calc u ≪ᵥ v : huv ... ≪ᵥ w : hvw end vector_measure
2231ddab8da370cf052430d90119ed5f3a34b832
61ccc57f9d72048e493dd6969b56ebd7f0a8f9e8
/src/algebra/category/Group/Z_Module_equivalence.lean
4b6394d2e5f6d1e9d17984127a905172996426d6
[ "Apache-2.0" ]
permissive
jtristan/mathlib
375b3c8682975df28f79f53efcb7c88840118467
8fa8f175271320d675277a672f59ec53abd62f10
refs/heads/master
1,651,072,765,551
1,588,255,641,000
1,588,255,641,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,289
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 algebra.category.Module.basic /-! The forgetful functor from ℤ-modules to additive commutative groups is an equivalence of categories. TODO: either use this equivalence to transport the monoidal structure from `Module ℤ` to `Ab`, or, having constructed that monoidal structure directly, show this functor is monoidal. -/ open category_theory open category_theory.equivalence /-- The forgetful functor from `ℤ` modules to `AddCommGroup` is full. -/ instance : full (forget₂ (Module ℤ) AddCommGroup) := { preimage := λ A B f, { to_fun := f, add := λ x y, add_monoid_hom.map_add f x y, smul := λ n x, begin convert add_monoid_hom.map_int_module_smul f n x, apply congr_arg, congr, end } } /-- The forgetful functor from `ℤ` modules to `AddCommGroup` is essentially surjective. -/ instance : ess_surj (forget₂ (Module ℤ) AddCommGroup) := { obj_preimage := λ A, Module.of ℤ A, iso' := λ A, { hom := 𝟙 A, inv := 𝟙 A, } } instance : is_equivalence (forget₂ (Module ℤ) AddCommGroup) := equivalence_of_fully_faithfully_ess_surj (forget₂ (Module ℤ) AddCommGroup)
43973d899746e1a509b26a8b0d1ca785b4358949
e0b0b1648286e442507eb62344760d5cd8d13f2d
/tests/lean/run/decClassical.lean
821ad9caaae594f8d90d9375e9539c860b9b8abe
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
304
lean
open Classical theorem ex : if (fun x => x + 1) = (fun x => x + 2) then False else True := by have (fun x => x + 1) ≠ (fun x => x + 2) by intro h have 1 = 2 from congrFun h 0 contradiction rw [ifNeg this] exact True.intro def tst (x : Nat) : Bool := if 1 < 2 then true else false
03bc0c999c7eb35a5afe4da686bbeb095f1b2a56
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/category_theory/types.lean
41c59d98a3a8b492037ad6c173a051d45c05f18e
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
11,116
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl -/ import category_theory.epi_mono import category_theory.functor.fully_faithful import logic.equiv.basic /-! # The category `Type`. In this section we set up the theory so that Lean's types and functions between them can be viewed as a `large_category` in our framework. Lean can not transparently view a function as a morphism in this category, and needs a hint in order to be able to type check. We provide the abbreviation `as_hom f` to guide type checking, as well as a corresponding notation `↾ f`. (Entered as `\upr `.) The notation is enabled using `open_locale category_theory.Type`. We provide various simplification lemmas for functors and natural transformations valued in `Type`. We define `ulift_functor`, from `Type u` to `Type (max u v)`, and show that it is fully faithful (but not, of course, essentially surjective). We prove some basic facts about the category `Type`: * epimorphisms are surjections and monomorphisms are injections, * `iso` is both `iso` and `equiv` to `equiv` (at least within a fixed universe), * every type level `is_lawful_functor` gives a categorical functor `Type ⥤ Type` (the corresponding fact about monads is in `src/category_theory/monad/types.lean`). -/ namespace category_theory -- morphism levels before object levels. See note [category_theory universes]. universes v v' w u u' /- The `@[to_additive]` attribute is just a hint that expressions involving this instance can still be additivized. -/ @[to_additive category_theory.types] instance types : large_category (Type u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } lemma types_hom {α β : Type u} : (α ⟶ β) = (α → β) := rfl lemma types_id (X : Type u) : 𝟙 X = id := rfl lemma types_comp {X Y Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := rfl @[simp] lemma types_id_apply (X : Type u) (x : X) : ((𝟙 X) : X → X) x = x := rfl @[simp] lemma types_comp_apply {X Y Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : (f ≫ g) x = g (f x) := rfl @[simp] lemma hom_inv_id_apply {X Y : Type u} (f : X ≅ Y) (x : X) : f.inv (f.hom x) = x := congr_fun f.hom_inv_id x @[simp] lemma inv_hom_id_apply {X Y : Type u} (f : X ≅ Y) (y : Y) : f.hom (f.inv y) = y := congr_fun f.inv_hom_id y /-- `as_hom f` helps Lean type check a function as a morphism in the category `Type`. -/ -- Unfortunately without this wrapper we can't use `category_theory` idioms, such as `is_iso f`. abbreviation as_hom {α β : Type u} (f : α → β) : α ⟶ β := f -- If you don't mind some notation you can use fewer keystrokes: localized "notation `↾` f : 200 := category_theory.as_hom f" in category_theory.Type -- type as \upr in VScode section -- We verify the expected type checking behaviour of `as_hom`. variables (α β γ : Type u) (f : α → β) (g : β → γ) example : α → γ := ↾f ≫ ↾g example [is_iso ↾f] : mono ↾f := by apply_instance example [is_iso ↾f] : ↾f ≫ inv ↾f = 𝟙 α := by simp end namespace functor variables {J : Type u} [category.{v} J] /-- The sections of a functor `J ⥤ Type` are the choices of a point `u j : F.obj j` for each `j`, such that `F.map f (u j) = u j` for every morphism `f : j ⟶ j'`. We later use these to define limits in `Type` and in many concrete categories. -/ def sections (F : J ⥤ Type w) : set (Π j, F.obj j) := { u | ∀ {j j'} (f : j ⟶ j'), F.map f (u j) = u j'} end functor namespace functor_to_types variables {C : Type u} [category.{v} C] (F G H : C ⥤ Type w) {X Y Z : C} variables (σ : F ⟶ G) (τ : G ⟶ H) @[simp] lemma map_comp_apply (f : X ⟶ Y) (g : Y ⟶ Z) (a : F.obj X) : (F.map (f ≫ g)) a = (F.map g) ((F.map f) a) := by simp [types_comp] @[simp] lemma map_id_apply (a : F.obj X) : (F.map (𝟙 X)) a = a := by simp [types_id] lemma naturality (f : X ⟶ Y) (x : F.obj X) : σ.app Y ((F.map f) x) = (G.map f) (σ.app X x) := congr_fun (σ.naturality f) x @[simp] lemma comp (x : F.obj X) : (σ ≫ τ).app X x = τ.app X (σ.app X x) := rfl variables {D : Type u'} [𝒟 : category.{u'} D] (I J : D ⥤ C) (ρ : I ⟶ J) {W : D} @[simp] lemma hcomp (x : (I ⋙ F).obj W) : (ρ ◫ σ).app W x = (G.map (ρ.app W)) (σ.app (I.obj W) x) := rfl @[simp] lemma map_inv_map_hom_apply (f : X ≅ Y) (x : F.obj X) : F.map f.inv (F.map f.hom x) = x := congr_fun (F.map_iso f).hom_inv_id x @[simp] lemma map_hom_map_inv_apply (f : X ≅ Y) (y : F.obj Y) : F.map f.hom (F.map f.inv y) = y := congr_fun (F.map_iso f).inv_hom_id y @[simp] lemma hom_inv_id_app_apply (α : F ≅ G) (X) (x) : α.inv.app X (α.hom.app X x) = x := congr_fun (α.hom_inv_id_app X) x @[simp] lemma inv_hom_id_app_apply (α : F ≅ G) (X) (x) : α.hom.app X (α.inv.app X x) = x := congr_fun (α.inv_hom_id_app X) x end functor_to_types /-- The isomorphism between a `Type` which has been `ulift`ed to the same universe, and the original type. -/ def ulift_trivial (V : Type u) : ulift.{u} V ≅ V := by tidy /-- The functor embedding `Type u` into `Type (max u v)`. Write this as `ulift_functor.{5 2}` to get `Type 2 ⥤ Type 5`. -/ def ulift_functor : Type u ⥤ Type (max u v) := { obj := λ X, ulift.{v} X, map := λ X Y f, λ x : ulift.{v} X, ulift.up (f x.down) } @[simp] lemma ulift_functor_map {X Y : Type u} (f : X ⟶ Y) (x : ulift.{v} X) : ulift_functor.map f x = ulift.up (f x.down) := rfl instance ulift_functor_full : full.{u} ulift_functor := { preimage := λ X Y f x, (f (ulift.up x)).down } instance ulift_functor_faithful : faithful ulift_functor := { map_injective' := λ X Y f g p, funext $ λ x, congr_arg ulift.down ((congr_fun p (ulift.up x)) : ((ulift.up (f x)) = (ulift.up (g x)))) } /-- The functor embedding `Type u` into `Type u` via `ulift` is isomorphic to the identity functor. -/ def ulift_functor_trivial : ulift_functor.{u u} ≅ 𝟭 _ := nat_iso.of_components ulift_trivial (by tidy) /-- Any term `x` of a type `X` corresponds to a morphism `punit ⟶ X`. -/ -- TODO We should connect this to a general story about concrete categories -- whose forgetful functor is representable. def hom_of_element {X : Type u} (x : X) : punit ⟶ X := λ _, x lemma hom_of_element_eq_iff {X : Type u} (x y : X) : hom_of_element x = hom_of_element y ↔ x = y := ⟨λ H, congr_fun H punit.star, by cc⟩ /-- A morphism in `Type` is a monomorphism if and only if it is injective. See <https://stacks.math.columbia.edu/tag/003C>. -/ lemma mono_iff_injective {X Y : Type u} (f : X ⟶ Y) : mono f ↔ function.injective f := begin split, { intros H x x' h, resetI, rw ←hom_of_element_eq_iff at ⊢ h, exact (cancel_mono f).mp h }, { exact λ H, ⟨λ Z, H.comp_left⟩ } end lemma injective_of_mono {X Y : Type u} (f : X ⟶ Y) [hf : mono f] : function.injective f := (mono_iff_injective f).1 hf /-- A morphism in `Type` is an epimorphism if and only if it is surjective. See <https://stacks.math.columbia.edu/tag/003C>. -/ lemma epi_iff_surjective {X Y : Type u} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin split, { rintros ⟨H⟩, refine function.surjective_of_right_cancellable_Prop (λ g₁ g₂ hg, _), rw [← equiv.ulift.symm.injective.comp_left.eq_iff], apply H, change ulift.up ∘ (g₁ ∘ f) = ulift.up ∘ (g₂ ∘ f), rw hg }, { exact λ H, ⟨λ Z, H.injective_comp_right⟩ } end lemma surjective_of_epi {X Y : Type u} (f : X ⟶ Y) [hf : epi f] : function.surjective f := (epi_iff_surjective f).1 hf section /-- `of_type_functor m` converts from Lean's `Type`-based `category` to `category_theory`. This allows us to use these functors in category theory. -/ def of_type_functor (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] : Type u ⥤ Type v := { obj := m, map := λα β, _root_.functor.map, map_id' := assume α, _root_.functor.map_id, map_comp' := assume α β γ f g, funext $ assume a, is_lawful_functor.comp_map f g _ } variables (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] @[simp] lemma of_type_functor_obj : (of_type_functor m).obj = m := rfl @[simp] lemma of_type_functor_map {α β} (f : α → β) : (of_type_functor m).map f = (_root_.functor.map f : m α → m β) := rfl end end category_theory -- Isomorphisms in Type and equivalences. namespace equiv universe u variables {X Y : Type u} /-- Any equivalence between types in the same universe gives a categorical isomorphism between those types. -/ def to_iso (e : X ≃ Y) : X ≅ Y := { hom := e.to_fun, inv := e.inv_fun, hom_inv_id' := funext e.left_inv, inv_hom_id' := funext e.right_inv } @[simp] lemma to_iso_hom {e : X ≃ Y} : e.to_iso.hom = e := rfl @[simp] lemma to_iso_inv {e : X ≃ Y} : e.to_iso.inv = e.symm := rfl end equiv universe u namespace category_theory.iso open category_theory variables {X Y : Type u} /-- Any isomorphism between types gives an equivalence. -/ def to_equiv (i : X ≅ Y) : X ≃ Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := λ x, congr_fun i.hom_inv_id x, right_inv := λ y, congr_fun i.inv_hom_id y } @[simp] lemma to_equiv_fun (i : X ≅ Y) : (i.to_equiv : X → Y) = i.hom := rfl @[simp] lemma to_equiv_symm_fun (i : X ≅ Y) : (i.to_equiv.symm : Y → X) = i.inv := rfl @[simp] lemma to_equiv_id (X : Type u) : (iso.refl X).to_equiv = equiv.refl X := rfl @[simp] lemma to_equiv_comp {X Y Z : Type u} (f : X ≅ Y) (g : Y ≅ Z) : (f ≪≫ g).to_equiv = f.to_equiv.trans (g.to_equiv) := rfl end category_theory.iso namespace category_theory /-- A morphism in `Type u` is an isomorphism if and only if it is bijective. -/ lemma is_iso_iff_bijective {X Y : Type u} (f : X ⟶ Y) : is_iso f ↔ function.bijective f := iff.intro (λ i, (by exactI as_iso f : X ≅ Y).to_equiv.bijective) (λ b, is_iso.of_iso (equiv.of_bijective f b).to_iso) instance : split_epi_category (Type u) := { is_split_epi_of_epi := λ X Y f hf, is_split_epi.mk' { section_ := function.surj_inv $ (epi_iff_surjective f).1 hf, id' := funext $ function.right_inverse_surj_inv $ (epi_iff_surjective f).1 hf } } end category_theory -- We prove `equiv_iso_iso` and then use that to sneakily construct `equiv_equiv_iso`. -- (In this order the proofs are handled by `obviously`.) /-- Equivalences (between types in the same universe) are the same as (isomorphic to) isomorphisms of types. -/ @[simps] def equiv_iso_iso {X Y : Type u} : (X ≃ Y) ≅ (X ≅ Y) := { hom := λ e, e.to_iso, inv := λ i, i.to_equiv, } /-- Equivalences (between types in the same universe) are the same as (equivalent to) isomorphisms of types. -/ def equiv_equiv_iso {X Y : Type u} : (X ≃ Y) ≃ (X ≅ Y) := (equiv_iso_iso).to_equiv @[simp] lemma equiv_equiv_iso_hom {X Y : Type u} (e : X ≃ Y) : equiv_equiv_iso e = e.to_iso := rfl @[simp] lemma equiv_equiv_iso_inv {X Y : Type u} (e : X ≅ Y) : equiv_equiv_iso.symm e = e.to_equiv := rfl
fff5ddcddd37566dd30c2011161f3a64376cc889
1e3a43e8ba59c6fe1c66775b6e833e721eaf1675
/src/data/real/ennreal.lean
46fd9355460ad1cd20fc12e57d79e0f5950c974b
[ "Apache-2.0" ]
permissive
Sterrs/mathlib
ea6910847b8dfd18500486de9ab0ee35704a3f52
d9327e433804004aa1dc65091bbe0de1e5a08c5e
refs/heads/master
1,650,769,884,257
1,587,808,694,000
1,587,808,694,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,685
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Yury Kudryashov Extended non-negative reals -/ import data.real.nnreal import data.set.intervals noncomputable theory open classical set open_locale classical variables {α : Type*} {β : Type*} /-- The extended nonnegative real numbers. This is usually denoted [0, ∞], and is relevant as the codomain of a measure. -/ @[derive canonically_ordered_comm_semiring, derive complete_linear_order, derive densely_ordered] def ennreal := with_top nnreal localized "notation `∞` := (⊤ : ennreal)" in ennreal namespace ennreal variables {a b c d : ennreal} {r p q : nnreal} instance : inhabited ennreal := ⟨0⟩ instance : has_coe nnreal ennreal := ⟨ option.some ⟩ instance : can_lift ennreal nnreal := { coe := coe, cond := λ r, r ≠ ∞, prf := λ x hx, ⟨option.get $ option.ne_none_iff_is_some.1 hx, option.some_get _⟩ } @[simp] lemma none_eq_top : (none : ennreal) = (⊤ : ennreal) := rfl @[simp] lemma some_eq_coe (a : nnreal) : (some a : ennreal) = (↑a : ennreal) := rfl /-- `to_nnreal x` returns `x` if it is real, otherwise 0. -/ protected def to_nnreal : ennreal → nnreal | (some r) := r | none := 0 /-- `to_real x` returns `x` if it is real, `0` otherwise. -/ protected def to_real (a : ennreal) : real := coe (a.to_nnreal) /-- `of_real x` returns `x` if it is nonnegative, `0` otherwise. -/ protected def of_real (r : real) : ennreal := coe (nnreal.of_real r) @[simp, norm_cast] lemma to_nnreal_coe : (r : ennreal).to_nnreal = r := rfl @[simp] lemma coe_to_nnreal : ∀{a:ennreal}, a ≠ ∞ → ↑(a.to_nnreal) = a | (some r) h := rfl | none h := (h rfl).elim @[simp] lemma of_real_to_real {a : ennreal} (h : a ≠ ∞) : ennreal.of_real (a.to_real) = a := by simp [ennreal.to_real, ennreal.of_real, h] @[simp] lemma to_real_of_real {r : real} (h : 0 ≤ r) : ennreal.to_real (ennreal.of_real r) = r := by simp [ennreal.to_real, ennreal.of_real, nnreal.coe_of_real _ h] lemma coe_to_nnreal_le_self : ∀{a:ennreal}, ↑(a.to_nnreal) ≤ a | (some r) := by rw [some_eq_coe, to_nnreal_coe]; exact le_refl _ | none := le_top lemma coe_nnreal_eq (r : nnreal) : (r : ennreal) = ennreal.of_real r := by { rw [ennreal.of_real, nnreal.of_real], cases r with r h, congr, dsimp, rw max_eq_left h } lemma of_real_eq_coe_nnreal {x : real} (h : 0 ≤ x) : ennreal.of_real x = @coe nnreal ennreal _ (⟨x, h⟩ : nnreal) := by { rw [coe_nnreal_eq], refl } @[simp, norm_cast] lemma coe_zero : ↑(0 : nnreal) = (0 : ennreal) := rfl @[simp, norm_cast] lemma coe_one : ↑(1 : nnreal) = (1 : ennreal) := rfl @[simp] lemma to_real_nonneg {a : ennreal} : 0 ≤ a.to_real := by simp [ennreal.to_real] @[simp] lemma top_to_nnreal : ∞.to_nnreal = 0 := rfl @[simp] lemma top_to_real : ∞.to_real = 0 := rfl @[simp] lemma coe_to_real (r : nnreal) : (r : ennreal).to_real = r := rfl @[simp] lemma zero_to_nnreal : (0 : ennreal).to_nnreal = 0 := rfl @[simp] lemma zero_to_real : (0 : ennreal).to_real = 0 := rfl @[simp] lemma of_real_zero : ennreal.of_real (0 : ℝ) = 0 := by simp [ennreal.of_real]; refl @[simp] lemma of_real_one : ennreal.of_real (1 : ℝ) = (1 : ennreal) := by simp [ennreal.of_real] lemma of_real_to_real_le {a : ennreal} : ennreal.of_real (a.to_real) ≤ a := if ha : a = ∞ then ha.symm ▸ le_top else le_of_eq (of_real_to_real ha) lemma forall_ennreal {p : ennreal → Prop} : (∀a, p a) ↔ (∀r:nnreal, p r) ∧ p ∞ := ⟨assume h, ⟨assume r, h _, h _⟩, assume ⟨h₁, h₂⟩ a, match a with some r := h₁ _ | none := h₂ end⟩ lemma to_nnreal_eq_zero_iff (x : ennreal) : x.to_nnreal = 0 ↔ x = 0 ∨ x = ⊤ := ⟨begin cases x, { simp [none_eq_top] }, { have A : some (0:nnreal) = (0:ennreal) := rfl, simp [ennreal.to_nnreal, A] {contextual := tt} } end, by intro h; cases h; simp [h]⟩ lemma to_real_eq_zero_iff (x : ennreal) : x.to_real = 0 ↔ x = 0 ∨ x = ⊤ := by simp [ennreal.to_real, to_nnreal_eq_zero_iff] @[simp] lemma coe_ne_top : (r : ennreal) ≠ ∞ := with_top.coe_ne_top @[simp] lemma top_ne_coe : ∞ ≠ (r : ennreal) := with_top.top_ne_coe @[simp] lemma of_real_ne_top {r : ℝ} : ennreal.of_real r ≠ ∞ := by simp [ennreal.of_real] @[simp] lemma top_ne_of_real {r : ℝ} : ∞ ≠ ennreal.of_real r := by simp [ennreal.of_real] @[simp] lemma zero_ne_top : 0 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_zero : ∞ ≠ 0 := top_ne_coe @[simp] lemma one_ne_top : 1 ≠ ∞ := coe_ne_top @[simp] lemma top_ne_one : ∞ ≠ 1 := top_ne_coe @[simp, norm_cast] lemma coe_eq_coe : (↑r : ennreal) = ↑q ↔ r = q := with_top.coe_eq_coe @[simp, norm_cast] lemma coe_le_coe : (↑r : ennreal) ≤ ↑q ↔ r ≤ q := with_top.coe_le_coe @[simp, norm_cast] lemma coe_lt_coe : (↑r : ennreal) < ↑q ↔ r < q := with_top.coe_lt_coe lemma coe_mono : monotone (coe : nnreal → ennreal) := λ _ _, coe_le_coe.2 @[simp, norm_cast] lemma coe_eq_zero : (↑r : ennreal) = 0 ↔ r = 0 := coe_eq_coe @[simp, norm_cast] lemma zero_eq_coe : 0 = (↑r : ennreal) ↔ 0 = r := coe_eq_coe @[simp, norm_cast] lemma coe_eq_one : (↑r : ennreal) = 1 ↔ r = 1 := coe_eq_coe @[simp, norm_cast] lemma one_eq_coe : 1 = (↑r : ennreal) ↔ 1 = r := coe_eq_coe @[simp, norm_cast] lemma coe_nonneg : 0 ≤ (↑r : ennreal) ↔ 0 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_pos : 0 < (↑r : ennreal) ↔ 0 < r := coe_lt_coe @[simp, norm_cast] lemma coe_add : ↑(r + p) = (r + p : ennreal) := with_top.coe_add @[simp, norm_cast] lemma coe_mul : ↑(r * p) = (r * p : ennreal) := with_top.coe_mul @[simp, norm_cast] lemma coe_bit0 : (↑(bit0 r) : ennreal) = bit0 r := coe_add @[simp, norm_cast] lemma coe_bit1 : (↑(bit1 r) : ennreal) = bit1 r := by simp [bit1] lemma coe_two : ((2:nnreal) : ennreal) = 2 := by norm_cast protected lemma zero_lt_one : 0 < (1 : ennreal) := canonically_ordered_semiring.zero_lt_one @[simp] lemma one_lt_two : (1:ennreal) < 2 := coe_one ▸ coe_two ▸ by exact_mod_cast one_lt_two @[simp] lemma two_pos : (0:ennreal) < 2 := lt_trans ennreal.zero_lt_one one_lt_two lemma two_ne_zero : (2:ennreal) ≠ 0 := ne_of_gt two_pos lemma two_ne_top : (2:ennreal) ≠ ∞ := coe_two ▸ coe_ne_top @[simp] lemma add_top : a + ∞ = ∞ := with_top.add_top @[simp] lemma top_add : ∞ + a = ∞ := with_top.top_add instance : is_semiring_hom (coe : nnreal → ennreal) := by refine_struct {..}; simp @[simp, norm_cast] lemma coe_pow (n : ℕ) : (↑(r^n) : ennreal) = r^n := is_monoid_hom.map_pow coe r n lemma add_eq_top : a + b = ∞ ↔ a = ∞ ∨ b = ∞ := with_top.add_eq_top _ _ lemma add_lt_top : a + b < ∞ ↔ a < ∞ ∧ b < ∞ := with_top.add_lt_top _ _ lemma to_nnreal_add {r₁ r₂ : ennreal} (h₁ : r₁ < ⊤) (h₂ : r₂ < ⊤) : (r₁ + r₂).to_nnreal = r₁.to_nnreal + r₂.to_nnreal := begin rw [← coe_eq_coe, coe_add, coe_to_nnreal, coe_to_nnreal, coe_to_nnreal]; apply @ne_top_of_lt ennreal _ _ ⊤, exact h₂, exact h₁, exact add_lt_top.2 ⟨h₁, h₂⟩ end /- rw has trouble with the generic lt_top_iff_ne_top and bot_lt_iff_ne_bot (contrary to erw). This is solved with the next lemmas -/ protected lemma lt_top_iff_ne_top : a < ∞ ↔ a ≠ ∞ := lt_top_iff_ne_top protected lemma bot_lt_iff_ne_bot : 0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot lemma add_ne_top : a + b ≠ ∞ ↔ a ≠ ∞ ∧ b ≠ ∞ := by simpa only [lt_top_iff_ne_top] using add_lt_top lemma mul_top : a * ∞ = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.mul_top h } end lemma top_mul : ∞ * a = (if a = 0 then 0 else ∞) := begin split_ifs, { simp [h] }, { exact with_top.top_mul h } end @[simp] lemma top_mul_top : ∞ * ∞ = ∞ := with_top.top_mul_top lemma top_pow {n:ℕ} (h : 0 < n) : ∞^n = ∞ := nat.le_induction (pow_one _) (λ m hm hm', by rw [pow_succ, hm', top_mul_top]) _ (nat.succ_le_of_lt h) lemma mul_eq_top {a b : ennreal} : a * b = ⊤ ↔ (a ≠ 0 ∧ b = ⊤) ∨ (a = ⊤ ∧ b ≠ 0) := with_top.mul_eq_top_iff lemma mul_ne_top {a b : ennreal} : a ≠ ∞ → b ≠ ∞ → a * b ≠ ∞ := by simp [(≠), mul_eq_top] {contextual := tt} lemma mul_lt_top {a b : ennreal} : a < ⊤ → b < ⊤ → a * b < ⊤ := by simpa only [ennreal.lt_top_iff_ne_top] using mul_ne_top lemma pow_eq_top : ∀ n:ℕ, a^n=∞ → a=∞ | 0 := by simp | (n+1) := λ o, (mul_eq_top.1 o).elim (λ h, pow_eq_top n h.2) and.left lemma pow_ne_top (h : a ≠ ∞) {n:ℕ} : a^n ≠ ∞ := mt (pow_eq_top n) h lemma pow_lt_top : a < ∞ → ∀ n:ℕ, a^n < ∞ := by simpa only [lt_top_iff_ne_top] using pow_ne_top @[simp, norm_cast] lemma coe_finset_sum {s : finset α} {f : α → nnreal} : ↑(s.sum f) = (s.sum (λa, f a) : ennreal) := (s.sum_hom coe).symm @[simp, norm_cast] lemma coe_finset_prod {s : finset α} {f : α → nnreal} : ↑(s.prod f) = (s.prod (λa, f a) : ennreal) := (s.prod_hom coe).symm section order @[simp] lemma bot_eq_zero : (⊥ : ennreal) = 0 := rfl @[simp] lemma coe_lt_top : coe r < ∞ := with_top.coe_lt_top r @[simp] lemma not_top_le_coe : ¬ (⊤:ennreal) ≤ ↑r := with_top.not_top_le_coe r lemma zero_lt_coe_iff : 0 < (↑p : ennreal) ↔ 0 < p := coe_lt_coe @[simp, norm_cast] lemma one_le_coe_iff : (1:ennreal) ≤ ↑r ↔ 1 ≤ r := coe_le_coe @[simp, norm_cast] lemma coe_le_one_iff : ↑r ≤ (1:ennreal) ↔ r ≤ 1 := coe_le_coe @[simp, norm_cast] lemma coe_lt_one_iff : (↑p : ennreal) < 1 ↔ p < 1 := coe_lt_coe @[simp, norm_cast] lemma one_lt_coe_iff : 1 < (↑p : ennreal) ↔ 1 < p := coe_lt_coe @[simp, norm_cast] lemma coe_nat (n : nat) : ((n : nnreal) : ennreal) = n := with_top.coe_nat n @[simp] lemma nat_ne_top (n : nat) : (n : ennreal) ≠ ⊤ := with_top.nat_ne_top n @[simp] lemma top_ne_nat (n : nat) : (⊤ : ennreal) ≠ n := with_top.top_ne_nat n lemma le_coe_iff : a ≤ ↑r ↔ (∃p:nnreal, a = p ∧ p ≤ r) := with_top.le_coe_iff r a lemma coe_le_iff : ↑r ≤ a ↔ (∀p:nnreal, a = p → r ≤ p) := with_top.coe_le_iff r a lemma lt_iff_exists_coe : a < b ↔ (∃p:nnreal, a = p ∧ ↑p < b) := with_top.lt_iff_exists_coe a b lemma pow_le_pow {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := begin cases a, { cases m, { rw eq_bot_iff.mpr h, exact le_refl _ }, { rw [none_eq_top, top_pow (nat.succ_pos m)], exact le_top } }, { rw [some_eq_coe, ← coe_pow, ← coe_pow, coe_le_coe], exact pow_le_pow (by simpa using ha) h } end @[simp] lemma max_eq_zero_iff : max a b = 0 ↔ a = 0 ∧ b = 0 := by simp only [le_zero_iff_eq.symm, max_le_iff] @[simp] lemma max_zero_left : max 0 a = a := max_eq_right (zero_le a) @[simp] lemma max_zero_right : max a 0 = a := max_eq_left (zero_le a) -- TODO: why this is not a `rfl`? There is some hidden diamond here. @[simp] lemma sup_eq_max : a ⊔ b = max a b := eq_of_forall_ge_iff $ λ c, sup_le_iff.trans max_le_iff.symm protected lemma pow_pos : 0 < a → ∀ n : ℕ, 0 < a^n := canonically_ordered_semiring.pow_pos protected lemma pow_ne_zero : a ≠ 0 → ∀ n : ℕ, a^n ≠ 0 := by simpa only [zero_lt_iff_ne_zero] using ennreal.pow_pos @[simp] lemma not_lt_zero : ¬ a < 0 := by simp lemma add_lt_add_iff_left : a < ⊤ → (a + c < a + b ↔ c < b) := with_top.add_lt_add_iff_left lemma add_lt_add_iff_right : a < ⊤ → (c + a < b + a ↔ c < b) := with_top.add_lt_add_iff_right lemma lt_add_right (ha : a < ⊤) (hb : 0 < b) : a < a + b := by rwa [← add_lt_add_iff_left ha, add_zero] at hb lemma le_of_forall_epsilon_le : ∀{a b : ennreal}, (∀ε:nnreal, 0 < ε → b < ∞ → a ≤ b + ε) → a ≤ b | a none h := le_top | none (some a) h := have (⊤:ennreal) ≤ ↑a + ↑(1:nnreal), from h 1 zero_lt_one coe_lt_top, by rw [← coe_add] at this; exact (not_top_le_coe this).elim | (some a) (some b) h := by simp only [none_eq_top, some_eq_coe, coe_add.symm, coe_le_coe, coe_lt_top, true_implies_iff] at *; exact nnreal.le_of_forall_epsilon_le h lemma lt_iff_exists_rat_btwn : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ (nnreal.of_real q:ennreal) < b) := ⟨λ h, begin rcases lt_iff_exists_coe.1 h with ⟨p, rfl, _⟩, rcases dense h with ⟨c, pc, cb⟩, rcases lt_iff_exists_coe.1 cb with ⟨r, rfl, _⟩, rcases (nnreal.lt_iff_exists_rat_btwn _ _).1 (coe_lt_coe.1 pc) with ⟨q, hq0, pq, qr⟩, exact ⟨q, hq0, coe_lt_coe.2 pq, lt_trans (coe_lt_coe.2 qr) cb⟩ end, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_real_btwn : a < b ↔ (∃r:ℝ, 0 ≤ r ∧ a < ennreal.of_real r ∧ (ennreal.of_real r:ennreal) < b) := ⟨λ h, let ⟨q, q0, aq, qb⟩ := ennreal.lt_iff_exists_rat_btwn.1 h in ⟨q, rat.cast_nonneg.2 q0, aq, qb⟩, λ ⟨q, q0, qa, qb⟩, lt_trans qa qb⟩ lemma lt_iff_exists_nnreal_btwn : a < b ↔ (∃r:nnreal, a < r ∧ (r : ennreal) < b) := with_top.lt_iff_exists_coe_btwn lemma lt_iff_exists_add_pos_lt : a < b ↔ (∃ r : nnreal, 0 < r ∧ a + r < b) := begin refine ⟨λ hab, _, λ ⟨r, rpos, hr⟩, lt_of_le_of_lt (le_add_right (le_refl _)) hr⟩, cases a, { simpa using hab }, rcases lt_iff_exists_real_btwn.1 hab with ⟨c, c_nonneg, ac, cb⟩, let d : nnreal := ⟨c, c_nonneg⟩, have ad : a < d, { rw of_real_eq_coe_nnreal c_nonneg at ac, exact coe_lt_coe.1 ac }, refine ⟨d-a, nnreal.sub_pos.2 ad, _⟩, rw [some_eq_coe, ← coe_add], convert cb, have : nnreal.of_real c = d, by { rw [← nnreal.coe_eq, nnreal.coe_of_real _ c_nonneg], refl }, rw [add_comm, this], exact nnreal.sub_add_cancel_of_le (le_of_lt ad) end lemma coe_nat_lt_coe {n : ℕ} : (n : ennreal) < r ↔ ↑n < r := ennreal.coe_nat n ▸ coe_lt_coe lemma coe_lt_coe_nat {n : ℕ} : (r : ennreal) < n ↔ r < n := ennreal.coe_nat n ▸ coe_lt_coe @[norm_cast] lemma coe_nat_lt_coe_nat {m n : ℕ} : (m : ennreal) < n ↔ m < n := ennreal.coe_nat n ▸ coe_nat_lt_coe.trans nat.cast_lt lemma coe_nat_ne_top {n : ℕ} : (n : ennreal) ≠ ∞ := ennreal.coe_nat n ▸ coe_ne_top lemma coe_nat_mono : strict_mono (coe : ℕ → ennreal) := λ _ _, coe_nat_lt_coe_nat.2 @[norm_cast] lemma coe_nat_le_coe_nat {m n : ℕ} : (m : ennreal) ≤ n ↔ m ≤ n := coe_nat_mono.le_iff_le instance : char_zero ennreal := ⟨coe_nat_mono.injective⟩ protected lemma exists_nat_gt {r : ennreal} (h : r ≠ ⊤) : ∃n:ℕ, r < n := begin rcases lt_iff_exists_coe.1 (lt_top_iff_ne_top.2 h) with ⟨r, rfl, hb⟩, rcases exists_nat_gt r with ⟨n, hn⟩, exact ⟨n, coe_lt_coe_nat.2 hn⟩, end lemma add_lt_add (ac : a < c) (bd : b < d) : a + b < c + d := begin rcases dense ac with ⟨a', aa', a'c⟩, rcases lt_iff_exists_coe.1 aa' with ⟨aR, rfl, _⟩, rcases lt_iff_exists_coe.1 a'c with ⟨a'R, rfl, _⟩, rcases dense bd with ⟨b', bb', b'd⟩, rcases lt_iff_exists_coe.1 bb' with ⟨bR, rfl, _⟩, rcases lt_iff_exists_coe.1 b'd with ⟨b'R, rfl, _⟩, have I : ↑aR + ↑bR < ↑a'R + ↑b'R := begin rw [← coe_add, ← coe_add, coe_lt_coe], apply add_lt_add (coe_lt_coe.1 aa') (coe_lt_coe.1 bb') end, have J : ↑a'R + ↑b'R ≤ c + d := add_le_add' (le_of_lt a'c) (le_of_lt b'd), apply lt_of_lt_of_le I J end @[norm_cast] lemma coe_min : ((min r p:nnreal):ennreal) = min r p := coe_mono.map_min @[norm_cast] lemma coe_max : ((max r p:nnreal):ennreal) = max r p := coe_mono.map_max end order section complete_lattice lemma coe_Sup {s : set nnreal} : bdd_above s → (↑(Sup s) : ennreal) = (⨆a∈s, ↑a) := with_top.coe_Sup lemma coe_Inf {s : set nnreal} : s.nonempty → (↑(Inf s) : ennreal) = (⨅a∈s, ↑a) := with_top.coe_Inf @[simp] lemma top_mem_upper_bounds {s : set ennreal} : ∞ ∈ upper_bounds s := assume x hx, le_top lemma coe_mem_upper_bounds {s : set nnreal} : ↑r ∈ upper_bounds ((coe : nnreal → ennreal) '' s) ↔ r ∈ upper_bounds s := by simp [upper_bounds, ball_image_iff, -mem_image, *] {contextual := tt} lemma infi_ennreal {α : Type*} [complete_lattice α] {f : ennreal → α} : (⨅n, f n) = (⨅n:nnreal, f n) ⊓ f ⊤ := le_antisymm (le_inf (le_infi $ assume i, infi_le _ _) (infi_le _ _)) (le_infi $ forall_ennreal.2 ⟨assume r, inf_le_left_of_le $ infi_le _ _, inf_le_right⟩) end complete_lattice section mul lemma mul_le_mul : a ≤ b → c ≤ d → a * c ≤ b * d := canonically_ordered_semiring.mul_le_mul lemma mul_left_mono : monotone ((*) a) := λ b c, mul_le_mul (le_refl a) lemma mul_right_mono : monotone (λ x, x * a) := λ b c h, mul_le_mul h (le_refl a) lemma max_mul : max a b * c = max (a * c) (b * c) := mul_right_mono.map_max lemma mul_max : a * max b c = max (a * b) (a * c) := mul_left_mono.map_max lemma mul_eq_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b = a * c ↔ b = c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm, nnreal.mul_eq_mul_left] {contextual := tt}, end lemma mul_eq_mul_right : c ≠ 0 → c ≠ ∞ → (a * c = b * c ↔ a = b) := mul_comm c a ▸ mul_comm c b ▸ mul_eq_mul_left lemma mul_le_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b ≤ a * c ↔ b ≤ c) := begin cases a; cases b; cases c; simp [none_eq_top, some_eq_coe, mul_top, top_mul, -coe_mul, coe_mul.symm] {contextual := tt}, assume h, exact mul_le_mul_left (zero_lt_iff_ne_zero.2 h) end lemma mul_le_mul_right : c ≠ 0 → c ≠ ∞ → (a * c ≤ b * c ↔ a ≤ b) := mul_comm c a ▸ mul_comm c b ▸ mul_le_mul_left lemma mul_lt_mul_left : a ≠ 0 → a ≠ ⊤ → (a * b < a * c ↔ b < c) := λ h0 ht, by simp only [mul_le_mul_left h0 ht, lt_iff_le_not_le] lemma mul_lt_mul_right : c ≠ 0 → c ≠ ∞ → (a * c < b * c ↔ a < b) := mul_comm c a ▸ mul_comm c b ▸ mul_lt_mul_left lemma mul_eq_zero {a b : ennreal} : a * b = 0 ↔ a = 0 ∨ b = 0 := canonically_ordered_comm_semiring.mul_eq_zero_iff _ _ end mul section sub instance : has_sub ennreal := ⟨λa b, Inf {d | a ≤ d + b}⟩ @[norm_cast] lemma coe_sub : ↑(p - r) = (↑p:ennreal) - r := le_antisymm (le_Inf $ assume b (hb : ↑p ≤ b + r), coe_le_iff.2 $ by rintros d rfl; rwa [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add] at hb) (Inf_le $ show (↑p : ennreal) ≤ ↑(p - r) + ↑r, by rw [← coe_add, coe_le_coe, ← nnreal.sub_le_iff_le_add]) @[simp] lemma top_sub_coe : ∞ - ↑r = ∞ := top_unique $ le_Inf $ by simp [add_eq_top] @[simp] lemma sub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := le_antisymm (Inf_le $ le_add_left h) (zero_le _) @[simp] lemma sub_self : a - a = 0 := sub_eq_zero_of_le $ le_refl _ @[simp] lemma zero_sub : 0 - a = 0 := le_antisymm (Inf_le $ zero_le _) (zero_le _) @[simp] lemma sub_infty : a - ∞ = 0 := le_antisymm (Inf_le $ by simp) (zero_le _) lemma sub_le_sub (h₁ : a ≤ b) (h₂ : d ≤ c) : a - c ≤ b - d := Inf_le_Inf $ assume e (h : b ≤ e + d), calc a ≤ b : h₁ ... ≤ e + d : h ... ≤ e + c : add_le_add' (le_refl _) h₂ @[simp] lemma add_sub_self : ∀{a b : ennreal}, b < ∞ → (a + b) - b = a | a none := by simp [none_eq_top] | none (some b) := by simp [none_eq_top, some_eq_coe] | (some a) (some b) := by simp [some_eq_coe]; rw [← coe_add, ← coe_sub, coe_eq_coe, nnreal.add_sub_cancel] @[simp] lemma add_sub_self' (h : a < ∞) : (a + b) - a = b := by rw [add_comm, add_sub_self h] lemma add_left_inj (h : a < ∞) : a + b = a + c ↔ b = c := ⟨λ e, by simpa [h] using congr_arg (λ x, x - a) e, congr_arg _⟩ lemma add_right_inj (h : a < ∞) : b + a = c + a ↔ b = c := by rw [add_comm, add_comm c, add_left_inj h] @[simp] lemma sub_add_cancel_of_le : ∀{a b : ennreal}, b ≤ a → (a - b) + b = a := begin simp [forall_ennreal, le_coe_iff, -add_comm] {contextual := tt}, rintros r p x rfl h, rw [← coe_sub, ← coe_add, nnreal.sub_add_cancel_of_le h] end @[simp] lemma add_sub_cancel_of_le (h : b ≤ a) : b + (a - b) = a := by rwa [add_comm, sub_add_cancel_of_le] lemma sub_add_self_eq_max : (a - b) + b = max a b := match le_total a b with | or.inl h := by simp [h, max_eq_right] | or.inr h := by simp [h, max_eq_left] end lemma le_sub_add_self : a ≤ (a - b) + b := by { rw sub_add_self_eq_max, exact le_max_left a b } @[simp] protected lemma sub_le_iff_le_add : a - b ≤ c ↔ a ≤ c + b := iff.intro (assume h : a - b ≤ c, calc a ≤ (a - b) + b : le_sub_add_self ... ≤ c + b : add_le_add_right' h) (assume h : a ≤ c + b, calc a - b ≤ (c + b) - b : sub_le_sub h (le_refl _) ... ≤ c : Inf_le (le_refl (c + b))) protected lemma sub_le_iff_le_add' : a - b ≤ c ↔ a ≤ b + c := add_comm c b ▸ ennreal.sub_le_iff_le_add lemma sub_eq_of_add_eq : b ≠ ∞ → a + b = c → c - b = a := λ hb hc, hc ▸ add_sub_self (lt_top_iff_ne_top.2 hb) protected lemma sub_le_of_sub_le (h : a - b ≤ c) : a - c ≤ b := ennreal.sub_le_iff_le_add.2 $ by { rw add_comm, exact ennreal.sub_le_iff_le_add.1 h } protected lemma sub_lt_sub_self : a ≠ ⊤ → a ≠ 0 → 0 < b → a - b < a := match a, b with | none, _ := by { have := none_eq_top, assume h, contradiction } | (some a), none := by {intros, simp only [none_eq_top, sub_infty, zero_lt_iff_ne_zero], assumption} | (some a), (some b) := begin simp only [some_eq_coe, coe_sub.symm, coe_pos, coe_eq_zero, coe_lt_coe, ne.def], assume h₁ h₂, apply nnreal.sub_lt_self, exact zero_lt_iff_ne_zero.2 h₂ end end @[simp] lemma sub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by simpa [-ennreal.sub_le_iff_le_add] using @ennreal.sub_le_iff_le_add a b 0 @[simp] lemma zero_lt_sub_iff_lt : 0 < a - b ↔ b < a := by simpa [ennreal.bot_lt_iff_ne_bot, -sub_eq_zero_iff_le] using not_iff_not.2 (@sub_eq_zero_iff_le a b) lemma lt_sub_iff_add_lt : a < b - c ↔ a + c < b := begin cases a, { simp }, cases c, { simp }, cases b, { simp only [true_iff, coe_lt_top, some_eq_coe, top_sub_coe, none_eq_top, ← coe_add] }, simp only [some_eq_coe], rw [← coe_add, ← coe_sub, coe_lt_coe, coe_lt_coe, nnreal.lt_sub_iff_add_lt], end lemma sub_le_self (a b : ennreal) : a - b ≤ a := ennreal.sub_le_iff_le_add.2 $ le_add_of_nonneg_right' $ zero_le _ @[simp] lemma sub_zero : a - 0 = a := eq.trans (add_zero (a - 0)).symm $ by simp /-- A version of triangle inequality for difference as a "distance". -/ lemma sub_le_sub_add_sub : a - c ≤ a - b + (b - c) := ennreal.sub_le_iff_le_add.2 $ calc a ≤ a - b + b : le_sub_add_self ... ≤ a - b + ((b - c) + c) : add_le_add_left' le_sub_add_self ... = a - b + (b - c) + c : (add_assoc _ _ _).symm lemma sub_sub_cancel (h : a < ∞) (h2 : b ≤ a) : a - (a - b) = b := by rw [← add_right_inj (lt_of_le_of_lt (sub_le_self _ _) h), sub_add_cancel_of_le (sub_le_self _ _), add_sub_cancel_of_le h2] lemma sub_left_inj {a b c : ennreal} (ha : a < ⊤) (hb : b ≤ a) (hc : c ≤ a) : a - b = a - c ↔ b = c := iff.intro begin assume h, have : a - (a - b) = a - (a - c), rw h, rw [sub_sub_cancel ha hb, sub_sub_cancel ha hc] at this, exact this end (λ h, by rw h) lemma sub_mul (h : 0 < b → b < a → c ≠ ∞) : (a - b) * c = a * c - b * c := begin cases le_or_lt a b with hab hab, { simp [hab, mul_right_mono hab] }, symmetry, cases eq_or_lt_of_le (zero_le b) with hb hb, { subst b, simp }, apply sub_eq_of_add_eq, { exact mul_ne_top (ne_top_of_lt hab) (h hb hab) }, rw [← add_mul, sub_add_cancel_of_le (le_of_lt hab)] end lemma mul_sub (h : 0 < c → c < b → a ≠ ∞) : a * (b - c) = a * b - a * c := by { simp only [mul_comm a], exact sub_mul h } lemma sub_mul_ge : a * c - b * c ≤ (a - b) * c := begin -- with `0 < b → b < a → c ≠ ∞` Lean names the first variable `a` by_cases h : ∀ (hb : 0 < b), b < a → c ≠ ∞, { rw [sub_mul h], exact le_refl _ }, { push_neg at h, rcases h with ⟨hb, hba, hc⟩, subst c, simp only [mul_top, if_neg (ne_of_gt hb), if_neg (ne_of_gt $ lt_trans hb hba), sub_self, zero_le] } end end sub section sum open finset /-- sum of finte numbers is still finite -/ lemma sum_lt_top {s : finset α} {f : α → ennreal} : (∀a∈s, f a < ⊤) → s.sum f < ⊤ := with_top.sum_lt_top /-- sum of finte numbers is still finite -/ lemma sum_lt_top_iff {s : finset α} {f : α → ennreal} : s.sum f < ⊤ ↔ (∀a∈s, f a < ⊤) := with_top.sum_lt_top_iff /-- seeing `ennreal` as `nnreal` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_nnreal_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ⊤) : ennreal.to_nnreal (s.sum f) = s.sum (λa, ennreal.to_nnreal (f a)) := begin rw [← coe_eq_coe, coe_to_nnreal, coe_finset_sum, sum_congr], { refl }, { intros x hx, rw coe_to_nnreal, rw ← ennreal.lt_top_iff_ne_top, exact hf x hx }, { rw ← ennreal.lt_top_iff_ne_top, exact sum_lt_top hf } end /-- seeing `ennreal` as `real` does not change their sum, unless one of the `ennreal` is infinity -/ lemma to_real_sum {s : finset α} {f : α → ennreal} (hf : ∀a∈s, f a < ⊤) : ennreal.to_real (s.sum f) = s.sum (λa, ennreal.to_real (f a)) := by { rw [ennreal.to_real, to_nnreal_sum hf, nnreal.coe_sum], refl } end sum section interval variables {x y z : ennreal} {ε ε₁ ε₂ : ennreal} {s : set ennreal} protected lemma Ico_eq_Iio : (Ico 0 y) = (Iio y) := ext $ assume a, iff.intro (assume ⟨_, hx⟩, hx) (assume hx, ⟨zero_le _, hx⟩) lemma mem_Iio_self_add : x ≠ ⊤ → 0 < ε → x ∈ Iio (x + ε) := assume xt ε0, lt_add_right (by rwa lt_top_iff_ne_top) ε0 lemma not_mem_Ioo_self_sub : x = 0 → x ∉ Ioo (x - ε) y := assume x0, by simp [x0] lemma mem_Ioo_self_sub_add : x ≠ ⊤ → x ≠ 0 → 0 < ε₁ → 0 < ε₂ → x ∈ Ioo (x - ε₁) (x + ε₂) := assume xt x0 ε0 ε0', ⟨ennreal.sub_lt_sub_self xt x0 ε0, lt_add_right (by rwa [lt_top_iff_ne_top]) ε0'⟩ end interval section bit @[simp] lemma bit0_inj : bit0 a = bit0 b ↔ a = b := ⟨λh, begin rcases (lt_trichotomy a b) with h₁| h₂| h₃, { exact (absurd h (ne_of_lt (add_lt_add h₁ h₁))) }, { exact h₂ }, { exact (absurd h.symm (ne_of_lt (add_lt_add h₃ h₃))) } end, λh, congr_arg _ h⟩ @[simp] lemma bit0_eq_zero_iff : bit0 a = 0 ↔ a = 0 := by simpa only [bit0_zero] using @bit0_inj a 0 @[simp] lemma bit0_eq_top_iff : bit0 a = ∞ ↔ a = ∞ := by rw [bit0, add_eq_top, or_self] @[simp] lemma bit1_inj : bit1 a = bit1 b ↔ a = b := ⟨λh, begin unfold bit1 at h, rwa [add_right_inj, bit0_inj] at h, simp [lt_top_iff_ne_top] end, λh, congr_arg _ h⟩ @[simp] lemma bit1_ne_zero : bit1 a ≠ 0 := by unfold bit1; simp @[simp] lemma bit1_eq_one_iff : bit1 a = 1 ↔ a = 0 := by simpa only [bit1_zero] using @bit1_inj a 0 @[simp] lemma bit1_eq_top_iff : bit1 a = ∞ ↔ a = ∞ := by unfold bit1; rw add_eq_top; simp end bit section inv instance : has_inv ennreal := ⟨λa, Inf {b | 1 ≤ a * b}⟩ instance : has_div ennreal := ⟨λa b, a * b⁻¹⟩ lemma div_def : a / b = a * b⁻¹ := rfl lemma mul_div_assoc : (a * b) / c = a * (b / c) := mul_assoc _ _ _ @[simp] lemma inv_zero : (0 : ennreal)⁻¹ = ∞ := show Inf {b : ennreal | 1 ≤ 0 * b} = ∞, by simp; refl @[simp] lemma inv_top : (∞ : ennreal)⁻¹ = 0 := bot_unique $ le_of_forall_le_of_dense $ λ a (h : a > 0), Inf_le $ by simp [*, ne_of_gt h, top_mul] @[simp, norm_cast] lemma coe_inv (hr : r ≠ 0) : (↑r⁻¹ : ennreal) = (↑r)⁻¹ := le_antisymm (le_Inf $ assume b (hb : 1 ≤ ↑r * b), coe_le_iff.2 $ by rintros b rfl; rwa [← coe_mul, ← coe_one, coe_le_coe, ← nnreal.inv_le hr] at hb) (Inf_le $ by simp; rw [← coe_mul, nnreal.mul_inv_cancel hr]; exact le_refl 1) lemma coe_inv_le : (↑r⁻¹ : ennreal) ≤ (↑r)⁻¹ := if hr : r = 0 then by simp only [hr, nnreal.inv_zero, inv_zero, coe_zero, zero_le] else by simp only [coe_inv hr, le_refl] @[norm_cast] lemma coe_inv_two : ((2⁻¹:nnreal):ennreal) = 2⁻¹ := by rw [coe_inv (ne_of_gt zero_lt_two), coe_two] @[simp, norm_cast] lemma coe_div (hr : r ≠ 0) : (↑(p / r) : ennreal) = p / r := show ↑(p * r⁻¹) = ↑p * (↑r)⁻¹, by rw [coe_mul, coe_inv hr] @[simp] lemma inv_one : (1:ennreal)⁻¹ = 1 := by simpa only [coe_inv one_ne_zero, coe_one] using coe_eq_coe.2 nnreal.inv_one @[simp] lemma div_one {a : ennreal} : a / 1 = a := by simp [ennreal.div_def] protected lemma inv_pow {n : ℕ} : (a^n)⁻¹ = (a⁻¹)^n := begin by_cases a = 0; cases a; cases n; simp [*, none_eq_top, some_eq_coe, zero_pow, top_pow, nat.zero_lt_succ] at *, rw [← coe_inv h, ← coe_pow, ← coe_inv, nnreal.inv_pow, coe_pow], rw [← ne.def] at h, rw [← zero_lt_iff_ne_zero] at *, apply pow_pos h end @[simp] lemma inv_inv : (a⁻¹)⁻¹ = a := by by_cases a = 0; cases a; simp [*, none_eq_top, some_eq_coe, -coe_inv, (coe_inv _).symm] at * lemma inv_involutive : function.involutive (λ a:ennreal, a⁻¹) := λ a, ennreal.inv_inv lemma inv_bijective : function.bijective (λ a:ennreal, a⁻¹) := ennreal.inv_involutive.bijective @[simp] lemma inv_eq_inv : a⁻¹ = b⁻¹ ↔ a = b := inv_bijective.1.eq_iff @[simp] lemma inv_eq_top : a⁻¹ = ∞ ↔ a = 0 := inv_zero ▸ inv_eq_inv lemma inv_ne_top : a⁻¹ ≠ ∞ ↔ a ≠ 0 := by simp @[simp] lemma inv_eq_zero : a⁻¹ = 0 ↔ a = ∞ := inv_top ▸ inv_eq_inv lemma inv_ne_zero : a⁻¹ ≠ 0 ↔ a ≠ ∞ := by simp @[simp] lemma inv_pos : 0 < a⁻¹ ↔ a ≠ ∞ := zero_lt_iff_ne_zero.trans inv_ne_zero @[simp] lemma inv_lt_inv : a⁻¹ < b⁻¹ ↔ b < a := begin cases a; cases b; simp only [some_eq_coe, none_eq_top, inv_top], { simp only [lt_irrefl] }, { exact inv_pos.trans lt_top_iff_ne_top.symm }, { simp only [not_lt_zero, not_top_lt] }, { cases eq_or_lt_of_le (zero_le a) with ha ha; cases eq_or_lt_of_le (zero_le b) with hb hb, { subst a, subst b, simp }, { subst a, simp }, { subst b, simp [zero_lt_iff_ne_zero, lt_top_iff_ne_top, inv_ne_top] }, { rw [← coe_inv (ne_of_gt ha), ← coe_inv (ne_of_gt hb), coe_lt_coe, coe_lt_coe], simp only [nnreal.coe_lt_coe.symm] at *, exact inv_lt_inv ha hb } } end lemma inv_lt_iff_inv_lt : a⁻¹ < b ↔ b⁻¹ < a := by simpa only [inv_inv] using @inv_lt_inv a b⁻¹ lemma lt_inv_iff_lt_inv : a < b⁻¹ ↔ b < a⁻¹ := by simpa only [inv_inv] using @inv_lt_inv a⁻¹ b @[simp, priority 1100] -- higher than le_inv_iff_mul_le lemma inv_le_inv : a⁻¹ ≤ b⁻¹ ↔ b ≤ a := by simp only [le_iff_lt_or_eq, inv_lt_inv, inv_eq_inv, eq_comm] lemma inv_le_iff_inv_le : a⁻¹ ≤ b ↔ b⁻¹ ≤ a := by simpa only [inv_inv] using @inv_le_inv a b⁻¹ lemma le_inv_iff_le_inv : a ≤ b⁻¹ ↔ b ≤ a⁻¹ := by simpa only [inv_inv] using @inv_le_inv a⁻¹ b @[simp] lemma inv_lt_one : a⁻¹ < 1 ↔ 1 < a := inv_lt_iff_inv_lt.trans $ by rw [inv_one] lemma top_div : ∞ / a = if a = ∞ then 0 else ∞ := by by_cases a = ∞; simp [div_def, top_mul, *] @[simp] lemma div_top : a / ∞ = 0 := by simp only [div_def, inv_top, mul_zero] @[simp] lemma zero_div : 0 / a = 0 := zero_mul a⁻¹ lemma div_eq_top : a / b = ⊤ ↔ (a ≠ 0 ∧ b = 0) ∨ (a = ⊤ ∧ b ≠ ⊤) := by simp [ennreal.div_def, ennreal.mul_eq_top] lemma le_div_iff_mul_le (h0 : b ≠ 0 ∨ c ≠ 0) (ht : b ≠ ⊤ ∨ c ≠ ⊤) : a ≤ c / b ↔ a * b ≤ c := begin cases b, { simp at ht, split, { assume ha, simp at ha, simp [ha] }, { contrapose, assume ha, simp at ha, have : a * ⊤ = ⊤, by simp [ennreal.mul_eq_top, ha], simp [this, ht] } }, by_cases hb : b ≠ 0, { have : (b : ennreal) ≠ 0, by simp [hb], rw [← ennreal.mul_le_mul_left this coe_ne_top], suffices : ↑b * a ≤ (↑b * ↑b⁻¹) * c ↔ a * ↑b ≤ c, { simpa [some_eq_coe, div_def, hb, mul_left_comm, mul_comm, mul_assoc] }, rw [← coe_mul, nnreal.mul_inv_cancel hb, coe_one, one_mul, mul_comm] }, { simp at hb, simp [hb] at h0, have : c / 0 = ⊤, by simp [div_eq_top, h0], simp [hb, this] } end lemma div_le_iff_le_mul (hb0 : b ≠ 0 ∨ c ≠ ⊤) (hbt : b ≠ ⊤ ∨ c ≠ 0) : a / b ≤ c ↔ a ≤ c * b := begin suffices : a * b⁻¹ ≤ c ↔ a ≤ c / b⁻¹, by simpa [div_def], apply (le_div_iff_mul_le _ _).symm, simpa [inv_ne_zero] using hbt, simpa [inv_ne_zero] using hb0 end lemma div_le_of_le_mul (h : a ≤ b * c) : a / c ≤ b := begin by_cases h0 : c = 0, { have : a = 0, by simpa [h0] using h, simp [*] }, by_cases hinf : c = ⊤, by simp [hinf], exact (div_le_iff_le_mul (or.inl h0) (or.inl hinf)).2 h end lemma mul_lt_of_lt_div (h : a < b / c) : a * c < b := by { contrapose! h, exact ennreal.div_le_of_le_mul h } lemma inv_le_iff_le_mul : (b = ⊤ → a ≠ 0) → (a = ⊤ → b ≠ 0) → (a⁻¹ ≤ b ↔ 1 ≤ a * b) := begin cases a; cases b; simp [none_eq_top, some_eq_coe, mul_top, top_mul] {contextual := tt}, by_cases a = 0; simp [*, -coe_mul, coe_mul.symm, -coe_inv, (coe_inv _).symm, nnreal.inv_le] end @[simp] lemma le_inv_iff_mul_le : a ≤ b⁻¹ ↔ a * b ≤ 1 := begin cases b, { by_cases a = 0; simp [*, none_eq_top, mul_top] }, by_cases b = 0; simp [*, some_eq_coe, le_div_iff_mul_le], suffices : a ≤ 1 / b ↔ a * b ≤ 1, { simpa [div_def, h] }, exact le_div_iff_mul_le (or.inl (mt coe_eq_coe.1 h)) (or.inl coe_ne_top) end lemma mul_inv_cancel (h0 : a ≠ 0) (ht : a ≠ ⊤) : a * a⁻¹ = 1 := begin lift a to nnreal using ht, norm_cast at h0, norm_cast, exact nnreal.mul_inv_cancel h0 end lemma inv_mul_cancel (h0 : a ≠ 0) (ht : a ≠ ∞) : a⁻¹ * a = 1 := mul_comm a a⁻¹ ▸ mul_inv_cancel h0 ht lemma mul_le_iff_le_inv {a b r : ennreal} (hr₀ : r ≠ 0) (hr₁ : r ≠ ⊤) : (r * a ≤ b ↔ a ≤ r⁻¹ * b) := by rw [← @ennreal.mul_le_mul_left _ a _ hr₀ hr₁, ← mul_assoc, mul_inv_cancel hr₀ hr₁, one_mul] lemma le_of_forall_lt_one_mul_lt : ∀{x y : ennreal}, (∀a<1, a * x ≤ y) → x ≤ y := forall_ennreal.2 $ and.intro (assume r, forall_ennreal.2 $ and.intro (assume q h, coe_le_coe.2 $ nnreal.le_of_forall_lt_one_mul_lt $ assume a ha, begin rw [← coe_le_coe, coe_mul], exact h _ (coe_lt_coe.2 ha) end) (assume h, le_top)) (assume r hr, have ((1 / 2 : nnreal) : ennreal) * ⊤ ≤ r := hr _ (coe_lt_coe.2 ((@nnreal.coe_lt_coe (1/2) 1).1 one_half_lt_one)), have ne : ((1 / 2 : nnreal) : ennreal) ≠ 0, begin rw [(≠), coe_eq_zero], refine zero_lt_iff_ne_zero.1 _, show 0 < (1 / 2 : ℝ), exact div_pos zero_lt_one _root_.two_pos end, by rwa [mul_top, if_neg ne] at this) lemma div_add_div_same {a b c : ennreal} : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma div_self (h0 : a ≠ 0) (hI : a ≠ ∞) : a / a = 1 := mul_inv_cancel h0 hI lemma mul_div_cancel (h0 : a ≠ 0) (hI : a ≠ ∞) : (b / a) * a = b := by rw [div_def, mul_assoc, inv_mul_cancel h0 hI, mul_one] lemma mul_div_cancel' (h0 : a ≠ 0) (hI : a ≠ ∞) : a * (b / a) = b := by rw [mul_comm, mul_div_cancel h0 hI] lemma inv_two_add_inv_two : (2:ennreal)⁻¹ + 2⁻¹ = 1 := by rw [← two_mul, ← div_def, div_self two_ne_zero two_ne_top] lemma add_halves (a : ennreal) : a / 2 + a / 2 = a := by rw [div_def, ← mul_add, inv_two_add_inv_two, mul_one] @[simp] lemma div_zero_iff {a b : ennreal} : a / b = 0 ↔ a = 0 ∨ b = ⊤ := by simp [div_def, mul_eq_zero] @[simp] lemma div_pos_iff {a b : ennreal} : 0 < a / b ↔ a ≠ 0 ∧ b ≠ ⊤ := by simp [zero_lt_iff_ne_zero, not_or_distrib] lemma half_pos {a : ennreal} (h : 0 < a) : 0 < a / 2 := by simp [ne_of_gt h] lemma one_half_lt_one : (2⁻¹:ennreal) < 1 := inv_lt_one.2 $ one_lt_two lemma half_lt_self {a : ennreal} (hz : a ≠ 0) (ht : a ≠ ⊤) : a / 2 < a := begin lift a to nnreal using ht, have h : (2 : ennreal) = ((2 : nnreal) : ennreal), from rfl, have h' : (2 : nnreal) ≠ 0, from _root_.two_ne_zero', rw [h, ← coe_div h', coe_lt_coe], -- `norm_cast` fails to apply `coe_div` norm_cast at hz, exact nnreal.half_lt_self hz end lemma sub_half (h : a ≠ ∞) : a - a / 2 = a / 2 := begin lift a to nnreal using h, exact sub_eq_of_add_eq (mul_ne_top coe_ne_top $ by simp) (add_halves a) end lemma one_sub_inv_two : (1:ennreal) - 2⁻¹ = 2⁻¹ := by simpa only [div_def, one_mul] using sub_half one_ne_top lemma exists_inv_nat_lt {a : ennreal} (h : a ≠ 0) : ∃n:ℕ, (n:ennreal)⁻¹ < a := @inv_inv a ▸ by simp only [inv_lt_inv, ennreal.exists_nat_gt (inv_ne_top.2 h)] end inv section real lemma to_real_add (ha : a ≠ ⊤) (hb : b ≠ ⊤) : (a+b).to_real = a.to_real + b.to_real := begin lift a to nnreal using ha, lift b to nnreal using hb, refl end lemma to_real_add_le : (a+b).to_real ≤ a.to_real + b.to_real := if ha : a = ⊤ then by simp only [ha, top_add, top_to_real, zero_add, to_real_nonneg] else if hb : b = ⊤ then by simp only [hb, add_top, top_to_real, add_zero, to_real_nonneg] else le_of_eq (to_real_add ha hb) lemma of_real_add {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) : ennreal.of_real (p + q) = ennreal.of_real p + ennreal.of_real q := by rw [ennreal.of_real, ennreal.of_real, ennreal.of_real, ← coe_add, coe_eq_coe, nnreal.of_real_add hp hq] @[simp] lemma to_real_le_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real ≤ b.to_real ↔ a ≤ b := begin lift a to nnreal using ha, lift b to nnreal using hb, norm_cast end @[simp] lemma to_real_lt_to_real (ha : a ≠ ⊤) (hb : b ≠ ⊤) : a.to_real < b.to_real ↔ a < b := begin lift a to nnreal using ha, lift b to nnreal using hb, norm_cast end lemma to_real_max (hr : a ≠ ⊤) (hp : b ≠ ⊤) : ennreal.to_real (max a b) = max (ennreal.to_real a) (ennreal.to_real b) := (le_total a b).elim (λ h, by simp only [h, (ennreal.to_real_le_to_real hr hp).2 h, max_eq_right]) (λ h, by simp only [h, (ennreal.to_real_le_to_real hp hr).2 h, max_eq_left]) lemma to_nnreal_pos_iff : 0 < a.to_nnreal ↔ (0 < a ∧ a ≠ ∞) := begin cases a, { simp [none_eq_top] }, { simp [some_eq_coe] } end lemma to_real_pos_iff : 0 < a.to_real ↔ (0 < a ∧ a ≠ ∞):= (nnreal.coe_pos).trans to_nnreal_pos_iff lemma of_real_le_of_real {p q : ℝ} (h : p ≤ q) : ennreal.of_real p ≤ ennreal.of_real q := by simp [ennreal.of_real, nnreal.of_real_le_of_real h] @[simp] lemma of_real_le_of_real_iff {p q : ℝ} (h : 0 ≤ q) : ennreal.of_real p ≤ ennreal.of_real q ↔ p ≤ q := by rw [ennreal.of_real, ennreal.of_real, coe_le_coe, nnreal.of_real_le_of_real_iff h] @[simp] lemma of_real_lt_of_real_iff {p q : ℝ} (h : 0 < q) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff h] lemma of_real_lt_of_real_iff_of_nonneg {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real p < ennreal.of_real q ↔ p < q := by rw [ennreal.of_real, ennreal.of_real, coe_lt_coe, nnreal.of_real_lt_of_real_iff_of_nonneg hp] @[simp] lemma of_real_pos {p : ℝ} : 0 < ennreal.of_real p ↔ 0 < p := by simp [ennreal.of_real] @[simp] lemma of_real_eq_zero {p : ℝ} : ennreal.of_real p = 0 ↔ p ≤ 0 := by simp [ennreal.of_real] lemma of_real_le_iff_le_to_real {a : ℝ} {b : ennreal} (hb : b ≠ ⊤) : ennreal.of_real a ≤ b ↔ a ≤ ennreal.to_real b := begin lift b to nnreal using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_le_iff_le_coe end lemma of_real_lt_iff_lt_to_real {a : ℝ} {b : ennreal} (ha : 0 ≤ a) (hb : b ≠ ⊤) : ennreal.of_real a < b ↔ a < ennreal.to_real b := begin lift b to nnreal using hb, simpa [ennreal.of_real, ennreal.to_real] using nnreal.of_real_lt_iff_lt_coe ha end lemma le_of_real_iff_to_real_le {a : ennreal} {b : ℝ} (ha : a ≠ ⊤) (hb : 0 ≤ b) : a ≤ ennreal.of_real b ↔ ennreal.to_real a ≤ b := begin lift a to nnreal using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.le_of_real_iff_coe_le hb end lemma to_real_le_of_le_of_real {a : ennreal} {b : ℝ} (hb : 0 ≤ b) (h : a ≤ ennreal.of_real b) : ennreal.to_real a ≤ b := have ha : a ≠ ⊤, from ne_top_of_le_ne_top of_real_ne_top h, (le_of_real_iff_to_real_le ha hb).1 h lemma lt_of_real_iff_to_real_lt {a : ennreal} {b : ℝ} (ha : a ≠ ⊤) : a < ennreal.of_real b ↔ ennreal.to_real a < b := begin lift a to nnreal using ha, simpa [ennreal.of_real, ennreal.to_real] using nnreal.lt_of_real_iff_coe_lt end lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) : ennreal.of_real (p * q) = (ennreal.of_real p) * (ennreal.of_real q) := by { simp only [ennreal.of_real, coe_mul.symm, coe_eq_coe], exact nnreal.of_real_mul hp } lemma to_real_of_real_mul (c : ℝ) (a : ennreal) (h : 0 ≤ c) : ennreal.to_real ((ennreal.of_real c) * a) = c * ennreal.to_real a := begin cases a, { simp only [none_eq_top, ennreal.to_real, top_to_nnreal, nnreal.coe_zero, mul_zero, mul_top], by_cases h' : c ≤ 0, { rw [if_pos], { simp }, { convert of_real_zero, exact le_antisymm h' h } }, { rw [if_neg], refl, rw [of_real_eq_zero], assumption } }, { simp only [ennreal.to_real, ennreal.to_nnreal], simp only [some_eq_coe, ennreal.of_real, coe_mul.symm, to_nnreal_coe, nnreal.coe_mul], congr, apply nnreal.coe_of_real, exact h } end @[simp] lemma to_real_mul_top (a : ennreal) : ennreal.to_real (a * ⊤) = 0 := begin by_cases h : a = 0, { rw [h, zero_mul, zero_to_real] }, { rw [mul_top, if_neg h, top_to_real] } end @[simp] lemma to_real_top_mul (a : ennreal) : ennreal.to_real (⊤ * a) = 0 := by { rw mul_comm, exact to_real_mul_top _ } lemma to_real_eq_to_real {a b : ennreal} (ha : a < ⊤) (hb : b < ⊤) : ennreal.to_real a = ennreal.to_real b ↔ a = b := begin rw ennreal.lt_top_iff_ne_top at *, split, { assume h, apply le_antisymm, rw ← to_real_le_to_real ha hb, exact le_of_eq h, rw ← to_real_le_to_real hb ha, exact le_of_eq h.symm }, { assume h, rw h } end lemma to_real_mul_to_real {a b : ennreal} : (ennreal.to_real a) * (ennreal.to_real b) = ennreal.to_real (a * b) := begin by_cases ha : a = ⊤, { rw ha, simp }, by_cases hb : b = ⊤, { rw hb, simp }, have ha : ennreal.of_real (ennreal.to_real a) = a := of_real_to_real ha, have hb : ennreal.of_real (ennreal.to_real b) = b := of_real_to_real hb, conv_rhs { rw [← ha, ← hb, ← of_real_mul to_real_nonneg] }, rw [to_real_of_real (mul_nonneg to_real_nonneg to_real_nonneg)] end end real section infi variables {ι : Sort*} {f g : ι → ennreal} lemma infi_add : infi f + a = ⨅i, f i + a := le_antisymm (le_infi $ assume i, add_le_add' (infi_le _ _) $ le_refl _) (ennreal.sub_le_iff_le_add.1 $ le_infi $ assume i, ennreal.sub_le_iff_le_add.2 $ infi_le _ _) lemma supr_sub : (⨆i, f i) - a = (⨆i, f i - a) := le_antisymm (ennreal.sub_le_iff_le_add.2 $ supr_le $ assume i, ennreal.sub_le_iff_le_add.1 $ le_supr _ i) (supr_le $ assume i, ennreal.sub_le_sub (le_supr _ _) (le_refl a)) lemma sub_infi : a - (⨅i, f i) = (⨆i, a - f i) := begin refine (eq_of_forall_ge_iff $ λ c, _), rw [ennreal.sub_le_iff_le_add, add_comm, infi_add], simp [ennreal.sub_le_iff_le_add, sub_eq_add_neg, add_comm], end lemma Inf_add {s : set ennreal} : Inf s + a = ⨅b∈s, b + a := by simp [Inf_eq_infi, infi_add] lemma add_infi {a : ennreal} : a + infi f = ⨅b, a + f b := by rw [add_comm, infi_add]; simp [add_comm] lemma infi_add_infi (h : ∀i j, ∃k, f k + g k ≤ f i + g j) : infi f + infi g = (⨅a, f a + g a) := suffices (⨅a, f a + g a) ≤ infi f + infi g, from le_antisymm (le_infi $ assume a, add_le_add' (infi_le _ _) (infi_le _ _)) this, calc (⨅a, f a + g a) ≤ (⨅ a a', f a + g a') : le_infi $ assume a, le_infi $ assume a', let ⟨k, h⟩ := h a a' in infi_le_of_le k h ... ≤ infi f + infi g : by simp [add_infi, infi_add, -add_comm, -le_infi_iff]; exact le_refl _ lemma infi_sum {f : ι → α → ennreal} {s : finset α} [nonempty ι] (h : ∀(t : finset α) (i j : ι), ∃k, ∀a∈t, f k a ≤ f i a ∧ f k a ≤ f j a) : (⨅i, s.sum (f i)) = s.sum (λa, ⨅i, f i a) := finset.induction_on s (by simp) $ assume a s ha ih, have ∀ (i j : ι), ∃ (k : ι), f k a + s.sum (f k) ≤ f i a + s.sum (f j), from assume i j, let ⟨k, hk⟩ := h (insert a s) i j in ⟨k, add_le_add' (hk a (finset.mem_insert_self _ _)).left $ finset.sum_le_sum $ assume a ha, (hk _ $ finset.mem_insert_of_mem ha).right⟩, by simp [ha, ih.symm, infi_add_infi this] end infi section supr lemma supr_coe_nat : (⨆n:ℕ, (n : ennreal)) = ⊤ := (supr_eq_top _).2 $ assume b hb, ennreal.exists_nat_gt (lt_top_iff_ne_top.1 hb) end supr end ennreal
04feeba07219ea0899c9c802cbdf69db9d3b8200
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/group_theory/eckmann_hilton.lean
9a60bf7806bf96fe18c459faf7d7736a19dcc205
[ "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
1,910
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau, Robert Y. Lewis -/ import tactic.basic universe u namespace eckmann_hilton variables {X : Type u} local notation a `<`m`>` b := m a b class is_unital (m : X → X → X) (e : X) : Prop := (one_mul : ∀ x : X, (e <m> x) = x) (mul_one : ∀ x : X, (x <m> e) = x) lemma group.is_unital [G : group X] : is_unital (*) (1 : X) := { ..G } variables {m₁ m₂ : X → X → X} {e₁ e₂ : X} variables (h₁ : is_unital m₁ e₁) (h₂ : is_unital m₂ e₂) variables (distrib : ∀ a b c d, ((a <m₂> b) <m₁> (c <m₂> d)) = ((a <m₁> c) <m₂> (b <m₁> d))) include h₁ h₂ distrib lemma one : e₁ = e₂ := by simpa only [h₁.one_mul, h₁.mul_one, h₂.one_mul, h₂.mul_one] using distrib e₂ e₁ e₁ e₂ lemma mul : (m₁ = m₂) := begin funext a b, calc m₁ a b = m₁ (m₂ a e₁) (m₂ e₁ b) : by simp only [one h₁ h₂ distrib, h₁.one_mul, h₁.mul_one, h₂.one_mul, h₂.mul_one] ... = m₂ a b : by simp only [distrib, h₁.one_mul, h₁.mul_one, h₂.one_mul, h₂.mul_one] end lemma mul_comm : is_commutative _ m₂ := ⟨λ a b, by simpa [mul h₁ h₂ distrib, h₂.one_mul, h₂.mul_one] using distrib e₂ a b e₂⟩ lemma mul_assoc : is_associative _ m₂ := ⟨λ a b c, by simpa [mul h₁ h₂ distrib, h₂.one_mul, h₂.mul_one] using distrib a b e₂ c⟩ def comm_monoid : comm_monoid X := { mul := m₂, one := e₂, mul_comm := (mul_comm h₁ h₂ distrib).comm, mul_assoc := (mul_assoc h₁ h₂ distrib).assoc, ..h₂ } def comm_group [G : group X] (distrib : ∀ a b c d, ((a * b) <m₁> (c * d)) = ((a <m₁> c) * (b <m₁> d))) : comm_group X := { mul_comm := (eckmann_hilton.comm_monoid h₁ group.is_unital distrib).mul_comm, ..G } end eckmann_hilton
21275995fc4b05172650469088141c893f3420cc
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Data/Json/Parser.lean
1255653ae61bd7200690e96afa97d1c223f29369
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
5,433
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Marc Huisinga -/ import Lean.Data.Json.Basic import Lean.Data.Parsec namespace Lean open Std (RBNode RBNode.singleton RBNode.leaf) namespace Json.Parser open Lean.Parsec @[inline] def hexChar : Parsec Nat := do let c ← anyChar if '0' ≤ c ∧ c ≤ '9' then pure $ c.val.toNat - '0'.val.toNat else if 'a' ≤ c ∧ c ≤ 'f' then pure $ c.val.toNat - 'a'.val.toNat else if 'A' ≤ c ∧ c ≤ 'F' then pure $ c.val.toNat - 'A'.val.toNat else fail "invalid hex character" def escapedChar : Parsec Char := do let c ← anyChar match c with | '\\' => '\\' | '"' => '"' | '/' => '/' | 'b' => '\x08' | 'f' => '\x0c' | 'n' => '\n' | 'r' => '\x0d' | 't' => '\t' | 'u' => let u1 ← hexChar; let u2 ← hexChar; let u3 ← hexChar; let u4 ← hexChar Char.ofNat $ 4096*u1 + 256*u2 + 16*u3 + u4 | _ => fail "illegal \\u escape" partial def strCore (acc : String) : Parsec String := do let c ← peek! if c = '"' then -- " skip acc else let c ← anyChar let ec ← if c = '\\' then escapedChar -- as to whether c.val > 0xffff should be split up and encoded with multiple \u, -- the JSON standard is not definite: both directly printing the character -- and encoding it with multiple \u is allowed. we choose the former. else if 0x0020 ≤ c.val ∧ c.val ≤ 0x10ffff then c else fail "unexpected character in string" strCore (acc.push ec) def str : Parsec String := strCore "" partial def natCore (acc digits : Nat) : Parsec (Nat × Nat) := do let some c ← peek? | (acc, digits) if '0' ≤ c ∧ c ≤ '9' then skip let acc' := 10*acc + (c.val.toNat - '0'.val.toNat) natCore acc' (digits+1) else (acc, digits) @[inline] def lookahead (p : Char → Prop) (desc : String) [DecidablePred p] : Parsec Unit := do let c ← peek! if p c then () else fail $ "expected " ++ desc @[inline] def natNonZero : Parsec Nat := do lookahead (fun c => '1' ≤ c ∧ c ≤ '9') "1-9" let (n, _) ← natCore 0 0 n @[inline] def natNumDigits : Parsec (Nat × Nat) := do lookahead (fun c => '0' ≤ c ∧ c ≤ '9') "digit" natCore 0 0 @[inline] def natMaybeZero : Parsec Nat := do let (n, _) ← natNumDigits n def num : Parsec JsonNumber := do let c ← peek! let sign : Int ← if c = '-' then skip pure (-1 : Int) else pure 1 let c ← peek! let res ← if c = '0' then skip pure 0 else natNonZero let c? ← peek? let res : JsonNumber ← if c? = some '.' then skip let (n, d) ← natNumDigits if d > USize.size then fail "too many decimals" let mantissa' := sign * (res * (10^d : Nat) + n) let exponent' := d JsonNumber.mk mantissa' exponent' else JsonNumber.fromInt (sign * res) let c? ← peek? if c? = some 'e' ∨ c? = some 'E' then skip let c ← peek! if c = '-' then skip let n ← natMaybeZero res.shiftr n else if c = '+' then skip let n ← natMaybeZero if n > USize.size then fail "exp too large" res.shiftl n else res partial def arrayCore (anyCore : Unit → Parsec Json) (acc : Array Json) : Parsec (Array Json) := do let hd ← anyCore () let acc' := acc.push hd let c ← anyChar if c = ']' then ws acc' else if c = ',' then ws arrayCore anyCore acc' else fail "unexpected character in array" partial def objectCore (anyCore : Unit → Parsec Json) : Parsec (RBNode String (fun _ => Json)) := do lookahead (fun c => c = '"') "\""; skip; -- " let k ← strCore ""; ws lookahead (fun c => c = ':') ":"; skip; ws let v ← anyCore () let c ← anyChar if c = '}' then ws RBNode.singleton k v else if c = ',' then ws let kvs ← objectCore anyCore kvs.insert compare k v else fail "unexpected character in object" -- takes a unit parameter so that -- we can use the equation compiler and recursion partial def anyCore (u : Unit) : Parsec Json := do let c ← peek! if c = '[' then skip; ws let c ← peek! if c = ']' then skip; ws Json.arr (Array.mkEmpty 0) else let a ← arrayCore anyCore (Array.mkEmpty 4) Json.arr a else if c = '{' then skip; ws let c ← peek! if c = '}' then skip; ws Json.obj (RBNode.leaf) else let kvs ← objectCore anyCore Json.obj kvs else if c = '\"' then skip let s ← strCore "" ws Json.str s else if c = 'f' then skipString "false"; ws Json.bool false else if c = 't' then skipString "true"; ws Json.bool true else if c = 'n' then skipString "null"; ws Json.null else if c = '-' ∨ ('0' ≤ c ∧ c ≤ '9') then let n ← num ws Json.num n else fail "unexpected input" def any : Parsec Json := do ws let res ← anyCore () eof res end Json.Parser namespace Json def parse (s : String) : Except String Lean.Json := match Json.Parser.any s.mkIterator with | Parsec.ParseResult.success _ res => Except.ok res | Parsec.ParseResult.error it err => Except.error s!"offset {it.i.repr}: {err}" end Json end Lean
66cc25151529f3f067e4d254c7cff48dba44dad3
de8d0cdc3dc15aa390280472764229d0e14e734c
/src/pointwise_convergence.lean
1c861e0f725adc4387360f34ea17ae16e039ac1e
[]
no_license
amesnard0/lean-topology
94720ccf0af34961b24b52b96bcfb19df5c8f544
e8f6a720c435cb59d098579a26f6eb70ea05f91a
refs/heads/main
1,682,525,569,376
1,622,116,766,000
1,622,116,766,000
358,047,823
0
0
null
null
null
null
UTF-8
Lean
false
false
5,867
lean
import tactic import data.set.finite import topological_spaces import neighbourhoods import topological_spaces2 open set open_locale classical open topological_space -- Convergence simple : def pointwise_lim {X Y : Type} [topological_space Y] (f : ℕ → (X → Y)) (F : X → Y) : Prop := ∀ (x : X), seq_lim (λ n, f n x) (F x) -- Topologie produit sur X → Y : instance fnct.topological_space (X Y : Type) [topological_space Y] : topological_space (X → Y) := topological_space.generate_from (X → Y) {U | ∃ (x : X) (Ux : set Y) (hUx : is_open Ux), U = {f : X → Y | f x ∈ Ux}} -- Base de la topologie produit (intersections finies de générateurs) : lemma is_open_fnct_iff {X Y : Type} [topological_space Y] {s : set (X → Y)} : is_open s ↔ ∀ f ∈ s, ∃ (D : set X) (φ : X → set Y) (hD : finite D) (hφ : ∀ x ∉ D, φ x = univ), (∀ x, is_open (φ x)) ∧ (∀ x, f x ∈ φ x) ∧ ({f' : X → Y | ∀ x, f' x ∈ φ x} ⊆ s) := begin split, { intros hyp f hf, induction hyp with U hU A B hA1 hB1 hA2 hB2 C hC1 hC2, { rcases hU with ⟨ x, Ux, hUx, hU ⟩, use [{x}, (λ x', ite (x' = x) Ux univ)], split, exact finite_singleton x, repeat {split}, intros x' hx', simp, intro H, exfalso, exact hx' H, intro x', split_ifs, exact hUx, exact univ_mem, intro x', split_ifs, rw h, rw hU at hf, exact hf, simp, intros f' hf', rw hU, specialize hf' x, simp at hf', exact hf', }, { rcases hA2 hf.1 with ⟨ D1, φ1, hD1, hφ1, hoφ1, hfφ1, hA ⟩, rcases hB2 hf.2 with ⟨ D2, φ2, hD2, hφ2, hoφ2, hfφ2, hB ⟩, use [(D1 ∪ D2), (λ x, (φ1 x) ∩ (φ2 x))], split, exact finite.union hD1 hD2, repeat {split}, intros x hx, rw union_def at hx, simp at hx, push_neg at hx, simp [hφ1 x hx.1, hφ2 x hx.2], intro x, exact inter (hoφ1 x) (hoφ2 x), intro x, split, exact hfφ1 x, exact hfφ2 x, intros f' hf', split, apply hA, intro x, exact (hf' x).1, apply hB, intro x, exact (hf' x).2, }, { rcases hf with ⟨c, hcC, hfc⟩, rcases hC2 c hcC hfc with ⟨ D, φ, hD, hφ, hoφ, hfφ, hc ⟩, use [D, φ], split, exact hD, repeat {split}, exact hφ, exact hoφ, exact hfφ, intros f' hf', use [c, hcC, hc hf'], }, { use [∅, (λ x, univ)], split, exact finite_empty, repeat {split}, simp, intro x, exact univ_mem, repeat {simp}, }, }, { intro hyp, choose D_ φ_ H1 H2 H3 H4 H5 using hyp, have clef : s = ⋃₀ { ({f' : X → Y | ∀ x, f' x ∈ φ_ f H x}) | (f : X → Y) (H : f ∈ s)}, { apply le_antisymm, { intros f hf, use {f' : X → Y | ∀ x, f' x ∈ φ_ f hf x}, use [f, hf, H4 f hf], }, { rintros f ⟨ V, ⟨f', hf', hV⟩, hfV⟩, rw ← hV at hfV, exact H5 f' hf' hfV, }, }, rw clef, apply union, rintros V ⟨ f, hf, hV ⟩, have clef2 : V = ⋂₀ { ({f' : X → Y | f' x ∈ φ_ f hf x }) | x ∈ D_ f hf }, { apply le_antisymm, { intros f' hf', rintros Vx ⟨ x, hx, hVx ⟩, rw ← hVx, rw ← hV at hf', exact hf' x, }, { intros f' hf', rw ← hV, intro x, cases em (x ∈ D_ f hf) with hx1 hx2, apply hf' {f' : X → Y | f' x ∈ φ_ f hf x }, use [x, hx1], rw H2 f hf x hx2, simp, }, }, rw clef2, apply finite_inter, { let ψ := λ x, {f' : X → Y | f' x ∈ φ_ f hf x}, have : {_x : set (X → Y) | ∃ (x : X) (H : x ∈ D_ f hf), {f' : X → Y | f' x ∈ φ_ f hf x} = _x} = ψ '' (D_ f hf), { apply le_antisymm, { rintros V ⟨x, hx, hV⟩, rw ← hV, clear hV V, use x, split, exact hx, refl, }, { rintros V ⟨x, hx, hV⟩, rw ← hV, clear hV V, use x, split, exact hx, refl, }, }, rw this, exact finite.image ψ (H1 f hf), }, rintros Vx ⟨ x, hx, hVx ⟩, rw ← hVx, apply generated_open.generator, use [x, φ_ f hf x], split, exact H3 f hf x, refl, }, end -- Cette topologie est la topologie de la convergence simple : example {X Y : Type} [topological_space Y] (f : ℕ → (X → Y)) (F : X → Y) : pointwise_lim f F ↔ seq_lim f F := begin split, { intro hyp, intros V hV, rcases (is_neighbourhood_iff F).1 hV with ⟨U, hU, hFU, hUV⟩, rw is_open_fnct_iff at hU, rcases hU F hFU with ⟨D, φ, hD, hφ, h1, h2, h3⟩, cases em (D.nonempty) with hD1 hD2, { have clef : ∀ x, ∃ (N : ℕ), ∀ n ≥ N, f n x ∈ φ x, { intros x, have hφx : (φ x) ∈ neighbourhoods (F x), { rw is_neighbourhood_iff, use [φ x, h1 x, h2 x], }, exact hyp x (φ x) hφx, }, choose ψ hψ using clef, cases finite.exists_maximal_wrt ψ D hD hD1 with x₀ hx₀, rw exists_prop at hx₀, let N := ψ x₀, have hN : ∀ x ∈ D, N ≥ ψ x, { intros x hx, cases le_total N (ψ x) with H1 H2, exact ge_of_eq (hx₀.2 x hx H1), exact H2, }, use N, intros n hn, apply hUV, apply h3, intro x, cases em (x ∈ D) with hx1 hx2, exact hψ x n (ge_trans hn (hN x hx1)), rw hφ x hx2, simp, }, { rw nonempty_def at hD2, push_neg at hD2, use 0, intros n hn, apply hUV, apply h3, intro x, rw hφ x (hD2 x), simp, }, }, { intro hyp, intros x Vx hVx, rcases (is_neighbourhood_iff (F x)).1 hVx with ⟨Ux, hUx, hxUx, hUxVx⟩, let V := {g : X → Y | g x ∈ Vx}, have hV: V ∈ neighbourhoods F, { rw is_neighbourhood_iff, use {g : X → Y | g x ∈ Ux}, repeat {split}, apply generated_open.generator, use [x, Ux, hUx], exact hxUx, intros g hg, exact hUxVx hg, }, cases hyp V hV with N hN, use N, intros n hn, exact hN n hn, }, end
ef3844d25dd4bad3b75e9700be265b6b423c02b5
57c233acf9386e610d99ed20ef139c5f97504ba3
/archive/imo/imo2008_q4.lean
8b1db18a76517819a456e16922937d7b34ec43f5
[ "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
5,534
lean
/- Copyright (c) 2021 Manuel Candales. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Manuel Candales -/ import data.real.basic import data.real.sqrt import data.real.nnreal /-! # IMO 2008 Q4 Find all functions `f : (0,∞) → (0,∞)` (so, `f` is a function from the positive real numbers to the positive real numbers) such that ``` (f(w)^2 + f(x)^2)/(f(y^2) + f(z^2)) = (w^2 + x^2)/(y^2 + z^2) ``` for all positive real numbers `w`, `x`, `y`, `z`, satisfying `wx = yz`. # Solution The desired theorem is that either `f = λ x, x` or `f = λ x, 1/x` -/ open real lemma abs_eq_one_of_pow_eq_one (x : ℝ) (n : ℕ) (hn : n ≠ 0) (h : x ^ n = 1) : |x| = 1 := by rw [← pow_left_inj (abs_nonneg x) zero_le_one (pos_iff_ne_zero.2 hn), one_pow, pow_abs, h, abs_one] theorem imo2008_q4 (f : ℝ → ℝ) (H₁ : ∀ x > 0, f(x) > 0) : (∀ w x y z : ℝ, 0 < w → 0 < x → 0 < y → 0 < z → w * x = y * z → (f(w) ^ 2 + f(x) ^ 2) / (f(y ^ 2) + f(z ^ 2)) = (w ^ 2 + x ^ 2) / (y ^ 2 + z ^ 2)) ↔ ((∀ x > 0, f(x) = x) ∨ (∀ x > 0, f(x) = 1 / x)) := begin split, swap, -- proof that f(x) = x and f(x) = 1/x satisfy the condition { rintros (h | h), { intros w x y z hw hx hy hz hprod, rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)] }, { intros w x y z hw hx hy hz hprod, rw [h w hw, h x hx, h (y ^ 2) (pow_pos hy 2), h (z ^ 2) (pow_pos hz 2)], have hy2z2 : y ^ 2 + z ^ 2 ≠ 0 := ne_of_gt (add_pos (pow_pos hy 2) (pow_pos hz 2)), have hz2y2 : z ^ 2 + y ^ 2 ≠ 0 := ne_of_gt (add_pos (pow_pos hz 2) (pow_pos hy 2)), have hp2 : w ^ 2 * x ^ 2 = y ^ 2 * z ^ 2, { rw [← mul_pow w x 2, ← mul_pow y z 2, hprod] }, field_simp [ne_of_gt hw, ne_of_gt hx, ne_of_gt hy, ne_of_gt hz, hy2z2, hz2y2, hp2], ring } }, -- proof that the only solutions are f(x) = x or f(x) = 1/x intro H₂, have h₀ : f(1) ≠ 0, { specialize H₁ 1 zero_lt_one, exact ne_of_gt H₁ }, have h₁ : f(1) = 1, { specialize H₂ 1 1 1 1 zero_lt_one zero_lt_one zero_lt_one zero_lt_one rfl, norm_num at H₂, simp only [← two_mul] at H₂, rw mul_div_mul_left (f(1) ^ 2) (f 1) two_ne_zero at H₂, rwa ← (div_eq_iff h₀).mpr (sq (f 1)) }, have h₂ : ∀ x > 0, (f(x) - x) * (f(x) - 1 / x) = 0, { intros x hx, have h1xss : 1 * x = (sqrt x) * (sqrt x), { rw [one_mul, mul_self_sqrt (le_of_lt hx)] }, specialize H₂ 1 x (sqrt x) (sqrt x) zero_lt_one hx (sqrt_pos.mpr hx) (sqrt_pos.mpr hx) h1xss, rw [h₁, one_pow 2, sq_sqrt (le_of_lt hx), ← two_mul (f(x)), ← two_mul x] at H₂, have hx_ne_0 : x ≠ 0 := ne_of_gt hx, have hfx_ne_0 : f(x) ≠ 0, { specialize H₁ x hx, exact ne_of_gt H₁ }, field_simp at H₂, have h1 : (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) = 0, { calc (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) = 2 * (f(x) - x) * (x * f(x) - x * 1 / x) : by ring ... = 2 * (f(x) - x) * (x * f(x) - 1) : by rw (mul_div_cancel_left 1 hx_ne_0) ... = ((1 + f(x) ^ 2) * (2 * x) - (1 + x ^ 2) * (2 * f(x))) : by ring ... = 0 : sub_eq_zero.mpr H₂ }, have h2x_ne_0 : 2 * x ≠ 0 := mul_ne_zero two_ne_zero hx_ne_0, calc ((f(x) - x) * (f(x) - 1 / x)) = (2 * x) * ((f(x) - x) * (f(x) - 1 / x)) / (2 * x) : (mul_div_cancel_left _ h2x_ne_0).symm ... = 0 : by { rw h1, exact zero_div (2 * x) } }, have h₃ : ∀ x > 0, f(x) = x ∨ f(x) = 1 / x, { simpa [sub_eq_zero] using h₂ }, by_contra' h, rcases h with ⟨⟨b, hb, hfb₁⟩, ⟨a, ha, hfa₁⟩⟩, obtain hfa₂ := or.resolve_right (h₃ a ha) hfa₁, -- f(a) ≠ 1/a, f(a) = a obtain hfb₂ := or.resolve_left (h₃ b hb) hfb₁, -- f(b) ≠ b, f(b) = 1/b have hab : a * b > 0 := mul_pos ha hb, have habss : a * b = sqrt(a * b) * sqrt(a * b) := (mul_self_sqrt (le_of_lt hab)).symm, specialize H₂ a b (sqrt (a * b)) (sqrt (a * b)) ha hb (sqrt_pos.mpr hab) (sqrt_pos.mpr hab) habss, rw [sq_sqrt (le_of_lt hab), ← two_mul (f(a * b)), ← two_mul (a * b)] at H₂, rw [hfa₂, hfb₂] at H₂, have h2ab_ne_0 : 2 * (a * b) ≠ 0 := mul_ne_zero two_ne_zero (ne_of_gt hab), specialize h₃ (a * b) hab, cases h₃ with hab₁ hab₂, -- f(ab) = ab → b^4 = 1 → b = 1 → f(b) = b → false { have H₃ : (a ^ 2 + (1 / b) ^ 2) / (2 * (a * b)) = (a ^ 2 + b ^ 2) / (2 * (a * b)) ↔ 1 / b ^ 2 = b ^ 2 ∨ 2 * (a * b) = 0, { field_simp [h2ab_ne_0], }, rw [hab₁, H₃] at H₂, obtain hb₁ := or.resolve_right H₂ h2ab_ne_0, field_simp [ne_of_gt hb] at hb₁, rw (show b ^ 2 * b ^ 2 = b ^ 4, by ring) at hb₁, obtain hb₂ := abs_eq_one_of_pow_eq_one b 4 (show 4 ≠ 0, by norm_num) hb₁.symm, rw abs_of_pos hb at hb₂, rw hb₂ at hfb₁, exact hfb₁ h₁ }, -- f(ab) = 1/ab → a^4 = 1 → a = 1 → f(a) = 1/a → false { have hb_ne_0 : b ≠ 0 := ne_of_gt hb, rw hab₂ at H₂, field_simp at H₂, rw ← sub_eq_zero at H₂, rw (show (a ^ 2 * b ^ 2 + 1) * (a * b) * (2 * (a * b)) - (a ^ 2 + b ^ 2) * (b ^ 2 * 2) = 2 * (b ^ 4) * (a ^ 4 - 1), by ring) at H₂, have h2b4_ne_0 : 2 * (b ^ 4) ≠ 0 := mul_ne_zero two_ne_zero (pow_ne_zero 4 hb_ne_0), have ha₁ : a ^ 4 = 1, { simpa [sub_eq_zero, h2b4_ne_0] using H₂ }, obtain ha₂ := abs_eq_one_of_pow_eq_one a 4 (show 4 ≠ 0, by norm_num) ha₁, rw abs_of_pos ha at ha₂, rw ha₂ at hfa₁, norm_num at hfa₁ }, end
616467ff50b938244156849302bdcc95c7f127f0
66a6486e19b71391cc438afee5f081a4257564ec
/heq.hlean
2fabb7438971760d5579bf81ec1038ea826118e2
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
1,801
hlean
-- Author: Floris van Doorn open eq is_trunc variables {I : Set} {P : I → Type} {i j k : I} {x x₁ x₂ : P i} {y y₁ y₂ : P j} {z : P k} {Q : Π⦃i⦄, P i → Type} structure heq (x : P i) (y : P j) : Type := (p : i = j) (q : x =[p] y) namespace eq notation x ` ==[`:50 P:0 `] `:0 y:50 := @heq _ P _ _ x y infix ` == `:50 := heq -- mostly for printing, since it will be almost always ambiguous what P is definition pathover_of_heq {p : i = j} (q : x ==[P] y) : x =[p] y := change_path !is_set.elim (heq.q q) definition eq_of_heq (p : x₁ ==[P] x₂) : x₁ = x₂ := eq_of_pathover_idp (pathover_of_heq p) definition heq.elim (p : x ==[P] y) (q : Q x) : Q y := begin induction p with p r, induction r, exact q end definition heq.refl [refl] (x : P i) : x ==[P] x := heq.mk idp idpo definition heq.rfl : x ==[P] x := heq.refl x definition heq.symm [symm] (p : x ==[P] y) : y ==[P] x := begin induction p with p q, constructor, exact q⁻¹ᵒ end definition heq_of_eq (p : x₁ = x₂) : x₁ ==[P] x₂ := heq.mk idp (pathover_idp_of_eq p) definition heq.trans [trans] (p : x ==[P] y) (p₂ : y ==[P] z) : x ==[P] z := begin induction p with p q, induction p₂ with p₂ q₂, constructor, exact q ⬝o q₂ end infix ` ⬝he `:72 := heq.trans postfix `⁻¹ʰᵉ`:(max+10) := heq.symm definition heq_of_heq_of_eq (p : x ==[P] y) (p₂ : y = y₂) : x ==[P] y₂ := p ⬝he heq_of_eq p₂ definition heq_of_eq_of_heq (p : x = x₂) (p₂ : x₂ ==[P] y) : x ==[P] y := heq_of_eq p ⬝he p₂ infix ` ⬝hep `:73 := concato_eq infix ` ⬝phe `:74 := eq_concato definition heq_tr (p : i = j) (x : P i) : x ==[P] transport P p x := heq.mk p !pathover_tr definition tr_heq (p : i = j) (x : P i) : transport P p x ==[P] x := (heq_tr p x)⁻¹ʰᵉ end eq
cbb37c4cd54f4b9341567a194e063404eac15094
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/meta/smt/smt_tactic.lean
01c2d6e3a4af159fdb260b9998ffe6a584ba4d94
[ "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
15,312
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.category import init.meta.simp_tactic import init.meta.smt.congruence_closure import init.meta.smt.ematch universe u run_cmd mk_simp_attr `pre_smt run_cmd mk_hinst_lemma_attr_set `ematch [] [`ematch_lhs] /-- Configuration for the smt tactic preprocessor. The preprocessor is applied whenever a new hypothesis is introduced. - simp_attr: is the attribute name for the simplification lemmas that are used during the preprocessing step. - max_steps: it is the maximum number of steps performed by the simplifier. - zeta: if tt, then zeta reduction (i.e., unfolding let-expressions) is used during preprocessing. -/ structure smt_pre_config := (simp_attr : name := `pre_smt) (max_steps : nat := 1000000) (zeta : bool := ff) /-- Configuration for the smt_state object. - em_attr: is the attribute name for the hinst_lemmas that are used for ematching -/ structure smt_config := (cc_cfg : cc_config := {}) (em_cfg : ematch_config := {}) (pre_cfg : smt_pre_config := {}) (em_attr : name := `ematch) meta def smt_config.set_classical (c : smt_config) (b : bool) : smt_config := {c with cc_cfg := { (c.cc_cfg) with em := b}} meta constant smt_goal : Type meta def smt_state := list smt_goal meta constant smt_state.mk : smt_config → tactic smt_state meta constant smt_state.to_format : smt_state → tactic_state → format /-- Return tt iff classical excluded middle was enabled at smt_state.mk -/ meta constant smt_state.classical : smt_state → bool meta def smt_tactic := state_t smt_state tactic meta instance : has_append smt_state := list.has_append meta instance : monad smt_tactic := state_t.monad _ _ /- We don't use the default state_t lift operation because only tactics that do not change hypotheses can be automatically lifted to smt_tactic. -/ meta constant tactic_to_smt_tactic (α : Type) : tactic α → smt_tactic α meta instance : monad.has_monad_lift tactic smt_tactic := ⟨tactic_to_smt_tactic⟩ meta instance (α : Type) : has_coe (tactic α) (smt_tactic α) := ⟨monad.monad_lift⟩ meta def smt_tactic_orelse {α : Type} (t₁ t₂ : smt_tactic α) : smt_tactic α := λ ss ts, result.cases_on (t₁ ss ts) result.success (λ e₁ ref₁ s', result.cases_on (t₂ ss ts) result.success result.exception) meta instance : monad_fail smt_tactic := { smt_tactic.monad with fail := λ α s, (tactic.fail (to_fmt s) : smt_tactic α) } meta instance : alternative smt_tactic := { smt_tactic.monad with failure := λ α, @tactic.failed α, orelse := @smt_tactic_orelse } namespace smt_tactic open tactic (transparency) meta constant intros : smt_tactic unit meta constant intron : nat → smt_tactic unit meta constant intro_lst : list name → smt_tactic unit /-- Try to close main goal by using equalities implied by the congruence closure module. -/ meta constant close : smt_tactic unit /-- Produce new facts using heuristic lemma instantiation based on E-matching. This tactic tries to match patterns from lemmas in the main goal with terms in the main goal. The set of lemmas is populated with theorems tagged with the attribute specified at smt_config.em_attr, and lemmas added using tactics such as `smt_tactic.add_lemmas`. The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`. Remark: the given predicate is applied to every new instance. The instance is only added to the state if the predicate returns tt. -/ meta constant ematch_core : (expr → bool) → smt_tactic unit /-- Produce new facts using heuristic lemma instantiation based on E-matching. This tactic tries to match patterns from the given lemmas with terms in the main goal. -/ meta constant ematch_using : hinst_lemmas → smt_tactic unit meta constant mk_ematch_eqn_lemmas_for_core : transparency → name → smt_tactic hinst_lemmas meta constant to_cc_state : smt_tactic cc_state meta constant to_em_state : smt_tactic ematch_state meta constant get_config : smt_tactic smt_config /-- Preprocess the given term using the same simplifications rules used when we introduce a new hypothesis. The result is pair containing the resulting term and a proof that it is equal to the given one. -/ meta constant preprocess : expr → smt_tactic (expr × expr) meta constant get_lemmas : smt_tactic hinst_lemmas meta constant set_lemmas : hinst_lemmas → smt_tactic unit meta constant add_lemmas : hinst_lemmas → smt_tactic unit meta def add_ematch_lemma_core (md : transparency) (as_simp : bool) (e : expr) : smt_tactic unit := do h ← hinst_lemma.mk_core md e as_simp, add_lemmas (mk_hinst_singleton h) meta def add_ematch_lemma_from_decl_core (md : transparency) (as_simp : bool) (n : name) : smt_tactic unit := do h ← hinst_lemma.mk_from_decl_core md n as_simp, add_lemmas (mk_hinst_singleton h) meta def add_ematch_eqn_lemmas_for_core (md : transparency) (n : name) : smt_tactic unit := do hs ← mk_ematch_eqn_lemmas_for_core md n, add_lemmas hs meta def ematch : smt_tactic unit := ematch_core (λ _, tt) meta def failed {α} : smt_tactic α := tactic.failed meta def fail {α : Type} {β : Type u} [has_to_format β] (msg : β) : smt_tactic α := tactic.fail msg meta def try {α : Type} (t : smt_tactic α) : smt_tactic unit := λ ss ts, result.cases_on (t ss ts) (λ ⟨a, new_ss⟩, result.success ((), new_ss)) (λ e ref s', result.success ((), ss) ts) /- (repeat_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def repeat_at_most : nat → smt_tactic unit → smt_tactic unit | 0 t := return () | (n+1) t := (do t, repeat_at_most n t) <|> return () /-- (repeat_exactly n t) : execute t n times -/ meta def repeat_exactly : nat → smt_tactic unit → smt_tactic unit | 0 t := return () | (n+1) t := do t, repeat_exactly n t meta def repeat : smt_tactic unit → smt_tactic unit := repeat_at_most 100000 meta def eblast : smt_tactic unit := repeat (ematch >> try close) open tactic protected meta def read : smt_tactic (smt_state × tactic_state) := do s₁ ← state_t.read, s₂ ← tactic.read, return (s₁, s₂) protected meta def write : smt_state × tactic_state → smt_tactic unit := λ ⟨ss, ts⟩ _ _, result.success ((), ss) ts private meta def mk_smt_goals_for (cfg : smt_config) : list expr → list smt_goal → list expr → tactic (list smt_goal × list expr) | [] sr tr := return (sr.reverse, tr.reverse) | (tg::tgs) sr tr := do tactic.set_goals [tg], [new_sg] ← smt_state.mk cfg | tactic.failed, [new_tg] ← get_goals | tactic.failed, mk_smt_goals_for tgs (new_sg::sr) (new_tg::tr) /- See slift -/ meta def slift_aux {α : Type} (t : tactic α) (cfg : smt_config) : smt_tactic α := λ ss, do _::sgs ← return ss | tactic.fail "slift tactic failed, there no smt goals to be solved", tg::tgs ← tactic.get_goals | tactic.failed, tactic.set_goals [tg], a ← t, new_tgs ← tactic.get_goals, (new_sgs, new_tgs) ← mk_smt_goals_for cfg new_tgs [] [], tactic.set_goals (new_tgs ++ tgs), return (a, new_sgs ++ sgs) /-- This lift operation will restart the SMT state. It is useful for using tactics that change the set of hypotheses. -/ meta def slift {α : Type} (t : tactic α) : smt_tactic α := get_config >>= slift_aux t meta def trace_state : smt_tactic unit := do (s₁, s₂) ← smt_tactic.read, trace (smt_state.to_format s₁ s₂) meta def trace {α : Type} [has_to_tactic_format α] (a : α) : smt_tactic unit := tactic.trace a meta def to_expr (q : pexpr) (allow_mvars := tt) : smt_tactic expr := tactic.to_expr q allow_mvars meta def classical : smt_tactic bool := do s ← state_t.read, return s.classical meta def num_goals : smt_tactic nat := λ ss, return (ss.length, ss) /- Low level primitives for managing set of goals -/ meta def get_goals : smt_tactic (list smt_goal × list expr) := do (g₁, _) ← smt_tactic.read, g₂ ← tactic.get_goals, return (g₁, g₂) meta def set_goals : list smt_goal → list expr → smt_tactic unit := λ g₁ g₂ ss, tactic.set_goals g₂ >> return ((), g₁) private meta def all_goals_core (tac : smt_tactic unit) : list smt_goal → list expr → list smt_goal → list expr → smt_tactic unit | [] ts acs act := set_goals acs (ts ++ act) | (s :: ss) [] acs act := fail "ill-formed smt_state" | (s :: ss) (t :: ts) acs act := do set_goals [s] [t], tac, (new_ss, new_ts) ← get_goals, all_goals_core ss ts (acs ++ new_ss) (act ++ new_ts) /- Apply the given tactic to all goals. -/ meta def all_goals (tac : smt_tactic unit) : smt_tactic unit := do (ss, ts) ← get_goals, all_goals_core tac ss ts [] [] /- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : smt_tactic unit) (tac2 : smt_tactic unit) : smt_tactic unit := do (s::ss, t::ts) ← get_goals, set_goals [s] [t], tac1, all_goals tac2, (new_ss, new_ts) ← get_goals, set_goals (new_ss ++ ss) (new_ts ++ ts) meta instance : has_andthen (smt_tactic unit) (smt_tactic unit) (smt_tactic unit) := ⟨seq⟩ meta def focus1 {α} (tac : smt_tactic α) : smt_tactic α := do (s::ss, t::ts) ← get_goals, match ss with | [] := tac | _ := do set_goals [s] [t], a ← tac, (ss', ts') ← get_goals, set_goals (ss' ++ ss) (ts' ++ ts), return a end meta def solve1 (tac : smt_tactic unit) : smt_tactic unit := do (ss, gs) ← get_goals, match ss, gs with | [], _ := fail "solve1 tactic failed, there isn't any goal left to focus" | _, [] := fail "solve1 tactic failed, there isn't any smt goal left to focus" | s::ss, g::gs := do set_goals [s] [g], tac, (ss', gs') ← get_goals, match ss', gs' with | [], [] := set_goals ss gs | _, _ := fail "solve1 tactic failed, focused goal has not been solved" end end meta def swap : smt_tactic unit := do (ss, ts) ← get_goals, match ss, ts with | (s₁ :: s₂ :: ss), (t₁ :: t₂ :: ts) := set_goals (s₂ :: s₁ :: ss) (t₂ :: t₁ :: ts) | _, _ := failed end /-- Add a new goal for t, and the hypothesis (h : t) in the current goal. -/ meta def assert (h : name) (t : expr) : smt_tactic unit := tactic.assert_core h t >> swap >> intros >> swap >> try close /-- Add the hypothesis (h : t) in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : smt_tactic unit := tactic.assertv_core h t v >> intros >> return () /-- Add a new goal for t, and the hypothesis (h : t := ?M) in the current goal. -/ meta def define (h : name) (t : expr) : smt_tactic unit := tactic.define_core h t >> swap >> intros >> swap >> try close /-- Add the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : smt_tactic unit := tactic.definev_core h t v >> intros >> return () /-- Add (h : t := pr) to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : smt_tactic unit := match t with | none := do t ← infer_type pr, definev h t pr | some t := definev h t pr end /-- Add (h : t) to the current goal, given a proof (pr : t) -/ meta def note (h : name) (t : option expr := none) (pr : expr) : smt_tactic unit := match t with | none := do t ← infer_type pr, assertv h t pr | some t := assertv h t pr end meta def destruct (e : expr) : smt_tactic unit := smt_tactic.seq (tactic.destruct e) smt_tactic.intros meta def by_cases (e : expr) : smt_tactic unit := do c ← classical, if c then destruct (expr.app (expr.const `classical.em []) e) else do dec_e ← (mk_app `decidable [e] <|> fail "by_cases smt_tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases smt_tactic failed, type of given expression is not decidable"), em ← mk_app `decidable.em [e, inst], destruct em meta def by_contradiction : smt_tactic unit := do t ← target, c ← classical, if t.is_false then skip else if c then do apply (expr.app (expr.const `classical.by_contradiction []) t), intros else do dec_t ← (mk_app `decidable [t] <|> fail "by_contradiction smt_tactic failed, target is not a proposition"), inst ← (mk_instance dec_t <|> fail "by_contradiction smt_tactic failed, target is not decidable"), a ← mk_mapp `decidable.by_contradiction [some t, some inst], apply a, intros /- Return a proof for e, if 'e' is a known fact in the main goal. -/ meta def proof_for (e : expr) : smt_tactic expr := do cc ← to_cc_state, cc.proof_for e /- Return a refutation for e (i.e., a proof for (not e)), if 'e' has been refuted in the main goal. -/ meta def refutation_for (e : expr) : smt_tactic expr := do cc ← to_cc_state, cc.refutation_for e meta def get_facts : smt_tactic (list expr) := do cc ← to_cc_state, return $ cc.eqc_of expr.mk_true meta def get_refuted_facts : smt_tactic (list expr) := do cc ← to_cc_state, return $ cc.eqc_of expr.mk_false meta def add_ematch_lemma : expr → smt_tactic unit := add_ematch_lemma_core reducible ff meta def add_ematch_lhs_lemma : expr → smt_tactic unit := add_ematch_lemma_core reducible tt meta def add_ematch_lemma_from_decl : name → smt_tactic unit := add_ematch_lemma_from_decl_core reducible ff meta def add_ematch_lhs_lemma_from_decl : name → smt_tactic unit := add_ematch_lemma_from_decl_core reducible ff meta def add_ematch_eqn_lemmas_for : name → smt_tactic unit := add_ematch_eqn_lemmas_for_core reducible meta def add_lemmas_from_facts_core : list expr → smt_tactic unit | [] := return () | (f::fs) := do try (is_prop f >> guard (f.is_pi && bnot (f.is_arrow)) >> proof_for f >>= add_ematch_lemma_core reducible ff), add_lemmas_from_facts_core fs meta def add_lemmas_from_facts : smt_tactic unit := get_facts >>= add_lemmas_from_facts_core meta def induction (e : expr) (ids : list name := []) (rec : option name := none) : smt_tactic unit := slift (tactic.induction e ids rec >> return ()) -- pass on the information? meta def when (c : Prop) [decidable c] (tac : smt_tactic unit) : smt_tactic unit := if c then tac else skip meta def when_tracing (n : name) (tac : smt_tactic unit) : smt_tactic unit := when (is_trace_enabled_for n = tt) tac end smt_tactic open smt_tactic meta def using_smt {α} (t : smt_tactic α) (cfg : smt_config := {}) : tactic α := do ss ← smt_state.mk cfg, (a, _) ← (do a ← t, repeat close, return a) ss, return a meta def using_smt_with {α} (cfg : smt_config) (t : smt_tactic α) : tactic α := using_smt t cfg
7602297153c982b02efb77448ef063569b0e7f99
82e44445c70db0f03e30d7be725775f122d72f3e
/src/category_theory/subobject/lattice.lean
f56923aeb54e82b92f89c4f478fc857077b29c38
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
22,481
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Scott Morrison -/ import category_theory.subobject.factor_thru import category_theory.subobject.well_powered /-! # The lattice of subobjects We provide the `semilattice_inf_top (subobject X)` instance when `[has_pullback C]`, and the `semilattice_sup (subobject X)` instance when `[has_images C] [has_binary_coproducts C]`. -/ universes v₁ v₂ u₁ u₂ noncomputable theory open category_theory category_theory.category category_theory.limits variables {C : Type u₁} [category.{v₁} C] {X Y Z : C} variables {D : Type u₂} [category.{v₂} D] namespace category_theory namespace mono_over section has_top instance {X : C} : has_top (mono_over X) := { top := mk' (𝟙 _) } instance {X : C} : inhabited (mono_over X) := ⟨⊤⟩ /-- The morphism to the top object in `mono_over X`. -/ def le_top (f : mono_over X) : f ⟶ ⊤ := hom_mk f.arrow (comp_id _) @[simp] lemma top_left (X : C) : ((⊤ : mono_over X) : C) = X := rfl @[simp] lemma top_arrow (X : C) : (⊤ : mono_over X).arrow = 𝟙 X := rfl /-- `map f` sends `⊤ : mono_over X` to `⟨X, f⟩ : mono_over Y`. -/ def map_top (f : X ⟶ Y) [mono f] : (map f).obj ⊤ ≅ mk' f := iso_of_both_ways (hom_mk (𝟙 _) rfl) (hom_mk (𝟙 _) (by simp [id_comp f])) section variable [has_pullbacks C] /-- The pullback of the top object in `mono_over Y` is (isomorphic to) the top object in `mono_over X`. -/ def pullback_top (f : X ⟶ Y) : (pullback f).obj ⊤ ≅ ⊤ := iso_of_both_ways (le_top _) (hom_mk (pullback.lift f (𝟙 _) (by tidy)) (pullback.lift_snd _ _ _)) /-- There is a morphism from `⊤ : mono_over A` to the pullback of a monomorphism along itself; as the category is thin this is an isomorphism. -/ def top_le_pullback_self {A B : C} (f : A ⟶ B) [mono f] : (⊤ : mono_over A) ⟶ (pullback f).obj (mk' f) := hom_mk _ (pullback.lift_snd _ _ rfl) /-- The pullback of a monomorphism along itself is isomorphic to the top object. -/ def pullback_self {A B : C} (f : A ⟶ B) [mono f] : (pullback f).obj (mk' f) ≅ ⊤ := iso_of_both_ways (le_top _) (top_le_pullback_self _) end end has_top section has_bot variables [has_initial C] [initial_mono_class C] instance {X : C} : has_bot (mono_over X) := { bot := mk' (initial.to X) } @[simp] lemma bot_left (X : C) : ((⊥ : mono_over X) : C) = ⊥_ C := rfl @[simp] lemma bot_arrow {X : C} : (⊥ : mono_over X).arrow = initial.to X := rfl /-- The (unique) morphism from `⊥ : mono_over X` to any other `f : mono_over X`. -/ def bot_le {X : C} (f : mono_over X) : ⊥ ⟶ f := hom_mk (initial.to _) (by simp) /-- `map f` sends `⊥ : mono_over X` to `⊥ : mono_over Y`. -/ def map_bot (f : X ⟶ Y) [mono f] : (map f).obj ⊥ ≅ ⊥ := iso_of_both_ways (hom_mk (initial.to _) (by simp)) (hom_mk (𝟙 _) (by simp)) end has_bot section zero_order_bot variables [has_zero_object C] open_locale zero_object /-- The object underlying `⊥ : subobject B` is (up to isomorphism) the zero object. -/ def bot_coe_iso_zero {B : C} : ((⊥ : mono_over B) : C) ≅ 0 := initial_is_initial.unique_up_to_iso has_zero_object.zero_is_initial @[simp] lemma bot_arrow_eq_zero [has_zero_morphisms C] {B : C} : (⊥ : mono_over B).arrow = 0 := zero_of_source_iso_zero _ bot_coe_iso_zero end zero_order_bot section inf variables [has_pullbacks C] /-- When `[has_pullbacks C]`, `mono_over A` has "intersections", functorial in both arguments. As `mono_over A` is only a preorder, this doesn't satisfy the axioms of `semilattice_inf`, but we reuse all the names from `semilattice_inf` because they will be used to construct `semilattice_inf (subobject A)` shortly. -/ @[simps] def inf {A : C} : mono_over A ⥤ mono_over A ⥤ mono_over A := { obj := λ f, pullback f.arrow ⋙ map f.arrow, map := λ f₁ f₂ k, { app := λ g, begin apply hom_mk _ _, apply pullback.lift pullback.fst (pullback.snd ≫ k.left) _, rw [pullback.condition, assoc, w k], dsimp, rw [pullback.lift_snd_assoc, assoc, w k], end } }. /-- A morphism from the "infimum" of two objects in `mono_over A` to the first object. -/ def inf_le_left {A : C} (f g : mono_over A) : (inf.obj f).obj g ⟶ f := hom_mk _ rfl /-- A morphism from the "infimum" of two objects in `mono_over A` to the second object. -/ def inf_le_right {A : C} (f g : mono_over A) : (inf.obj f).obj g ⟶ g := hom_mk _ pullback.condition /-- A morphism version of the `le_inf` axiom. -/ def le_inf {A : C} (f g h : mono_over A) : (h ⟶ f) → (h ⟶ g) → (h ⟶ (inf.obj f).obj g) := begin intros k₁ k₂, refine hom_mk (pullback.lift k₂.left k₁.left _) _, rw [w k₁, w k₂], erw [pullback.lift_snd_assoc, w k₁], end end inf section sup variables [has_images C] [has_binary_coproducts C] /-- When `[has_images C] [has_binary_coproducts C]`, `mono_over A` has a `sup` construction, which is functorial in both arguments, and which on `subobject A` will induce a `semilattice_sup`. -/ def sup {A : C} : mono_over A ⥤ mono_over A ⥤ mono_over A := curry_obj ((forget A).prod (forget A) ⋙ uncurry.obj over.coprod ⋙ image) /-- A morphism version of `le_sup_left`. -/ def le_sup_left {A : C} (f g : mono_over A) : f ⟶ (sup.obj f).obj g := begin refine hom_mk (coprod.inl ≫ factor_thru_image _) _, erw [category.assoc, image.fac, coprod.inl_desc], refl, end /-- A morphism version of `le_sup_right`. -/ def le_sup_right {A : C} (f g : mono_over A) : g ⟶ (sup.obj f).obj g := begin refine hom_mk (coprod.inr ≫ factor_thru_image _) _, erw [category.assoc, image.fac, coprod.inr_desc], refl, end /-- A morphism version of `sup_le`. -/ def sup_le {A : C} (f g h : mono_over A) : (f ⟶ h) → (g ⟶ h) → ((sup.obj f).obj g ⟶ h) := begin intros k₁ k₂, refine hom_mk _ _, apply image.lift ⟨_, h.arrow, coprod.desc k₁.left k₂.left, _⟩, { dsimp, ext1, { simp [w k₁] }, { simp [w k₂] } }, { apply image.lift_fac } end end sup end mono_over namespace subobject section order_top instance order_top {X : C} : order_top (subobject X) := { top := quotient.mk' ⊤, le_top := begin refine quotient.ind' (λ f, _), exact ⟨mono_over.le_top f⟩, end, ..subobject.partial_order X} instance {X : C} : inhabited (subobject X) := ⟨⊤⟩ lemma top_eq_id (B : C) : (⊤ : subobject B) = subobject.mk (𝟙 B) := rfl lemma underlying_iso_top_hom {B : C} : (underlying_iso (𝟙 B)).hom = (⊤ : subobject B).arrow := by { convert underlying_iso_hom_comp_eq_mk (𝟙 B), simp only [comp_id], } instance top_arrow_is_iso {B : C} : is_iso ((⊤ : subobject B).arrow) := by { rw ←underlying_iso_top_hom, apply_instance, } @[simp, reassoc] lemma underlying_iso_inv_top_arrow {B : C} : (underlying_iso _).inv ≫ (⊤ : subobject B).arrow = 𝟙 B := underlying_iso_arrow _ @[simp] lemma map_top (f : X ⟶ Y) [mono f] : (map f).obj ⊤ = subobject.mk f := quotient.sound' ⟨mono_over.map_top f⟩ lemma top_factors {A B : C} (f : A ⟶ B) : (⊤ : subobject B).factors f := ⟨f, comp_id _⟩ lemma is_iso_iff_mk_eq_top {X Y : C} (f : X ⟶ Y) [mono f] : is_iso f ↔ mk f = ⊤ := ⟨λ _, by exactI mk_eq_mk_of_comm _ _ (as_iso f) (category.comp_id _), λ h, by { rw [←of_mk_le_mk_comp h.le, category.comp_id], exact is_iso.of_iso (iso_of_mk_eq_mk _ _ h) }⟩ lemma is_iso_arrow_iff_eq_top {Y : C} (P : subobject Y) : is_iso P.arrow ↔ P = ⊤ := by rw [is_iso_iff_mk_eq_top, mk_arrow] instance is_iso_top_arrow {Y : C} : is_iso (⊤ : subobject Y).arrow := by rw is_iso_arrow_iff_eq_top lemma mk_eq_top_of_is_iso {X Y : C} (f : X ⟶ Y) [is_iso f] : mk f = ⊤ := (is_iso_iff_mk_eq_top f).mp infer_instance lemma eq_top_of_is_iso_arrow {Y : C} (P : subobject Y) [is_iso P.arrow] : P = ⊤ := (is_iso_arrow_iff_eq_top P).mp infer_instance section variables [has_pullbacks C] lemma pullback_top (f : X ⟶ Y) : (pullback f).obj ⊤ = ⊤ := quotient.sound' ⟨mono_over.pullback_top f⟩ lemma pullback_self {A B : C} (f : A ⟶ B) [mono f] : (pullback f).obj (mk f) = ⊤ := quotient.sound' ⟨mono_over.pullback_self f⟩ end end order_top section order_bot variables [has_initial C] [initial_mono_class C] instance order_bot {X : C} : order_bot (subobject X) := { bot := quotient.mk' ⊥, bot_le := begin refine quotient.ind' (λ f, _), exact ⟨mono_over.bot_le f⟩, end, ..subobject.partial_order X } lemma bot_eq_initial_to {B : C} : (⊥ : subobject B) = subobject.mk (initial.to B) := rfl /-- The object underlying `⊥ : subobject B` is (up to isomorphism) the initial object. -/ def bot_coe_iso_initial {B : C} : ((⊥ : subobject B) : C) ≅ ⊥_ C := underlying_iso _ lemma map_bot (f : X ⟶ Y) [mono f] : (map f).obj ⊥ = ⊥ := quotient.sound' ⟨mono_over.map_bot f⟩ end order_bot section zero_order_bot variables [has_zero_object C] open_locale zero_object /-- The object underlying `⊥ : subobject B` is (up to isomorphism) the zero object. -/ def bot_coe_iso_zero {B : C} : ((⊥ : subobject B) : C) ≅ 0 := bot_coe_iso_initial ≪≫ initial_is_initial.unique_up_to_iso has_zero_object.zero_is_initial variables [has_zero_morphisms C] lemma bot_eq_zero {B : C} : (⊥ : subobject B) = subobject.mk (0 : 0 ⟶ B) := mk_eq_mk_of_comm _ _ (initial_is_initial.unique_up_to_iso has_zero_object.zero_is_initial) (by simp) @[simp] lemma bot_arrow {B : C} : (⊥ : subobject B).arrow = 0 := zero_of_source_iso_zero _ bot_coe_iso_zero lemma bot_factors_iff_zero {A B : C} (f : A ⟶ B) : (⊥ : subobject B).factors f ↔ f = 0 := ⟨by { rintro ⟨h, rfl⟩, simp }, by { rintro rfl, exact ⟨0, by simp⟩, }⟩ end zero_order_bot section functor variable (C) /-- Sending `X : C` to `subobject X` is a contravariant functor `Cᵒᵖ ⥤ Type`. -/ @[simps] def functor [has_pullbacks C] : Cᵒᵖ ⥤ Type (max u₁ v₁) := { obj := λ X, subobject X.unop, map := λ X Y f, (pullback f.unop).obj, map_id' := λ X, funext pullback_id, map_comp' := λ X Y Z f g, funext (pullback_comp _ _) } end functor section semilattice_inf_top variables [has_pullbacks C] /-- The functorial infimum on `mono_over A` descends to an infimum on `subobject A`. -/ def inf {A : C} : subobject A ⥤ subobject A ⥤ subobject A := thin_skeleton.map₂ mono_over.inf lemma inf_le_left {A : C} (f g : subobject A) : (inf.obj f).obj g ≤ f := quotient.induction_on₂' f g (λ a b, ⟨mono_over.inf_le_left _ _⟩) lemma inf_le_right {A : C} (f g : subobject A) : (inf.obj f).obj g ≤ g := quotient.induction_on₂' f g (λ a b, ⟨mono_over.inf_le_right _ _⟩) lemma le_inf {A : C} (h f g : subobject A) : h ≤ f → h ≤ g → h ≤ (inf.obj f).obj g := quotient.induction_on₃' h f g begin rintros f g h ⟨k⟩ ⟨l⟩, exact ⟨mono_over.le_inf _ _ _ k l⟩, end instance {B : C} : semilattice_inf_top (subobject B) := { inf := λ m n, (inf.obj m).obj n, inf_le_left := inf_le_left, inf_le_right := inf_le_right, le_inf := le_inf, ..subobject.order_top } lemma factors_left_of_inf_factors {A B : C} {X Y : subobject B} {f : A ⟶ B} (h : (X ⊓ Y).factors f) : X.factors f := factors_of_le _ (inf_le_left _ _) h lemma factors_right_of_inf_factors {A B : C} {X Y : subobject B} {f : A ⟶ B} (h : (X ⊓ Y).factors f) : Y.factors f := factors_of_le _ (inf_le_right _ _) h @[simp] lemma inf_factors {A B : C} {X Y : subobject B} (f : A ⟶ B) : (X ⊓ Y).factors f ↔ X.factors f ∧ Y.factors f := ⟨λ h, ⟨factors_left_of_inf_factors h, factors_right_of_inf_factors h⟩, begin revert X Y, refine quotient.ind₂' _, rintro X Y ⟨⟨g₁, rfl⟩, ⟨g₂, hg₂⟩⟩, exact ⟨_, pullback.lift_snd_assoc _ _ hg₂ _⟩, end⟩ lemma inf_arrow_factors_left {B : C} (X Y : subobject B) : X.factors (X ⊓ Y).arrow := (factors_iff _ _).mpr ⟨of_le (X ⊓ Y) X (inf_le_left X Y), by simp⟩ lemma inf_arrow_factors_right {B : C} (X Y : subobject B) : Y.factors (X ⊓ Y).arrow := (factors_iff _ _).mpr ⟨of_le (X ⊓ Y) Y (inf_le_right X Y), by simp⟩ @[simp] lemma finset_inf_factors {I : Type*} {A B : C} {s : finset I} {P : I → subobject B} (f : A ⟶ B) : (s.inf P).factors f ↔ ∀ i ∈ s, (P i).factors f := begin classical, apply finset.induction_on s, { simp [top_factors] }, { intros i s nm ih, simp [ih] }, end -- `i` is explicit here because often we'd like to defer a proof of `m` lemma finset_inf_arrow_factors {I : Type*} {B : C} (s : finset I) (P : I → subobject B) (i : I) (m : i ∈ s) : (P i).factors (s.inf P).arrow := begin revert i m, classical, apply finset.induction_on s, { rintro _ ⟨⟩, }, { intros i s nm ih j m, rw [finset.inf_insert], simp only [finset.mem_insert] at m, rcases m with (rfl|m), { rw ←factor_thru_arrow _ _ (inf_arrow_factors_left _ _), exact factors_comp_arrow _, }, { rw ←factor_thru_arrow _ _ (inf_arrow_factors_right _ _), apply factors_of_factors_right, exact ih _ m, } }, end lemma inf_eq_map_pullback' {A : C} (f₁ : mono_over A) (f₂ : subobject A) : (subobject.inf.obj (quotient.mk' f₁)).obj f₂ = (subobject.map f₁.arrow).obj ((subobject.pullback f₁.arrow).obj f₂) := begin apply quotient.induction_on' f₂, intro f₂, refl, end lemma inf_eq_map_pullback {A : C} (f₁ : mono_over A) (f₂ : subobject A) : (quotient.mk' f₁ ⊓ f₂ : subobject A) = (map f₁.arrow).obj ((pullback f₁.arrow).obj f₂) := inf_eq_map_pullback' f₁ f₂ lemma prod_eq_inf {A : C} {f₁ f₂ : subobject A} [has_binary_product f₁ f₂] : (f₁ ⨯ f₂) = f₁ ⊓ f₂ := le_antisymm (_root_.le_inf (limits.prod.fst).le (limits.prod.snd).le) ((prod.lift (_root_.inf_le_left.hom) (_root_.inf_le_right.hom))).le lemma inf_def {B : C} (m m' : subobject B) : m ⊓ m' = (inf.obj m).obj m' := rfl /-- `⊓` commutes with pullback. -/ lemma inf_pullback {X Y : C} (g : X ⟶ Y) (f₁ f₂) : (pullback g).obj (f₁ ⊓ f₂) = (pullback g).obj f₁ ⊓ (pullback g).obj f₂ := begin revert f₁, apply quotient.ind', intro f₁, erw [inf_def, inf_def, inf_eq_map_pullback', inf_eq_map_pullback', ← pullback_comp, ← map_pullback pullback.condition (pullback_is_pullback f₁.arrow g), ← pullback_comp, pullback.condition], refl, end /-- `⊓` commutes with map. -/ lemma inf_map {X Y : C} (g : Y ⟶ X) [mono g] (f₁ f₂) : (map g).obj (f₁ ⊓ f₂) = (map g).obj f₁ ⊓ (map g).obj f₂ := begin revert f₁, apply quotient.ind', intro f₁, erw [inf_def, inf_def, inf_eq_map_pullback', inf_eq_map_pullback', ← map_comp], dsimp, rw [pullback_comp, pullback_map_self], end end semilattice_inf_top section semilattice_sup variables [has_images C] [has_binary_coproducts C] /-- The functorial supremum on `mono_over A` descends to an supremum on `subobject A`. -/ def sup {A : C} : subobject A ⥤ subobject A ⥤ subobject A := thin_skeleton.map₂ mono_over.sup instance {B : C} : semilattice_sup (subobject B) := { sup := λ m n, (sup.obj m).obj n, le_sup_left := λ m n, quotient.induction_on₂' m n (λ a b, ⟨mono_over.le_sup_left _ _⟩), le_sup_right := λ m n, quotient.induction_on₂' m n (λ a b, ⟨mono_over.le_sup_right _ _⟩), sup_le := λ m n k, quotient.induction_on₃' m n k (λ a b c ⟨i⟩ ⟨j⟩, ⟨mono_over.sup_le _ _ _ i j⟩), ..subobject.partial_order B } lemma sup_factors_of_factors_left {A B : C} {X Y : subobject B} {f : A ⟶ B} (P : X.factors f) : (X ⊔ Y).factors f := factors_of_le f le_sup_left P lemma sup_factors_of_factors_right {A B : C} {X Y : subobject B} {f : A ⟶ B} (P : Y.factors f) : (X ⊔ Y).factors f := factors_of_le f le_sup_right P variables [has_initial C] [initial_mono_class C] instance {B : C} : semilattice_sup_bot (subobject B) := { ..subobject.order_bot, ..subobject.semilattice_sup } lemma finset_sup_factors {I : Type*} {A B : C} {s : finset I} {P : I → subobject B} {f : A ⟶ B} (h : ∃ i ∈ s, (P i).factors f) : (s.sup P).factors f := begin classical, revert h, apply finset.induction_on s, { rintro ⟨_, ⟨⟨⟩, _⟩⟩, }, { rintros i s nm ih ⟨j, ⟨m, h⟩⟩, simp only [finset.sup_insert], simp at m, rcases m with (rfl|m), { exact sup_factors_of_factors_left h, }, { exact sup_factors_of_factors_right (ih ⟨j, ⟨m, h⟩⟩), }, }, end end semilattice_sup section lattice variables [has_pullbacks C] [has_images C] [has_binary_coproducts C] instance {B : C} : lattice (subobject B) := { ..subobject.semilattice_inf_top, ..subobject.semilattice_sup } variables [has_initial C] [initial_mono_class C] instance {B : C} : bounded_lattice (subobject B) := { ..subobject.semilattice_inf_top, ..subobject.semilattice_sup_bot } end lattice section Inf variables [well_powered C] /-- The "wide cospan" diagram, with a small indexing type, constructed from a set of subobjects. (This is just the diagram of all the subobjects pasted together, but using `well_powered C` to make the diagram small.) -/ def wide_cospan {A : C} (s : set (subobject A)) : wide_pullback_shape (equiv_shrink _ '' s) ⥤ C := wide_pullback_shape.wide_cospan A (λ j : equiv_shrink _ '' s, (((equiv_shrink (subobject A)).symm j) : C)) (λ j, ((equiv_shrink (subobject A)).symm j).arrow) @[simp] lemma wide_cospan_map_term {A : C} (s : set (subobject A)) (j) : (wide_cospan s).map (wide_pullback_shape.hom.term j) = ((equiv_shrink (subobject A)).symm j).arrow := rfl /-- Auxiliary construction of a cone for `le_Inf`. -/ def le_Inf_cone {A : C} (s : set (subobject A)) (f : subobject A) (k : Π (g ∈ s), f ≤ g) : cone (wide_cospan s) := wide_pullback_shape.mk_cone f.arrow (λ j, underlying.map (hom_of_le (k _ (by { rcases j with ⟨-, ⟨g, ⟨m, rfl⟩⟩⟩, simpa using m, })))) (by tidy) @[simp] lemma le_Inf_cone_π_app_none {A : C} (s : set (subobject A)) (f : subobject A) (k : Π (g ∈ s), f ≤ g) : (le_Inf_cone s f k).π.app none = f.arrow := rfl variables [has_wide_pullbacks C] /-- The limit of `wide_cospan s`. (This will be the supremum of the set of subobjects.) -/ def wide_pullback {A : C} (s : set (subobject A)) : C := limits.limit (wide_cospan s) /-- The inclusion map from `wide_pullback s` to `A` -/ def wide_pullback_ι {A : C} (s : set (subobject A)) : wide_pullback s ⟶ A := limits.limit.π (wide_cospan s) none instance wide_pullback_ι_mono {A : C} (s : set (subobject A)) : mono (wide_pullback_ι s) := ⟨λ W u v h, limit.hom_ext (λ j, begin cases j, { exact h, }, { apply (cancel_mono ((equiv_shrink (subobject A)).symm j).arrow).1, rw [assoc, assoc], erw limit.w (wide_cospan s) (wide_pullback_shape.hom.term j), exact h, }, end)⟩ /-- When `[well_powered C]` and `[has_wide_pullbacks C]`, `subobject A` has arbitrary infimums. -/ def Inf {A : C} (s : set (subobject A)) : subobject A := subobject.mk (wide_pullback_ι s) lemma Inf_le {A : C} (s : set (subobject A)) (f ∈ s) : Inf s ≤ f := begin fapply le_of_comm, { refine (underlying_iso _).hom ≫ (limits.limit.π (wide_cospan s) (some ⟨equiv_shrink _ f, set.mem_image_of_mem (equiv_shrink (subobject A)) H⟩)) ≫ _, apply eq_to_hom, apply (congr_arg (λ X : subobject A, (X : C))), exact (equiv.symm_apply_apply _ _), }, { dsimp [Inf], simp only [category.comp_id, category.assoc, ←underlying_iso_hom_comp_eq_mk, subobject.arrow_congr, congr_arg_mpr_hom_left, iso.cancel_iso_hom_left], convert limit.w (wide_cospan s) (wide_pullback_shape.hom.term _), }, end. lemma le_Inf {A : C} (s : set (subobject A)) (f : subobject A) (k : Π (g ∈ s), f ≤ g) : f ≤ Inf s := begin fapply le_of_comm, { exact limits.limit.lift _ (le_Inf_cone s f k) ≫ (underlying_iso _).inv, }, { dsimp [Inf, wide_pullback_ι], simp, }, end instance {B : C} : complete_semilattice_Inf (subobject B) := { Inf := Inf, Inf_le := Inf_le, le_Inf := le_Inf, ..subobject.partial_order B } end Inf section Sup variables [well_powered C] [has_coproducts C] /-- The univesal morphism out of the coproduct of a set of subobjects, after using `[well_powered C]` to reindex by a small type. -/ def small_coproduct_desc {A : C} (s : set (subobject A)) : _ ⟶ A := limits.sigma.desc (λ j : equiv_shrink _ '' s, ((equiv_shrink (subobject A)).symm j).arrow) variables [has_images C] /-- When `[well_powered C] [has_images C] [has_coproducts C]`, `subobject A` has arbitrary supremums. -/ def Sup {A : C} (s : set (subobject A)) : subobject A := subobject.mk (image.ι (small_coproduct_desc s)) lemma le_Sup {A : C} (s : set (subobject A)) (f ∈ s) : f ≤ Sup s := begin fapply le_of_comm, { dsimp [Sup], refine _ ≫ factor_thru_image _ ≫ (underlying_iso _).inv, refine _ ≫ sigma.ι _ ⟨equiv_shrink _ f, (by simpa [set.mem_image] using H)⟩, exact eq_to_hom (congr_arg (λ X : subobject A, (X : C)) (equiv.symm_apply_apply _ _).symm), }, { dsimp [Sup, small_coproduct_desc], simp, dsimp, simp, }, end lemma symm_apply_mem_iff_mem_image {α β : Type*} (e : α ≃ β) (s : set α) (x : β) : e.symm x ∈ s ↔ x ∈ e '' s := ⟨λ h, ⟨e.symm x, h, by simp⟩, by { rintro ⟨a, m, rfl⟩, simpa using m, }⟩ lemma Sup_le {A : C} (s : set (subobject A)) (f : subobject A) (k : Π (g ∈ s), g ≤ f) : Sup s ≤ f := begin fapply le_of_comm, { dsimp [Sup], refine (underlying_iso _).hom ≫ image.lift ⟨_, f.arrow, _, _⟩, { refine sigma.desc _, rintro ⟨g, m⟩, refine underlying.map (hom_of_le (k _ _)), simpa [symm_apply_mem_iff_mem_image] using m, }, { ext j, rcases j with ⟨j, m⟩, dsimp [small_coproduct_desc], simp, dsimp, simp, }, }, { dsimp [Sup], simp, }, end instance {B : C} : complete_semilattice_Sup (subobject B) := { Sup := Sup, le_Sup := le_Sup, Sup_le := Sup_le, ..subobject.partial_order B } end Sup section complete_lattice variables [well_powered C] [has_wide_pullbacks C] [has_images C] [has_coproducts C] [initial_mono_class C] instance {B : C} : complete_lattice (subobject B) := { ..subobject.semilattice_inf_top, ..subobject.semilattice_sup_bot, ..subobject.complete_semilattice_Inf, ..subobject.complete_semilattice_Sup, } end complete_lattice end subobject end category_theory
b9b99dc49302a61bf18defa3535e666ef3b45eb1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/lie/semisimple.lean
d76852391a9c73700e4e42fd9b7175b82d160a9e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,593
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.solvable /-! # Semisimple Lie algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The famous Cartan-Dynkin-Killing classification of semisimple Lie algebras renders them one of the most important classes of Lie algebras. In this file we define simple and semisimple Lie algebras and prove some basic related results. ## Main definitions * `lie_module.is_irreducible` * `lie_algebra.is_simple` * `lie_algebra.is_semisimple` * `lie_algebra.is_semisimple_iff_no_solvable_ideals` * `lie_algebra.is_semisimple_iff_no_abelian_ideals` * `lie_algebra.abelian_radical_iff_solvable_is_abelian` ## Tags lie algebra, radical, simple, semisimple -/ universes u v w w₁ w₂ /-- A Lie module is irreducible if it is zero or its only non-trivial Lie submodule is itself. -/ class lie_module.is_irreducible (R : Type u) (L : Type v) (M : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] : Prop := (irreducible : ∀ (N : lie_submodule R L M), N ≠ ⊥ → N = ⊤) namespace lie_algebra variables (R : Type u) (L : Type v) variables [comm_ring R] [lie_ring L] [lie_algebra R L] /-- A Lie algebra is simple if it is irreducible as a Lie module over itself via the adjoint action, and it is non-Abelian. -/ class is_simple extends lie_module.is_irreducible R L L : Prop := (non_abelian : ¬is_lie_abelian L) /-- A semisimple Lie algebra is one with trivial radical. Note that the label 'semisimple' is apparently not universally agreed [upon](https://mathoverflow.net/questions/149391/on-radicals-of-a-lie-algebra#comment383669_149391) for general coefficients. We are following [Seligman, page 15](seligman1967) and using the label for the weakest of the various properties which are all equivalent over a field of characteristic zero. -/ class is_semisimple : Prop := (semisimple : radical R L = ⊥) lemma is_semisimple_iff_no_solvable_ideals : is_semisimple R L ↔ ∀ (I : lie_ideal R L), is_solvable R I → I = ⊥ := ⟨λ h, Sup_eq_bot.mp h.semisimple, λ h, ⟨Sup_eq_bot.mpr h⟩⟩ lemma is_semisimple_iff_no_abelian_ideals : is_semisimple R L ↔ ∀ (I : lie_ideal R L), is_lie_abelian I → I = ⊥ := begin rw is_semisimple_iff_no_solvable_ideals, split; intros h₁ I h₂, { haveI : is_lie_abelian I := h₂, apply h₁, exact lie_algebra.of_abelian_is_solvable R I, }, { haveI : is_solvable R I := h₂, rw ← abelian_of_solvable_ideal_eq_bot_iff, apply h₁, exact abelian_derived_abelian_of_ideal I, }, end @[simp] lemma center_eq_bot_of_semisimple [h : is_semisimple R L] : center R L = ⊥ := by { rw is_semisimple_iff_no_abelian_ideals at h, apply h, apply_instance, } /-- A simple Lie algebra is semisimple. -/ @[priority 100] instance is_semisimple_of_is_simple [h : is_simple R L] : is_semisimple R L := begin rw is_semisimple_iff_no_abelian_ideals, intros I hI, obtain @⟨⟨h₁⟩, h₂⟩ := id h, by_contradiction contra, rw [h₁ I contra, lie_abelian_iff_equiv_lie_abelian lie_ideal.top_equiv] at hI, exact h₂ hI, end /-- A semisimple Abelian Lie algebra is trivial. -/ lemma subsingleton_of_semisimple_lie_abelian [is_semisimple R L] [h : is_lie_abelian L] : subsingleton L := begin rw [is_lie_abelian_iff_center_eq_top R L, center_eq_bot_of_semisimple] at h, exact (lie_submodule.subsingleton_iff R L L).mp (subsingleton_of_bot_eq_top h), end lemma abelian_radical_of_semisimple [is_semisimple R L] : is_lie_abelian (radical R L) := by { rw is_semisimple.semisimple, exact is_lie_abelian_bot R L, } /-- The two properties shown to be equivalent here are possible definitions for a Lie algebra to be reductive. Note that there is absolutely [no agreement](https://mathoverflow.net/questions/284713/) on what the label 'reductive' should mean when the coefficients are not a field of characteristic zero. -/ lemma abelian_radical_iff_solvable_is_abelian [is_noetherian R L] : is_lie_abelian (radical R L) ↔ ∀ (I : lie_ideal R L), is_solvable R I → is_lie_abelian I := begin split, { rintros h₁ I h₂, rw lie_ideal.solvable_iff_le_radical at h₂, exact (lie_ideal.hom_of_le_injective h₂).is_lie_abelian h₁, }, { intros h, apply h, apply_instance, }, end lemma ad_ker_eq_bot_of_semisimple [is_semisimple R L] : (ad R L).ker = ⊥ := by simp end lie_algebra
c68ce65e1b807730536f049d38180a82be7fd253
65807aed539a1b7077e26f006d2ee5724004fd5d
/src/chap1.lean
fcfc712326e4e65aab5e58a2a106372f9081d6d3
[]
no_license
b-mehta/generating-functions
d6c00769c751b3c4e5fd681a33fbcba43ab9243a
2fc00b2ba7ed92d1e24682124cac146d23b47f92
refs/heads/master
1,671,586,110,726
1,601,063,036,000
1,601,063,036,000
296,391,458
0
0
null
null
null
null
UTF-8
Lean
false
false
9,779
lean
import ring_theory.power_series import combinatorics.composition import data.nat.parity open power_series noncomputable theory variables {α : Type*} /-- The sequence from section 1.1 of GFology -/ def sequence_one_one : ℕ → ℚ | 0 := 0 | (n+1) := 2 * sequence_one_one n + 1 /-- Inductive proof of the formula -/ lemma inductive_proof : ∀ n, sequence_one_one n = 2^n - 1 | 0 := rfl | (n+1) := begin rw [sequence_one_one, inductive_proof n, pow_succ], ring, end -- TODO: multivariate version /-- Differentiate a power series -/ def differentiate [semiring α] : power_series α →+ power_series α := { to_fun := λ f, mk (λ n, (n + 1) * coeff α (n+1) f), map_zero' := begin ext, simp, end, map_add' := λ x y, begin ext, simp [mul_add], end } @[simp] lemma coeff_differentiate [semiring α] (f : power_series α) (n : ℕ) : coeff _ n (differentiate f) = (n+1) * coeff _ (n+1) f := coeff_mk _ _ section prod_map variables {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ ↪ α₂) (g : β₁ ↪ β₂) def embedding.prod_map : (α₁ × β₁) ↪ α₂ × β₂ := { to_fun := prod.map f g, inj' := λ x y h, prod.ext (f.injective (prod.ext_iff.1 h).1) (g.injective (prod.ext_iff.1 h).2) } variables {f} {g} @[simp] def embedding.coe_prod_map : ⇑(embedding.prod_map f g) = prod.map f g := rfl end prod_map /-- Product rule -/ lemma diff_mul [comm_semiring α] (f g : power_series α) : differentiate (f * g) = differentiate f * g + f * differentiate g := begin ext, simp only [coeff_mul, add_monoid_hom.map_add, coeff_differentiate], transitivity (finset.nat.antidiagonal (n + 1)).sum (λ (p : ℕ × ℕ), (↑(p.fst)) * (coeff α (p.fst)) f * (coeff α p.snd) g) + (finset.nat.antidiagonal (n + 1)).sum (λ (p : ℕ × ℕ), (coeff α p.fst) f * ((↑(p.snd)) * (coeff α p.snd) g)), { rw ← finset.sum_add_distrib, rw finset.mul_sum, apply finset.sum_congr rfl, intros x hx, rw [← mul_assoc _ (↑x.snd) _, mul_comm ((coeff α x.fst) f) (↑x.snd), mul_assoc, mul_assoc, ← add_mul, ← nat.cast_add, finset.nat.mem_antidiagonal.1 hx], simp }, { refine congr (congr rfl _) _, { simp [finset.nat.sum_antidiagonal_succ] }, { rw [← finset.nat.map_swap_antidiagonal, finset.sum_map], symmetry, rw [← finset.nat.map_swap_antidiagonal, finset.sum_map, finset.nat.sum_antidiagonal_succ], simp } } end @[simp] lemma diff_const [semiring α] (a : α) : differentiate (C α a) = 0 := begin ext, simp [coeff_C], end @[simp] lemma diff_one [semiring α] : differentiate (1 : power_series α) = 0 := diff_const _ @[simp] lemma diff_X [semiring α] : differentiate (X : power_series α) = 1 := begin ext, cases n, { simp [-coeff_zero_eq_constant_coeff] }, have : n.succ + 1 ≠ 1, rintro ⟨⟩, simp [-coeff_zero_eq_constant_coeff, coeff_X, nat.succ_ne_zero, if_neg this], end /-- The generating function for a sequence is just the power series whose coefficients are the sequence. -/ @[reducible] def generating_function (f : ℕ → α) : power_series α := power_series.mk f -- example {α : Type*} [field α] {a b c : α} (h : a * c = b) : a = b * c⁻¹ := -- begin -- library_search, -- end @[simp] lemma constant_coeff_mk (f : ℕ → α) [semiring α] : constant_coeff _ (mk f) = f 0 := begin rw [← coeff_zero_eq_constant_coeff_apply, coeff_mk], end -- @[simp] lemma coeff_C_mul [semiring α] (n : ℕ) (φ : power_series α) (a : α) : -- coeff α n (C α a * φ) = a * coeff α n φ := -- begin -- sorry -- open PR to mathlib so sorry here -- end -- @[simp] -- lemma coeff_smul (a : α) (n : ℕ) (f : power_series α) [semiring α] : -- coeff _ n (a • f) = a * coeff _ n f := -- begin -- change coeff _ _ (C _ _ * _) = _, -- rw coeff_C_mul, -- end @[simp] lemma constant_coeff_smul (a : α) (f : power_series α) [semiring α] : constant_coeff _ (a • f) = a * constant_coeff _ f := begin change constant_coeff _ (C _ _ * _) = _, simp, end lemma eq_mul_inv_iff [field α] {a b c : power_series α} (h : constant_coeff _ c ≠ 0) : a = b * c⁻¹ ↔ a * c = b := ⟨λ k, by simp [k, mul_assoc, power_series.inv_mul _ h], λ k, by simp [← k, mul_assoc, power_series.mul_inv _ h]⟩ lemma mul_inv_eq_iff [field α] {a b c : power_series α} (h : constant_coeff _ c ≠ 0) : a * c⁻¹ = b ↔ a = b * c := ⟨λ k, by simp [← k, mul_assoc, power_series.inv_mul _ h], λ k, by simp [k, mul_assoc, power_series.mul_inv _ h]⟩ lemma diff_inv [field α] (f : power_series α) (h : constant_coeff _ f ≠ 0) : differentiate (f⁻¹) = - differentiate f * (f^2)⁻¹ := begin have : differentiate (f * f⁻¹) = 0, rw [power_series.mul_inv _ h, diff_one], rw [diff_mul, add_eq_zero_iff_neg_eq, neg_mul_eq_neg_mul, mul_inv_eq_iff h, neg_eq_iff_neg_eq] at this, rw [eq_mul_inv_iff, ← this, neg_neg, mul_comm f, pow_two, mul_assoc], rw [pow_two], simp [h], end lemma eq_inv_iff [field α] {a b : power_series α} (h : constant_coeff _ b ≠ 0) : a = b⁻¹ ↔ a * b = 1 := by rw [← eq_mul_inv_iff h, one_mul] lemma power_series.inv_eq_iff [field α] {a b : power_series α} (h : constant_coeff _ b ≠ 0) : b⁻¹ = a ↔ a * b = 1 := by rw [eq_comm, eq_inv_iff h] -- lemma big_geom (q : ℚ) : generating_function (λ n, q ^ n) = (1 - q • X)⁻¹ := -- begin -- rw eq_inv_iff, -- { rw [mul_sub, mul_one], -- ext, -- cases n, -- simp, -- simp [if_neg n.succ_ne_zero, coeff_smul, pow_succ] }, -- { simp }, -- end -- @[simp] -- lemma big_geom' (n : ℕ) (q : ℚ) : coeff _ n (1 - q • X)⁻¹ = q ^ n := -- begin -- rw [← big_geom, generating_function, coeff_mk], -- end -- lemma basic_geom : generating_function (λ n, (1 : ℚ)) = (1 - X)⁻¹ := -- by simpa using big_geom 1 -- @[simp] -- lemma basic_geom' (n : ℕ) : coeff ℚ n (1 - X)⁻¹ = 1 := -- by simpa using big_geom' n 1 -- lemma basic_arith_geom : generating_function (λ n, (n + 1 : ℚ)) = ((1 - X)^2)⁻¹ := -- calc generating_function (λ n, (n + 1 : ℚ)) -- = differentiate (generating_function (λ n, (1 : ℚ))) : power_series.ext (by simp) -- ... = ((1 - X)^2)⁻¹ : by simp [basic_geom, diff_inv] -- lemma generate_of_succ (f : ℕ → ℚ) (h : f 0 = 0) : -- generating_function f = X * generating_function (λ n, f (n+1)) := -- begin -- ext, -- cases n, -- simp [h], -- rw [mul_comm X], -- simp, -- end -- lemma basic_arith_geom' : generating_function (λ n, (n : ℚ)) = X * ((1 - X)^2)⁻¹ := -- begin -- rw [generate_of_succ], -- simp [basic_arith_geom], -- simp, -- end -- lemma my_seq : -- generating_function sequence_one_one = X * (1 - X)⁻¹ * (1 - (2 : ℚ) • X)⁻¹ := -- begin -- rw [eq_mul_inv_iff, eq_mul_inv_iff, generating_function], -- { ext, -- cases n, -- { simp [sequence_one_one] }, -- cases n, -- { simp [mul_sub, sub_mul, ← mul_assoc, sequence_one_one, coeff_smul, ← sub_add], }, -- { have : ¬(n.succ.succ = 1), rintro ⟨⟩, -- simp [mul_sub, sub_mul, ← mul_assoc, coeff_X, sequence_one_one, coeff_smul, if_neg this] } }, -- { simp }, -- { simp }, -- end -- lemma gf_proof (n : ℕ) : sequence_one_one n = 2^n - 1 := -- begin -- suffices : coeff _ n (generating_function sequence_one_one) = 2^n - 1, -- simpa, -- have : (X : power_series ℚ) * (1 - X)⁻¹ * (1 - (2 : ℚ) • X)⁻¹ = X * ((2 : ℚ) • (1 - (2 : ℚ) • X)⁻¹ - (1 - X)⁻¹), -- rw [mul_inv_eq_iff, mul_assoc, sub_mul, algebra.smul_mul_assoc, power_series.inv_mul, -- mul_inv_eq_iff, mul_assoc, sub_mul, mul_comm (1 - X)⁻¹, mul_assoc, power_series.inv_mul, -- mul_one, algebra.smul_mul_assoc, one_mul, smul_sub, sub_sub_sub_cancel_right, two_smul]; -- simp, -- rw [my_seq, this], -- cases n, -- simp, -- rw mul_comm X, -- simp [mul_sub, coeff_smul, pow_succ], -- end -- /-- The sequence from section 1.2 of GFology -/ -- def sequence_one_two : ℕ → ℚ -- | 0 := 1 -- | (n+1) := 2 * sequence_one_two n + n -- lemma my_seq2 : -- generating_function sequence_one_two = (1 - (2:ℚ)•X + (2:ℚ)•X^2) * ((1 - X)^2)⁻¹ * (1 - (2:ℚ)•X)⁻¹ := -- begin -- rw [eq_mul_inv_iff, eq_mul_inv_iff], -- { ext, -- cases n, -- { simp [sequence_one_two, pow_two] }, -- cases n, -- { simp [← mul_assoc, coeff_X_pow, sequence_one_two, pow_two (1 - X), mul_sub, sub_mul], -- norm_num }, -- cases n, -- { simp [coeff_X_pow, mul_sub, sub_mul, pow_two (1 - X), sequence_one_two, ← mul_assoc, coeff_X], -- norm_num }, -- simp [pow_two (1 - X), mul_sub, sub_mul, sequence_one_two, ← mul_assoc, coeff_one_X, -- coeff_X_pow, coeff_X], -- ring }, -- { simp }, -- { simp }, -- end -- lemma gf_proof2 (n : ℕ) : sequence_one_two n = 2^(n+1) - n - 1 := -- begin -- suffices : coeff _ n (generating_function sequence_one_two) = 2^(n+1) - n - 1, -- simpa, -- have : (1 - (2:ℚ)•(X : power_series ℚ) + (2:ℚ)•X^2) * ((1-X)^2)⁻¹ * (1 - (2:ℚ)•X)⁻¹ = (2:ℚ)•(1 - (2:ℚ)•X)⁻¹ - ((1-X)^2)⁻¹, -- rw [mul_inv_eq_iff, sub_mul, algebra.smul_mul_assoc, power_series.inv_mul, -- mul_inv_eq_iff, sub_mul, mul_comm _⁻¹, mul_assoc, power_series.inv_mul], -- simp [← sub_add, sub_mul, mul_sub, two_smul], -- ring, -- simp, simp, simp, simp, -- rw [my_seq2, this], -- simp only [←basic_arith_geom, coeff_mk, coeff_smul, add_monoid_hom.map_sub, big_geom'], -- simp [sub_sub, pow_succ], -- end -- lemma inductive_proof2 : ∀ n, sequence_one_two n = 2^(n+1) - n - 1 -- | 0 := rfl -- | (n+1) := -- begin -- simp [sequence_one_two, inductive_proof2 n, pow_succ], -- ring, -- end
b8615c7a129566d63b50b64bc9ce290e991d34d8
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebraic_geometry/presheafed_space.lean
7438ac454d3b00fc8c925f4a4e2b4b41abe28dba
[]
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
12,903
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.sheaves.presheaf import Mathlib.PostPort universes v u l namespace Mathlib /-! # Presheafed spaces Introduces the category of topological spaces equipped with a presheaf (taking values in an arbitrary target category `C`.) We further describe how to apply functors and natural transformations to the values of the presheaves. -/ namespace algebraic_geometry /-- A `PresheafedSpace C` is a topological space equipped with a presheaf of `C`s. -/ structure PresheafedSpace (C : Type u) [category_theory.category C] where carrier : Top presheaf : Top.presheaf C carrier namespace PresheafedSpace protected instance coe_carrier {C : Type u} [category_theory.category C] : has_coe (PresheafedSpace C) Top := has_coe.mk fun (X : PresheafedSpace C) => carrier X @[simp] theorem as_coe {C : Type u} [category_theory.category C] (X : PresheafedSpace C) : carrier X = ↑X := rfl @[simp] theorem mk_coe {C : Type u} [category_theory.category C] (carrier : Top) (presheaf : Top.presheaf C carrier) : ↑(mk carrier presheaf) = carrier := rfl protected instance topological_space {C : Type u} [category_theory.category C] (X : PresheafedSpace C) : topological_space ↥X := category_theory.bundled.str (carrier X) /-- The constant presheaf on `X` with value `Z`. -/ def const {C : Type u} [category_theory.category C] (X : Top) (Z : C) : PresheafedSpace C := mk X (category_theory.functor.mk (fun (U : topological_space.opens ↥Xᵒᵖ) => Z) fun (U V : topological_space.opens ↥Xᵒᵖ) (f : U ⟶ V) => 𝟙) protected instance inhabited {C : Type u} [category_theory.category C] [Inhabited C] : Inhabited (PresheafedSpace C) := { default := const (Top.of pempty) Inhabited.default } /-- A morphism between presheafed spaces `X` and `Y` consists of a continuous map `f` between the underlying topological spaces, and a (notice contravariant!) map from the presheaf on `Y` to the pushforward of the presheaf on `X` via `f`. -/ structure hom {C : Type u} [category_theory.category C] (X : PresheafedSpace C) (Y : PresheafedSpace C) where base : ↑X ⟶ ↑Y c : PresheafedSpace.presheaf Y ⟶ base _* PresheafedSpace.presheaf X theorem ext {C : Type u} [category_theory.category C] {X : PresheafedSpace C} {Y : PresheafedSpace C} (α : hom X Y) (β : hom X Y) (w : hom.base α = hom.base β) (h : hom.c α ≫ category_theory.whisker_right (category_theory.nat_trans.op (category_theory.iso.inv (topological_space.opens.map_iso (hom.base α) (hom.base β) w))) (PresheafedSpace.presheaf X) = hom.c β) : α = β := sorry /-- The identity morphism of a `PresheafedSpace`. -/ def id {C : Type u} [category_theory.category C] (X : PresheafedSpace C) : hom X X := hom.mk 𝟙 (category_theory.iso.inv (category_theory.functor.left_unitor (PresheafedSpace.presheaf X)) ≫ category_theory.whisker_right (category_theory.nat_trans.op (category_theory.iso.hom (topological_space.opens.map_id (carrier X)))) (PresheafedSpace.presheaf X)) protected instance hom_inhabited {C : Type u} [category_theory.category C] (X : PresheafedSpace C) : Inhabited (hom X X) := { default := id X } /-- Composition of morphisms of `PresheafedSpace`s. -/ def comp {C : Type u} [category_theory.category C] {X : PresheafedSpace C} {Y : PresheafedSpace C} {Z : PresheafedSpace C} (α : hom X Y) (β : hom Y Z) : hom X Z := hom.mk (hom.base α ≫ hom.base β) (hom.c β ≫ category_theory.whisker_left (category_theory.functor.op (topological_space.opens.map (hom.base β))) (hom.c α) ≫ category_theory.iso.inv (Top.presheaf.pushforward.comp (PresheafedSpace.presheaf X) (hom.base α) (hom.base β))) /- The proofs below can be done by `tidy`, but it is too slow, and we don't have a tactic caching mechanism. -/ /-- The category of PresheafedSpaces. Morphisms are pairs, a continuous map and a presheaf map from the presheaf on the target to the pushforward of the presheaf on the source. -/ protected instance category_of_PresheafedSpaces (C : Type u) [category_theory.category C] : category_theory.category (PresheafedSpace C) := category_theory.category.mk @[simp] theorem id_base {C : Type u} [category_theory.category C] (X : PresheafedSpace C) : hom.base 𝟙 = 𝟙 := rfl theorem id_c {C : Type u} [category_theory.category C] (X : PresheafedSpace C) : hom.c 𝟙 = category_theory.iso.inv (category_theory.functor.left_unitor (PresheafedSpace.presheaf X)) ≫ category_theory.whisker_right (category_theory.nat_trans.op (category_theory.iso.hom (topological_space.opens.map_id (carrier X)))) (PresheafedSpace.presheaf X) := rfl @[simp] theorem id_c_app {C : Type u} [category_theory.category C] (X : PresheafedSpace C) (U : topological_space.opens ↥(carrier X)ᵒᵖ) : category_theory.nat_trans.app (hom.c 𝟙) U = category_theory.eq_to_hom (opposite.op_induction (fun (U : topological_space.opens ↥(carrier X)) => subtype.cases_on U fun (U_val : set ↥(carrier X)) (U_property : is_open U_val) => Eq.refl (category_theory.functor.obj (PresheafedSpace.presheaf X) (opposite.op { val := U_val, property := U_property }))) U) := sorry @[simp] theorem comp_base {C : Type u} [category_theory.category C] {X : PresheafedSpace C} {Y : PresheafedSpace C} {Z : PresheafedSpace C} (f : X ⟶ Y) (g : Y ⟶ Z) : hom.base (f ≫ g) = hom.base f ≫ hom.base g := rfl @[simp] theorem comp_c_app {C : Type u} [category_theory.category C] {X : PresheafedSpace C} {Y : PresheafedSpace C} {Z : PresheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (U : topological_space.opens ↥(carrier Z)ᵒᵖ) : category_theory.nat_trans.app (hom.c (α ≫ β)) U = category_theory.nat_trans.app (hom.c β) U ≫ category_theory.nat_trans.app (hom.c α) (opposite.op (category_theory.functor.obj (topological_space.opens.map (hom.base β)) (opposite.unop U))) ≫ category_theory.nat_trans.app (category_theory.iso.inv (Top.presheaf.pushforward.comp (PresheafedSpace.presheaf X) (hom.base α) (hom.base β))) U := rfl theorem congr_app {C : Type u} [category_theory.category C] {X : PresheafedSpace C} {Y : PresheafedSpace C} {α : X ⟶ Y} {β : X ⟶ Y} (h : α = β) (U : topological_space.opens ↥(carrier Y)ᵒᵖ) : category_theory.nat_trans.app (hom.c α) U = category_theory.nat_trans.app (hom.c β) U ≫ category_theory.functor.map (PresheafedSpace.presheaf X) (category_theory.eq_to_hom (Eq._oldrec (Eq.refl (category_theory.functor.obj (category_theory.functor.op (topological_space.opens.map (hom.base α))) U)) h)) := sorry /-- The forgetful functor from `PresheafedSpace` to `Top`. -/ def forget (C : Type u) [category_theory.category C] : PresheafedSpace C ⥤ Top := category_theory.functor.mk (fun (X : PresheafedSpace C) => ↑X) fun (X Y : PresheafedSpace C) (f : X ⟶ Y) => hom.base f /-- The restriction of a presheafed space along an open embedding into the space. -/ @[simp] theorem restrict_carrier {C : Type u} [category_theory.category C] {U : Top} (X : PresheafedSpace C) (f : U ⟶ ↑X) (h : open_embedding ⇑f) : carrier (restrict X f h) = U := Eq.refl (carrier (restrict X f h)) /-- The map from the restriction of a presheafed space. -/ @[simp] theorem of_restrict_c_app {C : Type u} [category_theory.category C] (U : Top) (X : PresheafedSpace C) (f : U ⟶ ↑X) (h : open_embedding ⇑f) (V : topological_space.opens ↥(carrier X)ᵒᵖ) : category_theory.nat_trans.app (hom.c (of_restrict U X f h)) V = category_theory.functor.map (PresheafedSpace.presheaf X) (category_theory.has_hom.hom.op (coe_fn (equiv.symm (category_theory.adjunction.hom_equiv (is_open_map.adjunction (of_restrict._proof_2 U X f h)) (category_theory.functor.obj (topological_space.opens.map f) (opposite.unop V)) (opposite.unop V))) 𝟙)) := Eq.refl (category_theory.nat_trans.app (hom.c (of_restrict U X f h)) V) /-- The map to the restriction of a presheafed space along the canonical inclusion from the top subspace. -/ @[simp] theorem to_restrict_top_base_to_fun_coe {C : Type u} [category_theory.category C] (X : PresheafedSpace C) (x : ↥↑X) : ↑(coe_fn (hom.base (to_restrict_top X)) x) = x := Eq.refl ↑(coe_fn (hom.base (to_restrict_top X)) x) /-- The isomorphism from the restriction to the top subspace. -/ def restrict_top_iso {C : Type u} [category_theory.category C] (X : PresheafedSpace C) : restrict X (topological_space.opens.inclusion ⊤) (restrict_top_iso._proof_1 X) ≅ X := category_theory.iso.mk (of_restrict (category_theory.functor.obj (topological_space.opens.to_Top ↑X) ⊤) X (topological_space.opens.inclusion ⊤) sorry) (to_restrict_top X) /-- The global sections, notated Gamma. -/ @[simp] theorem Γ_obj {C : Type u} [category_theory.category C] (X : PresheafedSpace Cᵒᵖ) : category_theory.functor.obj Γ X = category_theory.functor.obj (PresheafedSpace.presheaf (opposite.unop X)) (opposite.op ⊤) := Eq.refl (category_theory.functor.obj Γ X) theorem Γ_obj_op {C : Type u} [category_theory.category C] (X : PresheafedSpace C) : category_theory.functor.obj Γ (opposite.op X) = category_theory.functor.obj (PresheafedSpace.presheaf X) (opposite.op ⊤) := rfl theorem Γ_map_op {C : Type u} [category_theory.category C] {X : PresheafedSpace C} {Y : PresheafedSpace C} (f : X ⟶ Y) : category_theory.functor.map Γ (category_theory.has_hom.hom.op f) = category_theory.nat_trans.app (hom.c f) (opposite.op ⊤) ≫ category_theory.functor.map (PresheafedSpace.presheaf X) (category_theory.has_hom.hom.op (topological_space.opens.le_map_top (hom.base f) ⊤)) := rfl end PresheafedSpace end algebraic_geometry namespace category_theory namespace functor /-- We can apply a functor `F : C ⥤ D` to the values of the presheaf in any `PresheafedSpace C`, giving a functor `PresheafedSpace C ⥤ PresheafedSpace D` -/ def map_presheaf {C : Type u} [category C] {D : Type u} [category D] (F : C ⥤ D) : algebraic_geometry.PresheafedSpace C ⥤ algebraic_geometry.PresheafedSpace D := mk (fun (X : algebraic_geometry.PresheafedSpace C) => algebraic_geometry.PresheafedSpace.mk (algebraic_geometry.PresheafedSpace.carrier X) (algebraic_geometry.PresheafedSpace.presheaf X ⋙ F)) fun (X Y : algebraic_geometry.PresheafedSpace C) (f : X ⟶ Y) => algebraic_geometry.PresheafedSpace.hom.mk (algebraic_geometry.PresheafedSpace.hom.base f) (whisker_right (algebraic_geometry.PresheafedSpace.hom.c f) F) @[simp] theorem map_presheaf_obj_X {C : Type u} [category C] {D : Type u} [category D] (F : C ⥤ D) (X : algebraic_geometry.PresheafedSpace C) : ↑(obj (map_presheaf F) X) = ↑X := rfl @[simp] theorem map_presheaf_obj_presheaf {C : Type u} [category C] {D : Type u} [category D] (F : C ⥤ D) (X : algebraic_geometry.PresheafedSpace C) : algebraic_geometry.PresheafedSpace.presheaf (obj (map_presheaf F) X) = algebraic_geometry.PresheafedSpace.presheaf X ⋙ F := rfl @[simp] theorem map_presheaf_map_f {C : Type u} [category C] {D : Type u} [category D] (F : C ⥤ D) {X : algebraic_geometry.PresheafedSpace C} {Y : algebraic_geometry.PresheafedSpace C} (f : X ⟶ Y) : algebraic_geometry.PresheafedSpace.hom.base (map (map_presheaf F) f) = algebraic_geometry.PresheafedSpace.hom.base f := rfl @[simp] theorem map_presheaf_map_c {C : Type u} [category C] {D : Type u} [category D] (F : C ⥤ D) {X : algebraic_geometry.PresheafedSpace C} {Y : algebraic_geometry.PresheafedSpace C} (f : X ⟶ Y) : algebraic_geometry.PresheafedSpace.hom.c (map (map_presheaf F) f) = whisker_right (algebraic_geometry.PresheafedSpace.hom.c f) F := rfl end functor namespace nat_trans /-- A natural transformation induces a natural transformation between the `map_presheaf` functors. -/ def on_presheaf {C : Type u} [category C] {D : Type u} [category D] {F : C ⥤ D} {G : C ⥤ D} (α : F ⟶ G) : functor.map_presheaf G ⟶ functor.map_presheaf F := mk fun (X : algebraic_geometry.PresheafedSpace C) => algebraic_geometry.PresheafedSpace.hom.mk 𝟙 (whisker_left (algebraic_geometry.PresheafedSpace.presheaf X) α ≫ iso.inv (functor.left_unitor (algebraic_geometry.PresheafedSpace.presheaf X ⋙ G)) ≫ whisker_right (nat_trans.op (iso.hom (topological_space.opens.map_id (algebraic_geometry.PresheafedSpace.carrier X)))) (algebraic_geometry.PresheafedSpace.presheaf X ⋙ G))
11b848124c1cfff1d4f48955e6571c8ee5ae521a
8c02fed42525b65813b55c064afe2484758d6d09
/src/spec/spec.lean
1be9ffc8bde6e2a0af152e9df0ecebdf25900aef
[ "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
13,095
lean
-- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the MIT license. import ..smtexpr import ..bitvector import ..irsem import ..irsem_exec import ..irsem_smt import ..freevar import ..verifyopt import .lemmas_basic import smt2.syntax import smt2.solvers.z3 import system.io namespace spec -- This inductive predicate formally defines the equality relation between -- SMT expressions and LEAN values. -- bool is LEAN's datatype, and sbool is the SMT boolean expression defined in AliveInLean. -- bool.tt is LEAN's true, bool.ff is LEAN's false. mutual inductive b_equiv, bv_equiv with b_equiv : sbool → bool → Prop -- SMT's true constant is equivalent to LEAN's true. | tt: b_equiv sbool.tt bool.tt | ff: b_equiv sbool.ff bool.ff -- In the semantics of 'and', short-circuiting was necessary because -- the former version (2.5) of SMT-LIB defined x / 0 as "undefined". -- This short-circuiting enables defining this expression as 'false': -- (and ff (= (bvudiv 1 0) ...)) must be false | and1: ∀ (s1 s2:sbool) (b1 b2:bool), b_equiv s1 b1 → (b1 = tt → b_equiv s2 b2) → b_equiv (s1.and s2) (band b1 b2) | and2: ∀ (s1 s2:sbool) (b1 b2:bool), b_equiv s2 b2 → (b2 = tt → b_equiv s1 b1) → b_equiv (s1.and s2) (band b1 b2) | or1: ∀ (s1 s2:sbool) (b1 b2:bool), b_equiv s1 b1 → (b1 = ff → b_equiv s2 b2) → b_equiv (s1.or s2) (bor b1 b2) | or2: ∀ (s1 s2:sbool) (b1 b2:bool), b_equiv s2 b2 → (b2 = ff → b_equiv s1 b1) → b_equiv (s1.or s2) (bor b1 b2) | xor: ∀ (s1 s2:sbool) (b1 b2:bool), b_equiv s1 b1 → b_equiv s2 b2 → b_equiv (s1.xor s2) (bxor b1 b2) | not: ∀ (s:sbool) (b:bool), b_equiv s b → b_equiv (s.not) (bnot b) | ite: ∀ (sc s1 s2: sbool) (bc b1 b2:bool), b_equiv sc bc → b_equiv s1 b1 → b_equiv s2 b2 → b_equiv (sbool.ite sc s1 s2) (cond bc b1 b2) | eq: ∀ (sz:size) (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → b_equiv (sbool.eqbv s1 s2) (bitvector.eq b1 b2) | ne: ∀ (sz:size) (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → b_equiv (sbool.nebv s1 s2) (bitvector.ne b1 b2) | ult: ∀ (sz:size) (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → b_equiv (sbool.ult s1 s2) (bitvector.ult b1 b2) | ule: ∀ (sz:size) (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → b_equiv (sbool.ule s1 s2) (bitvector.ule b1 b2) | slt: ∀ (sz:size) (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → b_equiv (sbool.slt s1 s2) (bitvector.slt b1 b2) | sle: ∀ (sz:size) (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → b_equiv (sbool.sle s1 s2) (bitvector.sle b1 b2) -- Relates sbitvec and bitvector where bitvector is a LEAN value. with bv_equiv : Π {sz:size}, sbitvec sz → bitvector sz → Prop | const: ∀ {sz:size} (n:nat) (H:n < 2^sz.val), bv_equiv (sbitvec.const sz n) ⟨n, H⟩ | add: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → bv_equiv (s1.add s2) (b1.add b2) | sub: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → bv_equiv (s1.sub s2) (b1.sub b2) | mul: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → bv_equiv (s1.mul s2) (b1.mul b2) | and: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → bv_equiv (s1.and s2) (b1.bitwise_and b2) | or: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → bv_equiv (s1.or s2) (b1.bitwise_or b2) | xor: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → bv_equiv (s1.xor s2) (b1.bitwise_xor b2) | shl: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → (bitvector.ult b2 (bitvector.of_int sz (int.of_nat sz.val)) = tt) → bv_equiv (s1.shl s2) (b1.shl b2) | lshr: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → (bitvector.ult b2 (bitvector.of_int sz (int.of_nat sz.val)) = tt) → bv_equiv (s1.lshr s2) (b1.lshr b2) | ashr: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → (bitvector.ult b2 (bitvector.of_int sz (int.of_nat sz.val)) = tt) → bv_equiv (s1.ashr s2) (b1.ashr b2) | udiv: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → (bitvector.ne b2 (bitvector.zero sz) = tt) → -- Div by 0 is UB bv_equiv (s1.udiv s2) (b1.udiv b2) | urem: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → (bitvector.ne b2 (bitvector.zero sz) = tt) → -- Div by 0 is UB bv_equiv (s1.urem s2) (b1.urem b2) | sdiv: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → (bitvector.ne b2 (bitvector.zero sz) = tt) → -- Div by 0 is UB (bitvector.ne b1 (bitvector.int_min sz) = tt) ∨ (bitvector.ne b2 (bitvector.all_one sz) = tt) → -- (INT_MIN / -1 is UB) bv_equiv (s1.sdiv s2) (b1.sdiv b2) | srem: ∀ {sz:size} (s1 s2:sbitvec sz) (b1 b2:bitvector sz), bv_equiv s1 b1 → bv_equiv s2 b2 → (bitvector.ne b2 (bitvector.zero sz) = tt) → -- Div by 0 is UB (bitvector.ne b1 (bitvector.int_min sz) = tt) ∨ (bitvector.ne b2 (bitvector.all_one sz) = tt) → -- (INT_MIN / -1 is UB) bv_equiv (s1.srem s2) (b1.srem b2) | ite: ∀ {sz:size} (sc: sbool) (bc:bool) (s1 s2:sbitvec sz) (b1 b2:bitvector sz), b_equiv sc bc → (bc = tt → bv_equiv s1 b1) → (bc = ff → bv_equiv s2 b2) → bv_equiv (sbitvec.ite sc s1 s2) (cond bc b1 b2) | of_bool: ∀ (s:sbool) (b:bool), b_equiv s b → bv_equiv (sbitvec.of_bool s) (bitvector.of_bool b) | trunc: ∀ (fromsz tosz:size) (H:tosz.val < fromsz.val) (s:sbitvec fromsz) (b:bitvector fromsz), bv_equiv s b → bv_equiv (sbitvec.trunc tosz s) (bitvector.trunc tosz b) | zext: ∀ (fromsz tosz:size) (H:tosz.val > fromsz.val) (s:sbitvec fromsz) (b:bitvector fromsz), bv_equiv s b → bv_equiv (sbitvec.zext tosz s) (bitvector.zext tosz b) | sext: ∀ (fromsz tosz:size) (H:tosz.val > fromsz.val) (s:sbitvec fromsz) (b:bitvector fromsz), bv_equiv s b → bv_equiv (sbitvec.sext tosz s) (bitvector.sext tosz b) open irsem open freevar open opt @[reducible] def intty_smt := irsem_smt.intty @[reducible] def intty_exec := irsem_exec.intty @[reducible] def valty_smt := irsem_smt.valty @[reducible] def valty_exec := irsem_exec.valty @[reducible] def equals_size : valty_smt → valty_exec → bool | (irsem.valty.ival sz1 v1 p1) (irsem.valty.ival sz2 v2 p2) := sz1 = sz2 @[reducible] def poisonty_smt := irsem_smt.poisonty @[reducible] def poisonty_exec := irsem_exec.poisonty -- Equivalence of two poison values. inductive poison_equiv: irsem_smt.poisonty → irsem_exec.poisonty → Prop | intro: Π (ps:poisonty_smt) (pe:poisonty_exec), b_equiv ps pe → poison_equiv ps pe -- Equivalence of (concrete-value, poison) inductive val_equiv: valty_smt → valty_exec → Prop | poison_intty: Π (szs:size) (vs:intty_smt szs) (ps:poisonty_smt) (sze:size) (ve:intty_exec sze) (pe:poisonty_exec), poison_equiv ps pe → szs = sze → pe = irsem_exec.pbl.ff → val_equiv (irsem.valty.ival szs vs ps) (irsem.valty.ival sze ve pe) | concrete_intty: Π (sz:size) (vs:intty_smt sz) (ps:poisonty_smt) (ve:intty_exec sz) (pe:poisonty_exec), poison_equiv ps pe → bv_equiv vs ve → pe = irsem_exec.pbl.tt → val_equiv (irsem.valty.ival sz vs ps) (irsem.valty.ival sz ve pe) @[reducible] def regfile_smt := irsem_smt.regfile @[reducible] def regfile_exec := irsem_exec.regfile -- Equivalence of two Register files. inductive regfile_equiv: regfile_smt → regfile_exec → Prop | empty: ∀ rs re, rs = regfile.empty irsem_smt → re = regfile.empty irsem_exec → regfile_equiv rs re | update: ∀ rs re vs ve rname rs' re', regfile_equiv rs re → val_equiv vs ve → rs' = regfile.update irsem_smt rs rname vs → re' = regfile.update irsem_exec re rname ve → regfile_equiv rs' re' @[reducible] def none_or_some {α β:Type} (os: option α) (oe:option β) (P:α → β → Prop) := (os = none ∧ oe = none) ∨ (∃ s e, os = some s ∧ oe = some e ∧ (P s e)) def regfile_sametypes (rs:regfile_smt) (re:regfile_exec) := ∀ (rname:string) os oe, os = regfile.get irsem_smt rs rname ∧ oe = regfile.get irsem_exec re rname → none_or_some os oe (λ vs ve, equals_size vs ve = tt) def irstate_smt := irsem_smt.irstate def irstate_exec := irsem_exec.irstate @[reducible] def has_no_ub: irstate_exec → bool | (ubs, rs) := ubs -- Equivalence of two IR states. inductive irstate_equiv: irstate_smt → irstate_exec → Prop | noub: ∀ ubs ube rs re, regfile_equiv rs re → b_equiv ubs ube → ube = irsem_exec.bbl.tt → irstate_equiv (ubs, rs) (ube, re) | ub: ∀ ubs ube rs re, -- if UB, register files may differ. b_equiv ubs ube → ube = irsem_exec.bbl.ff → regfile_sametypes rs re → -- but they should have same type! irstate_equiv (ubs, rs) (ube, re) -- Smallstep preserves equivalence between two states. def step_both := ∀ {ss:irstate_smt} {se:irstate_exec} {i:instruction} {oss':option irstate_smt} {ose':option irstate_exec} (HSTEQ: irstate_equiv ss se) (HOSS': oss' = step irsem_smt ss i) (HOSE': ose' = step irsem_exec se i), none_or_some oss' ose' (λ ss' se', irstate_equiv ss' se') -- Bigstep on an open program def encode (ss:irstate_smt) (se:irstate_exec) (η:freevar.env) := irstate_equiv (η⟦ss⟧) se def bigstep_both:= ∀ ss se p oss' ose' η (HENC:encode ss se η) (HOSS': oss' = bigstep irsem_smt ss p) (HOSE': ose' = bigstep irsem_exec se p), none_or_some oss' ose' (λ ss' se', encode ss' se' η) def init_state_encode:= ∀ (freevars:list (string × ty)) (sg sg':std_gen) ise iss (HUNQ: list.unique $ freevars.map prod.fst) (HIE:(ise, sg') = create_init_state_exec freevars sg) (HIS:iss = create_init_state_smt freevars), ∃ η, encode iss ise η -- Correctness of freevar.get is not necessary because an SMT solver -- will fail if a variable is missing. If it returns a redundant variable, -- it does not participate in the execution of a program, so it's still okay. -- Refinement inductive val_refines : valty_exec → valty_exec → Prop | poison_intty: ∀ sz (isrc:intty_exec sz) psrc (itgt:intty_exec sz) ptgt, psrc = irsem_exec.pbl.ff → val_refines (valty.ival sz isrc psrc) (valty.ival sz itgt ptgt) | concrete_intty: ∀ sz (isrc:intty_exec sz) psrc (itgt:intty_exec sz) ptgt, psrc = irsem_exec.pbl.tt → ptgt = irsem_exec.pbl.tt → isrc = itgt → val_refines (valty.ival sz isrc psrc) (valty.ival sz itgt ptgt) def check_val_exec_spec:= ∀ vsrc vtgt (H:opt.check_val irsem_exec vsrc vtgt = some tt), val_refines vsrc vtgt inductive ub_refines: irstate_exec → irstate_exec → Prop | noub: ∀ src tgt, irstate.getub irsem_exec src = irsem_exec.bbl.tt → irstate.getub irsem_exec tgt = irsem_exec.bbl.tt → ub_refines src tgt | ub: ∀ src tgt, irstate.getub irsem_exec src = irsem_exec.bbl.ff → ub_refines src tgt def irstate_refines (se:irstate_exec) (se':irstate_exec): Prop := ub_refines se se' ∧ ∀ r, none_or_some (irstate.getreg irsem_exec se r) (irstate.getreg irsem_exec se' r) (λ v1 v2, val_refines v1 v2) def root_refines (ssrc:irstate_exec) (stgt:irstate_exec) (root:string): Prop := ub_refines ssrc stgt ∧ (irstate.getub irsem_exec ssrc = irsem_exec.bbl.tt → ∃ v1 v2, some v1 = irstate.getreg irsem_exec ssrc root ∧ some v2 = irstate.getreg irsem_exec stgt root ∧ val_refines v1 v2) def refines_finalstate (psrc ptgt:program) (se0:irstate_exec) := ∀ se se', some se = bigstep irsem_exec se0 psrc → some se' = bigstep irsem_exec se0 ptgt → irstate_refines se se' def root_refines_finalstate (psrc ptgt:program) (se0:irstate_exec) (root:string):= ∀ se se', some se = bigstep irsem_exec se0 psrc → some se' = bigstep irsem_exec se0 ptgt → root_refines se se' root def refines_smt (psrc ptgt:program) := ∀ (η:freevar.env) ss0 se0, encode ss0 se0 η → refines_finalstate psrc ptgt se0 def root_refines_smt (psrc ptgt:program) (ss0:irstate_smt) (root:string) := ∀ (η:freevar.env) se0, encode ss0 se0 η → root_refines_finalstate psrc ptgt se0 root def refines_single_reg_correct := ∀ (psrc ptgt:program) (root:string) (ss0:irstate_smt) sb (HSREF:some sb = check_single_reg0 irsem_smt psrc ptgt root ss0) (HEQ:∀ (η0:freevar.env) e, b_equiv (η0⟦sb⟧) e → e = tt), root_refines_smt psrc ptgt ss0 root end spec
9acbef9299d05b89ceaffcd5cb2c4dda8e631f23
0d22ec5e0205ec4203aae2ddf07e1f695ff21a61
/src/step3.lean
d7b58a7ffbe526219de5a6cc9544ba9af5fc4d09
[ "Apache-2.0" ]
permissive
shingtaklam1324/step3-06-q8-lean
4611fda6b002797d38d3f625253960dcfeb2a987
20e5161fab8b5c3c2dd051bd707a26f1dc50dac2
refs/heads/master
1,649,936,589,910
1,585,242,273,000
1,585,242,273,000
250,318,324
2
0
Apache-2.0
1,585,389,271,000
1,585,241,690,000
Lean
UTF-8
Lean
false
false
3,068
lean
/- 2006 STEP 3 Question 8 -/ import data.polynomial data.real.basic tactic open polynomial /- Δ is a function takes takes polynomials in x to polynomials in x; that is, given any polynomial h(x), there is a polynomial called Δh(x) which is obtained from h(x) using the rules that define Δ. -/ variable Δ : polynomial ℝ → polynomial ℝ include Δ /- These rules are as follows -/ variable Δ1 : Δ X = C 1 variable Δ2 : ∀ (f g : polynomial ℝ), Δ(f + g) = Δ f + Δ g variable Δ3 : ∀ (k : ℝ) (f : polynomial ℝ), Δ(C k * f) = C k * Δ f variable Δ4 : ∀ (f g : polynomial ℝ), Δ(f * g) = f * Δ g + g * Δ f include Δ1 Δ2 Δ3 Δ4 /- Using these rules show that, if f(x) is a polynomial of degree zero (that is, a constant), then Δ f(x) = 0. -/ -- First, show that Δ 1 is 0 lemma Δ_one : Δ (C 1) = 0 := begin -- If we can prove that Δ 1 + Δ 1 = Δ 1, then Δ 1 = 0 follows -- Therefore we have a proof of Δ 1 = 0 if we have a proof of Δ 1 + Δ 1 = Δ 1 suffices H : Δ 1 + Δ 1 = Δ 1, rwa add_left_eq_self at H, -- Δ 1 + Δ 1 = Δ (1 * 1) conv begin to_rhs, rw (show (1 : polynomial ℝ) = 1 * 1, by ring), end, -- By rule 4, this expands rw Δ4, -- This then simplifies down to our desired result ring, end -- Having shown that Δ 1 is 0, Δ c (for c ∈ ℝ), is also 0 lemma Δ_const (a : ℝ) : Δ (C a) = 0 := begin -- Δ c = Δ (c * 1) rw (show (C a) = (C a) * (C 1), by rw [<-C_mul,mul_one]), -- By rule 3 we can expand this rw Δ3, -- We know from above that Δ 1 is 0 rw Δ_one Δ, simp, -- Therefore Δ c must be 0 repeat {assumption} end /- Calculate Δx^2 and Δx^3 -/ lemma ΔXsquared : Δ (X^2) = 2*X := begin -- Δ (x^2) = Δ (x*x) rw pow_two, -- By rule 4, this is the same as X * Δ X + X * Δ X rw Δ4, -- By rule 1, this is just X * 1 + X * 1 rw Δ1, -- Which is 2*X rw mul_comm, rw <-add_mul, norm_num, end lemma ΔXcubed : Δ (X^3) = 3*X^2 := begin -- Δ (x^3) = Δ (x * x^2) rw (show (X:polynomial ℝ)^3 = X * X^2, by ring), -- Use rule 4 to expand this rw Δ4, -- Then use the result for Δx^2 rw ΔXsquared Δ, rw <-mul_assoc, rw Δ1, rw mul_comm, rw <-mul_assoc, rw <-pow_two, rw <-mul_add, rw mul_comm, refl, repeat {assumption}, end /- Prove that Δh(x) ≡ dh(x)/dx for any polynomial h(x). You should make it clear whenever you use one of the above rules in your proof. -/ lemma ΔXn (n : ℕ) : Δ (X^(n+1)) = C (n+1)*X^n := begin induction n with d hd, { -- base case rw [pow_one, Δ1, nat.cast_zero], simp, }, rw [nat.succ_eq_add_one, pow_succ, Δ4, Δ1, hd, pow_succ, nat.cast_add, nat.cast_one], rw (show C (1:ℝ) = 1, by simp), simp, ring, end lemma Δ_is_derivative (p : polynomial ℝ) : Δ p = derivative p := begin apply p.induction_on, { intro a, rw Δ_const Δ, simp, repeat {assumption}}, { intros p q hp hq, rw Δ2, rw hp, rw hq, simp,}, intros a n IH, rw [Δ4, Δ_const Δ, ΔXn Δ, mul_zero, add_zero, derivative_monomial, <-mul_assoc], simp, repeat {assumption}, end
d590338648c61cd110db9c5821529311a03baf05
367134ba5a65885e863bdc4507601606690974c1
/src/data/multiset/nat_antidiagonal.lean
7bb1e2b071760fda5e8b733e0b16b68a30cb8302
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
1,487
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import data.multiset.nodup import data.list.nat_antidiagonal /-! # The "antidiagonal" {(0,n), (1,n-1), ..., (n,0)} as a multiset. -/ namespace multiset namespace nat /-- The antidiagonal of a natural number `n` is the multiset of pairs `(i,j)` such that `i+j = n`. -/ def antidiagonal (n : ℕ) : multiset (ℕ × ℕ) := list.nat.antidiagonal n /-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, mem_coe, list.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by rw [antidiagonal, coe_card, list.nat.length_antidiagonal] /-- The antidiagonal of `0` is the list `[(0,0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := rfl /-- The antidiagonal of `n` does not contain duplicate entries. -/ @[simp] lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := coe_nodup.2 $ list.nat.nodup_antidiagonal n @[simp] lemma antidiagonal_succ {n : ℕ} : antidiagonal (n + 1) = (0, n + 1) ::ₘ ((antidiagonal n).map (prod.map nat.succ id)) := by simp only [antidiagonal, list.nat.antidiagonal_succ, coe_map, cons_coe] end nat end multiset
0a9467cdf65b97df374894f3d70e2ed86527998b
94e33a31faa76775069b071adea97e86e218a8ee
/src/geometry/euclidean/basic.lean
d67d199e4960f098c365402f2578d66a5764cab2
[ "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
56,972
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Manuel Candales -/ import analysis.inner_product_space.projection import analysis.special_functions.trigonometric.inverse import algebra.quadratic_discriminant import linear_algebra.affine_space.finite_dimensional import analysis.calculus.conformal.normed_space /-! # Euclidean spaces This file makes some definitions and proves very basic geometrical results about real inner product spaces and Euclidean affine spaces. Results about real inner product spaces that involve the norm and inner product but not angles generally go in `analysis.normed_space.inner_product`. Results with longer proofs or more geometrical content generally go in separate files. ## Main definitions * `inner_product_geometry.angle` is the undirected angle between two vectors. * `euclidean_geometry.angle`, with notation `∠`, is the undirected angle determined by three points. * `euclidean_geometry.orthogonal_projection` is the orthogonal projection of a point onto an affine subspace. * `euclidean_geometry.reflection` is the reflection of a point in an affine subspace. ## Implementation notes To declare `P` as the type of points in a Euclidean affine space with `V` as the type of vectors, use `[inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]`. This works better with `out_param` to make `V` implicit in most cases than having a separate type alias for Euclidean affine spaces. Rather than requiring Euclidean affine spaces to be finite-dimensional (as in the definition on Wikipedia), this is specified only for those theorems that need it. ## References * https://en.wikipedia.org/wiki/Euclidean_space -/ noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space namespace inner_product_geometry /-! ### Geometrical results on real inner product spaces This section develops some geometrical definitions and results on real inner product spaces, where those definitions and results can most conveniently be developed in terms of vectors and then used to deduce corresponding results for Euclidean affine spaces. -/ variables {V : Type*} [inner_product_space ℝ V] /-- The undirected angle between two vectors. If either vector is 0, this is π/2. See `orientation.oangle` for the corresponding oriented angle definition. -/ def angle (x y : V) : ℝ := real.arccos (inner x y / (∥x∥ * ∥y∥)) lemma continuous_at_angle {x : V × V} (hx1 : x.1 ≠ 0) (hx2 : x.2 ≠ 0) : continuous_at (λ y : V × V, angle y.1 y.2) x := real.continuous_arccos.continuous_at.comp $ continuous_inner.continuous_at.div ((continuous_norm.comp continuous_fst).mul (continuous_norm.comp continuous_snd)).continuous_at (by simp [hx1, hx2]) lemma angle_smul_smul {c : ℝ} (hc : c ≠ 0) (x y : V) : angle (c • x) (c • y) = angle x y := have c * c ≠ 0, from mul_ne_zero hc hc, by rw [angle, angle, real_inner_smul_left, inner_smul_right, norm_smul, norm_smul, real.norm_eq_abs, mul_mul_mul_comm _ (∥x∥), abs_mul_abs_self, ← mul_assoc c c, mul_div_mul_left _ _ this] @[simp] lemma _root_.linear_isometry.angle_map {E F : Type*} [inner_product_space ℝ E] [inner_product_space ℝ F] (f : E →ₗᵢ[ℝ] F) (u v : E) : angle (f u) (f v) = angle u v := by rw [angle, angle, f.inner_map_map, f.norm_map, f.norm_map] lemma is_conformal_map.preserves_angle {E F : Type*} [inner_product_space ℝ E] [inner_product_space ℝ F] {f' : E →L[ℝ] F} (h : is_conformal_map f') (u v : E) : angle (f' u) (f' v) = angle u v := begin obtain ⟨c, hc, li, rfl⟩ := h, exact (angle_smul_smul hc _ _).trans (li.angle_map _ _) end /-- If a real differentiable map `f` is conformal at a point `x`, then it preserves the angles at that point. -/ lemma conformal_at.preserves_angle {E F : Type*} [inner_product_space ℝ E] [inner_product_space ℝ F] {f : E → F} {x : E} {f' : E →L[ℝ] F} (h : has_fderiv_at f f' x) (H : conformal_at f x) (u v : E) : angle (f' u) (f' v) = angle u v := let ⟨f₁, h₁, c⟩ := H in h₁.unique h ▸ is_conformal_map.preserves_angle c u v /-- The cosine of the angle between two vectors. -/ lemma cos_angle (x y : V) : real.cos (angle x y) = inner x y / (∥x∥ * ∥y∥) := real.cos_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 /-- The angle between two vectors does not depend on their order. -/ lemma angle_comm (x y : V) : angle x y = angle y x := begin unfold angle, rw [real_inner_comm, mul_comm] end /-- The angle between the negation of two vectors. -/ @[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y := begin unfold angle, rw [inner_neg_neg, norm_neg, norm_neg] end /-- The angle between two vectors is nonnegative. -/ lemma angle_nonneg (x y : V) : 0 ≤ angle x y := real.arccos_nonneg _ /-- The angle between two vectors is at most π. -/ lemma angle_le_pi (x y : V) : angle x y ≤ π := real.arccos_le_pi _ /-- The angle between a vector and the negation of another vector. -/ lemma angle_neg_right (x y : V) : angle x (-y) = π - angle x y := begin unfold angle, rw [←real.arccos_neg, norm_neg, inner_neg_right, neg_div] end /-- The angle between the negation of a vector and another vector. -/ lemma angle_neg_left (x y : V) : angle (-x) y = π - angle x y := by rw [←angle_neg_neg, neg_neg, angle_neg_right] /-- The angle between the zero vector and a vector. -/ @[simp] lemma angle_zero_left (x : V) : angle 0 x = π / 2 := begin unfold angle, rw [inner_zero_left, zero_div, real.arccos_zero] end /-- The angle between a vector and the zero vector. -/ @[simp] lemma angle_zero_right (x : V) : angle x 0 = π / 2 := begin unfold angle, rw [inner_zero_right, zero_div, real.arccos_zero] end /-- The angle between a nonzero vector and itself. -/ @[simp] lemma angle_self {x : V} (hx : x ≠ 0) : angle x x = 0 := begin unfold angle, rw [←real_inner_self_eq_norm_mul_norm, div_self (λ h, hx (inner_self_eq_zero.1 h)), real.arccos_one] end /-- The angle between a nonzero vector and its negation. -/ @[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x ≠ 0) : angle x (-x) = π := by rw [angle_neg_right, angle_self hx, sub_zero] /-- The angle between the negation of a nonzero vector and that vector. -/ @[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x ≠ 0) : angle (-x) x = π := by rw [angle_comm, angle_self_neg_of_nonzero hx] /-- The angle between a vector and a positive multiple of a vector. -/ @[simp] lemma angle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle x (r • y) = angle x y := begin unfold angle, rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), ←mul_assoc, mul_comm _ r, mul_assoc, mul_div_mul_left _ _ (ne_of_gt hr)] end /-- The angle between a positive multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle (r • x) y = angle x y := by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm] /-- The angle between a vector and a negative multiple of a vector. -/ @[simp] lemma angle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle x (r • y) = angle x (-y) := by rw [←neg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr), angle_neg_right] /-- The angle between a negative multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle (r • x) y = angle (-x) y := by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm] /-- The cosine of the angle between two vectors, multiplied by the product of their norms. -/ lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (∥x∥ * ∥y∥) = inner x y := begin rw [cos_angle, div_mul_cancel_of_imp], simp [or_imp_distrib] { contextual := tt }, end /-- The sine of the angle between two vectors, multiplied by the product of their norms. -/ lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (∥x∥ * ∥y∥) = real.sqrt (inner x x * inner y y - inner x y * inner x y) := begin unfold angle, rw [real.sin_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2, ←real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), ←real.sqrt_mul' _ (mul_self_nonneg _), sq, real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), real_inner_self_eq_norm_mul_norm, real_inner_self_eq_norm_mul_norm], by_cases h : (∥x∥ * ∥y∥) = 0, { rw [(show ∥x∥ * ∥x∥ * (∥y∥ * ∥y∥) = (∥x∥ * ∥y∥) * (∥x∥ * ∥y∥), by ring), h, mul_zero, mul_zero, zero_sub], cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left, zero_mul, neg_zero] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right, zero_mul, neg_zero] } }, { field_simp [h], ring_nf } end /-- The angle between two vectors is zero if and only if they are nonzero and one is a positive multiple of the other. -/ lemma angle_eq_zero_iff {x y : V} : angle x y = 0 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin rw [angle, ← real_inner_div_norm_mul_norm_eq_one_iff, real.arccos_eq_zero, has_le.le.le_iff_eq, eq_comm], exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 end /-- The angle between two vectors is π if and only if they are nonzero and one is a negative multiple of the other. -/ lemma angle_eq_pi_iff {x y : V} : angle x y = π ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin rw [angle, ← real_inner_div_norm_mul_norm_eq_neg_one_iff, real.arccos_eq_pi, has_le.le.le_iff_eq], exact (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 end /-- If the angle between two vectors is π, the angles between those vectors and a third vector add to π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = π) : angle x z + angle y z = π := begin rcases angle_eq_pi_iff.1 h with ⟨hx, ⟨r, ⟨hr, rfl⟩⟩⟩, rw [angle_smul_left_of_neg x z hr, angle_neg_left, add_sub_cancel'_right] end /-- Two vectors have inner product 0 if and only if the angle between them is π/2. -/ lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : ⟪x, y⟫ = 0 ↔ angle x y = π / 2 := iff.symm $ by simp [angle, or_imp_distrib] { contextual := tt } /-- If the angle between two vectors is π, the inner product equals the negative product of the norms. -/ lemma inner_eq_neg_mul_norm_of_angle_eq_pi {x y : V} (h : angle x y = π) : ⟪x, y⟫ = - (∥x∥ * ∥y∥) := by simp [← cos_angle_mul_norm_mul_norm, h] /-- If the angle between two vectors is 0, the inner product equals the product of the norms. -/ lemma inner_eq_mul_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : ⟪x, y⟫ = ∥x∥ * ∥y∥ := by simp [← cos_angle_mul_norm_mul_norm, h] /-- The inner product of two non-zero vectors equals the negative product of their norms if and only if the angle between the two vectors is π. -/ lemma inner_eq_neg_mul_norm_iff_angle_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : ⟪x, y⟫ = - (∥x∥ * ∥y∥) ↔ angle x y = π := begin refine ⟨λ h, _, inner_eq_neg_mul_norm_of_angle_eq_pi⟩, have h₁ : (∥x∥ * ∥y∥) ≠ 0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne', rw [angle, h, neg_div, div_self h₁, real.arccos_neg_one], end /-- The inner product of two non-zero vectors equals the product of their norms if and only if the angle between the two vectors is 0. -/ lemma inner_eq_mul_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ angle x y = 0 := begin refine ⟨λ h, _, inner_eq_mul_norm_of_angle_eq_zero⟩, have h₁ : (∥x∥ * ∥y∥) ≠ 0 := (mul_pos (norm_pos_iff.mpr hx) (norm_pos_iff.mpr hy)).ne', rw [angle, h, div_self h₁, real.arccos_one], end /-- If the angle between two vectors is π, the norm of their difference equals the sum of their norms. -/ lemma norm_sub_eq_add_norm_of_angle_eq_pi {x y : V} (h : angle x y = π) : ∥x - y∥ = ∥x∥ + ∥y∥ := begin rw ← sq_eq_sq (norm_nonneg (x - y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)), rw [norm_sub_pow_two_real, inner_eq_neg_mul_norm_of_angle_eq_pi h], ring, end /-- If the angle between two vectors is 0, the norm of their sum equals the sum of their norms. -/ lemma norm_add_eq_add_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : ∥x + y∥ = ∥x∥ + ∥y∥ := begin rw ← sq_eq_sq (norm_nonneg (x + y)) (add_nonneg (norm_nonneg x) (norm_nonneg y)), rw [norm_add_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h], ring, end /-- If the angle between two vectors is 0, the norm of their difference equals the absolute value of the difference of their norms. -/ lemma norm_sub_eq_abs_sub_norm_of_angle_eq_zero {x y : V} (h : angle x y = 0) : ∥x - y∥ = |∥x∥ - ∥y∥| := begin rw [← sq_eq_sq (norm_nonneg (x - y)) (abs_nonneg (∥x∥ - ∥y∥)), norm_sub_pow_two_real, inner_eq_mul_norm_of_angle_eq_zero h, sq_abs (∥x∥ - ∥y∥)], ring, end /-- The norm of the difference of two non-zero vectors equals the sum of their norms if and only the angle between the two vectors is π. -/ lemma norm_sub_eq_add_norm_iff_angle_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : ∥x - y∥ = ∥x∥ + ∥y∥ ↔ angle x y = π := begin refine ⟨λ h, _, norm_sub_eq_add_norm_of_angle_eq_pi⟩, rw ← inner_eq_neg_mul_norm_iff_angle_eq_pi hx hy, obtain ⟨hxy₁, hxy₂⟩ := ⟨norm_nonneg (x - y), add_nonneg (norm_nonneg x) (norm_nonneg y)⟩, rw [← sq_eq_sq hxy₁ hxy₂, norm_sub_pow_two_real] at h, calc inner x y = (∥x∥ ^ 2 + ∥y∥ ^ 2 - (∥x∥ + ∥y∥) ^ 2) / 2 : by linarith ... = -(∥x∥ * ∥y∥) : by ring, end /-- The norm of the sum of two non-zero vectors equals the sum of their norms if and only the angle between the two vectors is 0. -/ lemma norm_add_eq_add_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : ∥x + y∥ = ∥x∥ + ∥y∥ ↔ angle x y = 0 := begin refine ⟨λ h, _, norm_add_eq_add_norm_of_angle_eq_zero⟩, rw ← inner_eq_mul_norm_iff_angle_eq_zero hx hy, obtain ⟨hxy₁, hxy₂⟩ := ⟨norm_nonneg (x + y), add_nonneg (norm_nonneg x) (norm_nonneg y)⟩, rw [← sq_eq_sq hxy₁ hxy₂, norm_add_pow_two_real] at h, calc inner x y = ((∥x∥ + ∥y∥) ^ 2 - ∥x∥ ^ 2 - ∥y∥ ^ 2)/ 2 : by linarith ... = ∥x∥ * ∥y∥ : by ring, end /-- The norm of the difference of two non-zero vectors equals the absolute value of the difference of their norms if and only the angle between the two vectors is 0. -/ lemma norm_sub_eq_abs_sub_norm_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : ∥x - y∥ = |∥x∥ - ∥y∥| ↔ angle x y = 0 := begin refine ⟨λ h, _, norm_sub_eq_abs_sub_norm_of_angle_eq_zero⟩, rw ← inner_eq_mul_norm_iff_angle_eq_zero hx hy, have h1 : ∥x - y∥ ^ 2 = (∥x∥ - ∥y∥) ^ 2, { rw h, exact sq_abs (∥x∥ - ∥y∥) }, rw norm_sub_pow_two_real at h1, calc inner x y = ((∥x∥ + ∥y∥) ^ 2 - ∥x∥ ^ 2 - ∥y∥ ^ 2)/ 2 : by linarith ... = ∥x∥ * ∥y∥ : by ring, end /-- The norm of the sum of two vectors equals the norm of their difference if and only if the angle between them is π/2. -/ lemma norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (x y : V) : ∥x + y∥ = ∥x - y∥ ↔ angle x y = π / 2 := begin rw [← sq_eq_sq (norm_nonneg (x + y)) (norm_nonneg (x - y)), ← inner_eq_zero_iff_angle_eq_pi_div_two x y, norm_add_pow_two_real, norm_sub_pow_two_real], split; intro h; linarith, end end inner_product_geometry namespace euclidean_geometry /-! ### Geometrical results on Euclidean affine spaces This section develops some geometrical definitions and results on Euclidean affine spaces. -/ open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] local notation `⟪`x`, `y`⟫` := @inner ℝ V _ x y include V /-- The undirected angle at `p2` between the line segments to `p1` and `p3`. If either of those points equals `p2`, this is π/2. Use `open_locale euclidean_geometry` to access the `∠ p1 p2 p3` notation. -/ def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2) localized "notation `∠` := euclidean_geometry.angle" in euclidean_geometry lemma continuous_at_angle {x : P × P × P} (hx12 : x.1 ≠ x.2.1) (hx32 : x.2.2 ≠ x.2.1) : continuous_at (λ y : P × P × P, ∠ y.1 y.2.1 y.2.2) x := begin let f : P × P × P → V × V := λ y, (y.1 -ᵥ y.2.1, y.2.2 -ᵥ y.2.1), have hf1 : (f x).1 ≠ 0, by simp [hx12], have hf2 : (f x).2 ≠ 0, by simp [hx32], exact (inner_product_geometry.continuous_at_angle hf1 hf2).comp ((continuous_fst.vsub continuous_snd.fst).prod_mk (continuous_snd.snd.vsub continuous_snd.fst)).continuous_at end /-- The angle at a point does not depend on the order of the other two points. -/ lemma angle_comm (p1 p2 p3 : P) : ∠ p1 p2 p3 = ∠ p3 p2 p1 := angle_comm _ _ /-- The angle at a point is nonnegative. -/ lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ p1 p2 p3 := angle_nonneg _ _ /-- The angle at a point is at most π. -/ lemma angle_le_pi (p1 p2 p3 : P) : ∠ p1 p2 p3 ≤ π := angle_le_pi _ _ /-- The angle ∠AAB at a point. -/ lemma angle_eq_left (p1 p2 : P) : ∠ p1 p1 p2 = π / 2 := begin unfold angle, rw vsub_self, exact angle_zero_left _ end /-- The angle ∠ABB at a point. -/ lemma angle_eq_right (p1 p2 : P) : ∠ p1 p2 p2 = π / 2 := by rw [angle_comm, angle_eq_left] /-- The angle ∠ABA at a point. -/ lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ p1 p2 p1 = 0 := angle_self (λ he, h (vsub_eq_zero_iff_eq.1 he)) /-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p1 p3 = 0 := begin unfold angle at h, rw angle_eq_pi_iff at h, rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩, unfold angle, rw angle_eq_zero_iff, rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2, use [hp1p2, -r + 1, add_pos (neg_pos_of_neg hr) zero_lt_one], rw [add_smul, ←neg_vsub_eq_vsub_rev p1 p2, smul_neg], simp [←hpr] end /-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p3 p1 = 0 := begin rw angle_comm at h, exact angle_eq_zero_of_angle_eq_pi_left h end /-- If ∠BCD = π, then ∠ABC = ∠ABD. -/ lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p2 p3 = ∠ p1 p2 p4 := begin unfold angle at *, rcases angle_eq_pi_iff.1 h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩, rw [eq_comm], convert angle_smul_right_of_pos (p1 -ᵥ p2) (p3 -ᵥ p2) (add_pos (neg_pos_of_neg hr) zero_lt_one), rw [add_smul, ← neg_vsub_eq_vsub_rev p2 p3, smul_neg, neg_smul, ← hpr], simp end /-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p3 p2 + ∠ p1 p3 p4 = π := begin unfold angle at h, rw [angle_comm p1 p3 p2, angle_comm p1 p3 p4], unfold angle, exact angle_add_angle_eq_pi_of_angle_eq_pi _ h end /-- Vertical Angles Theorem: angles opposite each other, formed by two intersecting straight lines, are equal. -/ lemma angle_eq_angle_of_angle_eq_pi_of_angle_eq_pi {p1 p2 p3 p4 p5 : P} (hapc : ∠ p1 p5 p3 = π) (hbpd : ∠ p2 p5 p4 = π) : ∠ p1 p5 p2 = ∠ p3 p5 p4 := by linarith [angle_add_angle_eq_pi_of_angle_eq_pi p1 hbpd, angle_comm p4 p5 p1, angle_add_angle_eq_pi_of_angle_eq_pi p4 hapc, angle_comm p4 p5 p3] /-- If ∠ABC = π then dist A B ≠ 0. -/ lemma left_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p1 p2 ≠ 0 := begin by_contra heq, rw [dist_eq_zero] at heq, rw [heq, angle_eq_left] at h, exact real.pi_ne_zero (by linarith), end /-- If ∠ABC = π then dist C B ≠ 0. -/ lemma right_dist_ne_zero_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p3 p2 ≠ 0 := left_dist_ne_zero_of_angle_eq_pi $ (angle_comm _ _ _).trans h /-- If ∠ABC = π, then (dist A C) = (dist A B) + (dist B C). -/ lemma dist_eq_add_dist_of_angle_eq_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : dist p1 p3 = dist p1 p2 + dist p3 p2 := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_add_norm_of_angle_eq_pi h, end /-- If A ≠ B and C ≠ B then ∠ABC = π if and only if (dist A C) = (dist A B) + (dist B C). -/ lemma dist_eq_add_dist_iff_angle_eq_pi {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) : dist p1 p3 = dist p1 p2 + dist p3 p2 ↔ ∠ p1 p2 p3 = π := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_add_norm_iff_angle_eq_pi ((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)), end /-- If ∠ABC = 0, then (dist A C) = abs ((dist A B) - (dist B C)). -/ lemma dist_eq_abs_sub_dist_of_angle_eq_zero {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = 0) : (dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_abs_sub_norm_of_angle_eq_zero h, end /-- If A ≠ B and C ≠ B then ∠ABC = 0 if and only if (dist A C) = abs ((dist A B) - (dist B C)). -/ lemma dist_eq_abs_sub_dist_iff_angle_eq_zero {p1 p2 p3 : P} (hp1p2 : p1 ≠ p2) (hp3p2 : p3 ≠ p2) : (dist p1 p3) = |(dist p1 p2) - (dist p3 p2)| ↔ ∠ p1 p2 p3 = 0 := begin rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, dist_eq_norm_vsub V, ← vsub_sub_vsub_cancel_right], exact norm_sub_eq_abs_sub_norm_iff_angle_eq_zero ((λ he, hp1p2 (vsub_eq_zero_iff_eq.1 he))) (λ he, hp3p2 (vsub_eq_zero_iff_eq.1 he)), end /-- The midpoint of the segment AB is the same distance from A as it is from B. -/ lemma dist_left_midpoint_eq_dist_right_midpoint (p1 p2 : P) : dist p1 (midpoint ℝ p1 p2) = dist p2 (midpoint ℝ p1 p2) := by rw [dist_left_midpoint p1 p2, dist_right_midpoint p1 p2] /-- If M is the midpoint of the segment AB, then ∠AMB = π. -/ lemma angle_midpoint_eq_pi (p1 p2 : P) (hp1p2 : p1 ≠ p2) : ∠ p1 (midpoint ℝ p1 p2) p2 = π := have p2 -ᵥ midpoint ℝ p1 p2 = -(p1 -ᵥ midpoint ℝ p1 p2), by { rw neg_vsub_eq_vsub_rev, simp }, by simp [angle, this, hp1p2, -zero_lt_one] /-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B then ∠CMA = π / 2. -/ lemma angle_left_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) : ∠ p3 (midpoint ℝ p1 p2) p1 = π / 2 := begin let m : P := midpoint ℝ p1 p2, have h1 : p3 -ᵥ p1 = (p3 -ᵥ m) - (p1 -ᵥ m) := (vsub_sub_vsub_cancel_right p3 p1 m).symm, have h2 : p3 -ᵥ p2 = (p3 -ᵥ m) + (p1 -ᵥ m), { rw [left_vsub_midpoint, ← midpoint_vsub_right, vsub_add_vsub_cancel] }, rw [dist_eq_norm_vsub V p3 p1, dist_eq_norm_vsub V p3 p2, h1, h2] at h, exact (norm_add_eq_norm_sub_iff_angle_eq_pi_div_two (p3 -ᵥ m) (p1 -ᵥ m)).mp h.symm, end /-- If M is the midpoint of the segment AB and C is the same distance from A as it is from B then ∠CMB = π / 2. -/ lemma angle_right_midpoint_eq_pi_div_two_of_dist_eq {p1 p2 p3 : P} (h : dist p3 p1 = dist p3 p2) : ∠ p3 (midpoint ℝ p1 p2) p2 = π / 2 := by rw [midpoint_comm p1 p2, angle_left_midpoint_eq_pi_div_two_of_dist_eq h.symm] /-- The inner product of two vectors given with `weighted_vsub`, in terms of the pairwise distances. -/ lemma inner_weighted_vsub {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P) (h₂ : ∑ i in s₂, w₂ i = 0) : inner (s₁.weighted_vsub p₁ w₁) (s₂.weighted_vsub p₂ w₂) = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / 2 := begin rw [finset.weighted_vsub_apply, finset.weighted_vsub_apply, inner_sum_smul_sum_smul_of_sum_eq_zero _ h₁ _ h₂], simp_rw [vsub_sub_vsub_cancel_right], rcongr i₁ i₂; rw dist_eq_norm_vsub V (p₁ i₁) (p₂ i₂) end /-- The distance between two points given with `affine_combination`, in terms of the pairwise distances between the points in that combination. -/ lemma dist_affine_combination {ι : Type*} {s : finset ι} {w₁ w₂ : ι → ℝ} (p : ι → P) (h₁ : ∑ i in s, w₁ i = 1) (h₂ : ∑ i in s, w₂ i = 1) : by have a₁ := s.affine_combination p w₁; have a₂ := s.affine_combination p w₂; exact dist a₁ a₂ * dist a₁ a₂ = (-∑ i₁ in s, ∑ i₂ in s, (w₁ - w₂) i₁ * (w₁ - w₂) i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / 2 := begin rw [dist_eq_norm_vsub V (s.affine_combination p w₁) (s.affine_combination p w₂), ←inner_self_eq_norm_mul_norm, finset.affine_combination_vsub], have h : ∑ i in s, (w₁ - w₂) i = 0, { simp_rw [pi.sub_apply, finset.sum_sub_distrib, h₁, h₂, sub_self] }, exact inner_weighted_vsub p h p h end /-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal to that between `p₁` and `p₂`. (In two dimensions, this says that the diagonals of a kite are orthogonal.) -/ lemma inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁) (hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := begin have h : ⟪(c₂ -ᵥ c₁) + (c₂ -ᵥ c₁), p₂ -ᵥ p₁⟫ = 0, { conv_lhs { congr, congr, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₁, skip, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₂ }, rw [sub_add_sub_comm, inner_sub_left], conv_lhs { congr, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₂, skip, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₁ }, rw [dist_comm p₁, dist_comm p₂, dist_eq_norm_vsub V _ p₁, dist_eq_norm_vsub V _ p₂, ←real_inner_add_sub_eq_zero_iff] at hc₁ hc₂, simp_rw [←neg_vsub_eq_vsub_rev c₁, ←neg_vsub_eq_vsub_rev c₂, sub_neg_eq_add, neg_add_eq_sub, hc₁, hc₂, sub_zero] }, simpa [inner_add_left, ←mul_two, (by norm_num : (2 : ℝ) ≠ 0)] using h end /-- The squared distance between points on a line (expressed as a multiple of a fixed vector added to a point) and another point, expressed as a quadratic. -/ lemma dist_smul_vadd_sq (r : ℝ) (v : V) (p₁ p₂ : P) : dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ = ⟪v, v⟫ * r * r + 2 * ⟪v, p₁ -ᵥ p₂⟫ * r + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ := begin rw [dist_eq_norm_vsub V _ p₂, ←real_inner_self_eq_norm_mul_norm, vadd_vsub_assoc, real_inner_add_add_self, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right], ring end /-- The condition for two points on a line to be equidistant from another point. -/ lemma dist_smul_vadd_eq_dist {v : V} (p₁ p₂ : P) (hv : v ≠ 0) (r : ℝ) : dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ (r = 0 ∨ r = -2 * ⟪v, p₁ -ᵥ p₂⟫ / ⟪v, v⟫) := begin conv_lhs { rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_smul_vadd_sq, ←sub_eq_zero, add_sub_assoc, dist_eq_norm_vsub V p₁ p₂, ←real_inner_self_eq_norm_mul_norm, sub_self] }, have hvi : ⟪v, v⟫ ≠ 0, by simpa using hv, have hd : discrim ⟪v, v⟫ (2 * ⟪v, p₁ -ᵥ p₂⟫) 0 = (2 * inner v (p₁ -ᵥ p₂)) * (2 * inner v (p₁ -ᵥ p₂)), { rw discrim, ring }, rw [quadratic_eq_zero_iff hvi hd, add_left_neg, zero_div, neg_mul_eq_neg_mul, ←mul_sub_right_distrib, sub_eq_add_neg, ←mul_two, mul_assoc, mul_div_assoc, mul_div_mul_left, mul_div_assoc], norm_num end open affine_subspace finite_dimensional /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in a two-dimensional subspace containing those points (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two {s : affine_subspace ℝ P} [finite_dimensional ℝ s.direction] (hd : finrank ℝ s.direction = 2) {c₁ c₂ p₁ p₂ p : P} (hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have ho : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hp₂c₁.symm) (hp₁c₂.trans hp₂c₂.symm), have hop : ⟪c₂ -ᵥ c₁, p -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (hp₁c₁.trans hpc₁.symm) (hp₁c₂.trans hpc₂.symm), let b : fin 2 → V := ![c₂ -ᵥ c₁, p₂ -ᵥ p₁], have hb : linear_independent ℝ b, { refine linear_independent_of_ne_zero_of_inner_eq_zero _ _, { intro i, fin_cases i; simp [b, hc.symm, hp.symm], }, { intros i j hij, fin_cases i; fin_cases j; try { exact false.elim (hij rfl) }, { exact ho }, { rw real_inner_comm, exact ho } } }, have hbs : submodule.span ℝ (set.range b) = s.direction, { refine eq_of_le_of_finrank_eq _ _, { rw [submodule.span_le, set.range_subset_iff], intro i, fin_cases i, { exact vsub_mem_direction hc₂s hc₁s }, { exact vsub_mem_direction hp₂s hp₁s } }, { rw [finrank_span_eq_card hb, fintype.card_fin, hd] } }, have hv : ∀ v ∈ s.direction, ∃ t₁ t₂ : ℝ, v = t₁ • (c₂ -ᵥ c₁) + t₂ • (p₂ -ᵥ p₁), { intros v hv, have hr : set.range b = {c₂ -ᵥ c₁, p₂ -ᵥ p₁}, { have hu : (finset.univ : finset (fin 2)) = {0, 1}, by dec_trivial, rw [←fintype.coe_image_univ, hu], simp, refl }, rw [←hbs, hr, submodule.mem_span_insert] at hv, rcases hv with ⟨t₁, v', hv', hv⟩, rw submodule.mem_span_singleton at hv', rcases hv' with ⟨t₂, rfl⟩, exact ⟨t₁, t₂, hv⟩ }, rcases hv (p -ᵥ p₁) (vsub_mem_direction hps hp₁s) with ⟨t₁, t₂, hpt⟩, simp only [hpt, inner_add_right, inner_smul_right, ho, mul_zero, add_zero, mul_eq_zero, inner_self_eq_zero, vsub_eq_zero_iff_eq, hc.symm, or_false] at hop, rw [hop, zero_smul, zero_add, ←eq_vadd_iff_vsub_eq] at hpt, subst hpt, have hp' : (p₂ -ᵥ p₁ : V) ≠ 0, { simp [hp.symm] }, have hp₂ : dist ((1 : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁) c₁ = r₁, { simp [hp₂c₁] }, rw [←hp₁c₁, dist_smul_vadd_eq_dist _ _ hp'] at hpc₁ hp₂, simp only [one_ne_zero, false_or] at hp₂, rw hp₂.symm at hpc₁, cases hpc₁; simp [hpc₁] end /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_finrank_eq_two [finite_dimensional ℝ V] (hd : finrank ℝ V = 2) {c₁ c₂ p₁ p₂ p : P} {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have hd' : finrank ℝ (⊤ : affine_subspace ℝ P).direction = 2, { rw [direction_top, finrank_top], exact hd }, exact eq_of_dist_eq_of_dist_eq_of_mem_of_finrank_eq_two hd' (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) hc hp hp₁c₁ hp₂c₁ hpc₁ hp₁c₂ hp₂c₂ hpc₂ end variables {V} /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : P := classical.some $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.directionᗮ) begin rw direction_mk' p s.directionᗮ, exact submodule.is_compl_orthogonal_of_complete_space, end /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection_fn` of that point onto the subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma inter_eq_singleton_orthogonal_projection_fn {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection_fn s p} := classical.some_spec $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.directionᗮ) begin rw direction_mk' p s.directionᗮ, exact submodule.is_compl_orthogonal_of_complete_space end /-- The `orthogonal_projection_fn` lies in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ s := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_left _ _ end /-- The `orthogonal_projection_fn` lies in the orthogonal subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ mk' p s.directionᗮ := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_right _ _ end /-- Subtracting `p` from its `orthogonal_projection_fn` produces a result in the orthogonal direction. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_vsub_mem_direction_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p -ᵥ p ∈ s.directionᗮ := direction_mk' p s.directionᗮ ▸ vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal p) (self_mem_mk' _ _) /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete. The corresponding linear map (mapping a vector to the difference between the projections of two points whose difference is that vector) is the `orthogonal_projection` for real inner product spaces, onto the direction of the affine subspace being projected onto. -/ def orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P →ᵃ[ℝ] s := { to_fun := λ p, ⟨orthogonal_projection_fn s p, orthogonal_projection_fn_mem p⟩, linear := orthogonal_projection s.direction, map_vadd' := λ p v, begin have hs : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ s := vadd_mem_of_mem_direction (orthogonal_projection s.direction v).2 (orthogonal_projection_fn_mem p), have ho : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ mk' (v +ᵥ p) s.directionᗮ, { rw [←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _) _, direction_mk', vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc], refine submodule.add_mem _ (orthogonal_projection_fn_vsub_mem_direction_orthogonal p) _, rw submodule.mem_orthogonal', intros w hw, rw [←neg_sub, inner_neg_left, orthogonal_projection_inner_eq_zero _ w hw, neg_zero], }, have hm : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ ({orthogonal_projection_fn s (v +ᵥ p)} : set P), { rw ←inter_eq_singleton_orthogonal_projection_fn (v +ᵥ p), exact set.mem_inter hs ho }, rw set.mem_singleton_iff at hm, ext, exact hm.symm end } @[simp] lemma orthogonal_projection_fn_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p = orthogonal_projection s p := rfl /-- The linear map corresponding to `orthogonal_projection`. -/ @[simp] lemma orthogonal_projection_linear {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] : (orthogonal_projection s).linear = _root_.orthogonal_projection s.direction := rfl /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection` of that point onto the subspace. -/ lemma inter_eq_singleton_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.directionᗮ) = {orthogonal_projection s p} := begin rw ←orthogonal_projection_fn_eq, exact inter_eq_singleton_orthogonal_projection_fn p end /-- The `orthogonal_projection` lies in the given subspace. -/ lemma orthogonal_projection_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ s := (orthogonal_projection s p).2 /-- The `orthogonal_projection` lies in the orthogonal subspace. -/ lemma orthogonal_projection_mem_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ mk' p s.directionᗮ := orthogonal_projection_fn_mem_orthogonal p /-- Subtracting a point in the given subspace from the `orthogonal_projection` produces a result in the direction of the given subspace. -/ lemma orthogonal_projection_vsub_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑(orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction) ∈ s.direction := (orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction).2 /-- Subtracting the `orthogonal_projection` from a point in the given subspace produces a result in the direction of the given subspace. -/ lemma vsub_orthogonal_projection_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction) ∈ s.direction := ((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction).2 /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : ↑(orthogonal_projection s p) = p ↔ p ∈ s := begin split, { exact λ h, h ▸ orthogonal_projection_mem p }, { intro h, have hp : p ∈ ((s : set P) ∩ mk' p s.directionᗮ) := ⟨h, self_mem_mk' p _⟩, rw [inter_eq_singleton_orthogonal_projection p] at hp, symmetry, exact hp } end @[simp] lemma orthogonal_projection_mem_subspace_eq_self {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : s) : orthogonal_projection s p = p := begin ext, rw orthogonal_projection_eq_self_iff, exact p.2 end /-- Orthogonal projection is idempotent. -/ @[simp] lemma orthogonal_projection_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection s (orthogonal_projection s p) = orthogonal_projection s p := begin ext, rw orthogonal_projection_eq_self_iff, exact orthogonal_projection_mem p, end lemma eq_orthogonal_projection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (orthogonal_projection s p : P) = (orthogonal_projection s' p : P) := begin change orthogonal_projection_fn s p = orthogonal_projection_fn s' p, congr, exact h end /-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/ lemma dist_orthogonal_projection_eq_zero_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : dist p (orthogonal_projection s p) = 0 ↔ p ∈ s := by rw [dist_comm, dist_eq_zero, orthogonal_projection_eq_self_iff] /-- The distance between a point and its orthogonal projection is nonzero if it does not lie in the subspace. -/ lemma dist_orthogonal_projection_ne_zero_of_not_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∉ s) : dist p (orthogonal_projection s p) ≠ 0 := mt dist_orthogonal_projection_eq_zero_iff.mp hp /-- Subtracting `p` from its `orthogonal_projection` produces a result in the orthogonal direction. -/ lemma orthogonal_projection_vsub_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : (orthogonal_projection s p : P) -ᵥ p ∈ s.directionᗮ := orthogonal_projection_fn_vsub_mem_direction_orthogonal p /-- Subtracting the `orthogonal_projection` from `p` produces a result in the orthogonal direction. -/ lemma vsub_orthogonal_projection_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : p -ᵥ orthogonal_projection s p ∈ s.directionᗮ := direction_mk' p s.directionᗮ ▸ vsub_mem_direction (self_mem_mk' _ _) (orthogonal_projection_mem_orthogonal s p) /-- Subtracting the `orthogonal_projection` from `p` produces a result in the kernel of the linear part of the orthogonal projection. -/ lemma orthogonal_projection_vsub_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : _root_.orthogonal_projection s.direction (p -ᵥ orthogonal_projection s p) = 0 := begin apply orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero, intros c hc, rw [← neg_vsub_eq_vsub_rev, inner_neg_right, (orthogonal_projection_vsub_mem_direction_orthogonal s p c hc), neg_zero] end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector was in the orthogonal direction. -/ lemma orthogonal_projection_vadd_eq_self {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.directionᗮ) : orthogonal_projection s (v +ᵥ p) = ⟨p, hp⟩ := begin have h := vsub_orthogonal_projection_mem_direction_orthogonal s (v +ᵥ p), rw [vadd_vsub_assoc, submodule.add_mem_iff_right _ hv] at h, refine (eq_of_vsub_eq_zero _).symm, ext, refine submodule.disjoint_def.1 s.direction.orthogonal_disjoint _ _ h, exact (_ : s.direction).2 end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) : orthogonal_projection s (r • (p2 -ᵥ orthogonal_projection s p2 : V) +ᵥ p1) = ⟨p1, hp⟩ := orthogonal_projection_vadd_eq_self hp (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) /-- The square of the distance from a point in `s` to `p2` equals the sum of the squares of the distances of the two points to the `orthogonal_projection`. -/ lemma dist_sq_eq_dist_orthogonal_projection_sq_add_dist_orthogonal_projection_sq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : dist p1 p2 * dist p1 p2 = dist p1 (orthogonal_projection s p2) * dist p1 (orthogonal_projection s p2) + dist p2 (orthogonal_projection s p2) * dist p2 (orthogonal_projection s p2) := begin rw [dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (orthogonal_projection s p2) p2, norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero], exact submodule.inner_right_of_mem_orthogonal (vsub_orthogonal_projection_mem_direction p2 hp1) (orthogonal_projection_vsub_mem_direction_orthogonal s p2), end /-- The square of the distance between two points constructed by adding multiples of the same orthogonal vector to points in the same subspace. -/ lemma dist_sq_smul_orthogonal_vadd_smul_orthogonal_vadd {s : affine_subspace ℝ P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 r2 : ℝ) {v : V} (hv : v ∈ s.directionᗮ) : dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) := calc dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ * ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ : by rw [dist_eq_norm_vsub V (r1 • v +ᵥ p1), vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, sub_smul, add_comm, add_sub_assoc] ... = ∥p1 -ᵥ p2∥ * ∥p1 -ᵥ p2∥ + ∥(r1 - r2) • v∥ * ∥(r1 - r2) • v∥ : norm_add_sq_eq_norm_sq_add_norm_sq_real (submodule.inner_right_of_mem_orthogonal (vsub_mem_direction hp1 hp2) (submodule.smul_mem _ _ hv)) ... = ∥(p1 -ᵥ p2 : V)∥ * ∥(p1 -ᵥ p2 : V)∥ + |r1 - r2| * |r1 - r2| * ∥v∥ * ∥v∥ : by { rw [norm_smul, real.norm_eq_abs], ring } ... = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) : by { rw [dist_eq_norm_vsub V p1, abs_mul_abs_self, mul_assoc] } /-- Reflection in an affine subspace, which is expected to be nonempty and complete. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in an affine subspace, is a more general sense of the word that includes both those common cases. -/ def reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P ≃ᵃⁱ[ℝ] P := affine_isometry_equiv.mk' (λ p, (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p) (_root_.reflection s.direction) ↑(classical.arbitrary s) begin intros p, let v := p -ᵥ ↑(classical.arbitrary s), let a : V := _root_.orthogonal_projection s.direction v, let b : P := ↑(classical.arbitrary s), have key : a +ᵥ b -ᵥ (v +ᵥ b) +ᵥ (a +ᵥ b) = a + a - v +ᵥ (b -ᵥ b +ᵥ b), { rw [← add_vadd, vsub_vadd_eq_vsub_sub, vsub_vadd, vadd_vsub], congr' 1, abel }, have : p = v +ᵥ ↑(classical.arbitrary s) := (vsub_vadd p ↑(classical.arbitrary s)).symm, simpa only [coe_vadd, reflection_apply, affine_map.map_vadd, orthogonal_projection_linear, orthogonal_projection_mem_subspace_eq_self, vadd_vsub, continuous_linear_map.coe_coe, continuous_linear_equiv.coe_coe, this] using key, end /-- The result of reflecting. -/ lemma reflection_apply (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s p = (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p := rfl lemma eq_reflection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (reflection s p : P) = (reflection s' p : P) := by unfreezingI { subst h } /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s (reflection s p) = p := begin have : ∀ a : s, ∀ b : V, (_root_.orthogonal_projection s.direction) b = 0 → reflection s (reflection s (b +ᵥ a)) = b +ᵥ a, { intros a b h, have : (a:P) -ᵥ (b +ᵥ a) = - b, { rw [vsub_vadd_eq_vsub_sub, vsub_self, zero_sub] }, simp [reflection, h, this] }, rw ← vsub_vadd p (orthogonal_projection s p), exact this (orthogonal_projection s p) _ (orthogonal_projection_vsub_orthogonal_projection s p), end /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : (reflection s).symm = reflection s := by { ext, rw ← (reflection s).injective.eq_iff, simp } /-- Reflection is involutive. -/ lemma reflection_involutive (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : function.involutive (reflection s) := reflection_reflection s /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : reflection s p = p ↔ p ∈ s := begin rw [←orthogonal_projection_eq_self_iff, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc, ←two_smul ℝ (↑(orthogonal_projection s p) -ᵥ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, simp [h] } end /-- Reflecting a point in two subspaces produces the same result if and only if the point has the same orthogonal projection in each of those subspaces. -/ lemma reflection_eq_iff_orthogonal_projection_eq (s₁ s₂ : affine_subspace ℝ P) [nonempty s₁] [nonempty s₂] [complete_space s₁.direction] [complete_space s₂.direction] (p : P) : reflection s₁ p = reflection s₂ p ↔ (orthogonal_projection s₁ p : P) = orthogonal_projection s₂ p := begin rw [reflection_apply, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc, vsub_sub_vsub_cancel_right, ←two_smul ℝ ((orthogonal_projection s₁ p : P) -ᵥ orthogonal_projection s₂ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, rw h } end /-- The distance between `p₁` and the reflection of `p₂` equals that between the reflection of `p₁` and `p₂`. -/ lemma dist_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p₁ p₂ : P) : dist p₁ (reflection s p₂) = dist (reflection s p₁) p₂ := begin conv_lhs { rw ←reflection_reflection s p₁ }, exact (reflection s).dist_map _ _ end /-- A point in the subspace is equidistant from another point and its reflection. -/ lemma dist_reflection_eq_of_mem (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] {p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) : dist p₁ (reflection s p₂) = dist p₁ p₂ := begin rw ←reflection_eq_self_iff p₁ at hp₁, convert (reflection s).dist_map p₁ p₂, rw hp₁ end /-- The reflection of a point in a subspace is contained in any larger subspace containing both the point and the subspace reflected in. -/ lemma reflection_mem_of_le_of_mem {s₁ s₂ : affine_subspace ℝ P} [nonempty s₁] [complete_space s₁.direction] (hle : s₁ ≤ s₂) {p : P} (hp : p ∈ s₂) : reflection s₁ p ∈ s₂ := begin rw [reflection_apply], have ho : ↑(orthogonal_projection s₁ p) ∈ s₂ := hle (orthogonal_projection_mem p), exact vadd_mem_of_mem_direction (vsub_mem_direction ho hp) ho end /-- Reflecting an orthogonal vector plus a point in the subspace produces the negation of that vector plus the point. -/ lemma reflection_orthogonal_vadd {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.directionᗮ) : reflection s (v +ᵥ p) = -v +ᵥ p := begin rw [reflection_apply, orthogonal_projection_vadd_eq_self hp hv, vsub_vadd_eq_vsub_sub], simp end /-- Reflecting a vector plus a point in the subspace produces the negation of that vector plus the point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma reflection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) : reflection s (r • (p₂ -ᵥ orthogonal_projection s p₂) +ᵥ p₁) = -(r • (p₂ -ᵥ orthogonal_projection s p₂)) +ᵥ p₁ := reflection_orthogonal_vadd hp₁ (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) omit V /-- A set of points is cospherical if they are equidistant from some point. In two dimensions, this is the same thing as being concyclic. -/ def cospherical (ps : set P) : Prop := ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius /-- The definition of `cospherical`. -/ lemma cospherical_def (ps : set P) : cospherical ps ↔ ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := iff.rfl /-- A subset of a cospherical set is cospherical. -/ lemma cospherical_subset {ps₁ ps₂ : set P} (hs : ps₁ ⊆ ps₂) (hc : cospherical ps₂) : cospherical ps₁ := begin rcases hc with ⟨c, r, hcr⟩, exact ⟨c, r, λ p hp, hcr p (hs hp)⟩ end include V /-- The empty set is cospherical. -/ lemma cospherical_empty : cospherical (∅ : set P) := begin use add_torsor.nonempty.some, simp, end omit V /-- A single point is cospherical. -/ lemma cospherical_singleton (p : P) : cospherical ({p} : set P) := begin use p, simp end include V /-- Two points are cospherical. -/ lemma cospherical_pair (p₁ p₂ : P) : cospherical ({p₁, p₂} : set P) := begin use [(2⁻¹ : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁, (2⁻¹ : ℝ) * (dist p₂ p₁)], intro p, rw [set.mem_insert_iff, set.mem_singleton_iff], rintro ⟨_|_⟩, { rw [dist_eq_norm_vsub V p₁, vsub_vadd_eq_vsub_sub, vsub_self, zero_sub, norm_neg, norm_smul, dist_eq_norm_vsub V p₂], simp }, { rw [H, dist_eq_norm_vsub V p₂, vsub_vadd_eq_vsub_sub, dist_eq_norm_vsub V p₂], conv_lhs { congr, congr, rw ←one_smul ℝ (p₂ -ᵥ p₁ : V) }, rw [←sub_smul, norm_smul], norm_num } end /-- Any three points in a cospherical set are affinely independent. -/ lemma cospherical.affine_independent {s : set P} (hs : cospherical s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := begin rw affine_independent_iff_not_collinear, intro hc, rw collinear_iff_of_mem ℝ (set.mem_range_self (0 : fin 3)) at hc, rcases hc with ⟨v, hv⟩, rw set.forall_range_iff at hv, have hv0 : v ≠ 0, { intro h, have he : p 1 = p 0, by simpa [h] using hv 1, exact (dec_trivial : (1 : fin 3) ≠ 0) (hpi he) }, rcases hs with ⟨c, r, hs⟩, have hs' := λ i, hs (p i) (set.mem_of_mem_of_subset (set.mem_range_self _) hps), choose f hf using hv, have hsd : ∀ i, dist ((f i • v) +ᵥ p 0) c = r, { intro i, rw ←hf, exact hs' i }, have hf0 : f 0 = 0, { have hf0' := hf 0, rw [eq_comm, ←@vsub_eq_zero_iff_eq V, vadd_vsub, smul_eq_zero] at hf0', simpa [hv0] using hf0' }, have hfi : function.injective f, { intros i j h, have hi := hf i, rw [h, ←hf j] at hi, exact hpi hi }, simp_rw [←hsd 0, hf0, zero_smul, zero_vadd, dist_smul_vadd_eq_dist (p 0) c hv0] at hsd, have hfn0 : ∀ i, i ≠ 0 → f i ≠ 0 := λ i, (hfi.ne_iff' hf0).2, have hfn0' : ∀ i, i ≠ 0 → f i = (-2) * ⟪v, (p 0 -ᵥ c)⟫ / ⟪v, v⟫, { intros i hi, have hsdi := hsd i, simpa [hfn0, hi] using hsdi }, have hf12 : f 1 = f 2, { rw [hfn0' 1 dec_trivial, hfn0' 2 dec_trivial] }, exact (dec_trivial : (1 : fin 3) ≠ 2) (hfi hf12) end end euclidean_geometry
f6268ee7e6b02cf2f409a2d53e908d24ea393dfc
ac89c256db07448984849346288e0eeffe8b20d0
/stage0/src/Lean/Parser/Basic.lean
a9740fa7d441f3bbb24eee95730d38280b6ac9e6
[ "Apache-2.0" ]
permissive
chepinzhang/lean4
002cc667f35417a418f0ebc9cb4a44559bb0ccac
24fe2875c68549b5481f07c57eab4ad4a0ae5305
refs/heads/master
1,688,942,838,326
1,628,801,942,000
1,628,801,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
76,132
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Data.Trie import Lean.Data.Position import Lean.Syntax import Lean.ToExpr import Lean.Environment import Lean.Attributes import Lean.Message import Lean.Compiler.InitAttr import Lean.ResolveName /-! # Basic Lean parser infrastructure The Lean parser was developed with the following primary goals in mind: * flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach. * extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens. * losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token" information for the use in tooling. * performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be necessary for this. Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we usually use the macro `leading_parser p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the declaration being defined. The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser` for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace. The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information: `collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST" token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel. If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator. This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these parallel parsers apart from the first token, though we might change this in the future if the need arises. Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly. Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips tokens until the next command keyword on error. -/ namespace Lean namespace Parser def isLitKind (k : SyntaxNodeKind) : Bool := k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind || k == scientificLitKind abbrev mkAtom (info : SourceInfo) (val : String) : Syntax := Syntax.atom info val abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax := Syntax.ident info rawVal val [] /- Return character after position `pos` -/ def getNext (input : String) (pos : Nat) : Char := input.get (input.next pos) /- Maximal (and function application) precedence. In the standard lean language, no parser has precedence higher than `maxPrec`. Note that nothing prevents users from using a higher precedence, but we strongly discourage them from doing it. -/ def maxPrec : Nat := eval_prec max def argPrec : Nat := eval_prec arg def leadPrec : Nat := eval_prec lead def minPrec : Nat := eval_prec min abbrev Token := String structure TokenCacheEntry where startPos : String.Pos := 0 stopPos : String.Pos := 0 token : Syntax := Syntax.missing structure ParserCache where tokenCache : TokenCacheEntry def initCacheForInput (input : String) : ParserCache := { tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/} } abbrev TokenTable := Trie Token abbrev SyntaxNodeKindSet := Std.PersistentHashMap SyntaxNodeKind Unit def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet := Std.PersistentHashMap.insert s k () /- Input string and related data. Recall that the `FileMap` is a helper structure for mapping `String.Pos` in the input string to line/column information. -/ structure InputContext where input : String fileName : String fileMap : FileMap deriving Inhabited /-- Input context derived from elaboration of previous commands. -/ structure ParserModuleContext where env : Environment options : Options -- for name lookup currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] structure ParserContext extends InputContext, ParserModuleContext where prec : Nat tokens : TokenTable quotDepth : Nat := 0 suppressInsideQuot : Bool := false savedPos? : Option String.Pos := none forbiddenTk? : Option Token := none def ParserContext.resolveName (ctx : ParserContext) (id : Name) : List (Name × List String) := ResolveName.resolveGlobalName ctx.env ctx.currNamespace ctx.openDecls id structure Error where unexpected : String := "" expected : List String := [] deriving Inhabited, BEq namespace Error private def expectedToString : List String → String | [] => "" | [e] => e | [e1, e2] => e1 ++ " or " ++ e2 | e::es => e ++ ", " ++ expectedToString es protected def toString (e : Error) : String := let unexpected := if e.unexpected == "" then [] else [e.unexpected] let expected := if e.expected == [] then [] else let expected := e.expected.toArray.qsort (fun e e' => e < e') let expected := expected.toList.eraseReps ["expected " ++ expectedToString expected] "; ".intercalate $ unexpected ++ expected instance : ToString Error := ⟨Error.toString⟩ def merge (e₁ e₂ : Error) : Error := match e₂ with | { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected } end Error structure ParserState where stxStack : Array Syntax := #[] /-- Set to the precedence of the preceding (not surrounding) parser by `runLongestMatchParser` for the use of `checkLhsPrec` in trailing parsers. Note that with chaining, the preceding parser can be another trailing parser: in `1 * 2 + 3`, the preceding parser is '*' when '+' is executed. -/ lhsPrec : Nat := 0 pos : String.Pos := 0 cache : ParserCache errorMsg : Option Error := none namespace ParserState @[inline] def hasError (s : ParserState) : Bool := s.errorMsg != none @[inline] def stackSize (s : ParserState) : Nat := s.stxStack.size def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos } def setPos (s : ParserState) (pos : Nat) : ParserState := { s with pos := pos } def setCache (s : ParserState) (cache : ParserCache) : ParserState := { s with cache := cache } def pushSyntax (s : ParserState) (n : Syntax) : ParserState := { s with stxStack := s.stxStack.push n } def popSyntax (s : ParserState) : ParserState := { s with stxStack := s.stxStack.pop } def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz } def next (s : ParserState) (input : String) (pos : Nat) : ParserState := { s with pos := input.next pos } def toErrorMsg (ctx : ParserContext) (s : ParserState) : String := match s.errorMsg with | none => "" | some msg => let pos := ctx.fileMap.toPosition s.pos mkErrorStringWithPos ctx.fileName pos (toString msg) def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => if err != none && stack.size == iniStackSz then -- If there is an error but there are no new nodes on the stack, use `missing` instead. -- Thus we ensure the property that an syntax tree contains (at least) one `missing` node -- if (and only if) there was a parse error. -- We should not create an actual node of kind `k` in this case because it would mean we -- choose an "arbitrary" node (in practice the last one) in an alternative of the form -- `node k1 p1 <|> ... <|> node kn pn` when all parsers fail. With the code below we -- instead return a less misleading single `missing` node without randomly selecting any `ki`. let stack := stack.push Syntax.missing ⟨stack, lhsPrec, pos, cache, err⟩ else let newNode := Syntax.node k (stack.extract iniStackSz stack.size) let stack := stack.shrink iniStackSz let stack := stack.push newNode ⟨stack, lhsPrec, pos, cache, err⟩ def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size) let stack := stack.shrink (iniStackSz - 1) let stack := stack.push newNode ⟨stack, lhsPrec, pos, cache, err⟩ def setError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkUnexpectedError (s : ParserState) (msg : String) (expected : List String := []) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg, expected := expected }⟩ def mkEOIError (s : ParserState) (expected : List String := []) : ParserState := s.mkUnexpectedError "unexpected end of input" expected def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState := match s, initStackSz? with | ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ | ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := [ msg ] }⟩ def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) (initStackSz? : Option Nat := none) : ParserState := match s, initStackSz? with | ⟨stack, lhsPrec, _, cache, _⟩, none => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩ | ⟨stack, lhsPrec, _, cache, _⟩, some sz => ⟨stack.shrink sz |>.push Syntax.missing, lhsPrec, pos, cache, some { expected := ex }⟩ def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState := match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩ end ParserState def ParserFn := ParserContext → ParserState → ParserState instance : Inhabited ParserFn where default := fun ctx s => s inductive FirstTokens where | epsilon : FirstTokens | unknown : FirstTokens | tokens : List Token → FirstTokens | optTokens : List Token → FirstTokens deriving Inhabited namespace FirstTokens def seq : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => tks | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | tks, _ => tks def toOptional : FirstTokens → FirstTokens | tokens tks => optTokens tks | tks => tks def merge : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => toOptional tks | tks, epsilon => toOptional tks | tokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂) | _, _ => unknown def toStr : FirstTokens → String | epsilon => "epsilon" | unknown => "unknown" | tokens tks => toString tks | optTokens tks => "?" ++ toString tks instance : ToString FirstTokens := ⟨toStr⟩ end FirstTokens structure ParserInfo where collectTokens : List Token → List Token := id collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id firstTokens : FirstTokens := FirstTokens.unknown deriving Inhabited structure Parser where info : ParserInfo := {} fn : ParserFn deriving Inhabited abbrev TrailingParser := Parser def dbgTraceStateFn (label : String) (p : ParserFn) : ParserFn := fun c s => let sz := s.stxStack.size let s' := p c s dbg_trace "{label} pos: {s'.pos} err: {s'.errorMsg} out: {s'.stxStack.extract sz s'.stxStack.size}" s' def dbgTraceState (label : String) (p : Parser) : Parser where fn := dbgTraceStateFn label p.fn info := p.info @[noinline] def epsilonInfo : ParserInfo := { firstTokens := FirstTokens.epsilon } @[inline] def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn := fun c s => if p s.stxStack.back then s else s.mkUnexpectedError msg @[inline] def checkStackTop (p : Syntax → Bool) (msg : String) : Parser := { info := epsilonInfo, fn := checkStackTopFn p msg } @[inline] def andthenFn (p q : ParserFn) : ParserFn := fun c s => let s := p c s if s.hasError then s else q c s @[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.seq q.firstTokens } @[inline] def andthen (p q : Parser) : Parser := { info := andthenInfo p.info q.info, fn := andthenFn p.fn q.fn } instance : AndThen Parser := ⟨andthen⟩ @[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkNode n iniSz @[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkTrailingNode n iniSz @[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := fun s => (p.collectKinds s).insert n, firstTokens := p.firstTokens } @[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser := { info := nodeInfo n p.info, fn := nodeFn n p.fn } def errorFn (msg : String) : ParserFn := fun _ s => s.mkUnexpectedError msg @[inline] def error (msg : String) : Parser := { info := epsilonInfo, fn := errorFn msg } def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s => match c.savedPos? with | none => s | some pos => let pos := if delta then c.input.next pos else pos match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩ /- Generate an error at the position saved with the `withPosition` combinator. If `delta == true`, then it reports at saved position+1. This useful to make sure a parser consumed at least one character. -/ @[inline] def errorAtSavedPos (msg : String) (delta : Bool) : Parser := { fn := errorAtSavedPosFn msg delta } /- Succeeds if `c.prec <= prec` -/ def checkPrecFn (prec : Nat) : ParserFn := fun c s => if c.prec <= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" @[inline] def checkPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkPrecFn prec } /- Succeeds if `c.lhsPrec >= prec` -/ def checkLhsPrecFn (prec : Nat) : ParserFn := fun c s => if s.lhsPrec >= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" @[inline] def checkLhsPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkLhsPrecFn prec } def setLhsPrecFn (prec : Nat) : ParserFn := fun c s => if s.hasError then s else { s with lhsPrec := prec } @[inline] def setLhsPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := setLhsPrecFn prec } def checkInsideQuotFn : ParserFn := fun c s => if c.quotDepth > 0 && !c.suppressInsideQuot then s else s.mkUnexpectedError "unexpected syntax outside syntax quotation" @[inline] def checkInsideQuot : Parser := { info := epsilonInfo, fn := checkInsideQuotFn } def checkOutsideQuotFn : ParserFn := fun c s => if !c.quotDepth == 0 || c.suppressInsideQuot then s else s.mkUnexpectedError "unexpected syntax inside syntax quotation" @[inline] def checkOutsideQuot : Parser := { info := epsilonInfo, fn := checkOutsideQuotFn } def addQuotDepthFn (i : Int) (p : ParserFn) : ParserFn := fun c s => p { c with quotDepth := c.quotDepth + i |>.toNat } s @[inline] def incQuotDepth (p : Parser) : Parser := { info := p.info, fn := addQuotDepthFn 1 p.fn } @[inline] def decQuotDepth (p : Parser) : Parser := { info := p.info, fn := addQuotDepthFn (-1) p.fn } def suppressInsideQuotFn (p : ParserFn) : ParserFn := fun c s => p { c with suppressInsideQuot := true } s @[inline] def suppressInsideQuot (p : Parser) : Parser := { info := p.info, fn := suppressInsideQuotFn p.fn } @[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser := checkPrec prec >> node n p >> setLhsPrec prec @[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := { info := nodeInfo n p.info, fn := trailingNodeFn n p.fn } @[inline] def trailingNode (n : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parser) : TrailingParser := checkPrec prec >> checkLhsPrec lhsPrec >> trailingNodeAux n p >> setLhsPrec prec def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) (mergeErrors : Bool) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some error2⟩ => if pos == iniPos then ⟨stack, lhsPrec, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩ else s | other => other def orelseFnCore (p q : ParserFn) (mergeErrors : Bool) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s match s.errorMsg with | some errorMsg => if s.pos == iniPos then mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos mergeErrors else s | none => s @[inline] def orelseFn (p q : ParserFn) : ParserFn := orelseFnCore p q true @[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.merge q.firstTokens } /-- Run `p`, falling back to `q` if `p` failed without consuming any input. NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...` is fine as well. -/ @[inline] def orelse (p q : Parser) : Parser := { info := orelseInfo p.info q.info, fn := orelseFn p.fn q.fn } instance : OrElse Parser := ⟨orelse⟩ @[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := { collectTokens := info.collectTokens, collectKinds := info.collectKinds } def atomicFn (p : ParserFn) : ParserFn := fun c s => let iniPos := s.pos match p c s with | ⟨stack, lhsPrec, _, cache, some msg⟩ => ⟨stack, lhsPrec, iniPos, cache, some msg⟩ | other => other @[inline] def atomic (p : Parser) : Parser := { info := p.info, fn := atomicFn p.fn } def optionalFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s s.mkNode nullKind iniSz @[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds, firstTokens := p.firstTokens.toOptional } @[inline] def optionalNoAntiquot (p : Parser) : Parser := { info := optionaInfo p.info, fn := optionalFn p.fn } def lookaheadFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s else s.restore iniSz iniPos @[inline] def lookahead (p : Parser) : Parser := { info := p.info, fn := lookaheadFn p.fn } def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s.restore iniSz iniPos else let s := s.restore iniSz iniPos s.mkUnexpectedError s!"unexpected {msg}" @[inline] def notFollowedBy (p : Parser) (msg : String) : Parser := { fn := notFollowedByFn p.fn msg } partial def manyAux (p : ParserFn) : ParserFn := fun c s => do let iniSz := s.stackSize let iniPos := s.pos let mut s := p c s if s.hasError then return if iniPos == s.pos then s.restore iniSz iniPos else s if iniPos == s.pos then return s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything" if s.stackSize > iniSz + 1 then s := s.mkNode nullKind iniSz manyAux p c s @[inline] def manyFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := manyAux p c s s.mkNode nullKind iniSz @[inline] def manyNoAntiquot (p : Parser) : Parser := { info := noFirstTokenInfo p.info, fn := manyFn p.fn } @[inline] def many1Fn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := andthenFn p (manyAux p) c s s.mkNode nullKind iniSz @[inline] def many1NoAntiquot (p : Parser) : Parser := { info := p.info, fn := many1Fn p.fn } private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn := let rec parse (pOpt : Bool) (c s) := do let sz := s.stackSize let pos := s.pos let mut s := p c s if s.hasError then if s.pos > pos then return s.mkNode nullKind iniSz else if pOpt then s := s.restore sz pos return s.mkNode nullKind iniSz else -- append `Syntax.missing` to make clear that List is incomplete s := s.pushSyntax Syntax.missing return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz let sz := s.stackSize let pos := s.pos s := sep c s if s.hasError then s := s.restore sz pos return s.mkNode nullKind iniSz if s.stackSize > sz + 1 then s := s.mkNode nullKind sz parse allowTrailingSep c s parse pOpt def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz true c s def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz false c s @[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds } @[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds, firstTokens := p.firstTokens } @[inline] def sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepByInfo p.info sep.info, fn := sepByFn allowTrailingSep p.fn sep.fn } @[inline] def sepBy1NoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepBy1Info p.info sep.info, fn := sepBy1Fn allowTrailingSep p.fn sep.fn } /- Apply `f` to the syntax object produced by `p` -/ def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn := fun c s => let s := p c s if s.hasError then s else let stx := s.stxStack.back s.popSyntax.pushSyntax (f stx) @[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds } @[inline] def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser := { info := withResultOfInfo p.info, fn := withResultOfFn p.fn f } @[inline] def many1Unbox (p : Parser) : Parser := withResultOf (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s.mkEOIError else if p (c.input.get i) then s.next c.input i else s.mkUnexpectedError errorMsg partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else if p (c.input.get i) then s else takeUntilFn p c (s.next c.input i) def takeWhileFn (p : Char → Bool) : ParserFn := takeUntilFn (fun c => !p c) @[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn := andthenFn (satisfyFn p errorMsg) (takeWhileFn p) partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then eoi s else let curr := input.get i let i := input.next i if curr == '-' then if input.atEnd i then eoi s else let curr := input.get i if curr == '/' then -- "-/" end of comment if nesting == 1 then s.next input i else finishCommentBlock (nesting-1) c (s.next input i) else finishCommentBlock nesting c (s.next input i) else if curr == '/' then if input.atEnd i then eoi s else let curr := input.get i if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i) else finishCommentBlock nesting c (s.setPos i) else finishCommentBlock nesting c (s.setPos i) where eoi s := s.mkUnexpectedError "unterminated comment" /- Consume whitespace and comments -/ partial def whitespace : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr == '\t' then s.mkUnexpectedError "tabs are not allowed; please configure your editor to expand them" else if curr.isWhitespace then whitespace c (s.next input i) else if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i) else s else if curr == '/' then let startPos := i let i := input.next i let curr := input.get i if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' || curr == '!' then s -- "/--" and "/-!" doc comment are actual tokens else andthenFn (finishCommentBlock 1) whitespace c (s.next input i) else s else s def mkEmptySubstringAt (s : String) (p : Nat) : Substring := { str := s, startPos := p, stopPos := p } private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos if trailingWs then let s := whitespace c s let stopPos' := s.pos let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val.bsize)) val s.pushSyntax atom else let trailing := mkEmptySubstringAt input stopPos let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val.bsize)) val s.pushSyntax atom /-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/ @[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s => let startPos := s.pos let s := p c s if s.hasError then s else rawAux startPos trailingWs c s @[inline] def chFn (c : Char) (trailingWs := false) : ParserFn := rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs def rawCh (c : Char) (trailingWs := false) : Parser := { fn := chFn c trailingWs } def hexDigitFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let i := input.next i if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i else s.mkUnexpectedError "invalid hexadecimal numeral" def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i if isQuotable curr then s.next input i else if curr == 'x' then andthenFn hexDigitFn hexDigitFn c (s.next input i) else if curr == 'u' then andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i) else s.mkUnexpectedError "invalid escape sequence" def isQuotableCharDefault (c : Char) : Bool := c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't' def quotedCharFn : ParserFn := quotedCharCoreFn isQuotableCharDefault /-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/ def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let info := SourceInfo.original leading startPos trailing stopPos s.pushSyntax (Syntax.mkLit n val info) def charLitFnAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let s := s.setPos (input.next i) let s := if curr == '\\' then quotedCharFn c s else s if s.hasError then s else let i := s.pos let curr := input.get i let s := s.setPos (input.next i) if curr == '\'' then mkNodeToken charLitKind startPos c s else s.mkUnexpectedError "missing end of character literal" partial def strLitFnAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkUnexpectedErrorAt "unterminated string literal" startPos else let curr := input.get i let s := s.setPos (input.next i) if curr == '\"' then mkNodeToken strLitKind startPos c s else if curr == '\\' then andthenFn quotedCharFn (strLitFnAux startPos) c s else strLitFnAux startPos c s def decimalNumberFn (startPos : Nat) (c : ParserContext) : ParserState → ParserState := fun s => let s := takeWhileFn (fun c => c.isDigit) c s let input := c.input let i := s.pos let curr := input.get i if curr == '.' || curr == 'e' || curr == 'E' then let s := parseOptDot s let s := parseOptExp s mkNodeToken scientificLitKind startPos c s else mkNodeToken numLitKind startPos c s where parseOptDot s := let input := c.input let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s parseOptExp s := let input := c.input let i := s.pos let curr := input.get i if curr == 'e' || curr == 'E' then let i := input.next i let i := if input.get i == '-' then input.next i else i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s def binNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s mkNodeToken numLitKind startPos c s def octalNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s mkNodeToken numLitKind startPos c s def hexNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s mkNodeToken numLitKind startPos c s def numberFnAux : ParserFn := fun c s => let input := c.input let startPos := s.pos if input.atEnd startPos then s.mkEOIError else let curr := input.get startPos if curr == '0' then let i := input.next startPos let curr := input.get i if curr == 'b' || curr == 'B' then binNumberFn startPos c (s.next input i) else if curr == 'o' || curr == 'O' then octalNumberFn startPos c (s.next input i) else if curr == 'x' || curr == 'X' then hexNumberFn startPos c (s.next input i) else decimalNumberFn startPos c (s.setPos i) else if curr.isDigit then decimalNumberFn startPos c (s.next input startPos) else s.mkError "numeral" def isIdCont : String → ParserState → Bool := fun input s => let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i if input.atEnd i then false else let curr := input.get i isIdFirst curr || isIdBeginEscape curr else false private def isToken (idStartPos idStopPos : Nat) (tk : Option Token) : Bool := match tk with | none => false | some tk => -- if a token is both a symbol and a valid identifier (i.e. a keyword), -- we want it to be recognized as a symbol tk.bsize ≥ idStopPos - idStartPos def mkTokenAndFixPos (startPos : Nat) (tk : Option Token) : ParserFn := fun c s => match tk with | none => s.mkErrorAt "token" startPos | some tk => if c.forbiddenTk? == some tk then s.mkErrorAt "forbidden token" startPos else let input := c.input let leading := mkEmptySubstringAt input startPos let stopPos := startPos + tk.bsize let s := s.setPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing stopPos) tk s.pushSyntax atom def mkIdResult (startPos : Nat) (tk : Option Token) (val : Name) : ParserFn := fun c s => let stopPos := s.pos if isToken startPos stopPos tk then mkTokenAndFixPos startPos tk c s else let input := c.input let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring } let s := whitespace c s let trailingStopPos := s.pos let leading := mkEmptySubstringAt input startPos let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring } let info := SourceInfo.original leading startPos trailing stopPos let atom := mkIdent info rawVal val s.pushSyntax atom partial def identFnAux (startPos : Nat) (tk : Option Token) (r : Name) : ParserFn := let rec parse (r : Name) (c s) := do let input := c.input let i := s.pos if input.atEnd i then return s.mkEOIError let curr := input.get i if isIdBeginEscape curr then let startPart := input.next i let s := takeUntilFn isIdEndEscape c (s.setPos startPart) if input.atEnd s.pos then return s.mkUnexpectedErrorAt "unterminated identifier escape" startPart let stopPart := s.pos let s := s.next c.input s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else if isIdFirst curr then let startPart := i let s := takeWhileFn isIdRest c (s.next input i) let stopPart := s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else mkTokenAndFixPos startPos tk c s parse r private def isIdFirstOrBeginEscape (c : Char) : Bool := isIdFirst c || isIdBeginEscape c private def nameLitAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let s := identFnAux startPos none Name.anonymous c (s.next input startPos) if s.hasError then s else let stx := s.stxStack.back match stx with | Syntax.ident info rawStr _ _ => let s := s.popSyntax s.pushSyntax (Syntax.mkNameLit rawStr.toString info) | _ => s.mkError "invalid Name literal" private def tokenFnAux : ParserFn := fun c s => let input := c.input let i := s.pos let curr := input.get i if curr == '\"' then strLitFnAux i c (s.next input i) else if curr == '\'' then charLitFnAux i c (s.next input i) else if curr.isDigit then numberFnAux c s else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then nameLitAux i c s else let (_, tk) := c.tokens.matchPrefix input i identFnAux i tk Name.anonymous c s private def updateCache (startPos : Nat) (s : ParserState) : ParserState := -- do not cache token parsing errors, which are rare and usually fatal and thus not worth an extra field in `TokenCache` match s with | ⟨stack, lhsPrec, pos, cache, none⟩ => if stack.size == 0 then s else let tk := stack.back ⟨stack, lhsPrec, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩ | other => other def tokenFn (expected : List String := []) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError expected else let tkc := s.cache.tokenCache if tkc.startPos == i then let s := s.pushSyntax tkc.token s.setPos tkc.stopPos else let s := tokenFnAux c s updateCache i s def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax := let iniSz := s.stackSize let iniPos := s.pos let s := tokenFn [] c s if let some e := s.errorMsg then (s.restore iniSz iniPos, Except.error s) else let stx := s.stxStack.back (s.restore iniSz iniPos, Except.ok stx) def peekToken (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax := let tkc := s.cache.tokenCache if tkc.startPos == s.pos then (s, Except.ok tkc.token) else peekTokenAux c s /- Treat keywords as identifiers. -/ def rawIdentFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else identFnAux i none Name.anonymous c s @[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn := fun c s => let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn expected c s if s.hasError then s else match s.stxStack.back with | Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos initStackSz | _ => s.mkErrorsAt expected startPos initStackSz def symbolFnAux (sym : String) (errorMsg : String) : ParserFn := satisfySymbolFn (fun s => s == sym) [errorMsg] def symbolInfo (sym : String) : ParserInfo := { collectTokens := fun tks => sym :: tks, firstTokens := FirstTokens.tokens [ sym ] } @[inline] def symbolFn (sym : String) : ParserFn := symbolFnAux sym ("'" ++ sym ++ "'") @[inline] def symbolNoAntiquot (sym : String) : Parser := let sym := sym.trim { info := symbolInfo sym, fn := symbolFn sym } def checkTailNoWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing _ => trailing.stopPos == trailing.startPos | _ => false /-- Check if the following token is the symbol _or_ identifier `sym`. Useful for parsing local tokens that have not been added to the token table (but may have been so by some unrelated code). For example, the universe `max` Function is parsed using this combinator so that it can still be used as an identifier outside of universe (but registering it as a token in a Term Syntax would not break the universe Parser). -/ def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s => let initStackSz := s.stackSize let startPos := s.pos let s := tokenFn [errorMsg] c s if s.hasError then s else match s.stxStack.back with | Syntax.atom _ sym' => if sym == sym' then s else s.mkErrorAt errorMsg startPos initStackSz | Syntax.ident info rawVal _ _ => if sym == rawVal.toString then let s := s.popSyntax s.pushSyntax (Syntax.atom info sym) else s.mkErrorAt errorMsg startPos initStackSz | _ => s.mkErrorAt errorMsg startPos initStackSz @[inline] def nonReservedSymbolFn (sym : String) : ParserFn := nonReservedSymbolFnAux sym ("'" ++ sym ++ "'") def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := { firstTokens := if includeIdent then FirstTokens.tokens [ sym, "ident" ] else FirstTokens.tokens [ sym ] } @[inline] def nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser := let sym := sym.trim { info := nonReservedSymbolInfo sym includeIdent, fn := nonReservedSymbolFn sym } partial def strAux (sym : String) (errorMsg : String) (j : Nat) :ParserFn := let rec parse (j c s) := if sym.atEnd j then s else let i := s.pos let input := c.input if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg else parse (sym.next j) c (s.next input i) parse j def checkTailWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing _ => trailing.stopPos > trailing.startPos | _ => false def checkWsBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := s.stxStack.back if checkTailWs prev then s else s.mkError errorMsg def checkWsBefore (errorMsg : String := "space before") : Parser := { info := epsilonInfo, fn := checkWsBeforeFn errorMsg } def checkTailLinebreak (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing _ => trailing.contains '\n' | _ => false def checkLinebreakBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := s.stxStack.back if checkTailLinebreak prev then s else s.mkError errorMsg def checkLinebreakBefore (errorMsg : String := "line break") : Parser := { info := epsilonInfo fn := checkLinebreakBeforeFn errorMsg } private def pickNonNone (stack : Array Syntax) : Syntax := match stack.findRev? $ fun stx => !stx.isNone with | none => Syntax.missing | some stx => stx def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := pickNonNone s.stxStack if checkTailNoWs prev then s else s.mkError errorMsg def checkNoWsBefore (errorMsg : String := "no space before") : Parser := { info := epsilonInfo, fn := checkNoWsBeforeFn errorMsg } def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn := satisfySymbolFn (fun s => s == sym || s == asciiSym) expected def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := { collectTokens := fun tks => sym :: asciiSym :: tks, firstTokens := FirstTokens.tokens [ sym, asciiSym ] } @[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn := unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"] @[inline] def unicodeSymbolNoAntiquot (sym asciiSym : String) : Parser := let sym := sym.trim let asciiSym := asciiSym.trim { info := unicodeSymbolInfo sym asciiSym, fn := unicodeSymbolFn sym asciiSym } def mkAtomicInfo (k : String) : ParserInfo := { firstTokens := FirstTokens.tokens [ k ] } def numLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["numeral"] c s if !s.hasError && !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos initStackSz else s @[inline] def numLitNoAntiquot : Parser := { fn := numLitFn, info := mkAtomicInfo "numLit" } def scientificLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["scientific number"] c s if !s.hasError && !(s.stxStack.back.isOfKind scientificLitKind) then s.mkErrorAt "scientific number" iniPos initStackSz else s @[inline] def scientificLitNoAntiquot : Parser := { fn := scientificLitFn, info := mkAtomicInfo "scientificLit" } def strLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["string literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos initStackSz else s @[inline] def strLitNoAntiquot : Parser := { fn := strLitFn, info := mkAtomicInfo "strLit" } def charLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["char literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos initStackSz else s @[inline] def charLitNoAntiquot : Parser := { fn := charLitFn, info := mkAtomicInfo "charLit" } def nameLitFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["Name literal"] c s if !s.hasError && !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos initStackSz else s @[inline] def nameLitNoAntiquot : Parser := { fn := nameLitFn, info := mkAtomicInfo "nameLit" } def identFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if !s.hasError && !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos initStackSz else s @[inline] def identNoAntiquot : Parser := { fn := identFn, info := mkAtomicInfo "ident" } @[inline] def rawIdentNoAntiquot : Parser := { fn := rawIdentFn } def identEqFn (id : Name) : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let s := tokenFn ["identifier"] c s if s.hasError then s else match s.stxStack.back with | Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos initStackSz else s | _ => s.mkErrorAt "identifier" iniPos initStackSz @[inline] def identEq (id : Name) : Parser := { fn := identEqFn id, info := mkAtomicInfo "ident" } namespace ParserState def keepTop (s : Array Syntax) (startStackSize : Nat) : Array Syntax := let node := s.back s.shrink startStackSize |>.push node def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, err⟩ => ⟨keepTop stack oldStackSize, lhsPrec, pos, cache, err⟩ def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState := match s with | ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.shrink oldStackSize, lhsPrec, oldStopPos, cache, oldError⟩ def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, some err⟩ => if oldError == err then s else ⟨stack.shrink oldStackSize, lhsPrec, pos, cache, some (oldError.merge err)⟩ | other => other def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState := match s with | ⟨stack, lhsPrec, pos, cache, _⟩ => ⟨keepTop stack startStackSize, lhsPrec, pos, cache, none⟩ def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState := s.keepLatest startStackSize end ParserState def invalidLongestMatchParser (s : ParserState) : ParserState := s.mkError "longestMatch parsers must generate exactly one Syntax node" /-- Auxiliary function used to execute parsers provided to `longestMatchFn`. Push `left?` into the stack if it is not `none`, and execute `p`. Remark: `p` must produce exactly one syntax node. Remark: the `left?` is not none when we are processing trailing parsers. -/ def runLongestMatchParser (left? : Option Syntax) (startLhsPrec : Nat) (p : ParserFn) : ParserFn := fun c s => do /- We assume any registered parser `p` has one of two forms: * a direct call to `leadingParser` or `trailingParser` * a direct call to a (leading) token parser In the first case, we can extract the precedence of the parser by having `leadingParser/trailingParser` set `ParserState.lhsPrec` to it in the very end so that no nested parser can interfere. In the second case, the precedence is effectively `max` (there is a `checkPrec` merely for the convenience of the pretty printer) and there are no nested `leadingParser/trailingParser` calls, so the value of `lhsPrec` will not be changed by the parser (nor will it be read by any leading parser). Thus we initialize the field to `maxPrec` in the leading case. -/ let mut s := { s with lhsPrec := if left?.isSome then startLhsPrec else maxPrec } let startSize := s.stackSize if let some left := left? then s := s.pushSyntax left s := p c s -- stack contains `[..., result ]` if s.stackSize == startSize + 1 then s -- success or error with the expected number of nodes else if s.hasError then -- error with an unexpected number of nodes. s.shrinkStack startSize |>.pushSyntax Syntax.missing else -- parser succeded with incorrect number of nodes invalidLongestMatchParser s def longestMatchStep (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn) : ParserContext → ParserState → ParserState × Nat := fun c s => let prevErrorMsg := s.errorMsg let prevStopPos := s.pos let prevSize := s.stackSize let prevLhsPrec := s.lhsPrec let s := s.restore prevSize startPos let s := runLongestMatchParser left? startLhsPrec p c s match prevErrorMsg, s.errorMsg with | none, none => -- both succeeded if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.replaceLongest startSize, prio) else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then ({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio) -- keep prev -- it is not clear what the precedence of a choice node should be, so we conservatively take the minimum else ({s with lhsPrec := s.lhsPrec.min prevLhsPrec }, prio) | none, some _ => -- prev succeeded, current failed ({ s.restore prevSize prevStopPos with lhsPrec := prevLhsPrec }, prevPrio) | some oldError, some _ => -- both failed if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.keepNewError startSize, prio) else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.keepPrevError prevSize prevStopPos prevErrorMsg, prevPrio) else (s.mergeErrors prevSize oldError, prio) | some _, none => -- prev failed, current succeeded let successNode := s.stxStack.back let s := s.shrinkStack startSize -- restore stack to initial size to make sure (failure) nodes are removed from the stack (s.pushSyntax successNode, prio) -- put successNode back on the stack def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState := if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s def longestMatchFnAux (left? : Option Syntax) (startSize startLhsPrec : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser × Nat)) : ParserFn := let rec parse (prevPrio : Nat) (ps : List (Parser × Nat)) := match ps with | [] => fun _ s => longestMatchMkResult startSize s | p::ps => fun c s => let (s, prevPrio) := longestMatchStep left? startSize startLhsPrec startPos prevPrio p.2 p.1.fn c s parse prevPrio ps c s parse prevPrio ps def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn | [] => fun _ s => s.mkError "longestMatch: empty list" | [p] => fun c s => runLongestMatchParser left? s.lhsPrec p.1.fn c s | p::ps => fun c s => let startSize := s.stackSize let startLhsPrec := s.lhsPrec let startPos := s.pos let s := runLongestMatchParser left? s.lhsPrec p.1.fn c s longestMatchFnAux left? startSize startLhsPrec startPos p.2 ps c s def anyOfFn : List Parser → ParserFn | [], _, s => s.mkError "anyOf: empty list" | [p], c, s => p.fn c s | p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s @[inline] def checkColGeFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column ≥ savedPos.column then s else s.mkError errorMsg @[inline] def checkColGe (errorMsg : String := "checkColGe") : Parser := { fn := checkColGeFn errorMsg } @[inline] def checkColGtFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column > savedPos.column then s else s.mkError errorMsg @[inline] def checkColGt (errorMsg : String := "checkColGt") : Parser := { fn := checkColGtFn errorMsg } @[inline] def checkLineEqFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.line == savedPos.line then s else s.mkError errorMsg @[inline] def checkLineEq (errorMsg : String := "checkLineEq") : Parser := { fn := checkLineEqFn errorMsg } @[inline] def withPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with savedPos? := s.pos } s } @[inline] def withoutPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => let pos := c.fileMap.toPosition s.pos p.fn { c with savedPos? := none } s } @[inline] def withForbidden (tk : Token) (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := tk } s } @[inline] def withoutForbidden (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := none } s } def eoiFn : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else s.mkError "expected end of file" @[inline] def eoi : Parser := { fn := eoiFn } open Std (RBMap RBMap.empty) /-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/ def TokenMap (α : Type) := RBMap Name (List α) Name.quickCmp namespace TokenMap def insert (map : TokenMap α) (k : Name) (v : α) : TokenMap α := match map.find? k with | none => Std.RBMap.insert map k [v] | some vs => Std.RBMap.insert map k (v::vs) instance : Inhabited (TokenMap α) := ⟨RBMap.empty⟩ instance : EmptyCollection (TokenMap α) := ⟨RBMap.empty⟩ end TokenMap structure PrattParsingTables where leadingTable : TokenMap (Parser × Nat) := {} leadingParsers : List (Parser × Nat) := [] -- for supporting parsers we cannot obtain first token trailingTable : TokenMap (Parser × Nat) := {} trailingParsers : List (Parser × Nat) := [] -- for supporting parsers such as function application instance : Inhabited PrattParsingTables := ⟨{}⟩ /- The type `leadingIdentBehavior` specifies how the parsing table lookup function behaves for identifiers. The function `prattParser` uses two tables `leadingTable` and `trailingTable`. They map tokens to parsers. - `LeadingIdentBehavior.default`: if the leading token is an identifier, then `prattParser` just executes the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.symbol`: if the leading token is an identifier `<foo>`, and there are parsers `P` associated with the toek `<foo>`, then it executes `P`. Otherwise, it executes only the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.both`: if the leading token an identifier `<foo>`, the it executes the parsers associated with token `<foo>` and parsers associated with the auxiliary token "ident". We use `LeadingIdentBehavior.symbol` and `LeadingIdentBehavior.both` and `nonReservedSymbol` parser to implement the `tactic` parsers. The idea is to avoid creating a reserved symbol for each builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users may still use these symbols as identifiers (e.g., naming a function). -/ inductive LeadingIdentBehavior where | default | symbol | both deriving Inhabited, BEq /-- Each parser category is implemented using a Pratt's parser. The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`. Users and plugins may define extra categories. The method ``` categoryParser `term prec ``` executes the Pratt's parser for category `term` with precedence `prec`. That is, only parsers with precedence at least `prec` are considered. The method `termParser prec` is equivalent to the method above. -/ structure ParserCategory where tables : PrattParsingTables behavior : LeadingIdentBehavior deriving Inhabited abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (behavior : LeadingIdentBehavior) : ParserState × List α := let (s, stx) := peekToken c s let find (n : Name) : ParserState × List α := match map.find? n with | some as => (s, as) | _ => (s, []) match stx with | Except.ok (Syntax.atom _ sym) => find (Name.mkSimple sym) | Except.ok (Syntax.ident _ _ val _) => match behavior with | LeadingIdentBehavior.default => find identKind | LeadingIdentBehavior.symbol => match map.find? val with | some as => (s, as) | none => find identKind | LeadingIdentBehavior.both => match map.find? val with | some as => match map.find? identKind with | some as' => (s, as ++ as') | _ => (s, as) | none => find identKind | Except.ok (Syntax.node k _) => find k | Except.ok _ => (s, []) | Except.error s' => (s', []) abbrev CategoryParserFn := Name → ParserFn builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun _ => whitespace builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get def categoryParserFn (catName : Name) : ParserFn := fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s def categoryParser (catName : Name) (prec : Nat) : Parser := { fn := fun c s => categoryParserFn catName { c with prec := prec } s } -- Define `termParser` here because we need it for antiquotations @[inline] def termParser (prec : Nat := 0) : Parser := categoryParser `term prec /- ============== -/ /- Antiquotations -/ /- ============== -/ /-- Fail if previous token is immediately followed by ':'. -/ def checkNoImmediateColon : Parser := { fn := fun c s => let prev := s.stxStack.back if checkTailNoWs prev then let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr == ':' then s.mkUnexpectedError "unexpected ':'" else s else s } def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn := fun c s => match p c s with | s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected := [] } } | s' => s' def setExpected (expected : List String) (p : Parser) : Parser := { fn := setExpectedFn expected p.fn, info := p.info } def pushNone : Parser := { fn := fun c s => s.pushSyntax mkNullNode } -- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term. def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbolNoAntiquot "(" >> decQuotDepth termParser >> symbolNoAntiquot ")") def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr @[inline] def tokenWithAntiquotFn (p : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError || c.quotDepth == 0 then return s let iniSz := s.stackSize let iniPos := s.pos let s := (checkNoWsBefore >> symbolNoAntiquot "%" >> symbolNoAntiquot "$" >> checkNoWsBefore >> antiquotExpr).fn c s if s.hasError then return s.restore iniSz iniPos s.mkNode (`token_antiquot) (iniSz - 1) @[inline] def tokenWithAntiquot (p : Parser) : Parser where fn := tokenWithAntiquotFn p.fn info := p.info @[inline] def symbol (sym : String) : Parser := tokenWithAntiquot (symbolNoAntiquot sym) instance : Coe String Parser := ⟨fun s => symbol s ⟩ @[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser := tokenWithAntiquot (nonReservedSymbolNoAntiquot sym includeIdent) @[inline] def unicodeSymbol (sym asciiSym : String) : Parser := tokenWithAntiquot (unicodeSymbolNoAntiquot sym asciiSym) /-- Define parser for `$e` (if anonymous == true) and `$e:name`. Both forms can also be used with an appended `*` to turn them into an antiquotation "splice". If `kind` is given, it will additionally be checked when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which produces the syntax tree for `$e`. -/ def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser := let kind := (kind.getD Name.anonymous) ++ `antiquot let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name -- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different -- antiquotation kind via `noImmediateColon` let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP -- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> antiquotExpr >> nameP def tryAnti (c : ParserContext) (s : ParserState) : Bool := do if c.quotDepth == 0 then return false let (s, stx) := peekToken c s match stx with | Except.ok stx@(Syntax.atom _ sym) => sym == "$" | _ => false @[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn := fun c s => if tryAnti c s then orelseFn antiquotP p c s else p c s /-- Optimized version of `mkAntiquot ... <|> p`. -/ @[inline] def withAntiquot (antiquotP p : Parser) : Parser := { fn := withAntiquotFn antiquotP.fn p.fn, info := orelseInfo antiquotP.info p.info } def withoutInfo (p : Parser) : Parser := { fn := p.fn } /-- Parse `$[p]suffix`, e.g. `$[p],*`. -/ def mkAntiquotSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := let kind := kind ++ `antiquot_scope leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> symbol "[" >> node nullKind p >> symbol "]" >> suffix @[inline] def withAntiquotSuffixSpliceFn (kind : SyntaxNodeKind) (p suffix : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError || c.quotDepth == 0 || !s.stxStack.back.isAntiquot then return s let iniSz := s.stackSize let iniPos := s.pos let s := suffix c s if s.hasError then return s.restore iniSz iniPos s.mkNode (kind ++ `antiquot_suffix_splice) (s.stxStack.size - 2) /-- Parse `suffix` after an antiquotation, e.g. `$x,*`, and put both into a new node. -/ @[inline] def withAntiquotSuffixSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := { info := andthenInfo p.info suffix.info, fn := withAntiquotSuffixSpliceFn kind p.fn suffix.fn } def withAntiquotSpliceAndSuffix (kind : SyntaxNodeKind) (p suffix : Parser) := -- prevent `p`'s info from being collected twice withAntiquot (mkAntiquotSplice kind (withoutInfo p) suffix) (withAntiquotSuffixSplice kind p suffix) def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser := withAntiquot (mkAntiquot name kind anonymous) $ node kind p /- ===================== -/ /- End of Antiquotations -/ /- ===================== -/ def sepByElemParser (p : Parser) (sep : String) : Parser := withAntiquotSpliceAndSuffix `sepBy p (symbol (sep.trim ++ "*")) def sepBy (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepByNoAntiquot (sepByElemParser p sep) psep allowTrailingSep def sepBy1 (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepBy1NoAntiquot (sepByElemParser p sep) psep allowTrailingSep def categoryParserOfStackFn (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident _ _ catName _ => categoryParserFn catName ctx s | _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier") def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s } unsafe def evalParserConstUnsafe (declName : Name) : ParserFn := fun ctx s => match ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.Parser declName <|> ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.TrailingParser declName with | Except.ok p => p.fn ctx s | Except.error e => s.mkUnexpectedError s!"error running parser {declName}: {e}" @[implementedBy evalParserConstUnsafe] constant evalParserConst (declName : Name) : ParserFn unsafe def parserOfStackFnUnsafe (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident (val := parserName) .. => match ctx.resolveName parserName with | [(parserName, [])] => let iniSz := s.stackSize let s := evalParserConst parserName ctx s if !s.hasError && s.stackSize != iniSz + 1 then s.mkUnexpectedError "expected parser to return exactly one syntax object" else s | _::_::_ => s.mkUnexpectedError s!"ambiguous parser name {parserName}" | _ => s.mkUnexpectedError s!"unknown parser {parserName}" | _ => s.mkUnexpectedError ("failed to determine parser using syntax stack, the specified element on the stack is not an identifier") @[implementedBy parserOfStackFnUnsafe] constant parserOfStackFn (offset : Nat) : ParserFn def parserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => parserOfStackFn offset { c with prec := prec } s } /-- Run `declName` if possible and inside a quotation, or else `p`. The `ParserInfo` will always be taken from `p`. -/ def evalInsideQuot (declName : Name) (p : Parser) : Parser := { p with fn := fun c s => if c.quotDepth > 0 && !c.suppressInsideQuot && c.env.contains declName then evalParserConst declName c s else p.fn c s } private def mkResult (s : ParserState) (iniSz : Nat) : ParserState := if s.stackSize == iniSz + 1 then s else s.mkNode nullKind iniSz -- throw error instead? def leadingParserAux (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) : ParserFn := fun c s => do let iniSz := s.stackSize let (s, ps) := indexed tables.leadingTable c s behavior if s.hasError then return s let ps := tables.leadingParsers ++ ps if ps.isEmpty then return s.mkError (toString kind) let s := longestMatchFn none ps c s mkResult s iniSz @[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := withAntiquotFn antiquotParser (leadingParserAux kind tables behavior) def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn := fun c s => longestMatchFn left (ps ++ tables.trailingParsers) c s partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState := do let iniSz := s.stackSize let iniPos := s.pos let (s, ps) := indexed tables.trailingTable c s LeadingIdentBehavior.default if s.hasError then -- Discard token parse errors and break the trailing loop instead. -- The error will be flagged when the next leading position is parsed, unless the token -- is in fact valid there (e.g. EOI at command level, no-longer forbidden token) return s.restore iniSz iniPos if ps.isEmpty && tables.trailingParsers.isEmpty then return s -- no available trailing parser let left := s.stxStack.back let s := s.popSyntax let s := trailingLoopStep tables left ps c s if s.hasError then -- Discard non-consuming parse errors and break the trailing loop instead, restoring `left`. -- This is necessary for fallback parsers like `app` that pretend to be always applicable. return if s.pos == iniPos then s.restore (iniSz - 1) iniPos |>.pushSyntax left else s trailingLoop tables c s /-- Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power. In our implementation, parsers have precedence instead. This method selects a parser (or more, via `longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example: ``` syntax term:51 "≤" ident "<" term "|" term : index ``` Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`. After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`. Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible, modular and easier to understand. `antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers. It should not be added to the regular leading parsers because it would heavily overlap with antiquotation parsers nested inside them. -/ @[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := leadingParser kind tables behavior antiquotParser c s if s.hasError then s else trailingLoop tables c s def fieldIdxFn : ParserFn := fun c s => let initStackSz := s.stackSize let iniPos := s.pos let curr := c.input.get iniPos if curr.isDigit && curr != '0' then let s := takeWhileFn (fun c => c.isDigit) c s mkNodeToken fieldIdxKind iniPos c s else s.mkErrorAt "field index" iniPos initStackSz @[inline] def fieldIdx : Parser := withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) { fn := fieldIdxFn, info := mkAtomicInfo "fieldIdx" } @[inline] def skip : Parser := { fn := fun c s => s, info := epsilonInfo } end Parser namespace Syntax section variable {β : Type} {m : Type → Type} [Monad m] @[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β := s.getArgs.foldlM (flip f) b @[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β := Id.run (s.foldArgsM f b) @[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit := s.foldArgsM (fun s _ => f s) () end end Syntax end Lean
487096af27e1b77ec6600801da9c533f53175930
de7b3dbc03c2200899ec842ca1e7cba570a04fa1
/src/sort_benchmarks.lean
c9078a51a744689798caffa6294db57c33375995
[]
no_license
robertylewis/relevance_filter
4c48a0e02bbeef857f9c67b0f7dc8f3acd5b906a
d11544e08c6d3569410e312baf149412b168ebb4
refs/heads/master
1,670,019,263,018
1,597,851,640,000
1,597,851,640,000
105,209,556
0
1
null
null
null
null
UTF-8
Lean
false
false
1,256
lean
import .sort data.list.sort open native meta instance : inhabited float := ⟨0⟩ -- meta constant float.random : float set_option profiler true --set_option trace.array.update true /- all updates are destructive. I don't know why my array quicksort takes twice the time of list.qsort. They seem to scale at the same rate. -/ -- run_cmd -- --let arr := (mk_array 80 (1 : float)).map (λ _, float.random) in -- do return $ quicksort (λ a b, float.lt a b) $ (mk_array 8000 (1 : float)).map (λ _, float.random) -- -- return $ list.qsort (λ a b, float.lt a b) ((mk_array 8000 (1 : float)).map (λ _, float.random)).to_list -- #exit -- run_cmd let a := (mk_array 800 (1 : float)).map (λ _, float.random) -- .55 -- in tactic.trace $ ((a.write' 10 50).read' 10) + (a.read' 1) -- #exit -- run_cmd return $ merge_sort $ (mk_array 20000 (1 : float)).map (λ _, float.random) -- 4 sec -- run_cmd return $ quicksort (λ a b, a < b) $ (mk_array 20000 (1 : float)).map (λ _, float.random) -- .55 -- run_cmd return $ list.merge_sort (λ a b, a < b) ((list.repeat (0 : ℕ) 20000).map (λ _, float.random)) -- .24 -- run_cmd return $ list.qsort (λ a b, a < b) ((list.repeat (0 : ℕ) 20000).map (λ _, float.random)) -- .31
743f7ee1101a9f541935eeaf48c48bbd4507edf0
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/probability/stopping.lean
b45d42c26a784b5e1aa6bfabc2eb3dd42655ca56
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
61,931
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.function.conditional_expectation.real import topology.instances.discrete /-! # Filtration and stopping time This file defines some standard definition from the theory of stochastic processes including filtrations and stopping times. These definitions are used to model the amount of information at a specific time and is the first step in formalizing stochastic processes. ## Main definitions * `measure_theory.filtration`: a filtration on a measurable space * `measure_theory.adapted`: a sequence of functions `u` is said to be adapted to a filtration `f` if at each point in time `i`, `u i` is `f i`-strongly measurable * `measure_theory.prog_measurable`: a sequence of functions `u` is said to be progressively measurable with respect to a filtration `f` if at each point in time `i`, `u` restricted to `set.Iic i × Ω` is strongly measurable with respect to the product `measurable_space` structure where the σ-algebra used for `Ω` is `f i`. * `measure_theory.filtration.natural`: the natural filtration with respect to a sequence of measurable functions is the smallest filtration to which it is adapted to * `measure_theory.is_stopping_time`: a stopping time with respect to some filtration `f` is a function `τ` such that for all `i`, the preimage of `{j | j ≤ i}` along `τ` is `f i`-measurable * `measure_theory.is_stopping_time.measurable_space`: the σ-algebra associated with a stopping time ## Main results * `adapted.prog_measurable_of_continuous`: a continuous adapted process is progressively measurable. * `prog_measurable.stopped_process`: the stopped process of a progressively measurable process is progressively measurable. * `mem_ℒp_stopped_process`: if a process belongs to `ℒp` at every time in `ℕ`, then its stopped process belongs to `ℒp` as well. ## Tags filtration, stopping time, stochastic process -/ open filter order topological_space open_locale classical measure_theory nnreal ennreal topological_space big_operators namespace measure_theory /-! ### Filtrations -/ /-- A `filtration` on measurable space `Ω` with σ-algebra `m` is a monotone sequence of sub-σ-algebras of `m`. -/ structure filtration {Ω : Type*} (ι : Type*) [preorder ι] (m : measurable_space Ω) := (seq : ι → measurable_space Ω) (mono' : monotone seq) (le' : ∀ i : ι, seq i ≤ m) variables {Ω β ι : Type*} {m : measurable_space Ω} instance [preorder ι] : has_coe_to_fun (filtration ι m) (λ _, ι → measurable_space Ω) := ⟨λ f, f.seq⟩ namespace filtration variables [preorder ι] protected lemma mono {i j : ι} (f : filtration ι m) (hij : i ≤ j) : f i ≤ f j := f.mono' hij protected lemma le (f : filtration ι m) (i : ι) : f i ≤ m := f.le' i @[ext] protected lemma ext {f g : filtration ι m} (h : (f : ι → measurable_space Ω) = g) : f = g := by { cases f, cases g, simp only, exact h, } variable (ι) /-- The constant filtration which is equal to `m` for all `i : ι`. -/ def const (m' : measurable_space Ω) (hm' : m' ≤ m) : filtration ι m := ⟨λ _, m', monotone_const, λ _, hm'⟩ variable {ι} @[simp] lemma const_apply {m' : measurable_space Ω} {hm' : m' ≤ m} (i : ι) : const ι m' hm' i = m' := rfl instance : inhabited (filtration ι m) := ⟨const ι m le_rfl⟩ instance : has_le (filtration ι m) := ⟨λ f g, ∀ i, f i ≤ g i⟩ instance : has_bot (filtration ι m) := ⟨const ι ⊥ bot_le⟩ instance : has_top (filtration ι m) := ⟨const ι m le_rfl⟩ instance : has_sup (filtration ι m) := ⟨λ f g, { seq := λ i, f i ⊔ g i, mono' := λ i j hij, sup_le ((f.mono hij).trans le_sup_left) ((g.mono hij).trans le_sup_right), le' := λ i, sup_le (f.le i) (g.le i) }⟩ @[norm_cast] lemma coe_fn_sup {f g : filtration ι m} : ⇑(f ⊔ g) = f ⊔ g := rfl instance : has_inf (filtration ι m) := ⟨λ f g, { seq := λ i, f i ⊓ g i, mono' := λ i j hij, le_inf (inf_le_left.trans (f.mono hij)) (inf_le_right.trans (g.mono hij)), le' := λ i, inf_le_left.trans (f.le i) }⟩ @[norm_cast] lemma coe_fn_inf {f g : filtration ι m} : ⇑(f ⊓ g) = f ⊓ g := rfl instance : has_Sup (filtration ι m) := ⟨λ s, { seq := λ i, Sup ((λ f : filtration ι m, f i) '' s), mono' := λ i j hij, begin refine Sup_le (λ m' hm', _), rw [set.mem_image] at hm', obtain ⟨f, hf_mem, hfm'⟩ := hm', rw ← hfm', refine (f.mono hij).trans _, have hfj_mem : f j ∈ ((λ g : filtration ι m, g j) '' s), from ⟨f, hf_mem, rfl⟩, exact le_Sup hfj_mem, end, le' := λ i, begin refine Sup_le (λ m' hm', _), rw [set.mem_image] at hm', obtain ⟨f, hf_mem, hfm'⟩ := hm', rw ← hfm', exact f.le i, end, }⟩ lemma Sup_def (s : set (filtration ι m)) (i : ι) : Sup s i = Sup ((λ f : filtration ι m, f i) '' s) := rfl noncomputable instance : has_Inf (filtration ι m) := ⟨λ s, { seq := λ i, if set.nonempty s then Inf ((λ f : filtration ι m, f i) '' s) else m, mono' := λ i j hij, begin by_cases h_nonempty : set.nonempty s, swap, { simp only [h_nonempty, set.nonempty_image_iff, if_false, le_refl], }, simp only [h_nonempty, if_true, le_Inf_iff, set.mem_image, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂], refine λ f hf_mem, le_trans _ (f.mono hij), have hfi_mem : f i ∈ ((λ g : filtration ι m, g i) '' s), from ⟨f, hf_mem, rfl⟩, exact Inf_le hfi_mem, end, le' := λ i, begin by_cases h_nonempty : set.nonempty s, swap, { simp only [h_nonempty, if_false, le_refl], }, simp only [h_nonempty, if_true], obtain ⟨f, hf_mem⟩ := h_nonempty, exact le_trans (Inf_le ⟨f, hf_mem, rfl⟩) (f.le i), end, }⟩ lemma Inf_def (s : set (filtration ι m)) (i : ι) : Inf s i = if set.nonempty s then Inf ((λ f : filtration ι m, f i) '' s) else m := rfl noncomputable instance : complete_lattice (filtration ι m) := { le := (≤), le_refl := λ f i, le_rfl, le_trans := λ f g h h_fg h_gh i, (h_fg i).trans (h_gh i), le_antisymm := λ f g h_fg h_gf, filtration.ext $ funext $ λ i, (h_fg i).antisymm (h_gf i), sup := (⊔), le_sup_left := λ f g i, le_sup_left, le_sup_right := λ f g i, le_sup_right, sup_le := λ f g h h_fh h_gh i, sup_le (h_fh i) (h_gh _), inf := (⊓), inf_le_left := λ f g i, inf_le_left, inf_le_right := λ f g i, inf_le_right, le_inf := λ f g h h_fg h_fh i, le_inf (h_fg i) (h_fh i), Sup := Sup, le_Sup := λ s f hf_mem i, le_Sup ⟨f, hf_mem, rfl⟩, Sup_le := λ s f h_forall i, Sup_le $ λ m' hm', begin obtain ⟨g, hg_mem, hfm'⟩ := hm', rw ← hfm', exact h_forall g hg_mem i, end, Inf := Inf, Inf_le := λ s f hf_mem i, begin have hs : s.nonempty := ⟨f, hf_mem⟩, simp only [Inf_def, hs, if_true], exact Inf_le ⟨f, hf_mem, rfl⟩, end, le_Inf := λ s f h_forall i, begin by_cases hs : s.nonempty, swap, { simp only [Inf_def, hs, if_false], exact f.le i, }, simp only [Inf_def, hs, if_true, le_Inf_iff, set.mem_image, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂], exact λ g hg_mem, h_forall g hg_mem i, end, top := ⊤, bot := ⊥, le_top := λ f i, f.le' i, bot_le := λ f i, bot_le, } end filtration lemma measurable_set_of_filtration [preorder ι] {f : filtration ι m} {s : set Ω} {i : ι} (hs : measurable_set[f i] s) : measurable_set[m] s := f.le i s hs /-- A measure is σ-finite with respect to filtration if it is σ-finite with respect to all the sub-σ-algebra of the filtration. -/ class sigma_finite_filtration [preorder ι] (μ : measure Ω) (f : filtration ι m) : Prop := (sigma_finite : ∀ i : ι, sigma_finite (μ.trim (f.le i))) instance sigma_finite_of_sigma_finite_filtration [preorder ι] (μ : measure Ω) (f : filtration ι m) [hf : sigma_finite_filtration μ f] (i : ι) : sigma_finite (μ.trim (f.le i)) := by apply hf.sigma_finite -- can't exact here @[priority 100] instance is_finite_measure.sigma_finite_filtration [preorder ι] (μ : measure Ω) (f : filtration ι m) [is_finite_measure μ] : sigma_finite_filtration μ f := ⟨λ n, by apply_instance⟩ /-- Given a integrable function `g`, the conditional expectations of `g` with respect to a filtration is uniformly integrable. -/ lemma integrable.uniform_integrable_condexp_filtration [preorder ι] {μ : measure Ω} [is_finite_measure μ] {f : filtration ι m} {g : Ω → ℝ} (hg : integrable g μ) : uniform_integrable (λ i, μ[g | f i]) 1 μ := hg.uniform_integrable_condexp f.le section adapted_process variables [topological_space β] [preorder ι] {u v : ι → Ω → β} {f : filtration ι m} /-- A sequence of functions `u` is adapted to a filtration `f` if for all `i`, `u i` is `f i`-measurable. -/ def adapted (f : filtration ι m) (u : ι → Ω → β) : Prop := ∀ i : ι, strongly_measurable[f i] (u i) namespace adapted @[protected, to_additive] lemma mul [has_mul β] [has_continuous_mul β] (hu : adapted f u) (hv : adapted f v) : adapted f (u * v) := λ i, (hu i).mul (hv i) @[protected, to_additive] lemma inv [group β] [topological_group β] (hu : adapted f u) : adapted f u⁻¹ := λ i, (hu i).inv @[protected] lemma smul [has_smul ℝ β] [has_continuous_smul ℝ β] (c : ℝ) (hu : adapted f u) : adapted f (c • u) := λ i, (hu i).const_smul c @[protected] lemma strongly_measurable {i : ι} (hf : adapted f u) : strongly_measurable[m] (u i) := (hf i).mono (f.le i) lemma strongly_measurable_le {i j : ι} (hf : adapted f u) (hij : i ≤ j) : strongly_measurable[f j] (u i) := (hf i).mono (f.mono hij) end adapted lemma adapted_const (f : filtration ι m) (x : β) : adapted f (λ _ _, x) := λ i, strongly_measurable_const variable (β) lemma adapted_zero [has_zero β] (f : filtration ι m) : adapted f (0 : ι → Ω → β) := λ i, @strongly_measurable_zero Ω β (f i) _ _ variable {β} /-- Progressively measurable process. A sequence of functions `u` is said to be progressively measurable with respect to a filtration `f` if at each point in time `i`, `u` restricted to `set.Iic i × Ω` is measurable with respect to the product `measurable_space` structure where the σ-algebra used for `Ω` is `f i`. The usual definition uses the interval `[0,i]`, which we replace by `set.Iic i`. We recover the usual definition for index types `ℝ≥0` or `ℕ`. -/ def prog_measurable [measurable_space ι] (f : filtration ι m) (u : ι → Ω → β) : Prop := ∀ i, strongly_measurable[subtype.measurable_space.prod (f i)] (λ p : set.Iic i × Ω, u p.1 p.2) lemma prog_measurable_const [measurable_space ι] (f : filtration ι m) (b : β) : prog_measurable f ((λ _ _, b) : ι → Ω → β) := λ i, @strongly_measurable_const _ _ (subtype.measurable_space.prod (f i)) _ _ namespace prog_measurable variables [measurable_space ι] protected lemma adapted (h : prog_measurable f u) : adapted f u := begin intro i, have : u i = (λ p : set.Iic i × Ω, u p.1 p.2) ∘ (λ x, (⟨i, set.mem_Iic.mpr le_rfl⟩, x)) := rfl, rw this, exact (h i).comp_measurable measurable_prod_mk_left, end protected lemma comp {t : ι → Ω → ι} [topological_space ι] [borel_space ι] [metrizable_space ι] (h : prog_measurable f u) (ht : prog_measurable f t) (ht_le : ∀ i ω, t i ω ≤ i) : prog_measurable f (λ i ω, u (t i ω) ω) := begin intro i, have : (λ p : ↥(set.Iic i) × Ω, u (t (p.fst : ι) p.snd) p.snd) = (λ p : ↥(set.Iic i) × Ω, u (p.fst : ι) p.snd) ∘ (λ p : ↥(set.Iic i) × Ω, (⟨t (p.fst : ι) p.snd, set.mem_Iic.mpr ((ht_le _ _).trans p.fst.prop)⟩, p.snd)) := rfl, rw this, exact (h i).comp_measurable ((ht i).measurable.subtype_mk.prod_mk measurable_snd), end section arithmetic @[to_additive] protected lemma mul [has_mul β] [has_continuous_mul β] (hu : prog_measurable f u) (hv : prog_measurable f v) : prog_measurable f (λ i ω, u i ω * v i ω) := λ i, (hu i).mul (hv i) @[to_additive] protected lemma finset_prod' {γ} [comm_monoid β] [has_continuous_mul β] {U : γ → ι → Ω → β} {s : finset γ} (h : ∀ c ∈ s, prog_measurable f (U c)) : prog_measurable f (∏ c in s, U c) := finset.prod_induction U (prog_measurable f) (λ _ _, prog_measurable.mul) (prog_measurable_const _ 1) h @[to_additive] protected lemma finset_prod {γ} [comm_monoid β] [has_continuous_mul β] {U : γ → ι → Ω → β} {s : finset γ} (h : ∀ c ∈ s, prog_measurable f (U c)) : prog_measurable f (λ i a, ∏ c in s, U c i a) := by { convert prog_measurable.finset_prod' h, ext i a, simp only [finset.prod_apply], } @[to_additive] protected lemma inv [group β] [topological_group β] (hu : prog_measurable f u) : prog_measurable f (λ i ω, (u i ω)⁻¹) := λ i, (hu i).inv @[to_additive] protected lemma div [group β] [topological_group β] (hu : prog_measurable f u) (hv : prog_measurable f v) : prog_measurable f (λ i ω, u i ω / v i ω) := λ i, (hu i).div (hv i) end arithmetic end prog_measurable lemma prog_measurable_of_tendsto' {γ} [measurable_space ι] [metrizable_space β] (fltr : filter γ) [fltr.ne_bot] [fltr.is_countably_generated] {U : γ → ι → Ω → β} (h : ∀ l, prog_measurable f (U l)) (h_tendsto : tendsto U fltr (𝓝 u)) : prog_measurable f u := begin assume i, apply @strongly_measurable_of_tendsto (set.Iic i × Ω) β γ (measurable_space.prod _ (f i)) _ _ fltr _ _ _ _ (λ l, h l i), rw tendsto_pi_nhds at h_tendsto ⊢, intro x, specialize h_tendsto x.fst, rw tendsto_nhds at h_tendsto ⊢, exact λ s hs h_mem, h_tendsto {g | g x.snd ∈ s} (hs.preimage (continuous_apply x.snd)) h_mem, end lemma prog_measurable_of_tendsto [measurable_space ι] [metrizable_space β] {U : ℕ → ι → Ω → β} (h : ∀ l, prog_measurable f (U l)) (h_tendsto : tendsto U at_top (𝓝 u)) : prog_measurable f u := prog_measurable_of_tendsto' at_top h h_tendsto /-- A continuous and adapted process is progressively measurable. -/ theorem adapted.prog_measurable_of_continuous [topological_space ι] [metrizable_space ι] [measurable_space ι] [second_countable_topology ι] [opens_measurable_space ι] [metrizable_space β] (h : adapted f u) (hu_cont : ∀ ω, continuous (λ i, u i ω)) : prog_measurable f u := λ i, @strongly_measurable_uncurry_of_continuous_of_strongly_measurable _ _ (set.Iic i) _ _ _ _ _ _ _ (f i) _ (λ ω, (hu_cont ω).comp continuous_induced_dom) (λ j, (h j).mono (f.mono j.prop)) end adapted_process namespace filtration variables [topological_space β] [metrizable_space β] [mβ : measurable_space β] [borel_space β] [preorder ι] include mβ /-- Given a sequence of functions, the natural filtration is the smallest sequence of σ-algebras such that that sequence of functions is measurable with respect to the filtration. -/ def natural (u : ι → Ω → β) (hum : ∀ i, strongly_measurable (u i)) : filtration ι m := { seq := λ i, ⨆ j ≤ i, measurable_space.comap (u j) mβ, mono' := λ i j hij, bsupr_mono $ λ k, ge_trans hij, le' := λ i, begin refine supr₂_le _, rintros j hj s ⟨t, ht, rfl⟩, exact (hum j).measurable ht, end } lemma adapted_natural {u : ι → Ω → β} (hum : ∀ i, strongly_measurable[m] (u i)) : adapted (natural u hum) u := begin assume i, refine strongly_measurable.mono _ (le_supr₂_of_le i (le_refl i) le_rfl), rw strongly_measurable_iff_measurable_separable, exact ⟨measurable_iff_comap_le.2 le_rfl, (hum i).is_separable_range⟩ end section limit omit mβ variables {E : Type*} [has_zero E] [topological_space E] {ℱ : filtration ι m} {f : ι → Ω → E} {μ : measure Ω} /-- Given a process `f` and a filtration `ℱ`, if `f` converges to some `g` almost everywhere and `g` is `⨆ n, ℱ n`-measurable, then `limit_process f ℱ μ` chooses said `g`, else it returns 0. This definition is used to phrase the a.e. martingale convergence theorem `submartingale.ae_tendsto_limit_process` where an L¹-bounded submartingale `f` adapted to `ℱ` converges to `limit_process f ℱ μ` `μ`-almost everywhere. -/ noncomputable def limit_process (f : ι → Ω → E) (ℱ : filtration ι m) (μ : measure Ω . volume_tac) := if h : ∃ g : Ω → E, strongly_measurable[⨆ n, ℱ n] g ∧ ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (g ω)) then classical.some h else 0 lemma strongly_measurable_limit_process : strongly_measurable[⨆ n, ℱ n] (limit_process f ℱ μ) := begin rw limit_process, split_ifs with h h, exacts [(classical.some_spec h).1, strongly_measurable_zero] end lemma strongly_measurable_limit_process' : strongly_measurable[m] (limit_process f ℱ μ) := strongly_measurable_limit_process.mono (Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _)) lemma mem_ℒp_limit_process_of_snorm_bdd {R : ℝ≥0} {p : ℝ≥0∞} {F : Type*} [normed_add_comm_group F] {ℱ : filtration ℕ m} {f : ℕ → Ω → F} (hfm : ∀ n, ae_strongly_measurable (f n) μ) (hbdd : ∀ n, snorm (f n) p μ ≤ R) : mem_ℒp (limit_process f ℱ μ) p μ := begin rw limit_process, split_ifs with h, { refine ⟨strongly_measurable.ae_strongly_measurable ((classical.some_spec h).1.mono (Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _))), lt_of_le_of_lt (Lp.snorm_lim_le_liminf_snorm hfm _ (classical.some_spec h).2) (lt_of_le_of_lt _ (ennreal.coe_lt_top : ↑R < ∞))⟩, simp_rw [liminf_eq, eventually_at_top], exact Sup_le (λ b ⟨a, ha⟩, (ha a le_rfl).trans (hbdd _)) }, { exact zero_mem_ℒp } end end limit end filtration /-! ### Stopping times -/ /-- A stopping time with respect to some filtration `f` is a function `τ` such that for all `i`, the preimage of `{j | j ≤ i}` along `τ` is measurable with respect to `f i`. Intuitively, the stopping time `τ` describes some stopping rule such that at time `i`, we may determine it with the information we have at time `i`. -/ def is_stopping_time [preorder ι] (f : filtration ι m) (τ : Ω → ι) := ∀ i : ι, measurable_set[f i] $ {ω | τ ω ≤ i} lemma is_stopping_time_const [preorder ι] (f : filtration ι m) (i : ι) : is_stopping_time f (λ x, i) := λ j, by simp only [measurable_set.const] section measurable_set section preorder variables [preorder ι] {f : filtration ι m} {τ : Ω → ι} protected lemma is_stopping_time.measurable_set_le (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω ≤ i} := hτ i lemma is_stopping_time.measurable_set_lt_of_pred [pred_order ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω < i} := begin by_cases hi_min : is_min i, { suffices : {ω : Ω | τ ω < i} = ∅, by { rw this, exact @measurable_set.empty _ (f i), }, ext1 ω, simp only [set.mem_set_of_eq, set.mem_empty_eq, iff_false], rw is_min_iff_forall_not_lt at hi_min, exact hi_min (τ ω), }, have : {ω : Ω | τ ω < i} = τ ⁻¹' (set.Iio i) := rfl, rw [this, ←Iic_pred_of_not_is_min hi_min], exact f.mono (pred_le i) _ (hτ.measurable_set_le $ pred i), end end preorder section countable_stopping_time namespace is_stopping_time variables [partial_order ι] {τ : Ω → ι} {f : filtration ι m} protected lemma measurable_set_eq_of_countable (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[f i] {ω | τ ω = i} := begin have : {ω | τ ω = i} = {ω | τ ω ≤ i} \ (⋃ (j ∈ set.range τ) (hj : j < i), {ω | τ ω ≤ j}), { ext1 a, simp only [set.mem_set_of_eq, set.mem_range, set.Union_exists, set.Union_Union_eq', set.mem_diff, set.mem_Union, exists_prop, not_exists, not_and, not_le], split; intro h, { simp only [h, lt_iff_le_not_le, le_refl, and_imp, imp_self, implies_true_iff, and_self], }, { have h_lt_or_eq : τ a < i ∨ τ a = i := lt_or_eq_of_le h.1, rcases h_lt_or_eq with h_lt | rfl, { exfalso, exact h.2 a h_lt (le_refl (τ a)), }, { refl, }, }, }, rw this, refine (hτ.measurable_set_le i).diff _, refine measurable_set.bUnion h_countable (λ j hj, _), by_cases hji : j < i, { simp only [hji, set.Union_true], exact f.mono hji.le _ (hτ.measurable_set_le j), }, { simp only [hji, set.Union_false], exact @measurable_set.empty _ (f i), }, end protected lemma measurable_set_eq_of_encodable [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω = i} := hτ.measurable_set_eq_of_countable (set.to_countable _) i protected lemma measurable_set_lt_of_countable (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[f i] {ω | τ ω < i} := begin have : {ω | τ ω < i} = {ω | τ ω ≤ i} \ {ω | τ ω = i}, { ext1 ω, simp [lt_iff_le_and_ne], }, rw this, exact (hτ.measurable_set_le i).diff (hτ.measurable_set_eq_of_countable h_countable i), end protected lemma measurable_set_lt_of_encodable [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω < i} := hτ.measurable_set_lt_of_countable (set.to_countable _) i protected lemma measurable_set_ge_of_countable {ι} [linear_order ι] {τ : Ω → ι} {f : filtration ι m} (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[f i] {ω | i ≤ τ ω} := begin have : {ω | i ≤ τ ω} = {ω | τ ω < i}ᶜ, { ext1 ω, simp only [set.mem_set_of_eq, set.mem_compl_eq, not_lt], }, rw this, exact (hτ.measurable_set_lt_of_countable h_countable i).compl, end protected lemma measurable_set_ge_of_encodable {ι} [linear_order ι] {τ : Ω → ι} {f : filtration ι m} [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | i ≤ τ ω} := hτ.measurable_set_ge_of_countable (set.to_countable _) i end is_stopping_time end countable_stopping_time section linear_order variables [linear_order ι] {f : filtration ι m} {τ : Ω → ι} lemma is_stopping_time.measurable_set_gt (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | i < τ ω} := begin have : {ω | i < τ ω} = {ω | τ ω ≤ i}ᶜ, { ext1 ω, simp only [set.mem_set_of_eq, set.mem_compl_eq, not_le], }, rw this, exact (hτ.measurable_set_le i).compl, end section topological_space variables [topological_space ι] [order_topology ι] [first_countable_topology ι] /-- Auxiliary lemma for `is_stopping_time.measurable_set_lt`. -/ lemma is_stopping_time.measurable_set_lt_of_is_lub (hτ : is_stopping_time f τ) (i : ι) (h_lub : is_lub (set.Iio i) i) : measurable_set[f i] {ω | τ ω < i} := begin by_cases hi_min : is_min i, { suffices : {ω | τ ω < i} = ∅, by { rw this, exact @measurable_set.empty _ (f i), }, ext1 ω, simp only [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact is_min_iff_forall_not_lt.mp hi_min (τ ω), }, obtain ⟨seq, -, -, h_tendsto, h_bound⟩ : ∃ seq : ℕ → ι, monotone seq ∧ (∀ j, seq j ≤ i) ∧ tendsto seq at_top (𝓝 i) ∧ (∀ j, seq j < i), from h_lub.exists_seq_monotone_tendsto (not_is_min_iff.mp hi_min), have h_Ioi_eq_Union : set.Iio i = ⋃ j, {k | k ≤ seq j}, { ext1 k, simp only [set.mem_Iio, set.mem_Union, set.mem_set_of_eq], refine ⟨λ hk_lt_i, _, λ h_exists_k_le_seq, _⟩, { rw tendsto_at_top' at h_tendsto, have h_nhds : set.Ici k ∈ 𝓝 i, from mem_nhds_iff.mpr ⟨set.Ioi k, set.Ioi_subset_Ici le_rfl, is_open_Ioi, hk_lt_i⟩, obtain ⟨a, ha⟩ : ∃ (a : ℕ), ∀ (b : ℕ), b ≥ a → k ≤ seq b := h_tendsto (set.Ici k) h_nhds, exact ⟨a, ha a le_rfl⟩, }, { obtain ⟨j, hk_seq_j⟩ := h_exists_k_le_seq, exact hk_seq_j.trans_lt (h_bound j), }, }, have h_lt_eq_preimage : {ω | τ ω < i} = τ ⁻¹' (set.Iio i), { ext1 ω, simp only [set.mem_set_of_eq, set.mem_preimage, set.mem_Iio], }, rw [h_lt_eq_preimage, h_Ioi_eq_Union], simp only [set.preimage_Union, set.preimage_set_of_eq], exact measurable_set.Union (λ n, f.mono (h_bound n).le _ (hτ.measurable_set_le (seq n))), end lemma is_stopping_time.measurable_set_lt (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω < i} := begin obtain ⟨i', hi'_lub⟩ : ∃ i', is_lub (set.Iio i) i', from exists_lub_Iio i, cases lub_Iio_eq_self_or_Iio_eq_Iic i hi'_lub with hi'_eq_i h_Iio_eq_Iic, { rw ← hi'_eq_i at hi'_lub ⊢, exact hτ.measurable_set_lt_of_is_lub i' hi'_lub, }, { have h_lt_eq_preimage : {ω : Ω | τ ω < i} = τ ⁻¹' (set.Iio i) := rfl, rw [h_lt_eq_preimage, h_Iio_eq_Iic], exact f.mono (lub_Iio_le i hi'_lub) _ (hτ.measurable_set_le i'), }, end lemma is_stopping_time.measurable_set_ge (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | i ≤ τ ω} := begin have : {ω | i ≤ τ ω} = {ω | τ ω < i}ᶜ, { ext1 ω, simp only [set.mem_set_of_eq, set.mem_compl_eq, not_lt], }, rw this, exact (hτ.measurable_set_lt i).compl, end lemma is_stopping_time.measurable_set_eq (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {ω | τ ω = i} := begin have : {ω | τ ω = i} = {ω | τ ω ≤ i} ∩ {ω | τ ω ≥ i}, { ext1 ω, simp only [set.mem_set_of_eq, ge_iff_le, set.mem_inter_eq, le_antisymm_iff], }, rw this, exact (hτ.measurable_set_le i).inter (hτ.measurable_set_ge i), end lemma is_stopping_time.measurable_set_eq_le (hτ : is_stopping_time f τ) {i j : ι} (hle : i ≤ j) : measurable_set[f j] {ω | τ ω = i} := f.mono hle _ $ hτ.measurable_set_eq i lemma is_stopping_time.measurable_set_lt_le (hτ : is_stopping_time f τ) {i j : ι} (hle : i ≤ j) : measurable_set[f j] {ω | τ ω < i} := f.mono hle _ $ hτ.measurable_set_lt i end topological_space end linear_order section encodable lemma is_stopping_time_of_measurable_set_eq [preorder ι] [encodable ι] {f : filtration ι m} {τ : Ω → ι} (hτ : ∀ i, measurable_set[f i] {ω | τ ω = i}) : is_stopping_time f τ := begin intro i, rw show {ω | τ ω ≤ i} = ⋃ k ≤ i, {ω | τ ω = k}, by { ext, simp }, refine measurable_set.bUnion (set.to_countable _) (λ k hk, _), exact f.mono hk _ (hτ k), end end encodable end measurable_set namespace is_stopping_time protected lemma max [linear_order ι] {f : filtration ι m} {τ π : Ω → ι} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (λ ω, max (τ ω) (π ω)) := begin intro i, simp_rw [max_le_iff, set.set_of_and], exact (hτ i).inter (hπ i), end protected lemma max_const [linear_order ι] {f : filtration ι m} {τ : Ω → ι} (hτ : is_stopping_time f τ) (i : ι) : is_stopping_time f (λ ω, max (τ ω) i) := hτ.max (is_stopping_time_const f i) protected lemma min [linear_order ι] {f : filtration ι m} {τ π : Ω → ι} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (λ ω, min (τ ω) (π ω)) := begin intro i, simp_rw [min_le_iff, set.set_of_or], exact (hτ i).union (hπ i), end protected lemma min_const [linear_order ι] {f : filtration ι m} {τ : Ω → ι} (hτ : is_stopping_time f τ) (i : ι) : is_stopping_time f (λ ω, min (τ ω) i) := hτ.min (is_stopping_time_const f i) lemma add_const [add_group ι] [preorder ι] [covariant_class ι ι (function.swap (+)) (≤)] [covariant_class ι ι (+) (≤)] {f : filtration ι m} {τ : Ω → ι} (hτ : is_stopping_time f τ) {i : ι} (hi : 0 ≤ i) : is_stopping_time f (λ ω, τ ω + i) := begin intro j, simp_rw [← le_sub_iff_add_le], exact f.mono (sub_le_self j hi) _ (hτ (j - i)), end lemma add_const_nat {f : filtration ℕ m} {τ : Ω → ℕ} (hτ : is_stopping_time f τ) {i : ℕ} : is_stopping_time f (λ ω, τ ω + i) := begin refine is_stopping_time_of_measurable_set_eq (λ j, _), by_cases hij : i ≤ j, { simp_rw [eq_comm, ← nat.sub_eq_iff_eq_add hij, eq_comm], exact f.mono (j.sub_le i) _ (hτ.measurable_set_eq (j - i)) }, { rw not_le at hij, convert measurable_set.empty, ext ω, simp only [set.mem_empty_eq, iff_false], rintro (hx : τ ω + i = j), linarith }, end -- generalize to certain encodable type? lemma add {f : filtration ℕ m} {τ π : Ω → ℕ} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (τ + π) := begin intro i, rw (_ : {ω | (τ + π) ω ≤ i} = ⋃ k ≤ i, {ω | π ω = k} ∩ {ω | τ ω + k ≤ i}), { exact measurable_set.Union (λ k, measurable_set.Union_Prop (λ hk, (hπ.measurable_set_eq_le hk).inter (hτ.add_const_nat i))) }, ext ω, simp only [pi.add_apply, set.mem_set_of_eq, set.mem_Union, set.mem_inter_eq, exists_prop], refine ⟨λ h, ⟨π ω, by linarith, rfl, h⟩, _⟩, rintro ⟨j, hj, rfl, h⟩, assumption end section preorder variables [preorder ι] {f : filtration ι m} {τ π : Ω → ι} /-- The associated σ-algebra with a stopping time. -/ protected def measurable_space (hτ : is_stopping_time f τ) : measurable_space Ω := { measurable_set' := λ s, ∀ i : ι, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}), measurable_set_empty := λ i, (set.empty_inter {ω | τ ω ≤ i}).symm ▸ @measurable_set.empty _ (f i), measurable_set_compl := λ s hs i, begin rw (_ : sᶜ ∩ {ω | τ ω ≤ i} = (sᶜ ∪ {ω | τ ω ≤ i}ᶜ) ∩ {ω | τ ω ≤ i}), { refine measurable_set.inter _ _, { rw ← set.compl_inter, exact (hs i).compl }, { exact hτ i} }, { rw set.union_inter_distrib_right, simp only [set.compl_inter_self, set.union_empty] } end, measurable_set_Union := λ s hs i, begin rw forall_swap at hs, rw set.Union_inter, exact measurable_set.Union (hs i), end } protected lemma measurable_set (hτ : is_stopping_time f τ) (s : set Ω) : measurable_set[hτ.measurable_space] s ↔ ∀ i : ι, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) := iff.rfl lemma measurable_space_mono (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (hle : τ ≤ π) : hτ.measurable_space ≤ hπ.measurable_space := begin intros s hs i, rw (_ : s ∩ {ω | π ω ≤ i} = s ∩ {ω | τ ω ≤ i} ∩ {ω | π ω ≤ i}), { exact (hs i).inter (hπ i) }, { ext, simp only [set.mem_inter_eq, iff_self_and, and.congr_left_iff, set.mem_set_of_eq], intros hle' _, exact le_trans (hle _) hle' }, end lemma measurable_space_le_of_encodable [encodable ι] (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := begin intros s hs, change ∀ i, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) at hs, rw (_ : s = ⋃ i, s ∩ {ω | τ ω ≤ i}), { exact measurable_set.Union (λ i, f.le i _ (hs i)) }, { ext ω, split; rw set.mem_Union, { exact λ hx, ⟨τ ω, hx, le_rfl⟩ }, { rintro ⟨_, hx, _⟩, exact hx } } end lemma measurable_space_le' [is_countably_generated (at_top : filter ι)] [(at_top : filter ι).ne_bot] (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := begin intros s hs, change ∀ i, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) at hs, obtain ⟨seq : ℕ → ι, h_seq_tendsto⟩ := at_top.exists_seq_tendsto, rw (_ : s = ⋃ n, s ∩ {ω | τ ω ≤ seq n}), { exact measurable_set.Union (λ i, f.le (seq i) _ (hs (seq i))), }, { ext ω, split; rw set.mem_Union, { intros hx, suffices : ∃ i, τ ω ≤ seq i, from ⟨this.some, hx, this.some_spec⟩, rw tendsto_at_top at h_seq_tendsto, exact (h_seq_tendsto (τ ω)).exists, }, { rintro ⟨_, hx, _⟩, exact hx }, }, all_goals { apply_instance, }, end lemma measurable_space_le {ι} [semilattice_sup ι] {f : filtration ι m} {τ : Ω → ι} [is_countably_generated (at_top : filter ι)] (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := begin casesI is_empty_or_nonempty ι, { haveI : is_empty Ω := ⟨λ ω, is_empty.false (τ ω)⟩, intros s hsτ, suffices hs : s = ∅, by { rw hs, exact measurable_set.empty, }, haveI : unique (set Ω) := set.unique_empty, rw [unique.eq_default s, unique.eq_default ∅], }, exact measurable_space_le' hτ, end example {f : filtration ℕ m} {τ : Ω → ℕ} (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := hτ.measurable_space_le example {f : filtration ℝ m} {τ : Ω → ℝ} (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := hτ.measurable_space_le @[simp] lemma measurable_space_const (f : filtration ι m) (i : ι) : (is_stopping_time_const f i).measurable_space = f i := begin ext1 s, change measurable_set[(is_stopping_time_const f i).measurable_space] s ↔ measurable_set[f i] s, rw is_stopping_time.measurable_set, split; intro h, { specialize h i, simpa only [le_refl, set.set_of_true, set.inter_univ] using h, }, { intro j, by_cases hij : i ≤ j, { simp only [hij, set.set_of_true, set.inter_univ], exact f.mono hij _ h, }, { simp only [hij, set.set_of_false, set.inter_empty, measurable_set.empty], }, }, end lemma measurable_set_inter_eq_iff (hτ : is_stopping_time f τ) (s : set Ω) (i : ι) : measurable_set[hτ.measurable_space] (s ∩ {ω | τ ω = i}) ↔ measurable_set[f i] (s ∩ {ω | τ ω = i}) := begin have : ∀ j, ({ω : Ω | τ ω = i} ∩ {ω : Ω | τ ω ≤ j}) = {ω : Ω | τ ω = i} ∩ {ω | i ≤ j}, { intro j, ext1 ω, simp only [set.mem_inter_eq, set.mem_set_of_eq, and.congr_right_iff], intro hxi, rw hxi, }, split; intro h, { specialize h i, simpa only [set.inter_assoc, this, le_refl, set.set_of_true, set.inter_univ] using h, }, { intro j, rw [set.inter_assoc, this], by_cases hij : i ≤ j, { simp only [hij, set.set_of_true, set.inter_univ], exact f.mono hij _ h, }, { simp [hij], }, }, end lemma measurable_space_le_of_le_const (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ ω, τ ω ≤ i) : hτ.measurable_space ≤ f i := (measurable_space_mono hτ _ hτ_le).trans (measurable_space_const _ _).le lemma le_measurable_space_of_const_le (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ ω, i ≤ τ ω) : f i ≤ hτ.measurable_space := (measurable_space_const _ _).symm.le.trans (measurable_space_mono _ hτ hτ_le) end preorder instance sigma_finite_stopping_time {ι} [semilattice_sup ι] [order_bot ι] [(filter.at_top : filter ι).is_countably_generated] {μ : measure Ω} {f : filtration ι m} {τ : Ω → ι} [sigma_finite_filtration μ f] (hτ : is_stopping_time f τ) : sigma_finite (μ.trim hτ.measurable_space_le) := begin refine sigma_finite_trim_mono hτ.measurable_space_le _, { exact f ⊥, }, { exact hτ.le_measurable_space_of_const_le (λ _, bot_le), }, { apply_instance, }, end section linear_order variables [linear_order ι] {f : filtration ι m} {τ π : Ω → ι} protected lemma measurable_set_le' (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω ≤ i} := begin intro j, have : {ω : Ω | τ ω ≤ i} ∩ {ω : Ω | τ ω ≤ j} = {ω : Ω | τ ω ≤ min i j}, { ext1 ω, simp only [set.mem_inter_eq, set.mem_set_of_eq, le_min_iff], }, rw this, exact f.mono (min_le_right i j) _ (hτ _), end protected lemma measurable_set_gt' (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | i < τ ω} := begin have : {ω : Ω | i < τ ω} = {ω : Ω | τ ω ≤ i}ᶜ, by { ext1 ω, simp, }, rw this, exact (hτ.measurable_set_le' i).compl, end protected lemma measurable_set_eq' [topological_space ι] [order_topology ι] [first_countable_topology ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω = i} := begin rw [← set.univ_inter {ω | τ ω = i}, measurable_set_inter_eq_iff, set.univ_inter], exact hτ.measurable_set_eq i, end protected lemma measurable_set_ge' [topological_space ι] [order_topology ι] [first_countable_topology ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | i ≤ τ ω} := begin have : {ω | i ≤ τ ω} = {ω | τ ω = i} ∪ {ω | i < τ ω}, { ext1 ω, simp only [le_iff_lt_or_eq, set.mem_set_of_eq, set.mem_union_eq], rw [@eq_comm _ i, or_comm], }, rw this, exact (hτ.measurable_set_eq' i).union (hτ.measurable_set_gt' i), end protected lemma measurable_set_lt' [topological_space ι] [order_topology ι] [first_countable_topology ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω < i} := begin have : {ω | τ ω < i} = {ω | τ ω ≤ i} \ {ω | τ ω = i}, { ext1 ω, simp only [lt_iff_le_and_ne, set.mem_set_of_eq, set.mem_diff], }, rw this, exact (hτ.measurable_set_le' i).diff (hτ.measurable_set_eq' i), end section countable protected lemma measurable_set_eq_of_countable' (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω = i} := begin rw [← set.univ_inter {ω | τ ω = i}, measurable_set_inter_eq_iff, set.univ_inter], exact hτ.measurable_set_eq_of_countable h_countable i, end protected lemma measurable_set_eq_of_encodable' [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω = i} := hτ.measurable_set_eq_of_countable' (set.to_countable _) i protected lemma measurable_set_ge_of_countable' (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[hτ.measurable_space] {ω | i ≤ τ ω} := begin have : {ω | i ≤ τ ω} = {ω | τ ω = i} ∪ {ω | i < τ ω}, { ext1 ω, simp only [le_iff_lt_or_eq, set.mem_set_of_eq, set.mem_union_eq], rw [@eq_comm _ i, or_comm], }, rw this, exact (hτ.measurable_set_eq_of_countable' h_countable i).union (hτ.measurable_set_gt' i), end protected lemma measurable_set_ge_of_encodable' [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | i ≤ τ ω} := hτ.measurable_set_ge_of_countable' (set.to_countable _) i protected lemma measurable_set_lt_of_countable' (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω < i} := begin have : {ω | τ ω < i} = {ω | τ ω ≤ i} \ {ω | τ ω = i}, { ext1 ω, simp only [lt_iff_le_and_ne, set.mem_set_of_eq, set.mem_diff], }, rw this, exact (hτ.measurable_set_le' i).diff (hτ.measurable_set_eq_of_countable' h_countable i), end protected lemma measurable_set_lt_of_encodable' [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {ω | τ ω < i} := hτ.measurable_set_lt_of_countable' (set.to_countable _) i protected lemma measurable_space_le_of_countable (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) : hτ.measurable_space ≤ m := begin intros s hs, change ∀ i, measurable_set[f i] (s ∩ {ω | τ ω ≤ i}) at hs, rw (_ : s = ⋃ (i ∈ set.range τ), s ∩ {ω | τ ω ≤ i}), { exact measurable_set.bUnion h_countable (λ i _, f.le i _ (hs i)), }, { ext ω, split; rw set.mem_Union, { exact λ hx, ⟨τ ω, by simpa using hx⟩,}, { rintro ⟨i, hx⟩, simp only [set.mem_range, set.Union_exists, set.mem_Union, set.mem_inter_eq, set.mem_set_of_eq, exists_prop, exists_and_distrib_right] at hx, exact hx.1.2, } } end end countable protected lemma measurable [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [second_countable_topology ι] (hτ : is_stopping_time f τ) : measurable[hτ.measurable_space] τ := @measurable_of_Iic ι Ω _ _ _ hτ.measurable_space _ _ _ _ (λ i, hτ.measurable_set_le' i) protected lemma measurable_of_le [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [second_countable_topology ι] (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ ω, τ ω ≤ i) : measurable[f i] τ := hτ.measurable.mono (measurable_space_le_of_le_const _ hτ_le) le_rfl lemma measurable_space_min (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : (hτ.min hπ).measurable_space = hτ.measurable_space ⊓ hπ.measurable_space := begin refine le_antisymm _ _, { exact le_inf (measurable_space_mono _ hτ (λ _, min_le_left _ _)) (measurable_space_mono _ hπ (λ _, min_le_right _ _)), }, { intro s, change measurable_set[hτ.measurable_space] s ∧ measurable_set[hπ.measurable_space] s → measurable_set[(hτ.min hπ).measurable_space] s, simp_rw is_stopping_time.measurable_set, have : ∀ i, {ω | min (τ ω) (π ω) ≤ i} = {ω | τ ω ≤ i} ∪ {ω | π ω ≤ i}, { intro i, ext1 ω, simp, }, simp_rw [this, set.inter_union_distrib_left], exact λ h i, (h.left i).union (h.right i), }, end lemma measurable_set_min_iff (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set Ω) : measurable_set[(hτ.min hπ).measurable_space] s ↔ measurable_set[hτ.measurable_space] s ∧ measurable_set[hπ.measurable_space] s := by { rw measurable_space_min, refl, } lemma measurable_space_min_const (hτ : is_stopping_time f τ) {i : ι} : (hτ.min_const i).measurable_space = hτ.measurable_space ⊓ f i := by rw [hτ.measurable_space_min (is_stopping_time_const _ i), measurable_space_const] lemma measurable_set_min_const_iff (hτ : is_stopping_time f τ) (s : set Ω) {i : ι} : measurable_set[(hτ.min_const i).measurable_space] s ↔ measurable_set[hτ.measurable_space] s ∧ measurable_set[f i] s := by rw [measurable_space_min_const, measurable_space.measurable_set_inf] lemma measurable_set_inter_le [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set Ω) (hs : measurable_set[hτ.measurable_space] s) : measurable_set[(hτ.min hπ).measurable_space] (s ∩ {ω | τ ω ≤ π ω}) := begin simp_rw is_stopping_time.measurable_set at ⊢ hs, intro i, have : (s ∩ {ω | τ ω ≤ π ω} ∩ {ω | min (τ ω) (π ω) ≤ i}) = (s ∩ {ω | τ ω ≤ i}) ∩ {ω | min (τ ω) (π ω) ≤ i} ∩ {ω | min (τ ω) i ≤ min (min (τ ω) (π ω)) i}, { ext1 ω, simp only [min_le_iff, set.mem_inter_eq, set.mem_set_of_eq, le_min_iff, le_refl, true_and, and_true, true_or, or_true], by_cases hτi : τ ω ≤ i, { simp only [hτi, true_or, and_true, and.congr_right_iff], intro hx, split; intro h, { exact or.inl h, }, { cases h, { exact h, }, { exact hτi.trans h, }, }, }, simp only [hτi, false_or, and_false, false_and, iff_false, not_and, not_le, and_imp], refine λ hx hτ_le_π, lt_of_lt_of_le _ hτ_le_π, rw ← not_le, exact hτi, }, rw this, refine ((hs i).inter ((hτ.min hπ) i)).inter _, apply measurable_set_le, { exact (hτ.min_const i).measurable_of_le (λ _, min_le_right _ _), }, { exact ((hτ.min hπ).min_const i).measurable_of_le (λ _, min_le_right _ _), }, end lemma measurable_set_inter_le_iff [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set Ω) : measurable_set[hτ.measurable_space] (s ∩ {ω | τ ω ≤ π ω}) ↔ measurable_set[(hτ.min hπ).measurable_space] (s ∩ {ω | τ ω ≤ π ω}) := begin split; intro h, { have : s ∩ {ω | τ ω ≤ π ω} = s ∩ {ω | τ ω ≤ π ω} ∩ {ω | τ ω ≤ π ω}, by rw [set.inter_assoc, set.inter_self], rw this, exact measurable_set_inter_le _ _ _ h, }, { rw measurable_set_min_iff at h, exact h.1, }, end lemma measurable_set_le_stopping_time [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hτ.measurable_space] {ω | τ ω ≤ π ω} := begin rw hτ.measurable_set, intro j, have : {ω | τ ω ≤ π ω} ∩ {ω | τ ω ≤ j} = {ω | min (τ ω) j ≤ min (π ω) j} ∩ {ω | τ ω ≤ j}, { ext1 ω, simp only [set.mem_inter_eq, set.mem_set_of_eq, min_le_iff, le_min_iff, le_refl, and_true, and.congr_left_iff], intro h, simp only [h, or_self, and_true], by_cases hj : j ≤ π ω, { simp only [hj, h.trans hj, or_self], }, { simp only [hj, or_false], }, }, rw this, refine measurable_set.inter _ (hτ.measurable_set_le j), apply measurable_set_le, { exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, { exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, end lemma measurable_set_stopping_time_le [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hπ.measurable_space] {ω | τ ω ≤ π ω} := begin suffices : measurable_set[(hτ.min hπ).measurable_space] {ω : Ω | τ ω ≤ π ω}, by { rw measurable_set_min_iff hτ hπ at this, exact this.2, }, rw [← set.univ_inter {ω : Ω | τ ω ≤ π ω}, ← hτ.measurable_set_inter_le_iff hπ, set.univ_inter], exact measurable_set_le_stopping_time hτ hπ, end lemma measurable_set_eq_stopping_time [add_group ι] [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [measurable_singleton_class ι] [second_countable_topology ι] [has_measurable_sub₂ ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hτ.measurable_space] {ω | τ ω = π ω} := begin rw hτ.measurable_set, intro j, have : {ω | τ ω = π ω} ∩ {ω | τ ω ≤ j} = {ω | min (τ ω) j = min (π ω) j} ∩ {ω | τ ω ≤ j} ∩ {ω | π ω ≤ j}, { ext1 ω, simp only [set.mem_inter_eq, set.mem_set_of_eq], refine ⟨λ h, ⟨⟨_, h.2⟩, _⟩, λ h, ⟨_, h.1.2⟩⟩, { rw h.1, }, { rw ← h.1, exact h.2, }, { cases h with h' hσ_le, cases h' with h_eq hτ_le, rwa [min_eq_left hτ_le, min_eq_left hσ_le] at h_eq, }, }, rw this, refine measurable_set.inter (measurable_set.inter _ (hτ.measurable_set_le j)) (hπ.measurable_set_le j), apply measurable_set_eq_fun, { exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, { exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, end lemma measurable_set_eq_stopping_time_of_encodable [encodable ι] [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [measurable_singleton_class ι] [second_countable_topology ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hτ.measurable_space] {ω | τ ω = π ω} := begin rw hτ.measurable_set, intro j, have : {ω | τ ω = π ω} ∩ {ω | τ ω ≤ j} = {ω | min (τ ω) j = min (π ω) j} ∩ {ω | τ ω ≤ j} ∩ {ω | π ω ≤ j}, { ext1 ω, simp only [set.mem_inter_eq, set.mem_set_of_eq], refine ⟨λ h, ⟨⟨_, h.2⟩, _⟩, λ h, ⟨_, h.1.2⟩⟩, { rw h.1, }, { rw ← h.1, exact h.2, }, { cases h with h' hπ_le, cases h' with h_eq hτ_le, rwa [min_eq_left hτ_le, min_eq_left hπ_le] at h_eq, }, }, rw this, refine measurable_set.inter (measurable_set.inter _ (hτ.measurable_set_le j)) (hπ.measurable_set_le j), apply measurable_set_eq_fun_of_encodable, { exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, { exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, end end linear_order end is_stopping_time section linear_order /-! ## Stopped value and stopped process -/ /-- Given a map `u : ι → Ω → E`, its stopped value with respect to the stopping time `τ` is the map `x ↦ u (τ ω) x`. -/ def stopped_value (u : ι → Ω → β) (τ : Ω → ι) : Ω → β := λ ω, u (τ ω) ω lemma stopped_value_const (u : ι → Ω → β) (i : ι) : stopped_value u (λ ω, i) = u i := rfl variable [linear_order ι] /-- Given a map `u : ι → Ω → E`, the stopped process with respect to `τ` is `u i x` if `i ≤ τ ω`, and `u (τ ω) x` otherwise. Intuitively, the stopped process stops evolving once the stopping time has occured. -/ def stopped_process (u : ι → Ω → β) (τ : Ω → ι) : ι → Ω → β := λ i ω, u (min i (τ ω)) ω lemma stopped_process_eq_of_le {u : ι → Ω → β} {τ : Ω → ι} {i : ι} {ω : Ω} (h : i ≤ τ ω) : stopped_process u τ i ω = u i ω := by simp [stopped_process, min_eq_left h] lemma stopped_process_eq_of_ge {u : ι → Ω → β} {τ : Ω → ι} {i : ι} {ω : Ω} (h : τ ω ≤ i) : stopped_process u τ i ω = u (τ ω) ω := by simp [stopped_process, min_eq_right h] section prog_measurable variables [measurable_space ι] [topological_space ι] [order_topology ι] [second_countable_topology ι] [borel_space ι] [topological_space β] {u : ι → Ω → β} {τ : Ω → ι} {f : filtration ι m} lemma prog_measurable_min_stopping_time [metrizable_space ι] (hτ : is_stopping_time f τ) : prog_measurable f (λ i ω, min i (τ ω)) := begin intro i, let m_prod : measurable_space (set.Iic i × Ω) := measurable_space.prod _ (f i), let m_set : ∀ t : set (set.Iic i × Ω), measurable_space t := λ _, @subtype.measurable_space (set.Iic i × Ω) _ m_prod, let s := {p : set.Iic i × Ω | τ p.2 ≤ i}, have hs : measurable_set[m_prod] s, from @measurable_snd (set.Iic i) Ω _ (f i) _ (hτ i), have h_meas_fst : ∀ t : set (set.Iic i × Ω), measurable[m_set t] (λ x : t, ((x : set.Iic i × Ω).fst : ι)), from λ t, (@measurable_subtype_coe (set.Iic i × Ω) m_prod _).fst.subtype_coe, apply measurable.strongly_measurable, refine measurable_of_restrict_of_restrict_compl hs _ _, { refine @measurable.min _ _ _ _ _ (m_set s) _ _ _ _ _ (h_meas_fst s) _, refine @measurable_of_Iic ι s _ _ _ (m_set s) _ _ _ _ (λ j, _), have h_set_eq : (λ x : s, τ (x : set.Iic i × Ω).snd) ⁻¹' set.Iic j = (λ x : s, (x : set.Iic i × Ω).snd) ⁻¹' {ω | τ ω ≤ min i j}, { ext1 ω, simp only [set.mem_preimage, set.mem_Iic, iff_and_self, le_min_iff, set.mem_set_of_eq], exact λ _, ω.prop, }, rw h_set_eq, suffices h_meas : @measurable _ _ (m_set s) (f i) (λ x : s, (x : set.Iic i × Ω).snd), from h_meas (f.mono (min_le_left _ _) _ (hτ.measurable_set_le (min i j))), exact measurable_snd.comp (@measurable_subtype_coe _ m_prod _), }, { suffices h_min_eq_left : (λ x : sᶜ, min ↑((x : set.Iic i × Ω).fst) (τ (x : set.Iic i × Ω).snd)) = λ x : sᶜ, ↑((x : set.Iic i × Ω).fst), { rw [set.restrict, h_min_eq_left], exact h_meas_fst _, }, ext1 ω, rw min_eq_left, have hx_fst_le : ↑(ω : set.Iic i × Ω).fst ≤ i, from (ω : set.Iic i × Ω).fst.prop, refine hx_fst_le.trans (le_of_lt _), convert ω.prop, simp only [not_le, set.mem_compl_eq, set.mem_set_of_eq], }, end lemma prog_measurable.stopped_process [metrizable_space ι] (h : prog_measurable f u) (hτ : is_stopping_time f τ) : prog_measurable f (stopped_process u τ) := h.comp (prog_measurable_min_stopping_time hτ) (λ i x, min_le_left _ _) lemma prog_measurable.adapted_stopped_process [metrizable_space ι] (h : prog_measurable f u) (hτ : is_stopping_time f τ) : adapted f (stopped_process u τ) := (h.stopped_process hτ).adapted lemma prog_measurable.strongly_measurable_stopped_process [metrizable_space ι] (hu : prog_measurable f u) (hτ : is_stopping_time f τ) (i : ι) : strongly_measurable (stopped_process u τ i) := (hu.adapted_stopped_process hτ i).mono (f.le _) lemma strongly_measurable_stopped_value_of_le (h : prog_measurable f u) (hτ : is_stopping_time f τ) {n : ι} (hτ_le : ∀ ω, τ ω ≤ n) : strongly_measurable[f n] (stopped_value u τ) := begin have : stopped_value u τ = (λ (p : set.Iic n × Ω), u ↑(p.fst) p.snd) ∘ (λ ω, (⟨τ ω, hτ_le ω⟩, ω)), { ext1 ω, simp only [stopped_value, function.comp_app, subtype.coe_mk], }, rw this, refine strongly_measurable.comp_measurable (h n) _, exact (hτ.measurable_of_le hτ_le).subtype_mk.prod_mk measurable_id, end lemma measurable_stopped_value [metrizable_space β] [measurable_space β] [borel_space β] (hf_prog : prog_measurable f u) (hτ : is_stopping_time f τ) : measurable[hτ.measurable_space] (stopped_value u τ) := begin have h_str_meas : ∀ i, strongly_measurable[f i] (stopped_value u (λ ω, min (τ ω) i)), from λ i, strongly_measurable_stopped_value_of_le hf_prog (hτ.min_const i) (λ _, min_le_right _ _), intros t ht i, suffices : stopped_value u τ ⁻¹' t ∩ {ω : Ω | τ ω ≤ i} = stopped_value u (λ ω, min (τ ω) i) ⁻¹' t ∩ {ω : Ω | τ ω ≤ i}, by { rw this, exact ((h_str_meas i).measurable ht).inter (hτ.measurable_set_le i), }, ext1 ω, simp only [stopped_value, set.mem_inter_eq, set.mem_preimage, set.mem_set_of_eq, and.congr_left_iff], intro h, rw min_eq_left h, end end prog_measurable end linear_order section nat /-! ### Filtrations indexed by `ℕ` -/ open filtration variables {f : filtration ℕ m} {u : ℕ → Ω → β} {τ π : Ω → ℕ} lemma stopped_value_sub_eq_sum [add_comm_group β] (hle : τ ≤ π) : stopped_value u π - stopped_value u τ = λ ω, (∑ i in finset.Ico (τ ω) (π ω), (u (i + 1) - u i)) ω := begin ext ω, rw [finset.sum_Ico_eq_sub _ (hle ω), finset.sum_range_sub, finset.sum_range_sub], simp [stopped_value], end lemma stopped_value_sub_eq_sum' [add_comm_group β] (hle : τ ≤ π) {N : ℕ} (hbdd : ∀ ω, π ω ≤ N) : stopped_value u π - stopped_value u τ = λ ω, (∑ i in finset.range (N + 1), set.indicator {ω | τ ω ≤ i ∧ i < π ω} (u (i + 1) - u i)) ω := begin rw stopped_value_sub_eq_sum hle, ext ω, simp only [finset.sum_apply, finset.sum_indicator_eq_sum_filter], refine finset.sum_congr _ (λ _ _, rfl), ext i, simp only [finset.mem_filter, set.mem_set_of_eq, finset.mem_range, finset.mem_Ico], exact ⟨λ h, ⟨lt_trans h.2 (nat.lt_succ_iff.2 $ hbdd _), h⟩, λ h, h.2⟩ end section add_comm_monoid variables [add_comm_monoid β] /-- For filtrations indexed by `ℕ`, `adapted` and `prog_measurable` are equivalent. This lemma provides `adapted f u → prog_measurable f u`. See `prog_measurable.adapted` for the reverse direction, which is true more generally. -/ lemma adapted.prog_measurable_of_nat [topological_space β] [has_continuous_add β] (h : adapted f u) : prog_measurable f u := begin intro i, have : (λ p : ↥(set.Iic i) × Ω, u ↑(p.fst) p.snd) = λ p : ↥(set.Iic i) × Ω, ∑ j in finset.range (i + 1), if ↑p.fst = j then u j p.snd else 0, { ext1 p, rw finset.sum_ite_eq, have hp_mem : (p.fst : ℕ) ∈ finset.range (i + 1) := finset.mem_range_succ_iff.mpr p.fst.prop, simp only [hp_mem, if_true], }, rw this, refine finset.strongly_measurable_sum _ (λ j hj, strongly_measurable.ite _ _ _), { suffices h_meas : measurable[measurable_space.prod _ (f i)] (λ a : ↥(set.Iic i) × Ω, (a.fst : ℕ)), from h_meas (measurable_set_singleton j), exact measurable_fst.subtype_coe, }, { have h_le : j ≤ i, from finset.mem_range_succ_iff.mp hj, exact (strongly_measurable.mono (h j) (f.mono h_le)).comp_measurable measurable_snd, }, { exact strongly_measurable_const, }, end /-- For filtrations indexed by `ℕ`, the stopped process obtained from an adapted process is adapted. -/ lemma adapted.stopped_process_of_nat [topological_space β] [has_continuous_add β] (hu : adapted f u) (hτ : is_stopping_time f τ) : adapted f (stopped_process u τ) := (hu.prog_measurable_of_nat.stopped_process hτ).adapted lemma adapted.strongly_measurable_stopped_process_of_nat [topological_space β] [has_continuous_add β] (hτ : is_stopping_time f τ) (hu : adapted f u) (n : ℕ) : strongly_measurable (stopped_process u τ n) := hu.prog_measurable_of_nat.strongly_measurable_stopped_process hτ n lemma stopped_value_eq {N : ℕ} (hbdd : ∀ ω, τ ω ≤ N) : stopped_value u τ = λ x, (∑ i in finset.range (N + 1), set.indicator {ω | τ ω = i} (u i)) x := begin ext y, rw [stopped_value, finset.sum_apply, finset.sum_eq_single (τ y)], { rw set.indicator_of_mem, exact rfl }, { exact λ i hi hneq, set.indicator_of_not_mem hneq.symm _ }, { intro hy, rw set.indicator_of_not_mem, exact λ _, hy (finset.mem_range.2 $ lt_of_le_of_lt (hbdd _) (nat.lt_succ_self _)) } end lemma stopped_process_eq (n : ℕ) : stopped_process u τ n = set.indicator {a | n ≤ τ a} (u n) + ∑ i in finset.range n, set.indicator {ω | τ ω = i} (u i) := begin ext ω, rw [pi.add_apply, finset.sum_apply], cases le_or_lt n (τ ω), { rw [stopped_process_eq_of_le h, set.indicator_of_mem, finset.sum_eq_zero, add_zero], { intros m hm, rw finset.mem_range at hm, exact set.indicator_of_not_mem ((lt_of_lt_of_le hm h).ne.symm) _ }, { exact h } }, { rw [stopped_process_eq_of_ge (le_of_lt h), finset.sum_eq_single_of_mem (τ ω)], { rw [set.indicator_of_not_mem, zero_add, set.indicator_of_mem], { exact rfl }, -- refl does not work { exact not_le.2 h } }, { rwa [finset.mem_range] }, { intros b hb hneq, rw set.indicator_of_not_mem, exact hneq.symm } }, end end add_comm_monoid section normed_add_comm_group variables [normed_add_comm_group β] {p : ℝ≥0∞} {μ : measure Ω} lemma mem_ℒp_stopped_process (hτ : is_stopping_time f τ) (hu : ∀ n, mem_ℒp (u n) p μ) (n : ℕ) : mem_ℒp (stopped_process u τ n) p μ := begin rw stopped_process_eq, refine mem_ℒp.add _ _, { exact mem_ℒp.indicator (f.le n {a : Ω | n ≤ τ a} (hτ.measurable_set_ge n)) (hu n) }, { suffices : mem_ℒp (λ ω, ∑ (i : ℕ) in finset.range n, {a : Ω | τ a = i}.indicator (u i) ω) p μ, { convert this, ext1 ω, simp only [finset.sum_apply] }, refine mem_ℒp_finset_sum _ (λ i hi, mem_ℒp.indicator _ (hu i)), exact f.le i {a : Ω | τ a = i} (hτ.measurable_set_eq i) }, end lemma integrable_stopped_process (hτ : is_stopping_time f τ) (hu : ∀ n, integrable (u n) μ) (n : ℕ) : integrable (stopped_process u τ n) μ := by { simp_rw ← mem_ℒp_one_iff_integrable at hu ⊢, exact mem_ℒp_stopped_process hτ hu n, } lemma mem_ℒp_stopped_value (hτ : is_stopping_time f τ) (hu : ∀ n, mem_ℒp (u n) p μ) {N : ℕ} (hbdd : ∀ ω, τ ω ≤ N) : mem_ℒp (stopped_value u τ) p μ := begin rw stopped_value_eq hbdd, suffices : mem_ℒp (λ x, ∑ (i : ℕ) in finset.range (N + 1), {a : Ω | τ a = i}.indicator (u i) x) p μ, { convert this, ext1 ω, simp only [finset.sum_apply] }, refine mem_ℒp_finset_sum _ (λ i hi, mem_ℒp.indicator _ (hu i)), exact f.le i {a : Ω | τ a = i} (hτ.measurable_set_eq i) end lemma integrable_stopped_value (hτ : is_stopping_time f τ) (hu : ∀ n, integrable (u n) μ) {N : ℕ} (hbdd : ∀ ω, τ ω ≤ N) : integrable (stopped_value u τ) μ := by { simp_rw ← mem_ℒp_one_iff_integrable at hu ⊢, exact mem_ℒp_stopped_value hτ hu hbdd, } end normed_add_comm_group end nat section piecewise_const variables [preorder ι] {𝒢 : filtration ι m} {τ η : Ω → ι} {i j : ι} {s : set Ω} [decidable_pred (∈ s)] /-- Given stopping times `τ` and `η` which are bounded below, `set.piecewise s τ η` is also a stopping time with respect to the same filtration. -/ lemma is_stopping_time.piecewise_of_le (hτ_st : is_stopping_time 𝒢 τ) (hη_st : is_stopping_time 𝒢 η) (hτ : ∀ ω, i ≤ τ ω) (hη : ∀ x, i ≤ η x) (hs : measurable_set[𝒢 i] s) : is_stopping_time 𝒢 (s.piecewise τ η) := begin intro n, have : {x | s.piecewise τ η x ≤ n} = (s ∩ {ω | τ ω ≤ n}) ∪ (sᶜ ∩ {x | η x ≤ n}), { ext1 ω, simp only [set.piecewise, set.mem_inter_eq, set.mem_set_of_eq, and.congr_right_iff], by_cases hx : ω ∈ s; simp [hx], }, rw this, by_cases hin : i ≤ n, { have hs_n : measurable_set[𝒢 n] s, from 𝒢.mono hin _ hs, exact (hs_n.inter (hτ_st n)).union (hs_n.compl.inter (hη_st n)), }, { have hτn : ∀ ω, ¬ τ ω ≤ n := λ ω hτn, hin ((hτ ω).trans hτn), have hηn : ∀ ω, ¬ η ω ≤ n := λ ω hηn, hin ((hη ω).trans hηn), simp [hτn, hηn], }, end lemma is_stopping_time_piecewise_const (hij : i ≤ j) (hs : measurable_set[𝒢 i] s) : is_stopping_time 𝒢 (s.piecewise (λ _, i) (λ _, j)) := (is_stopping_time_const 𝒢 i).piecewise_of_le (is_stopping_time_const 𝒢 j) (λ x, le_rfl) (λ _, hij) hs lemma stopped_value_piecewise_const {ι' : Type*} {i j : ι'} {f : ι' → Ω → ℝ} : stopped_value f (s.piecewise (λ _, i) (λ _, j)) = s.piecewise (f i) (f j) := by { ext ω, rw stopped_value, by_cases hx : ω ∈ s; simp [hx] } lemma stopped_value_piecewise_const' {ι' : Type*} {i j : ι'} {f : ι' → Ω → ℝ} : stopped_value f (s.piecewise (λ _, i) (λ _, j)) = s.indicator (f i) + sᶜ.indicator (f j) := by { ext ω, rw stopped_value, by_cases hx : ω ∈ s; simp [hx] } end piecewise_const end measure_theory
3313e5242ddf2f0ff2cc2bd9a618ec4c1030f663
7bc35d4fbdda0c01e9b22a949940ee5cbb9800d0
/basis.lean
b0f0f99e1f17e406a2064e06a233a49480e38f47
[]
no_license
truonghoangle/manifolds
e6c2534dd46579f56ba99a48e2eb7ce51640e7c0
dcf4815b29ad363ec9712fd00b7756c36cfa7c1c
refs/heads/main
1,638,501,090,139
1,636,918,550,000
1,636,918,550,000
185,779,631
0
0
null
null
null
null
UTF-8
Lean
false
false
703
lean
import topology.constructions import equiv open topological_space noncomputable theory universes u v variables {α : Type u} {β : Type v} structure Top := (carrier : Type u) (struct : topological_space carrier) namespace Top instance : has_coe_to_sort Top := ⟨Type*, Top.carrier⟩ attribute [instance] Top.struct def restrict (X : Top) (s : set X) : Top := ⟨subtype s, by apply_instance⟩ end Top def is_continuous [topological_space α] [topological_space β] (f : α →. β) := continuous (f.as_subtype) structure phomeo (X Y : Top) extends X ≃. Y := (continuous_to_fun : is_continuous to_fun) (continuous_inv_fun : is_continuous inv_fun) infixr ` ≃ₜ. `:25 := phomeo
3d51a5387e7dc7dad6d361e4dac88e6613c39a2d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/dfinsupp/lex.lean
91aa1fa74b091f01fae8a4532ad24c21a5b8df78
[ "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,799
lean
/- Copyright (c) 2022 Junyan Xu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Junyan Xu -/ import data.dfinsupp.order import data.dfinsupp.ne_locus import order.well_founded_set /-! # Lexicographic order on finitely supported dependent functions This file defines the lexicographic order on `dfinsupp`. -/ variables {ι : Type*} {α : ι → Type*} namespace dfinsupp section has_zero variable [Π i, has_zero (α i)] /-- `dfinsupp.lex r s` is the lexicographic relation on `Π₀ i, α i`, where `ι` is ordered by `r`, and `α i` is ordered by `s i`. The type synonym `lex (Π₀ i, α i)` has an order given by `dfinsupp.lex (<) (λ i, (<))`. -/ protected def lex (r : ι → ι → Prop) (s : Π i, α i → α i → Prop) (x y : Π₀ i, α i) : Prop := pi.lex r s x y lemma _root_.pi.lex_eq_dfinsupp_lex {r : ι → ι → Prop} {s : Π i, α i → α i → Prop} (a b : Π₀ i, α i) : pi.lex r s (a : Π i, α i) b = dfinsupp.lex r s a b := rfl lemma lex_def {r : ι → ι → Prop} {s : Π i, α i → α i → Prop} {a b : Π₀ i, α i} : dfinsupp.lex r s a b ↔ ∃ j, (∀ d, r d j → a d = b d) ∧ s j (a j) (b j) := iff.rfl instance [has_lt ι] [Π i, has_lt (α i)] : has_lt (lex (Π₀ i, α i)) := ⟨λ f g, dfinsupp.lex (<) (λ i, (<)) (of_lex f) (of_lex g)⟩ lemma lex_lt_of_lt_of_preorder [Π i, preorder (α i)] (r) [is_strict_order ι r] {x y : Π₀ i, α i} (hlt : x < y) : ∃ i, (∀ j, r j i → x j ≤ y j ∧ y j ≤ x j) ∧ x i < y i := begin obtain ⟨hle, j, hlt⟩ := pi.lt_def.1 hlt, classical, have : (x.ne_locus y : set ι).well_founded_on r := (x.ne_locus y).finite_to_set.well_founded_on, obtain ⟨i, hi, hl⟩ := this.has_min {i | x i < y i} ⟨⟨j, mem_ne_locus.2 hlt.ne⟩, hlt⟩, exact ⟨i, λ k hk, ⟨hle k, of_not_not $ λ h, hl ⟨k, mem_ne_locus.2 (ne_of_not_le h).symm⟩ ((hle k).lt_of_not_le h) hk⟩, hi⟩, end lemma lex_lt_of_lt [Π i, partial_order (α i)] (r) [is_strict_order ι r] {x y : Π₀ i, α i} (hlt : x < y) : pi.lex r (λ i, (<)) x y := by { simp_rw [pi.lex, le_antisymm_iff], exact lex_lt_of_lt_of_preorder r hlt } instance lex.is_strict_order [linear_order ι] [Π i, partial_order (α i)] : is_strict_order (lex (Π₀ i, α i)) (<) := let i : is_strict_order (lex (Π i, α i)) (<) := pi.lex.is_strict_order in { irrefl := to_lex.surjective.forall.2 $ λ a, @irrefl _ _ i.to_is_irrefl a, trans := to_lex.surjective.forall₃.2 $ λ a b c, @trans _ _ i.to_is_trans a b c } variables [linear_order ι] /-- The partial order on `dfinsupp`s obtained by the lexicographic ordering. See `dfinsupp.lex.linear_order` for a proof that this partial order is in fact linear. -/ instance lex.partial_order [Π i, partial_order (α i)] : partial_order (lex (Π₀ i, α i)) := partial_order.lift (λ x, to_lex ⇑(of_lex x)) dfinsupp.coe_fn_injective section linear_order variable [Π i, linear_order (α i)] /-- Auxiliary helper to case split computably. There is no need for this to be public, as it can be written with `or.by_cases` on `lt_trichotomy` once the instances below are constructed. -/ private def lt_trichotomy_rec {P : lex (Π₀ i, α i) → lex (Π₀ i, α i) → Sort*} (h_lt : Π {f g}, to_lex f < to_lex g → P (to_lex f) (to_lex g)) (h_eq : Π {f g}, to_lex f = to_lex g → P (to_lex f) (to_lex g)) (h_gt : Π {f g}, to_lex g < to_lex f → P (to_lex f) (to_lex g)) : Π f g, P f g := lex.rec $ λ f, lex.rec $ λ g, match _, rfl : ∀ y, (f.ne_locus g).min = y → _ with | ⊤, h := h_eq (ne_locus_eq_empty.mp $ finset.min_eq_top.mp h) | (wit : ι), h := (mem_ne_locus.mp $ finset.mem_of_min h).lt_or_lt.by_cases (λ hwit, h_lt ⟨wit, λ j hj, not_mem_ne_locus.mp (finset.not_mem_of_lt_min hj h), hwit⟩) (λ hwit, h_gt ⟨wit, λ j hj, not_mem_ne_locus.mp (finset.not_mem_of_lt_min hj $ by rwa ne_locus_comm), hwit⟩) end @[irreducible] instance lex.decidable_le : @decidable_rel (lex (Π₀ i, α i)) (≤) := lt_trichotomy_rec (λ f g h, is_true $ or.inr h) (λ f g h, is_true $ or.inl $ congr_arg _ h) (λ f g h, is_false $ λ h', (lt_irrefl _ (h.trans_le h')).elim) @[irreducible] instance lex.decidable_lt : @decidable_rel (lex (Π₀ i, α i)) (<) := lt_trichotomy_rec (λ f g h, is_true h) (λ f g h, is_false h.not_lt) (λ f g h, is_false h.asymm) /-- The linear order on `dfinsupp`s obtained by the lexicographic ordering. -/ instance lex.linear_order : linear_order (lex (Π₀ i, α i)) := { le_total := lt_trichotomy_rec (λ f g h, or.inl h.le) (λ f g h, or.inl h.le) (λ f g h, or.inr h.le), decidable_lt := by apply_instance, decidable_le := by apply_instance, decidable_eq := by apply_instance, ..lex.partial_order } end linear_order variable [Π i, partial_order (α i)] lemma to_lex_monotone : monotone (@to_lex (Π₀ i, α i)) := λ a b h, le_of_lt_or_eq $ or_iff_not_imp_right.2 $ λ hne, by classical; exact ⟨finset.min' _ (nonempty_ne_locus_iff.2 hne), λ j hj, not_mem_ne_locus.1 (λ h, (finset.min'_le _ _ h).not_lt hj), (h _).lt_of_ne (mem_ne_locus.1 $ finset.min'_mem _ _)⟩ lemma lt_of_forall_lt_of_lt (a b : lex (Π₀ i, α i)) (i : ι) : (∀ j < i, of_lex a j = of_lex b j) → of_lex a i < of_lex b i → a < b := λ h1 h2, ⟨i, h1, h2⟩ end has_zero section covariants variables [linear_order ι] [Π i, add_monoid (α i)] [Π i, linear_order (α i)] /-! We are about to sneak in a hypothesis that might appear to be too strong. We assume `covariant_class` with *strict* inequality `<` also when proving the one with the *weak* inequality `≤`. This is actually necessary: addition on `lex (Π₀ i, α i)` may fail to be monotone, when it is "just" monotone on `α i`. -/ section left variables [Π i, covariant_class (α i) (α i) (+) (<)] instance lex.covariant_class_lt_left : covariant_class (lex (Π₀ i, α i)) (lex (Π₀ i, α i)) (+) (<) := ⟨λ f g h ⟨a, lta, ha⟩, ⟨a, λ j ja, congr_arg ((+) _) (lta j ja), add_lt_add_left ha _⟩⟩ instance lex.covariant_class_le_left : covariant_class (lex (Π₀ i, α i)) (lex (Π₀ i, α i)) (+) (≤) := has_add.to_covariant_class_left _ end left section right variables [Π i, covariant_class (α i) (α i) (function.swap (+)) (<)] instance lex.covariant_class_lt_right : covariant_class (lex (Π₀ i, α i)) (lex (Π₀ i, α i)) (function.swap (+)) (<) := ⟨λ f g h ⟨a, lta, ha⟩, ⟨a, λ j ja, congr_arg (+ (of_lex f j)) (lta j ja), add_lt_add_right ha _⟩⟩ instance lex.covariant_class_le_right : covariant_class (lex (Π₀ i, α i)) (lex (Π₀ i, α i)) (function.swap (+)) (≤) := has_add.to_covariant_class_right _ end right end covariants end dfinsupp
b873621b778877d6636db01d425f46e58505ea66
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/simple.lean
8d9e40fe477cb467e4a54884b041e90ce67f9b3d
[ "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
45
lean
import Int. variable x : Int variable y : Int
e2b80aa12db3a6a0c5dc915f15302a7c6e955964
4727251e0cd73359b15b664c3170e5d754078599
/src/order/filter/germ.lean
74ca4709019a2e859d5f357b4d2e9460bf5a6947
[ "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,358
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, Abhimanyu Pallavi Sudhir -/ import order.filter.basic import algebra.module.pi /-! # Germ of a function at a filter The germ of a function `f : α → β` at a filter `l : filter α` is the equivalence class of `f` with respect to the equivalence relation `eventually_eq l`: `f ≈ g` means `∀ᶠ x in l, f x = g x`. ## Main definitions We define * `germ l β` to be the space of germs of functions `α → β` at a filter `l : filter α`; * coercion from `α → β` to `germ l β`: `(f : germ l β)` is the germ of `f : α → β` at `l : filter α`; this coercion is declared as `has_coe_t`, so it does not require an explicit up arrow `↑`; * coercion from `β` to `germ l β`: `(↑c : germ l β)` is the germ of the constant function `λ x:α, c` at a filter `l`; this coercion is declared as `has_lift_t`, so it requires an explicit up arrow `↑`, see [TPiL][TPiL_coe] for details. * `map (F : β → γ) (f : germ l β)` to be the composition of a function `F` and a germ `f`; * `map₂ (F : β → γ → δ) (f : germ l β) (g : germ l γ)` to be the germ of `λ x, F (f x) (g x)` at `l`; * `f.tendsto lb`: we say that a germ `f : germ l β` tends to a filter `lb` if its representatives tend to `lb` along `l`; * `f.comp_tendsto g hg` and `f.comp_tendsto' g hg`: given `f : germ l β` and a function `g : γ → α` (resp., a germ `g : germ lc α`), if `g` tends to `l` along `lc`, then the composition `f ∘ g` is a well-defined germ at `lc`; * `germ.lift_pred`, `germ.lift_rel`: lift a predicate or a relation to the space of germs: `(f : germ l β).lift_pred p` means `∀ᶠ x in l, p (f x)`, and similarly for a relation. [TPiL_coe]: https://leanprover.github.io/theorem_proving_in_lean/type_classes.html#coercions-using-type-classes We also define `map (F : β → γ) : germ l β → germ l γ` sending each germ `f` to `F ∘ f`. For each of the following structures we prove that if `β` has this structure, then so does `germ l β`: * one-operation algebraic structures up to `comm_group`; * `mul_zero_class`, `distrib`, `semiring`, `comm_semiring`, `ring`, `comm_ring`; * `mul_action`, `distrib_mul_action`, `module`; * `preorder`, `partial_order`, and `lattice` structures, as well as `bounded_order`; * `ordered_cancel_comm_monoid` and `ordered_cancel_add_comm_monoid`. ## Tags filter, germ -/ namespace filter variables {α β γ δ : Type*} {l : filter α} {f g h : α → β} lemma const_eventually_eq' [ne_bot l] {a b : β} : (∀ᶠ x in l, a = b) ↔ a = b := eventually_const lemma const_eventually_eq [ne_bot l] {a b : β} : ((λ _, a) =ᶠ[l] (λ _, b)) ↔ a = b := @const_eventually_eq' _ _ _ _ a b lemma eventually_eq.comp_tendsto {f' : α → β} (H : f =ᶠ[l] f') {g : γ → α} {lc : filter γ} (hg : tendsto g lc l) : f ∘ g =ᶠ[lc] f' ∘ g := hg.eventually H /-- Setoid used to define the space of germs. -/ def germ_setoid (l : filter α) (β : Type*) : setoid (α → β) := { r := eventually_eq l, iseqv := ⟨eventually_eq.refl _, λ _ _, eventually_eq.symm, λ _ _ _, eventually_eq.trans⟩ } /-- The space of germs of functions `α → β` at a filter `l`. -/ def germ (l : filter α) (β : Type*) : Type* := quotient (germ_setoid l β) /-- Setoid used to define the filter product. This is a dependent version of `filter.germ_setoid`. -/ def product_setoid (l : filter α) (ε : α → Type*) : setoid (Π a, ε a) := { r := λ f g, ∀ᶠ a in l, f a = g a, iseqv := ⟨λ _, eventually_of_forall (λ _, rfl), λ _ _ h, h.mono (λ _, eq.symm), λ x y z h1 h2, h1.congr (h2.mono (λ x hx, hx ▸ iff.rfl))⟩ } /-- The filter product `Π (a : α), ε a` at a filter `l`. This is a dependent version of `filter.germ`. -/ @[protected] def product (l : filter α) (ε : α → Type*) : Type* := quotient (product_setoid l ε) namespace product variables {ε : α → Type*} instance : has_coe_t (Π a, ε a) (l.product ε) := ⟨quotient.mk'⟩ instance [Π a, inhabited (ε a)] : inhabited (l.product ε) := ⟨(↑(λ a, (default : ε a)) : l.product ε)⟩ end product namespace germ instance : has_coe_t (α → β) (germ l β) := ⟨quotient.mk'⟩ instance : has_lift_t β (germ l β) := ⟨λ c, ↑(λ (x : α), c)⟩ @[simp] lemma quot_mk_eq_coe (l : filter α) (f : α → β) : quot.mk _ f = (f : germ l β) := rfl @[simp] lemma mk'_eq_coe (l : filter α) (f : α → β) : quotient.mk' f = (f : germ l β) := rfl @[elab_as_eliminator] lemma induction_on (f : germ l β) {p : germ l β → Prop} (h : ∀ f : α → β, p f) : p f := quotient.induction_on' f h @[elab_as_eliminator] lemma induction_on₂ (f : germ l β) (g : germ l γ) {p : germ l β → germ l γ → Prop} (h : ∀ (f : α → β) (g : α → γ), p f g) : p f g := quotient.induction_on₂' f g h @[elab_as_eliminator] lemma induction_on₃ (f : germ l β) (g : germ l γ) (h : germ l δ) {p : germ l β → germ l γ → germ l δ → Prop} (H : ∀ (f : α → β) (g : α → γ) (h : α → δ), p f g h) : p f g h := quotient.induction_on₃' f g h H /-- Given a map `F : (α → β) → (γ → δ)` that sends functions eventually equal at `l` to functions eventually equal at `lc`, returns a map from `germ l β` to `germ lc δ`. -/ def map' {lc : filter γ} (F : (α → β) → (γ → δ)) (hF : (l.eventually_eq ⇒ lc.eventually_eq) F F) : germ l β → germ lc δ := quotient.map' F hF /-- Given a germ `f : germ l β` and a function `F : (α → β) → γ` sending eventually equal functions to the same value, returns the value `F` takes on functions having germ `f` at `l`. -/ def lift_on {γ : Sort*} (f : germ l β) (F : (α → β) → γ) (hF : (l.eventually_eq ⇒ (=)) F F) : γ := quotient.lift_on' f F hF @[simp] lemma map'_coe {lc : filter γ} (F : (α → β) → (γ → δ)) (hF : (l.eventually_eq ⇒ lc.eventually_eq) F F) (f : α → β) : map' F hF f = F f := rfl @[simp, norm_cast] lemma coe_eq : (f : germ l β) = g ↔ (f =ᶠ[l] g) := quotient.eq' alias coe_eq ↔ _ filter.eventually_eq.germ_eq /-- Lift a function `β → γ` to a function `germ l β → germ l γ`. -/ def map (op : β → γ) : germ l β → germ l γ := map' ((∘) op) $ λ f g H, H.mono $ λ x H, congr_arg op H @[simp] lemma map_coe (op : β → γ) (f : α → β) : map op (f : germ l β) = op ∘ f := rfl @[simp] lemma map_id : map id = (id : germ l β → germ l β) := by { ext ⟨f⟩, refl } lemma map_map (op₁ : γ → δ) (op₂ : β → γ) (f : germ l β) : map op₁ (map op₂ f) = map (op₁ ∘ op₂) f := induction_on f $ λ f, rfl /-- Lift a binary function `β → γ → δ` to a function `germ l β → germ l γ → germ l δ`. -/ def map₂ (op : β → γ → δ) : germ l β → germ l γ → germ l δ := quotient.map₂' (λ f g x, op (f x) (g x)) $ λ f f' Hf g g' Hg, Hg.mp $ Hf.mono $ λ x Hf Hg, by simp only [Hf, Hg] @[simp] lemma map₂_coe (op : β → γ → δ) (f : α → β) (g : α → γ) : map₂ op (f : germ l β) g = λ x, op (f x) (g x) := rfl /-- A germ at `l` of maps from `α` to `β` tends to `lb : filter β` if it is represented by a map which tends to `lb` along `l`. -/ protected def tendsto (f : germ l β) (lb : filter β) : Prop := lift_on f (λ f, tendsto f l lb) $ λ f g H, propext (tendsto_congr' H) @[simp, norm_cast] lemma coe_tendsto {f : α → β} {lb : filter β} : (f : germ l β).tendsto lb ↔ tendsto f l lb := iff.rfl alias coe_tendsto ↔ _ filter.tendsto.germ_tendsto /-- Given two germs `f : germ l β`, and `g : germ lc α`, where `l : filter α`, if `g` tends to `l`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/ def comp_tendsto' (f : germ l β) {lc : filter γ} (g : germ lc α) (hg : g.tendsto l) : germ lc β := lift_on f (λ f, g.map f) $ λ f₁ f₂ hF, (induction_on g $ λ g hg, coe_eq.2 $ hg.eventually hF) hg @[simp] lemma coe_comp_tendsto' (f : α → β) {lc : filter γ} {g : germ lc α} (hg : g.tendsto l) : (f : germ l β).comp_tendsto' g hg = g.map f := rfl /-- Given a germ `f : germ l β` and a function `g : γ → α`, where `l : filter α`, if `g` tends to `l` along `lc : filter γ`, then the composition `f ∘ g` is well-defined as a germ at `lc`. -/ def comp_tendsto (f : germ l β) {lc : filter γ} (g : γ → α) (hg : tendsto g lc l) : germ lc β := f.comp_tendsto' _ hg.germ_tendsto @[simp] lemma coe_comp_tendsto (f : α → β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) : (f : germ l β).comp_tendsto g hg = f ∘ g := rfl @[simp] lemma comp_tendsto'_coe (f : germ l β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) : f.comp_tendsto' _ hg.germ_tendsto = f.comp_tendsto g hg := rfl @[simp, norm_cast] lemma const_inj [ne_bot l] {a b : β} : (↑a : germ l β) = ↑b ↔ a = b := coe_eq.trans $ const_eventually_eq @[simp] lemma map_const (l : filter α) (a : β) (f : β → γ) : (↑a : germ l β).map f = ↑(f a) := rfl @[simp] lemma map₂_const (l : filter α) (b : β) (c : γ) (f : β → γ → δ) : map₂ f (↑b : germ l β) ↑c = ↑(f b c) := rfl @[simp] lemma const_comp_tendsto {l : filter α} (b : β) {lc : filter γ} {g : γ → α} (hg : tendsto g lc l) : (↑b : germ l β).comp_tendsto g hg = ↑b := rfl @[simp] lemma const_comp_tendsto' {l : filter α} (b : β) {lc : filter γ} {g : germ lc α} (hg : g.tendsto l) : (↑b : germ l β).comp_tendsto' g hg = ↑b := induction_on g (λ _ _, rfl) hg /-- Lift a predicate on `β` to `germ l β`. -/ def lift_pred (p : β → Prop) (f : germ l β) : Prop := lift_on f (λ f, ∀ᶠ x in l, p (f x)) $ λ f g H, propext $ eventually_congr $ H.mono $ λ x hx, hx ▸ iff.rfl @[simp] lemma lift_pred_coe {p : β → Prop} {f : α → β} : lift_pred p (f : germ l β) ↔ ∀ᶠ x in l, p (f x) := iff.rfl lemma lift_pred_const {p : β → Prop} {x : β} (hx : p x) : lift_pred p (↑x : germ l β) := eventually_of_forall $ λ y, hx @[simp] lemma lift_pred_const_iff [ne_bot l] {p : β → Prop} {x : β} : lift_pred p (↑x : germ l β) ↔ p x := @eventually_const _ _ _ (p x) /-- Lift a relation `r : β → γ → Prop` to `germ l β → germ l γ → Prop`. -/ def lift_rel (r : β → γ → Prop) (f : germ l β) (g : germ l γ) : Prop := quotient.lift_on₂' f g (λ f g, ∀ᶠ x in l, r (f x) (g x)) $ λ f g f' g' Hf Hg, propext $ eventually_congr $ Hg.mp $ Hf.mono $ λ x hf hg, hf ▸ hg ▸ iff.rfl @[simp] lemma lift_rel_coe {r : β → γ → Prop} {f : α → β} {g : α → γ} : lift_rel r (f : germ l β) g ↔ ∀ᶠ x in l, r (f x) (g x) := iff.rfl lemma lift_rel_const {r : β → γ → Prop} {x : β} {y : γ} (h : r x y) : lift_rel r (↑x : germ l β) ↑y := eventually_of_forall $ λ _, h @[simp] lemma lift_rel_const_iff [ne_bot l] {r : β → γ → Prop} {x : β} {y : γ} : lift_rel r (↑x : germ l β) ↑y ↔ r x y := @eventually_const _ _ _ (r x y) instance [inhabited β] : inhabited (germ l β) := ⟨↑(default : β)⟩ section monoid variables {M : Type*} {G : Type*} @[to_additive] instance [has_mul M] : has_mul (germ l M) := ⟨map₂ (*)⟩ @[simp, norm_cast, to_additive] lemma coe_mul [has_mul M] (f g : α → M) : ↑(f * g) = (f * g : germ l M) := rfl @[to_additive] instance [has_one M] : has_one (germ l M) := ⟨↑(1:M)⟩ @[simp, norm_cast, to_additive] lemma coe_one [has_one M] : ↑(1 : α → M) = (1 : germ l M) := rfl @[to_additive] instance [semigroup M] : semigroup (germ l M) := function.surjective.semigroup coe (surjective_quot_mk _) (λ a b, coe_mul a b) @[to_additive] instance [comm_semigroup M] : comm_semigroup (germ l M) := function.surjective.comm_semigroup coe (surjective_quot_mk _) (λ a b, coe_mul a b) @[to_additive add_left_cancel_semigroup] instance [left_cancel_semigroup M] : left_cancel_semigroup (germ l M) := { mul := (*), mul_left_cancel := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃ H, coe_eq.2 ((coe_eq.1 H).mono $ λ x, mul_left_cancel), .. germ.semigroup } @[to_additive add_right_cancel_semigroup] instance [right_cancel_semigroup M] : right_cancel_semigroup (germ l M) := { mul := (*), mul_right_cancel := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃ H, coe_eq.2 $ (coe_eq.1 H).mono $ λ x, mul_right_cancel, .. germ.semigroup } instance has_nat_pow [monoid G] : has_pow (germ l G) ℕ := ⟨λ f n, map (^ n) f⟩ @[simp] lemma coe_pow [monoid G] (f : α → G) (n : ℕ) : ↑(f ^ n) = (f ^ n : germ l G) := rfl instance has_int_pow [div_inv_monoid G] : has_pow (germ l G) ℤ := ⟨λ f z, map (^ z) f⟩ @[simp] lemma coe_zpow [div_inv_monoid G] (f : α → G) (z : ℤ) : ↑(f ^ z) = (f ^ z : germ l G) := rfl instance [has_scalar M β] : has_scalar M (germ l β) := ⟨λ c, map ((•) c)⟩ @[simp, norm_cast] lemma coe_smul [has_scalar M β] (c : M) (f : α → β) : ↑(c • f) = (c • f : germ l β) := rfl instance [add_monoid M] : add_monoid (germ l M) := function.surjective.add_monoid coe (surjective_quot_mk _) rfl (λ a b, coe_add a b) (λ _ _, rfl) @[to_additive] instance [monoid M] : monoid (germ l M) := function.surjective.monoid coe (surjective_quot_mk _) rfl (λ a b, coe_mul a b) coe_pow /-- coercion from functions to germs as a monoid homomorphism. -/ @[to_additive] def coe_mul_hom [monoid M] (l : filter α) : (α → M) →* germ l M := ⟨coe, rfl, λ f g, rfl⟩ /-- coercion from functions to germs as an additive monoid homomorphism. -/ add_decl_doc coe_add_hom @[simp, to_additive] lemma coe_coe_mul_hom [monoid M] : (coe_mul_hom l : (α → M) → germ l M) = coe := rfl @[to_additive] instance [comm_monoid M] : comm_monoid (germ l M) := { mul := (*), one := 1, .. germ.comm_semigroup, .. germ.monoid } @[to_additive] instance [has_inv G] : has_inv (germ l G) := ⟨map has_inv.inv⟩ @[simp, norm_cast, to_additive] lemma coe_inv [has_inv G] (f : α → G) : ↑f⁻¹ = (f⁻¹ : germ l G) := rfl @[to_additive] instance [has_div M] : has_div (germ l M) := ⟨map₂ (/)⟩ @[simp, norm_cast, to_additive] lemma coe_div [has_div M] (f g : α → M) : ↑(f / g) = (f / g : germ l M) := rfl instance [sub_neg_monoid G] : sub_neg_monoid (germ l G) := function.surjective.sub_neg_monoid coe (surjective_quot_mk _) rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) @[to_additive sub_neg_monoid] instance [div_inv_monoid G] : div_inv_monoid (germ l G) := function.surjective.div_inv_monoid coe (surjective_quot_mk _) rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) @[to_additive] instance [group G] : group (germ l G) := { mul := (*), one := 1, mul_left_inv := by { rintros ⟨f⟩, exact congr_arg (quot.mk _) (mul_left_inv f) }, .. germ.div_inv_monoid } @[to_additive] instance [comm_group G] : comm_group (germ l G) := { mul := (*), one := 1, inv := has_inv.inv, .. germ.group, .. germ.comm_monoid } end monoid section ring variables {R : Type*} instance nontrivial [nontrivial R] [ne_bot l] : nontrivial (germ l R) := let ⟨x, y, h⟩ := exists_pair_ne R in ⟨⟨↑x, ↑y, mt const_inj.1 h⟩⟩ instance [mul_zero_class R] : mul_zero_class (germ l R) := { zero := 0, mul := (*), mul_zero := λ f, induction_on f $ λ f, by { norm_cast, rw [mul_zero] }, zero_mul := λ f, induction_on f $ λ f, by { norm_cast, rw [zero_mul] } } instance [distrib R] : distrib (germ l R) := { mul := (*), add := (+), left_distrib := λ f g h, induction_on₃ f g h $ λ f g h, by { norm_cast, rw [left_distrib] }, right_distrib := λ f g h, induction_on₃ f g h $ λ f g h, by { norm_cast, rw [right_distrib] } } instance [semiring R] : semiring (germ l R) := { .. germ.add_comm_monoid, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class } /-- Coercion `(α → R) → germ l R` as a `ring_hom`. -/ def coe_ring_hom [semiring R] (l : filter α) : (α → R) →+* germ l R := { to_fun := coe, .. (coe_mul_hom l : _ →* germ l R), .. (coe_add_hom l : _ →+ germ l R) } @[simp] lemma coe_coe_ring_hom [semiring R] : (coe_ring_hom l : (α → R) → germ l R) = coe := rfl instance [ring R] : ring (germ l R) := { .. germ.add_comm_group, .. germ.monoid, .. germ.distrib, .. germ.mul_zero_class } instance [comm_semiring R] : comm_semiring (germ l R) := { .. germ.semiring, .. germ.comm_monoid } instance [comm_ring R] : comm_ring (germ l R) := { .. germ.ring, .. germ.comm_monoid } end ring section module variables {M N R : Type*} instance has_scalar' [has_scalar M β] : has_scalar (germ l M) (germ l β) := ⟨map₂ (•)⟩ @[simp, norm_cast] lemma coe_smul' [has_scalar M β] (c : α → M) (f : α → β) : ↑(c • f) = (c : germ l M) • (f : germ l β) := rfl instance [monoid M] [mul_action M β] : mul_action M (germ l β) := { one_smul := λ f, induction_on f $ λ f, by { norm_cast, simp only [one_smul] }, mul_smul := λ c₁ c₂ f, induction_on f $ λ f, by { norm_cast, simp only [mul_smul] } } instance mul_action' [monoid M] [mul_action M β] : mul_action (germ l M) (germ l β) := { one_smul := λ f, induction_on f $ λ f, by simp only [← coe_one, ← coe_smul', one_smul], mul_smul := λ c₁ c₂ f, induction_on₃ c₁ c₂ f $ λ c₁ c₂ f, by { norm_cast, simp only [mul_smul] } } instance [monoid M] [add_monoid N] [distrib_mul_action M N] : distrib_mul_action M (germ l N) := { smul_add := λ c f g, induction_on₂ f g $ λ f g, by { norm_cast, simp only [smul_add] }, smul_zero := λ c, by simp only [← coe_zero, ← coe_smul, smul_zero] } instance distrib_mul_action' [monoid M] [add_monoid N] [distrib_mul_action M N] : distrib_mul_action (germ l M) (germ l N) := { smul_add := λ c f g, induction_on₃ c f g $ λ c f g, by { norm_cast, simp only [smul_add] }, smul_zero := λ c, induction_on c $ λ c, by simp only [← coe_zero, ← coe_smul', smul_zero] } instance [semiring R] [add_comm_monoid M] [module R M] : module R (germ l M) := { add_smul := λ c₁ c₂ f, induction_on f $ λ f, by { norm_cast, simp only [add_smul] }, zero_smul := λ f, induction_on f $ λ f, by { norm_cast, simp only [zero_smul, coe_zero] } } instance module' [semiring R] [add_comm_monoid M] [module R M] : module (germ l R) (germ l M) := { add_smul := λ c₁ c₂ f, induction_on₃ c₁ c₂ f $ λ c₁ c₂ f, by { norm_cast, simp only [add_smul] }, zero_smul := λ f, induction_on f $ λ f, by simp only [← coe_zero, ← coe_smul', zero_smul] } end module instance [has_le β] : has_le (germ l β) := ⟨lift_rel (≤)⟩ @[simp] lemma coe_le [has_le β] : (f : germ l β) ≤ g ↔ (f ≤ᶠ[l] g) := iff.rfl lemma le_def [has_le β] : ((≤) : germ l β → germ l β → Prop) = lift_rel (≤) := rfl lemma const_le [has_le β] {x y : β} (h : x ≤ y) : (↑x : germ l β) ≤ ↑y := lift_rel_const h @[simp, norm_cast] lemma const_le_iff [has_le β] [ne_bot l] {x y : β} : (↑x : germ l β) ≤ ↑y ↔ x ≤ y := lift_rel_const_iff instance [preorder β] : preorder (germ l β) := { le := (≤), le_refl := λ f, induction_on f $ eventually_le.refl l, le_trans := λ f₁ f₂ f₃, induction_on₃ f₁ f₂ f₃ $ λ f₁ f₂ f₃, eventually_le.trans } instance [partial_order β] : partial_order (germ l β) := { le := (≤), le_antisymm := λ f g, induction_on₂ f g $ λ f g h₁ h₂, (eventually_le.antisymm h₁ h₂).germ_eq, .. germ.preorder } instance [has_bot β] : has_bot (germ l β) := ⟨↑(⊥:β)⟩ @[simp, norm_cast] lemma const_bot [has_bot β] : (↑(⊥:β) : germ l β) = ⊥ := rfl instance [has_le β] [order_bot β] : order_bot (germ l β) := { bot := ⊥, bot_le := λ f, induction_on f $ λ f, eventually_of_forall $ λ x, bot_le } instance [has_top β] : has_top (germ l β) := ⟨↑(⊤:β)⟩ @[simp, norm_cast] lemma const_top [has_top β] : (↑(⊤:β) : germ l β) = ⊤ := rfl instance [has_le β] [order_top β] : order_top (germ l β) := { top := ⊤, le_top := λ f, induction_on f $ λ f, eventually_of_forall $ λ x, le_top } instance [has_sup β] : has_sup (germ l β) := ⟨map₂ (⊔)⟩ @[simp, norm_cast] lemma const_sup [has_sup β] (a b : β) : ↑(a ⊔ b) = (↑a ⊔ ↑b : germ l β) := rfl instance [has_inf β] : has_inf (germ l β) := ⟨map₂ (⊓)⟩ @[simp, norm_cast] lemma const_inf [has_inf β] (a b : β) : ↑(a ⊓ b) = (↑a ⊓ ↑b : germ l β) := rfl instance [semilattice_sup β] : semilattice_sup (germ l β) := { sup := (⊔), le_sup_left := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, le_sup_left, le_sup_right := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, le_sup_right, sup_le := λ f₁ f₂ g, induction_on₃ f₁ f₂ g $ λ f₁ f₂ g h₁ h₂, h₂.mp $ h₁.mono $ λ x, sup_le, .. germ.partial_order } instance [semilattice_inf β] : semilattice_inf (germ l β) := { inf := (⊓), inf_le_left := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, inf_le_left, inf_le_right := λ f g, induction_on₂ f g $ λ f g, eventually_of_forall $ λ x, inf_le_right, le_inf := λ f₁ f₂ g, induction_on₃ f₁ f₂ g $ λ f₁ f₂ g h₁ h₂, h₂.mp $ h₁.mono $ λ x, le_inf, .. germ.partial_order } instance [lattice β] : lattice (germ l β) := { .. germ.semilattice_sup, .. germ.semilattice_inf } instance [has_le β] [bounded_order β] : bounded_order (germ l β) := { .. germ.order_bot, .. germ.order_top } @[to_additive] instance [ordered_cancel_comm_monoid β] : ordered_cancel_comm_monoid (germ l β) := { mul_le_mul_left := λ f g, induction_on₂ f g $ λ f g H h, induction_on h $ λ h, H.mono $ λ x H, mul_le_mul_left' H _, le_of_mul_le_mul_left := λ f g h, induction_on₃ f g h $ λ f g h H, H.mono $ λ x, le_of_mul_le_mul_left', .. germ.partial_order, .. germ.comm_monoid, .. germ.left_cancel_semigroup } @[to_additive] instance ordered_comm_group [ordered_comm_group β] : ordered_comm_group (germ l β) := { mul_le_mul_left := λ f g, induction_on₂ f g $ λ f g H h, induction_on h $ λ h, H.mono $ λ x H, mul_le_mul_left' H _, .. germ.partial_order, .. germ.comm_group } end germ end filter
5a4ab54aead1ce1312276e07dddb21bba21e6838
097294e9b80f0d9893ac160b9c7219aa135b51b9
/instructor/objects/prod_s_t.lean
e3a871c495b548598048a857e3853117d2837930
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
519
lean
-- Ordered pairs #eval prod.mk 2 3 -- represents (2, 3) #eval prod.mk 2 tt -- represents (2, tt) #eval prod.mk tt ff -- represents (tt, ff) #eval prod.mk -- a pair of pairs (prod.mk 2 tt) (prod.mk "Hello" 3) -- Notation #eval (2, 3) -- prod.mk 2 3 #eval (2, tt) -- etc. #eval (tt, ff) #eval ((2, tt), ("Hello", 3)) -- Functions #eval prod.fst ((2, tt), ("Hello", 3)) #eval prod.snd ((2, tt), ("Hello", 3)) -- Notation #eval (2, 3).1 -- fst #eval (2, 3).2 -- snd
f17e70108e8ed1ec993992f72c043acc60e77114
28b6e1a13d35e9b450f65c001660f4ec4713aa10
/Search/NTactic/Basic.lean
6b2db43f844f796aa313923e631834b32b693194
[ "Apache-2.0" ]
permissive
dselsam/search
14e3af3261a7a70f8e5885db9722b186f96fe1f5
67003b859d2228d291a3873af6279c1f61430c64
refs/heads/master
1,684,700,794,306
1,614,294,810,000
1,614,294,810,000
339,578,823
1
0
null
null
null
null
UTF-8
Lean
false
false
1,536
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Search.Transform.Classic import Search.SaveRestore import Search.Heuristic import Search.Generic.Heuristic import Search.Algorithm.BestFirst import Lean namespace Search namespace NTactic open Lean Lean.Meta Lean.Elab Lean.Elab.Term Lean.Elab.Tactic structure BState where mctx : MetavarContext goals : List MVarId def saveBState : TacticM BState := do pure { mctx := (← getMCtx), goals := (← get).goals } def BState.restore (b : BState) : TacticM Unit := do setMCtx b.mctx modify fun s => { s with goals := b.goals } deriving instance Inhabited for BState instance : SaveRestore TacticM BState where save := saveBState restore := BState.restore abbrev NTacticM := SearchT TacticM syntax (name := search) "search " ident : tactic @[tactic search] unsafe def evalSearch : Tactic := fun stx => do let (g, gs) ← Tactic.getMainGoal if !gs.isEmpty then throwError s!"`search` expecting only a single goal" let n : Name ← resolveGlobalConstNoOverload stx[1].getId match (← getEnv).evalConst (NTacticM Unit) {} n with | Except.error err => throwError err | Except.ok ntac => let ϕ : Heuristic TacticM (NTacticM Unit) := Generic.mkHeuristic (← getEnv) match (← bestFirstRestoring ϕ ntac) with | none => throwError s!"search {n} failed to solve" | some (s, _) => restore s end NTactic end Search
a444712babef731872ec80b341dee7d74f34cbea
d78da34857deb99eac819e7889eae59fdccec754
/src/article3.lean
a0262387e2440fbd9792731bbc1c9e1346d5d97c
[]
no_license
wudcscheme/conceptual-mathematics-in-lean
6ef168b69fb28eb25223db10ebb4b2fefad4dbdb
cc7877f528bfaf99a024844744e023acbfcadb1d
refs/heads/master
1,678,885,284,910
1,601,437,497,000
1,601,663,206,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,428
lean
import category_theory.category import category_theory.isomorphism import category_theory.types import category_theory.isomorphism import data.finset.basic import data.finset.sort import data.int.parity import .article2 namespace exercises universe u section endomaps open category_theory variables {α β: Type*} variables [category α] structure endomap (α : Type*) [category α] := (carrier : α) (endo : carrier ⟶ carrier) structure endomaps_map (dom: endomap α) (ima: endomap α) := (map : dom.carrier ⟶ ima.carrier) (preserve : dom.endo ≫ map = map ≫ ima.endo) -- Exercise 1 page 137 def endomap_maps_comp {A B C: endomap α} (f : endomaps_map A B) (g : endomaps_map B C) : endomaps_map A C := { map := f.map ≫ g.map, preserve := calc A.endo ≫ f.map ≫ g.map = (f.map ≫ B.endo) ≫ g.map : by rw [← category.assoc, f.preserve] ... = f.map ≫ g.map ≫ C.endo : by simp [g.preserve] ... = (f.map ≫ g.map) ≫ C.endo : by simp, } variables {A B : endomap α} @[simp] lemma endo_inj (f : endomaps_map A B) (pre) : (endomaps_map.mk f.map pre) = f := begin cases f, refl, end def endo_category : category (endomap α) := { hom := λ x y, endomaps_map x y, id := λ x, { map := 𝟙 x.carrier, preserve := by simp }, comp := λ _ _ _ f g, endomap_maps_comp f g, id_comp' := λ _ _ f, by {simp at *, unfold endomap_maps_comp, simp}, comp_id' := λ _ _ f, by {simp at *, unfold endomap_maps_comp, simp}, assoc' := λ _ _ _ _ f g h, by {simp, unfold endomap_maps_comp, simp} } def Endoset := @endomap Type* category_theory.types def Endoset_map (dom: Endoset) (ima: Endoset):= endomaps_map dom ima def endoset_category : category Endoset := endo_category def x : Endoset := ⟨ ℕ, λ n, n + 2 ⟩ def y : Endoset := ⟨ ℕ, λ n, n + 1 ⟩ def yx : endomaps_map y x := { map := λ n:ℕ, nat.mul n 2, preserve := by { ext a, change nat.mul (a + 1) 2 = (a * 2) + 2, simp, ring, } } -- Exercise 2 page 139 example {X: α} (endo r : X ⟶ X) (idem : idempotent endo) (ret : is_retraction endo r) : endo = 𝟙 X := calc endo = endo ≫ 𝟙 X : by simp ... = endo ≫ (endo ≫ r) : by {unfold is_retraction at ret, rw ←ret} ... = (endo ≫ endo) ≫ r : by simp ... = endo ≫ r : by rw idempotent.repeat ... = 𝟙 X : ret def involution {A : α} (f : A ⟶ A) := f ≫ f = 𝟙 A -- Exercise 4 page 140 def minus : endomap Type* := { carrier := ℤ, endo := λ x, -x } example : @involution Type* infer_instance ℤ (λ x:ℤ, -x) := begin unfold involution, ext, simp, end -- Exercise 5 page 140 example : @idempotent Type* infer_instance ℤ (λ x:ℤ, abs x) := { repeat := by { simp, ext, rw ← abs_abs, simp, } } -- Exercise 6 page 140 example : @is_iso Type* infer_instance ℤ ℤ (λ x:ℤ, x + 3) := { inv := λ x, x - 3, } lemma prod_ne_one_of_gr {a b: ℤ} (h: b > 1) : a * b ≠ 1 := begin intros prod, have h := int.eq_one_of_mul_eq_one_left (by linarith) prod, linarith, end -- Exercise 7 page 140 example (iso: @is_iso Type* infer_instance ℤ ℤ (λ x:ℤ, x * 5)) : false := begin have : iso.inv ≫ (λ x:ℤ, x * 5) = 𝟙 ℤ := @is_iso.inv_hom_id Type* infer_instance ℤ ℤ (λ x:ℤ, x * 5) iso, have h := congr_fun this 1, simp at h, exact prod_ne_one_of_gr (by linarith) h , end -- Exercise 8 page 140 example (A : α) (f : A ⟶ A) (inv: involution f) : f ≫ f ≫ f = f := begin unfold involution at inv, rw inv, exact category.comp_id _, end example (A : α) (f : A ⟶ A) [ide: idempotent f] : f ≫ f ≫ f = f := begin rw ide.repeat, rw ide.repeat, end end endomaps section irr_graphs variables {α β δ γ ε ζ : Type u} structure irr_graph (α : Type u) (β : Type u) := (s t : α → β) structure irr_graph_map (dom : irr_graph α β) (ima : irr_graph δ γ) := (fa : α → δ) (fd : β → γ) (pres: fd ∘ dom.s = ima.s ∘ fa) (pret: fd ∘ dom.t = ima.t ∘ fa) variables {A : irr_graph α β} {B : irr_graph δ γ} {C : irr_graph ε ζ} -- Exercise 11 page 142 def irr_graph_map_comp (f : irr_graph_map A B) (g : irr_graph_map B C) : irr_graph_map A C := { fa := g.fa ∘ f.fa, fd := g.fd ∘ f.fd, pres := calc (g.fd ∘ f.fd) ∘ A.s = g.fd ∘ (f.fd ∘ A.s) : by simp ... = g.fd ∘ (B.s ∘ f.fa) : by rw f.pres ... = (g.fd ∘ B.s) ∘ f.fa : by simp ... = (C.s ∘ g.fa) ∘ f.fa : by rw g.pres, pret := by { calc (g.fd ∘ f.fd) ∘ A.t = g.fd ∘ (f.fd ∘ A.t) : by simp ... = g.fd ∘ (B.t ∘ f.fa) : by rw f.pret ... = (g.fd ∘ B.t) ∘ f.fa : by simp ... = (C.t ∘ g.fa) ∘ f.fa : by rw g.pret, }, } def endo_to_irr_graph_on_obj (e: Endoset) : irr_graph e.carrier e.carrier := { s := id, t := e.endo } def endo_to_irr_graph_on_maps {A B : Endoset} (f: Endoset_map A B) : irr_graph_map (endo_to_irr_graph_on_obj A) (endo_to_irr_graph_on_obj B) := { fa := f.map, fd := f.map, pres := by { unfold endo_to_irr_graph_on_obj, simp, }, pret := by { exact f.preserve, } } -- Exercise 12 page 143 lemma endo_insertion_functorial {A B C : Endoset} (f: Endoset_map A B) (g: Endoset_map B C) : endo_to_irr_graph_on_maps( endomap_maps_comp f g ) = irr_graph_map_comp (endo_to_irr_graph_on_maps f) (endo_to_irr_graph_on_maps g) := begin refl end -- Exercise 13 page 144 example {A B : Endoset} (f : irr_graph_map (endo_to_irr_graph_on_obj A) (endo_to_irr_graph_on_obj B) ) : ∃ g : Endoset_map A B, endo_to_irr_graph_on_maps g = f := begin have : f.fd = f.fa := f.pres, use f.fa, { have pret := f.pret, rw this at pret, exact pret, }, { cases f, unfold endo_to_irr_graph_on_maps, simp, exact this.symm, } end end irr_graphs section simpler open category_theory variables {α β: Type*} variables [category α] structure simpler (α : Type*) [category α] := (dom : α) (ima : α) (map : dom ⟶ ima) structure simpler_map (dom: simpler α) (ima: simpler α) := (dommap : dom.dom ⟶ ima.dom) (imamap : dom.ima ⟶ ima.ima) (preserve : dom.map ≫ imamap = dommap ≫ ima.map) variables {A B : simpler α} @[simp] lemma simpler_inj (f : simpler_map A B) (pre) : (simpler_map.mk f.dommap f.imamap pre) = f := begin cases f, refl, end def simpler_maps_comp {A B C: simpler α} (f : simpler_map A B) (g : simpler_map B C) : simpler_map A C := { dommap := f.dommap ≫ g.dommap, imamap := f.imamap ≫ g.imamap, preserve := calc A.map ≫ f.imamap ≫ g.imamap = (f.dommap ≫ B.map) ≫ g.imamap : by rw [← category.assoc, f.preserve] ... = f.dommap ≫ B.map ≫ g.imamap : by rw [category.assoc] ... = f.dommap ≫ g.dommap ≫ C.map : by rw [← g.preserve] ... = (f.dommap ≫ g.dommap) ≫ C.map : by rw [← category.assoc], } instance simpler_category : category (simpler α) := { hom := λ x y, simpler_map x y, id := λ x, { dommap := 𝟙 x.dom, imamap := 𝟙 x.ima, preserve := by simp }, comp := λ _ _ _ f g, simpler_maps_comp f g, id_comp' := λ _ _ f, by {simp at *, unfold simpler_maps_comp, simp}, comp_id' := λ _ _ f, by {simp at *, unfold simpler_maps_comp, simp}, assoc' := λ _ _ _ _ f g h, by {simp, unfold simpler_maps_comp, simp} } def simpler_set := @simpler Type* category_theory.types def simpler_set_map (dom: simpler_set) (ima: simpler_set):= simpler_map dom ima def SimplerSetCategory := category simpler_set def endo_inclusion_on_objs (e : endomap α) : simpler α := ⟨ e.carrier, e.carrier, e.endo ⟩ def endo_inclusion_on_maps {A B : endomap α } (f : endomaps_map A B) : simpler_map (endo_inclusion_on_objs A) (endo_inclusion_on_objs B) := { dommap := f.map, imamap := f.map, preserve := f.preserve } -- Exercise 14 page 144 def AddOne : simpler_set := ⟨ ℕ, ℕ, λ n, n + 1 ⟩ def AddTwo : simpler_set := ⟨ ℕ, ℕ, λ n, n + 2 ⟩ def AddOneEndo : Endoset := ⟨ ℕ, λ n, n + 1 ⟩ def AddTwoEndo : Endoset := ⟨ ℕ, λ n, n + 2 ⟩ def AddOneToAddTwo : simpler_map (endo_inclusion_on_objs AddOneEndo) (endo_inclusion_on_objs AddTwoEndo) := { dommap := λ n:ℕ, nat.add n 1, imamap := λ n:ℕ, nat.add n 2, preserve := by { ext a, change nat.add (a + 1) 2 = (a + 2) + 1, simp, } } example : ¬ ∃ f, endo_inclusion_on_maps f = AddOneToAddTwo := begin intros h, rcases h with ⟨ f, h⟩ , unfold endo_inclusion_on_maps at h, unfold AddOneToAddTwo at h, simp at *, cases h, rw h_left at h_right, have := congr_fun h_right 0, exact (nat.succ_ne_self 1) this.symm, end end simpler section ref_graphs variables {α β δ γ ε ζ : Type u} structure ref_graph (α : Type u) (β : Type u) extends irr_graph α β := (i : β → α) (rets: s ∘ i = id) (rett: t ∘ i = id) structure ref_graph_map (dom : ref_graph α β) (ima : ref_graph δ γ) extends irr_graph_map dom.to_irr_graph ima.to_irr_graph := (prei: fa ∘ dom.i = ima.i ∘ fd) variables {A : ref_graph α β} {B : ref_graph δ γ} {C : ref_graph ε ζ} def ref_graph_map_comp (f : ref_graph_map A B) (g : ref_graph_map B C) : ref_graph_map A C := { prei := by { simp, calc (g.fa ∘ f.fa) ∘ A.i = g.fa ∘ (f.fa ∘ A.i) : by simp ... = g.fa ∘ B.i ∘ f.fd : by rw f.prei ... = (g.fa ∘ B.i) ∘ f.fd : by simp ... = (C.i ∘ g.fd) ∘ f.fd : by rw g.prei ... = C.i ∘ (g.fd ∘ f.fd) : by simp, }, ..irr_graph_map_comp f.to_irr_graph_map g.to_irr_graph_map, } -- Exercise 15 page 145 example : (A.i ∘ A.s) ∘ (A.i ∘ A.s) = A.i ∘ A.s := calc (A.i ∘ A.s) ∘ (A.i ∘ A.s) = A.i ∘ (A.s ∘ A.i) ∘ A.s : by simp ... = A.i ∘ A.s : by simp[A.rets] example : (A.i ∘ A.t) ∘ (A.i ∘ A.t) = A.i ∘ A.t := calc (A.i ∘ A.t) ∘ (A.i ∘ A.t) = A.i ∘ (A.t ∘ A.i) ∘ A.t : by simp ... = A.i ∘ A.t : by simp[A.rett] example : (A.i ∘ A.t) ∘ (A.i ∘ A.s) = A.i ∘ A.s := calc (A.i ∘ A.t) ∘ (A.i ∘ A.s) = A.i ∘ (A.t ∘ A.i) ∘ A.s : by simp ... = A.i ∘ A.s : by simp[A.rett] example : (A.i ∘ A.s) ∘ (A.i ∘ A.t) = A.i ∘ A.t := calc (A.i ∘ A.s) ∘ (A.i ∘ A.t) = A.i ∘ (A.s ∘ A.i) ∘ A.t : by simp ... = A.i ∘ A.t : by simp [A.rets] -- Exercise 16 page 145 example (f : ref_graph_map A B) : f.fd = B.s ∘ f.fa ∘ A.i := calc f.fd = (B.s ∘ B.i) ∘ f.fd : by simp [B.rets] ... = B.s ∘ (B.i ∘ f.fd) : by simp ... = B.s ∘ f.fa ∘ A.i : by rw f.prei end ref_graphs open category_theory variables {C : Type*} variables [category C] variables {A B T : C} def injective (a : A ⟶ B) := ∀ (T : C) (x1 x2 : T ⟶ A), x1 ≫ a = x2 ≫ a → x1 = x2 -- Exercise 18 page 146 theorem injective_of_retraction {a : A ⟶ B} {p : B ⟶ A} (ret: is_retraction a p) : injective a := begin intros T x1 x2 h, unfold is_retraction at ret, calc x1 = x1 ≫ 𝟙 A : by simp ... = x1 ≫ a ≫ p : by rw ret ... = (x1 ≫ a) ≫ p : by simp ... = x2 ≫ a ≫ p : by {rw h, simp} ... = x2 : by {simp [ret]} end section endo_example open category_theory inductive Xs : Type | x | z inductive Ys : Type | ybar | y | z def alpha : Xs → Xs | Xs.x := Xs.z | Xs.z := Xs.z def beta : Ys → Ys | Ys.ybar := Ys.y | Ys.y := Ys.z | Ys.z := Ys.z def as : Xs → Ys | Xs.x := Ys.y | Xs.z := Ys.z def X : Endoset := ⟨ Xs, alpha ⟩ def Y : Endoset := ⟨ Ys, beta ⟩ -- Exercise 19 page 147 def a : Endoset_map X Y := ⟨ as, by {ext, cases x; refl} ⟩ -- Exercise 20 page 147 -- FixMe simplify proof example : @injective Endoset endo_category X Y a := begin intros e x1 x2 h, cases x1, cases x2, unfold a at h, congr, ext, injections_and_clear, dsimp at *, have foo := congr_fun h_1 x, simp at foo, cases x1_map x, { cases x2_map x, refl, simp, unfold as at foo, simp at foo, exact foo, }, { cases x2_map x, simp, unfold as at foo, simp at foo, exact foo, refl, } end -- Exercise 21 page 147 def as_ret1 : Ys → Xs | Ys.ybar := Xs.x | Ys.y := Xs.x | Ys.z := Xs.z def as_ret2 : Ys → Xs | Ys.ybar := Xs.z | Ys.y := Xs.x | Ys.z := Xs.z -- FixMe simplify proof example : ∀ (f : Ys → Xs), f ∘ as = id → f = as_ret1 ∨ f = as_ret2 := begin intros f h, apply classical.or_iff_not_imp_left.mpr, intros notret1, ext, have h1: f Ys.ybar ≠ as_ret1 Ys.ybar, { have a1 : f Ys.y = as_ret1 Ys.y, {change (f ∘ as) Xs.x = Xs.x, rw h, refl}, have a2 : f Ys.z = as_ret1 Ys.z, {change (f ∘ as) Xs.z = Xs.z, rw h, refl}, intros eq_ybar, have eq : f = as_ret1 , {ext, cases x_1; assumption}, exact notret1 eq, }, cases x, { have :f Ys.ybar = as_ret1 Ys.ybar ∨ f Ys.ybar = as_ret2 Ys.ybar, { change f Ys.ybar = Xs.x ∨ f Ys.ybar = Xs.z, cases f Ys.ybar; simp }, cases this, exact false.elim (h1 this), exact this, }, { change (f ∘ as) Xs.x = Xs.x, rw h, simp, }, { change (f ∘ as) Xs.z = Xs.z, rw h, simp, } end -- Exercise 22 page 147 example : as_ret1 ∘ beta ≠ alpha ∘ as_ret1 := begin intros h, have := congr_fun h Ys.ybar, injections, end example : as_ret2 ∘ beta ≠ alpha ∘ as_ret2 := begin intros h, have := congr_fun h Ys.ybar, injections, end -- Exercise 25 page 148 example (α β δ γ : Type*) (A : irr_graph α β) (B : irr_graph δ γ) (f : irr_graph_map A B) : f.fd ∘ A.s = f.fd ∘ A.t → B.s ∘ f.fa = B.t ∘ f.fa := begin intros h, rw ← f.pres, rw h, rw f.pret, end -- Exercise 26 page 148 def zinc (n : ℤ) : ℚ := ↑ n def z5x_endo : Endoset := ⟨ ℤ, λ n, n * 5 ⟩ def q5x_endo : Endoset := ⟨ ℚ, λ p, p * 5 ⟩ -- part 1 def zinc_endo_map : Endoset_map z5x_endo q5x_endo := { map := zinc, preserve := by { ext, simp, change zinc (x * 5) = (zinc x) * 5, unfold zinc, simp, } } def x5 (p : ℚ) : ℚ := p * 5 -- part 2 example : ∃ (f : ℚ → ℚ), f ∘ x5 = id ∧ x5 ∘ f = id := begin use λ q, q / 5, split; { ext, simp, unfold x5, ring, } end lemma endomap_eq (α : Type*) [category α] (A : endomap α ) (B : endomap α) (f : endomaps_map A B) (g :endomaps_map A B) : f.map = g.map → f = g := begin intros h, cases f, cases g, simp at *, exact h, end -- part 3 example : @injective Endoset endo_category z5x_endo q5x_endo zinc_endo_map := begin intros e x1 x2 h, unfold zinc_endo_map at h, injections_and_clear, simp at h_1, change zinc ∘ x1.map = zinc ∘ x2.map at h_1, have caca : x1.map = x2.map, { ext, have foo := congr_fun h_1 x, simp at foo, unfold zinc at foo, norm_cast at *, exact foo, }, apply endomap_eq, exact caca, end -- Exercise 27 page 148 inductive Set27 : Type | x | y def a27 : Set27 → Set27 | Set27.x := Set27.y | Set27.y := Set27.y def X27 : Endoset := ⟨ Set27, a27 ⟩ def invert_map : Endoset_map X27 X27 := { map := a27, preserve := by { ext, cases x; refl, } } instance : category Endoset := endoset_category example (Y27 : Endoset) (auto : Y27.endo ≫ Y27.endo = 𝟙 Y27.carrier) (f: Endoset_map X27 Y27): ¬ @injective Endoset endoset_category X27 Y27 f := begin intros inj, suffices h: f.map Set27.x = f.map Set27.y, { unfold injective at inj, have := inj X27 (𝟙 X27) invert_map, simp at this, have foo := this (by { apply endomap_eq, ext, cases x, { rw h, refl, }, { refl, } }), unfold invert_map at foo, have caca := congr_arg (λ m:Endoset_map _ _, m.map) foo, simp at caca, have := congr_fun caca Set27.x, change Set27.x = Set27.y at this, simp at this_1, exact this_1, }, { have : Y27.endo (f.map Set27.x) = Y27.endo (f.map Set27.y) → f.map Set27.x = f.map Set27.y , { -- automorph is injective intros h, have := congr_arg Y27.endo h, have foo := congr_fun auto (f.map Set27.x), simp at foo, rw foo at this, have foo := congr_fun auto (f.map Set27.y), simp at foo, rw foo at this, exact this, }, apply this, have prex := congr_fun f.preserve Set27.x, have prey := congr_fun f.preserve Set27.y, simp at *, rw ← prey, rw ← prex, refl, } end end endo_example end exercises
80c0c89a43f66ec90909e724c4fd771d25349ce5
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/normed_space/hahn_banach/separation.lean
490875ab9ab2869c241532e98b0a3fa3e717e896
[ "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
10,589
lean
/- Copyright (c) 2022 Bhavik Mehta All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Yaël Dillies -/ import analysis.convex.cone.basic import analysis.convex.gauge /-! # Separation Hahn-Banach theorem In this file we prove the geometric Hahn-Banach theorem. For any two disjoint convex sets, there exists a continuous linear functional separating them, geometrically meaning that we can intercalate a plane between them. We provide many variations to stricten the result under more assumptions on the convex sets: * `geometric_hahn_banach_open`: One set is open. Weak separation. * `geometric_hahn_banach_open_point`, `geometric_hahn_banach_point_open`: One set is open, the other is a singleton. Weak separation. * `geometric_hahn_banach_open_open`: Both sets are open. Semistrict separation. * `geometric_hahn_banach_compact_closed`, `geometric_hahn_banach_closed_compact`: One set is closed, the other one is compact. Strict separation. * `geometric_hahn_banach_point_closed`, `geometric_hahn_banach_closed_point`: One set is closed, the other one is a singleton. Strict separation. * `geometric_hahn_banach_point_point`: Both sets are singletons. Strict separation. ## TODO * Eidelheit's theorem * `convex ℝ s → interior (closure s) ⊆ s` -/ open set open_locale pointwise variables {𝕜 E : Type*} /-- Given a set `s` which is a convex neighbourhood of `0` and a point `x₀` outside of it, there is a continuous linear functional `f` separating `x₀` and `s`, in the sense that it sends `x₀` to 1 and all of `s` to values strictly below `1`. -/ lemma separate_convex_open_set [seminormed_add_comm_group E] [normed_space ℝ E] {s : set E} (hs₀ : (0 : E) ∈ s) (hs₁ : convex ℝ s) (hs₂ : is_open s) {x₀ : E} (hx₀ : x₀ ∉ s) : ∃ f : E →L[ℝ] ℝ, f x₀ = 1 ∧ ∀ x ∈ s, f x < 1 := begin let f : E →ₗ.[ℝ] ℝ := linear_pmap.mk_span_singleton x₀ 1 (ne_of_mem_of_not_mem hs₀ hx₀).symm, obtain ⟨r, hr, hrs⟩ := metric.mem_nhds_iff.1 (filter.inter_mem (hs₂.mem_nhds hs₀) $ hs₂.neg.mem_nhds $ by rwa [mem_neg, neg_zero]), obtain ⟨φ, hφ₁, hφ₂⟩ := exists_extension_of_le_sublinear f (gauge s) (λ c hc, gauge_smul_of_nonneg hc.le) (gauge_add_le hs₁ $ absorbent_nhds_zero $ hs₂.mem_nhds hs₀) _, { refine ⟨φ.mk_continuous (r⁻¹) $ λ x, _, _, _⟩, { rw [real.norm_eq_abs, abs_le, neg_le, ←linear_map.map_neg], nth_rewrite 0 ←norm_neg x, suffices : ∀ x, φ x ≤ r⁻¹ * ∥x∥, { exact ⟨this _, this _⟩ }, refine λ x, (hφ₂ _).trans _, rw [←div_eq_inv_mul, ←gauge_ball hr], exact gauge_mono (absorbent_ball_zero hr) (hrs.trans $ inter_subset_left _ _) x }, { dsimp, rw [←submodule.coe_mk x₀ (submodule.mem_span_singleton_self _), hφ₁, linear_pmap.mk_span_singleton'_apply_self] }, { exact λ x hx, (hφ₂ x).trans_lt (gauge_lt_one_of_mem_of_open hs₁ hs₀ hs₂ hx) } }, rintro ⟨x, hx⟩, obtain ⟨y, rfl⟩ := submodule.mem_span_singleton.1 hx, rw linear_pmap.mk_span_singleton'_apply, simp only [mul_one, algebra.id.smul_eq_mul, submodule.coe_mk], obtain h | h := le_or_lt y 0, { exact h.trans (gauge_nonneg _) }, { rw [gauge_smul_of_nonneg h.le, smul_eq_mul, le_mul_iff_one_le_right h], exact one_le_gauge_of_not_mem (hs₁.star_convex hs₀) ((absorbent_ball_zero hr).subset $ hrs.trans $ inter_subset_left _ _).absorbs hx₀, apply_instance } end variables [normed_add_comm_group E] [normed_space ℝ E] {s t : set E} {x y : E} /-- A version of the **Hahn-Banach theorem**: given disjoint convex sets `s`, `t` where `s` is open, there is a continuous linear functional which separates them. -/ theorem geometric_hahn_banach_open (hs₁ : convex ℝ s) (hs₂ : is_open s) (ht : convex ℝ t) (disj : disjoint s t) : ∃ (f : E →L[ℝ] ℝ) (u : ℝ), (∀ a ∈ s, f a < u) ∧ ∀ b ∈ t, u ≤ f b := begin obtain rfl | ⟨a₀, ha₀⟩ := s.eq_empty_or_nonempty, { exact ⟨0, 0, by simp, λ b hb, le_rfl⟩ }, obtain rfl | ⟨b₀, hb₀⟩ := t.eq_empty_or_nonempty, { exact ⟨0, 1, λ a ha, zero_lt_one, by simp⟩ }, let x₀ := b₀ - a₀, let C := x₀ +ᵥ (s - t), have : (0:E) ∈ C := ⟨a₀ - b₀, sub_mem_sub ha₀ hb₀, by rw [vadd_eq_add, sub_add_sub_cancel', sub_self]⟩, have : convex ℝ C := (hs₁.sub ht).vadd _, have : x₀ ∉ C, { intro hx₀, rw ←add_zero x₀ at hx₀, exact disj.zero_not_mem_sub_set (vadd_mem_vadd_set_iff.1 hx₀) }, obtain ⟨f, hf₁, hf₂⟩ := separate_convex_open_set ‹0 ∈ C› ‹_› (hs₂.sub_right.vadd _) ‹x₀ ∉ C›, have : f b₀ = f a₀ + 1 := by simp [←hf₁], have forall_le : ∀ (a ∈ s) (b ∈ t), f a ≤ f b, { intros a ha b hb, have := hf₂ (x₀ + (a - b)) (vadd_mem_vadd_set $ sub_mem_sub ha hb), simp only [f.map_add, f.map_sub, hf₁] at this, linarith }, refine ⟨f, Inf (f '' t), image_subset_iff.1 (_ : f '' s ⊆ Iio (Inf (f '' t))), λ b hb, _⟩, { rw ←interior_Iic, refine interior_maximal (image_subset_iff.2 $ λ a ha, _) (f.is_open_map_of_ne_zero _ _ hs₂), { exact le_cInf (nonempty.image _ ⟨_, hb₀⟩) (ball_image_of_ball $ forall_le _ ha) }, { rintro rfl, simpa using hf₁ } }, { exact cInf_le ⟨f a₀, ball_image_of_ball $ forall_le _ ha₀⟩ (mem_image_of_mem _ hb) } end theorem geometric_hahn_banach_open_point (hs₁ : convex ℝ s) (hs₂ : is_open s) (disj : x ∉ s) : ∃ f : E →L[ℝ] ℝ, ∀ a ∈ s, f a < f x := let ⟨f, s, hs, hx⟩ := geometric_hahn_banach_open hs₁ hs₂ (convex_singleton x) (disjoint_singleton_right.2 disj) in ⟨f, λ a ha, lt_of_lt_of_le (hs a ha) (hx x (mem_singleton _))⟩ theorem geometric_hahn_banach_point_open (ht₁ : convex ℝ t) (ht₂ : is_open t) (disj : x ∉ t) : ∃ f : E →L[ℝ] ℝ, ∀ b ∈ t, f x < f b := let ⟨f, hf⟩ := geometric_hahn_banach_open_point ht₁ ht₂ disj in ⟨-f, by simpa⟩ theorem geometric_hahn_banach_open_open (hs₁ : convex ℝ s) (hs₂ : is_open s) (ht₁ : convex ℝ t) (ht₃ : is_open t) (disj : disjoint s t) : ∃ (f : E →L[ℝ] ℝ) (u : ℝ), (∀ a ∈ s, f a < u) ∧ ∀ b ∈ t, u < f b := begin obtain (rfl | ⟨a₀, ha₀⟩) := s.eq_empty_or_nonempty, { exact ⟨0, -1, by simp, λ b hb, by norm_num⟩ }, obtain (rfl | ⟨b₀, hb₀⟩) := t.eq_empty_or_nonempty, { exact ⟨0, 1, λ a ha, by norm_num, by simp⟩ }, obtain ⟨f, s, hf₁, hf₂⟩ := geometric_hahn_banach_open hs₁ hs₂ ht₁ disj, have hf : is_open_map f, { refine f.is_open_map_of_ne_zero _, rintro rfl, exact (hf₁ _ ha₀).not_le (hf₂ _ hb₀) }, refine ⟨f, s, hf₁, image_subset_iff.1 (_ : f '' t ⊆ Ioi s)⟩, rw ←interior_Ici, refine interior_maximal (image_subset_iff.2 hf₂) (f.is_open_map_of_ne_zero _ _ ht₃), rintro rfl, exact (hf₁ _ ha₀).not_le (hf₂ _ hb₀), end /-- A version of the **Hahn-Banach theorem**: given disjoint convex sets `s`, `t` where `s` is compact and `t` is closed, there is a continuous linear functional which strongly separates them. -/ theorem geometric_hahn_banach_compact_closed (hs₁ : convex ℝ s) (hs₂ : is_compact s) (ht₁ : convex ℝ t) (ht₂ : is_closed t) (disj : disjoint s t) : ∃ (f : E →L[ℝ] ℝ) (u v : ℝ), (∀ a ∈ s, f a < u) ∧ u < v ∧ ∀ b ∈ t, v < f b := begin obtain rfl | hs := s.eq_empty_or_nonempty, { exact ⟨0, -2, -1, by simp, by norm_num, λ b hb, by norm_num⟩ }, unfreezingI { obtain rfl | ht := t.eq_empty_or_nonempty }, { exact ⟨0, 1, 2, λ a ha, by norm_num, by norm_num, by simp⟩ }, obtain ⟨U, V, hU, hV, hU₁, hV₁, sU, tV, disj'⟩ := disj.exists_open_convexes hs₁ hs₂ ht₁ ht₂, obtain ⟨f, u, hf₁, hf₂⟩ := geometric_hahn_banach_open_open hU₁ hU hV₁ hV disj', obtain ⟨x, hx₁, hx₂⟩ := hs₂.exists_forall_ge hs f.continuous.continuous_on, have : f x < u := hf₁ x (sU hx₁), exact ⟨f, (f x + u)/2, u, λ a ha, by linarith [hx₂ a ha], by linarith, λ b hb, hf₂ b (tV hb)⟩, end /-- A version of the **Hahn-Banach theorem**: given disjoint convex sets `s`, `t` where `s` is closed, and `t` is compact, there is a continuous linear functional which strongly separates them. -/ theorem geometric_hahn_banach_closed_compact (hs₁ : convex ℝ s) (hs₂ : is_closed s) (ht₁ : convex ℝ t) (ht₂ : is_compact t) (disj : disjoint s t) : ∃ (f : E →L[ℝ] ℝ) (u v : ℝ), (∀ a ∈ s, f a < u) ∧ u < v ∧ ∀ b ∈ t, v < f b := let ⟨f, s, t, hs, st, ht⟩ := geometric_hahn_banach_compact_closed ht₁ ht₂ hs₁ hs₂ disj.symm in ⟨-f, -t, -s, by simpa using ht, by simpa using st, by simpa using hs⟩ theorem geometric_hahn_banach_point_closed (ht₁ : convex ℝ t) (ht₂ : is_closed t) (disj : x ∉ t) : ∃ (f : E →L[ℝ] ℝ) (u : ℝ), f x < u ∧ ∀ b ∈ t, u < f b := let ⟨f, u, v, ha, hst, hb⟩ := geometric_hahn_banach_compact_closed (convex_singleton x) is_compact_singleton ht₁ ht₂ (disjoint_singleton_left.2 disj) in ⟨f, v, hst.trans' $ ha x $ mem_singleton _, hb⟩ theorem geometric_hahn_banach_closed_point (hs₁ : convex ℝ s) (hs₂ : is_closed s) (disj : x ∉ s) : ∃ (f : E →L[ℝ] ℝ) (u : ℝ), (∀ a ∈ s, f a < u) ∧ u < f x := let ⟨f, s, t, ha, hst, hb⟩ := geometric_hahn_banach_closed_compact hs₁ hs₂ (convex_singleton x) is_compact_singleton (disjoint_singleton_right.2 disj) in ⟨f, s, ha, hst.trans $ hb x $ mem_singleton _⟩ /-- Special case of `normed_space.eq_iff_forall_dual_eq`. -/ theorem geometric_hahn_banach_point_point (hxy : x ≠ y) : ∃ (f : E →L[ℝ] ℝ), f x < f y := begin obtain ⟨f, s, t, hs, st, ht⟩ := geometric_hahn_banach_compact_closed (convex_singleton x) is_compact_singleton (convex_singleton y) is_closed_singleton (disjoint_singleton.2 hxy), exact ⟨f, by linarith [hs x rfl, ht y rfl]⟩, end /-- A closed convex set is the intersection of the halfspaces containing it. -/ lemma Inter_halfspaces_eq (hs₁ : convex ℝ s) (hs₂ : is_closed s) : (⋂ (l : E →L[ℝ] ℝ), {x | ∃ y ∈ s, l x ≤ l y}) = s := begin rw set.Inter_set_of, refine set.subset.antisymm (λ x hx, _) (λ x hx l, ⟨x, hx, le_rfl⟩), by_contra, obtain ⟨l, s, hlA, hl⟩ := geometric_hahn_banach_closed_point hs₁ hs₂ h, obtain ⟨y, hy, hxy⟩ := hx l, exact ((hxy.trans_lt (hlA y hy)).trans hl).not_le le_rfl, end
526c1c59a909893212146706be20fa5ad4409076
7cef822f3b952965621309e88eadf618da0c8ae9
/src/number_theory/sum_four_squares.lean
4b4ae4d06d78f33a95cd9537e3751cb7ba14fcf2
[ "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
12,015
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes ## Lagrange's four square theorem The main result in this file is `sum_four_squares`, a proof that every natural number is the sum of four square numbers. # Implementation Notes The proof used is close to Lagrange's original proof. -/ import data.zmod.basic field_theory.finite group_theory.perm.sign import data.int.parity open finset polynomial finite_field equiv namespace int lemma sum_two_squares_of_two_mul_sum_two_squares {m x y : ℤ} (h : 2 * m = x^2 + y^2) : m = ((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2 := have (x^2 + y^2).even, by simp [h.symm, even_mul], have hxaddy : (x + y).even, by simpa [pow_two] with parity_simps, have hxsuby : (x - y).even, by simpa [pow_two] with parity_simps, have (x^2 + y^2) % 2 = 0, by simp [h.symm], (domain.mul_left_inj (show (2*2 : ℤ) ≠ 0, from dec_trivial)).1 $ calc 2 * 2 * m = (x - y)^2 + (x + y)^2 : by rw [mul_assoc, h]; ring ... = (2 * ((x - y) / 2))^2 + (2 * ((x + y) / 2))^2 : by rw [int.mul_div_cancel' hxsuby, int.mul_div_cancel' hxaddy] ... = 2 * 2 * (((x - y) / 2) ^ 2 + ((x + y) / 2) ^ 2) : by simp [mul_add, _root_.pow_succ, mul_comm, mul_assoc, mul_left_comm] lemma exists_sum_two_squares_add_one_eq_k {p : ℕ} (hp : p.prime) : ∃ (a b : ℤ) (k : ℕ), a^2 + b^2 + 1 = k * p ∧ k < p := hp.eq_two_or_odd.elim (λ hp2, hp2.symm ▸ ⟨1, 0, 1, rfl, dec_trivial⟩) $ λ hp1, let ⟨a, b, hab⟩ := zmodp.sum_two_squares hp (-1) in have hab' : (p : ℤ) ∣ a.val_min_abs ^ 2 + b.val_min_abs ^ 2 + 1, from (zmodp.eq_zero_iff_dvd_int hp _).1 $ by simpa [eq_neg_iff_add_eq_zero] using hab, let ⟨k, hk⟩ := hab' in have hk0 : 0 ≤ k, from nonneg_of_mul_nonneg_left (by rw ← hk; exact (add_nonneg (add_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) zero_le_one)) (int.coe_nat_pos.2 hp.pos), ⟨a.val_min_abs, b.val_min_abs, k.nat_abs, by rw [hk, int.nat_abs_of_nonneg hk0, mul_comm], lt_of_mul_lt_mul_left (calc p * k.nat_abs = a.val_min_abs.nat_abs ^ 2 + b.val_min_abs.nat_abs ^ 2 + 1 : by rw [← int.coe_nat_inj', int.coe_nat_add, int.coe_nat_add, nat.pow_two, nat.pow_two, int.nat_abs_mul_self, int.nat_abs_mul_self, ← _root_.pow_two, ← _root_.pow_two, int.coe_nat_one, hk, int.coe_nat_mul, int.nat_abs_of_nonneg hk0] ... ≤ (p / 2) ^ 2 + (p / 2)^2 + 1 : add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmodp.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmodp.nat_abs_val_min_abs_le _) _)) (le_refl _) ... < (p / 2) ^ 2 + (p / 2)^ 2 + (p % 2)^2 + ((2 * (p / 2)^2 + (4 * (p / 2) * (p % 2)))) : by rw [hp1, nat.one_pow, mul_one]; exact (lt_add_iff_pos_right _).2 (add_pos_of_nonneg_of_pos (nat.zero_le _) (mul_pos dec_trivial (nat.div_pos hp.two_le dec_trivial))) ... = p * p : begin conv_rhs { rw [← nat.mod_add_div p 2] }, simp only [nat.pow_two], rw [← int.coe_nat_inj'], simp only [nat.pow_two, int.coe_nat_add, int.coe_nat_mul, int.coe_nat_bit0, int.coe_nat_one, two_mul, mul_add, add_mul], ring, end) (show 0 ≤ p, from nat.zero_le _)⟩ end int namespace nat open int open_locale classical private lemma sum_four_squares_of_two_mul_sum_four_squares {m a b c d : ℤ} (h : a^2 + b^2 + c^2 + d^2 = 2 * m) : ∃ w x y z : ℤ, w^2 + x^2 + y^2 + z^2 = m := have ∀ f : fin 4 → zmod 2, (f 0)^2 + (f 1)^2 + (f 2)^2 + (f 3)^2 = 0 → ∃ i : (fin 4), (f i)^2 + f (swap i 0 1)^2 = 0 ∧ f (swap i 0 2)^2 + f (swap i 0 3)^2 = 0, from dec_trivial, let f : fin 4 → ℤ := vector.nth (a::b::c::d::vector.nil) in let ⟨i, hσ⟩ := this (coe ∘ f) (by rw [← @zero_mul (zmod 2) _ m, ← show ((2 : ℤ) : zmod 2) = 0, from rfl, ← int.cast_mul, ← h]; simp only [int.cast_add, int.cast_pow]; refl) in let σ := swap i 0 in have h01 : 2 ∣ f (σ 0) ^ 2 + f (σ 1) ^ 2, from (@zmod.eq_zero_iff_dvd_int 2 _).1 $ by simpa [σ] using hσ.1, have h23 : 2 ∣ f (σ 2) ^ 2 + f (σ 3) ^ 2, from (@zmod.eq_zero_iff_dvd_int 2 _).1 $ by simpa using hσ.2, let ⟨x, hx⟩ := h01 in let ⟨y, hy⟩ := h23 in ⟨(f (σ 0) - f (σ 1)) / 2, (f (σ 0) + f (σ 1)) / 2, (f (σ 2) - f (σ 3)) / 2, (f (σ 2) + f (σ 3)) / 2, begin rw [← int.sum_two_squares_of_two_mul_sum_two_squares hx.symm, add_assoc, ← int.sum_two_squares_of_two_mul_sum_two_squares hy.symm, ← domain.mul_left_inj (show (2 : ℤ) ≠ 0, from dec_trivial), ← h, mul_add, ← hx, ← hy], have : univ.sum (λ x, f (σ x)^2) = univ.sum (λ x, f x^2), { conv_rhs { rw finset.sum_univ_perm σ } }, have fin4univ : (univ : finset (fin 4)).1 = 0::1::2::3::0, from dec_trivial, simpa [finset.sum_eq_multiset_sum, fin4univ, multiset.sum_cons, f] end⟩ private lemma prime_sum_four_squares {p : ℕ} (hp : p.prime) : ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = p := have hm : ∃ m < p, 0 < m ∧ ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = m * p, from let ⟨a, b, k, hk⟩ := exists_sum_two_squares_add_one_eq_k hp in ⟨k, hk.2, nat.pos_of_ne_zero $ (λ hk0, by rw [hk0, int.coe_nat_zero, zero_mul] at hk; exact ne_of_gt (show a^2 + b^2 + 1 > 0, from add_pos_of_nonneg_of_pos (add_nonneg (pow_two_nonneg _) (pow_two_nonneg _)) zero_lt_one) hk.1), a, b, 1, 0, by simpa [_root_.pow_two] using hk.1⟩, let m := nat.find hm in let ⟨a, b, c, d, (habcd : a^2 + b^2 + c^2 + d^2 = m * p)⟩ := (nat.find_spec hm).snd.2 in have hm0 : 0 < m, from (nat.find_spec hm).snd.1, have hmp : m < p, from (nat.find_spec hm).fst, m.mod_two_eq_zero_or_one.elim (λ hm2 : m % 2 = 0, let ⟨k, hk⟩ := (nat.dvd_iff_mod_eq_zero _ _).2 hm2 in have hk0 : 0 < k, from nat.pos_of_ne_zero $ λ _, by simp [*, lt_irrefl] at *, have hkm : k < m, by rw [hk, two_mul]; exact (lt_add_iff_pos_left _).2 hk0, false.elim $ nat.find_min hm hkm ⟨lt_trans hkm hmp, hk0, sum_four_squares_of_two_mul_sum_four_squares (show a^2 + b^2 + c^2 + d^2 = 2 * (k * p), by rw [habcd, hk, int.coe_nat_mul, mul_assoc]; simp)⟩) (λ hm2 : m % 2 = 1, if hm1 : m = 1 then ⟨a, b, c, d, by simp only [hm1, habcd, int.coe_nat_one, one_mul]⟩ else --have hm1 : 1 < m, from lt_of_le_of_ne hm0 (ne.symm hm1), let mp : ℕ+ := ⟨m, hm0⟩ in let w := (a : zmod mp).val_min_abs, x := (b : zmod mp).val_min_abs, y := (c : zmod mp).val_min_abs, z := (d : zmod mp).val_min_abs in have hnat_abs : w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ), by simp [_root_.pow_two], have hwxyzlt : w^2 + x^2 + y^2 + z^2 < m^2, from calc w^2 + x^2 + y^2 + z^2 = (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs ^2 + z.nat_abs ^ 2 : ℕ) : hnat_abs ... ≤ ((m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 + (m / 2) ^ 2 : ℕ) : int.coe_nat_le.2 $ add_le_add (add_le_add (add_le_add (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _)) (nat.pow_le_pow_of_le_left (zmod.nat_abs_val_min_abs_le _) _) ... = 4 * (m / 2 : ℕ) ^ 2 : by simp [_root_.pow_two, bit0, bit1, mul_add, add_mul] ... < 4 * (m / 2 : ℕ) ^ 2 + ((4 * (m / 2) : ℕ) * (m % 2 : ℕ) + (m % 2 : ℕ)^2) : (lt_add_iff_pos_right _).2 (by rw [hm2, int.coe_nat_one, _root_.one_pow, mul_one]; exact add_pos_of_nonneg_of_pos (int.coe_nat_nonneg _) zero_lt_one) ... = m ^ 2 : by conv_rhs {rw [← nat.mod_add_div m 2]}; simp [-nat.mod_add_div, mul_add, add_mul, bit0, bit1, mul_comm, mul_assoc, mul_left_comm, _root_.pow_add], have hwxyzabcd : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod mp) = ((a^2 + b^2 + c^2 + d^2 : ℤ) : zmod mp), by simp [w, x, y, z, pow_two], have hwxyz0 : ((w^2 + x^2 + y^2 + z^2 : ℤ) : zmod mp) = 0, by rw [hwxyzabcd, habcd, int.cast_mul, show ((m : ℤ) : zmod mp) = (mp : zmod mp), from rfl, int.cast_coe_nat, coe_coe, zmod.cast_self_eq_zero]; simp, let ⟨n, hn⟩ := (zmod.eq_zero_iff_dvd_int.1 hwxyz0) in have hn0 : 0 < n.nat_abs, from int.nat_abs_pos_of_ne_zero (λ hn0, have hwxyz0 : (w.nat_abs^2 + x.nat_abs^2 + y.nat_abs^2 + z.nat_abs^2 : ℕ) = 0, by rw [← int.coe_nat_eq_zero, ← hnat_abs]; rwa [hn0, mul_zero] at hn, have habcd0 : (m : ℤ) ∣ a ∧ (m : ℤ) ∣ b ∧ (m : ℤ) ∣ c ∧ (m : ℤ) ∣ d, by simpa [add_eq_zero_iff_eq_zero_of_nonneg (pow_two_nonneg _) (pow_two_nonneg _), nat.pow_two, w, x, y, z, zmod.eq_zero_iff_dvd_int] using hwxyz0, let ⟨ma, hma⟩ := habcd0.1, ⟨mb, hmb⟩ := habcd0.2.1, ⟨mc, hmc⟩ := habcd0.2.2.1, ⟨md, hmd⟩ := habcd0.2.2.2 in have hmdvdp : m ∣ p, from int.coe_nat_dvd.1 ⟨ma^2 + mb^2 + mc^2 + md^2, (domain.mul_left_inj (show (m : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 hm0)).1 $ by rw [← habcd, hma, hmb, hmc, hmd]; ring⟩, (hp.2 _ hmdvdp).elim hm1 (λ hmeqp, by simpa [lt_irrefl, hmeqp] using hmp)), have hawbxcydz : ((mp : ℕ) : ℤ) ∣ a * w + b * x + c * y + d * z, from zmod.eq_zero_iff_dvd_int.1 $ by rw [← hwxyz0]; simp; ring, have haxbwczdy : ((mp : ℕ) : ℤ) ∣ a * x - b * w - c * z + d * y, from zmod.eq_zero_iff_dvd_int.1 $ by simp; ring, have haybzcwdx : ((mp : ℕ) : ℤ) ∣ a * y + b * z - c * w - d * x, from zmod.eq_zero_iff_dvd_int.1 $ by simp; ring, have hazbycxdw : ((mp : ℕ) : ℤ) ∣ a * z - b * y + c * x - d * w, from zmod.eq_zero_iff_dvd_int.1 $ by simp; ring, let ⟨s, hs⟩ := hawbxcydz, ⟨t, ht⟩ := haxbwczdy, ⟨u, hu⟩ := haybzcwdx, ⟨v, hv⟩ := hazbycxdw in have hn_nonneg : 0 ≤ n, from nonneg_of_mul_nonneg_left (by erw [← hn]; repeat {try {refine add_nonneg _ _}, try {exact pow_two_nonneg _}}) (int.coe_nat_pos.2 hm0), have hnm : n.nat_abs < mp, from int.coe_nat_lt.1 (lt_of_mul_lt_mul_left (by rw [int.nat_abs_of_nonneg hn_nonneg, ← hn, ← _root_.pow_two]; exact hwxyzlt) (int.coe_nat_nonneg mp)), have hstuv : s^2 + t^2 + u^2 + v^2 = n.nat_abs * p, from (domain.mul_left_inj (show (m^2 : ℤ) ≠ 0, from pow_ne_zero 2 (int.coe_nat_ne_zero_iff_pos.2 hm0))).1 $ calc (m : ℤ)^2 * (s^2 + t^2 + u^2 + v^2) = ((mp : ℕ) * s)^2 + ((mp : ℕ) * t)^2 + ((mp : ℕ) * u)^2 + ((mp : ℕ) * v)^2 : by simp [mp]; ring ... = (w^2 + x^2 + y^2 + z^2) * (a^2 + b^2 + c^2 + d^2) : by simp only [hs.symm, ht.symm, hu.symm, hv.symm]; ring ... = _ : by rw [hn, habcd, int.nat_abs_of_nonneg hn_nonneg]; dsimp [mp]; ring, false.elim $ nat.find_min hm hnm ⟨lt_trans hnm hmp, hn0, s, t, u, v, hstuv⟩) lemma sum_four_squares : ∀ n : ℕ, ∃ a b c d : ℕ, a^2 + b^2 + c^2 + d^2 = n | 0 := ⟨0, 0, 0, 0, rfl⟩ | 1 := ⟨1, 0, 0, 0, rfl⟩ | n@(k+2) := have hm : (min_fac n).prime := min_fac_prime dec_trivial, have n / min_fac n < n := factors_lemma, let ⟨a, b, c, d, h₁⟩ := show ∃ a b c d : ℤ, a^2 + b^2 + c^2 + d^2 = min_fac n, from prime_sum_four_squares hm in let ⟨w, x, y, z, h₂⟩ := sum_four_squares (n / min_fac n) in ⟨(a * x - b * w - c * z + d * y).nat_abs, (a * y + b * z - c * w - d * x).nat_abs, (a * z - b * y + c * x - d * w).nat_abs, (a * w + b * x + c * y + d * z).nat_abs, begin rw [← int.coe_nat_inj', ← nat.mul_div_cancel' (min_fac_dvd (k+2)), int.coe_nat_mul, ← h₁, ← h₂], simp [nat.pow_two, int.coe_nat_add, int.nat_abs_mul_self'], ring, end⟩ end nat
b5bee400e96c605beb81690c657d2e76052ebcba
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/meta3.lean
ed8b1379a1fccc6754b22a6c910c3473013aae63
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,859
lean
import Lean.Meta open Lean open Lean.Meta def dbgOpt : Options := let opt : Options := {}; let opt := opt.setBool `trace.Meta true; -- let opt := opt.setBool `trace.Meta.check false; opt def print (msg : MessageData) : MetaM Unit := do trace[Meta.debug] msg def check (x : MetaM Bool) : MetaM Unit := unless (← x) do throwError "check failed" def getAssignment (m : Expr) : MetaM Expr := do let v? ← getExprMVarAssignment? m.mvarId!; (match v? with | some v => pure v | none => throwError "metavariable is not assigned") unsafe def run (mods : List Name) (x : MetaM Unit) (opts : Options := dbgOpt) : IO Unit := withImportModules (mods.map $ fun m => {module := m}) {} 0 fun env => do let x : MetaM Unit := do { x; printTraces }; discard $ x.toIO { options := opts } { env := env }; pure () def nat := mkConst `Nat def succ := mkConst `Nat.succ def add := mkAppN (mkConst `Add.add [levelZero]) #[nat, mkConst `Nat.add] def tst1 : MetaM Unit := do let d : DiscrTree Nat := {}; let mvar ← mkFreshExprMVar nat; let d ← d.insert (mkAppN add #[mvar, mkNatLit 10]) 1; let d ← d.insert (mkAppN add #[mkNatLit 0, mkNatLit 10]) 2; let d ← d.insert (mkAppN (mkConst `Nat.add) #[mkNatLit 0, mkNatLit 20]) 3; let d ← d.insert (mkAppN add #[mvar, mkNatLit 20]) 4; let d ← d.insert mvar 5; print (format d); let vs ← d.getMatch (mkAppN add #[mkNatLit 1, mkNatLit 10]); print (format vs); let t := mkAppN add #[mvar, mvar]; print t; let vs ← d.getMatch t; print (format vs); let vs ← d.getUnify t; print (format vs); let vs ← d.getUnify mvar; print (format vs); let vs ← d.getUnify $ mkAppN add #[mkNatLit 0, mvar]; print (format vs); let vs ← d.getUnify $ mkAppN add #[mvar, mkNatLit 20]; print (format vs); pure () #eval run [`Init.Data.Nat] tst1
d11d9c60ef2b12863e433ef98f7be68e9fad9829
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Parser/Do.lean
fe3fb0402280972d6b4066c4316cc19ea544f48d
[ "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
5,758
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term namespace Lean namespace Parser builtin_initialize registerBuiltinParserAttribute `builtinDoElemParser `doElem builtin_initialize registerBuiltinDynamicParserAttribute `doElemParser `doElem @[inline] def doElemParser (rbp : Nat := 0) : Parser := categoryParser `doElem rbp namespace Term def leftArrow : Parser := unicodeSymbol " ← " " <- " @[builtinTermParser] def liftMethod := parser!:0 leftArrow >> termParser def doSeqItem := parser! ppLine >> doElemParser >> optional "; " def doSeqIndent := parser! many1Indent doSeqItem def doSeqBracketed := parser! "{" >> withoutPosition (many1 doSeqItem) >> ppLine >> "}" def doSeq := doSeqBracketed <|> doSeqIndent def notFollowedByRedefinedTermToken := notFollowedBy ("if" <|> "match" <|> "let" <|> "have" <|> "do" <|> "dbgTrace!" <|> "assert!" <|> "for" <|> "unless" <|> "return" <|> "try") "token at 'do' element" @[builtinDoElemParser] def doLet := parser! "let " >> optional "mut " >> letDecl @[builtinDoElemParser] def doLetRec := parser! group ("let " >> nonReservedSymbol "rec ") >> letRecDecls def doIdDecl := parser! atomic (ident >> optType >> leftArrow) >> doElemParser def doPatDecl := parser! atomic (termParser >> leftArrow) >> doElemParser >> optional (" | " >> doElemParser) @[builtinDoElemParser] def doLetArrow := parser! "let " >> optional "mut " >> (doIdDecl <|> doPatDecl) -- We use `letIdDeclNoBinders` to define `doReassign`. -- Motivation: we do not reassign functions, and avoid parser conflict def letIdDeclNoBinders := node `Lean.Parser.Term.letIdDecl $ atomic (ident >> pushNone >> optType >> " := ") >> termParser @[builtinDoElemParser] def doReassign := parser! notFollowedByRedefinedTermToken >> (letIdDeclNoBinders <|> letPatDecl) @[builtinDoElemParser] def doReassignArrow := parser! notFollowedByRedefinedTermToken >> (doIdDecl <|> doPatDecl) @[builtinDoElemParser] def doHave := parser! "have " >> Term.haveDecl /- In `do` blocks, we support `if` without an `else`. Thus, we use indentation to prevent examples such as ``` if c_1 then if c_2 then action_1 else action_2 ``` from being parsed as ``` if c_1 then { if c_2 then { action_1 } else { action_2 } } ``` We also have special support for `else if` because we don't want to write ``` if c_1 then action_1 else if c_2 then action_2 else action_3 ``` -/ def elseIf := atomic (group (withPosition (" else " >> checkLineEq >> " if "))) @[builtinDoElemParser] def doIf := parser! withPosition $ "if " >> optIdent >> termParser >> " then " >> doSeq >> many (checkColGe "'else if' in 'do' must be indented" >> group (elseIf >> optIdent >> termParser >> " then " >> doSeq)) >> optional (checkColGe "'else' in 'do' must be indented" >> " else " >> doSeq) @[builtinDoElemParser] def doUnless := parser! "unless " >> withForbidden "do" termParser >> "do " >> doSeq @[builtinDoElemParser] def doFor := parser! "for " >> termParser >> " in " >> withForbidden "do" termParser >> "do " >> doSeq /- `match`-expression where the right-hand-side of alternatives is a `doSeq` instead of a `term` -/ def doMatchAlt : Parser := parser! sepBy1 termParser ", " >> darrow >> doSeq def doMatchAlts : Parser := parser! withPosition $ (optional "| ") >> sepBy1 doMatchAlt (checkColGe "alternatives must be indented" >> "| ") @[builtinDoElemParser] def doMatch := parser!:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> doMatchAlts def doCatch := parser! atomic ("catch " >> binderIdent) >> optional (" : " >> termParser) >> darrow >> doSeq def doCatchMatch := parser! "catch " >> doMatchAlts def doFinally := parser! "finally " >> doSeq @[builtinDoElemParser] def doTry := parser! "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally @[builtinDoElemParser] def doBreak := parser! "break" @[builtinDoElemParser] def doContinue := parser! "continue" @[builtinDoElemParser] def doReturn := parser!:leadPrec withPosition ("return " >> optional (checkLineEq >> termParser)) @[builtinDoElemParser] def doDbgTrace := parser!:leadPrec "dbgTrace! " >> ((interpolatedStr termParser) <|> termParser) @[builtinDoElemParser] def doAssert := parser!:leadPrec "assert! " >> termParser /- We use `notFollowedBy` to avoid counterintuitive behavior. For example, the `if`-term parser doesn't enforce indentation restrictions, but we don't want it to be used when `doIf` fails. Note that parser priorities would not solve this problem since the `doIf` parser is failing while the `if` parser is succeeding. -/ @[builtinDoElemParser] def doExpr := parser! notFollowedByRedefinedTermToken >> termParser @[builtinDoElemParser] def doNested := parser! "do " >> doSeq @[builtinTermParser] def «do» := parser!:maxPrec "do " >> doSeq @[builtinTermParser] def doElem.quot : Parser := parser! "`(doElem|" >> toggleInsideQuot doElemParser >> ")" /- macros for using `unless`, `for`, `try`, `return` as terms. They expand into `do unless ...`, `do for ...`, `do try ...`, and `do return ...` -/ @[builtinTermParser] def termUnless := parser! "unless " >> withForbidden "do" termParser >> "do " >> doSeq @[builtinTermParser] def termFor := parser! "for " >> termParser >> " in " >> withForbidden "do" termParser >> "do " >> doSeq @[builtinTermParser] def termTry := parser! "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally @[builtinTermParser] def termReturn := parser!:leadPrec withPosition ("return " >> optional (checkLineEq >> termParser)) end Term end Parser end Lean
7ec7c008d9d240418531b8b1b65e466cf49f514c
7cdf3413c097e5d36492d12cdd07030eb991d394
/world_experiments/world7/level10andathird.lean
729672e5a3372afdcdfe621598d6689b071bb752
[]
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
1,587
lean
import mynat.definition -- hide import mynat.add -- hide import game.world2.level10 -- hide namespace mynat -- hide /- # World 2 -- Addition World ## Level 7 -- `succ_ne_zero` Levels 7 to 16 are some more advanced facts about addition. If you want to see what theorems or tactics you have, look in the drop-down menus on the left. If you just want to skip these and move straight on to multiplication, click on "next world" on the top right. The four tactics `refl`, `exact`, `rw` and `induction` will get you through to the boss, `a * b = b * a`. If you want to stick with addition world and prove some trickier goals, you can, but you'll need to know some more tactics. For example the `symmetry` tactic can be used whenever the goal is a proposition defined by a symmetric binary relation, such as `=` or `≠`. Remember we already have `zero_ne_succ`, which here should be thought of as a *function* which takes as input a natural number `m` and outputs a proof that `zero ≠ succ(m)`. If you want to venture further into these bonus levels, you will almost certainly need the <a href="http://wwwf.imperial.ac.uk/~buzzard/xena/html/source/tactics/tacticindex.html" target="blank">tactic guide</a>, but I'll give you some hints along the way. If you are still totally stuck, ask at <a href="https://leanprover.zulipchat.com" target="blank">the Lean chat</a> in the new users stream. -/ /- Theorem Zero is not the successor of any natural number. -/ theorem succ_ne_zero {{a : mynat}} : succ a ≠ 0 := begin [less_leaky] symmetry, exact zero_ne_succ a, end end mynat
4abfa0e144f4198cacebdf734f3734a3b7caf0b9
94e33a31faa76775069b071adea97e86e218a8ee
/src/tactic/reserved_notation.lean
0f18d64545518ae262de0da086828a670cfdef77
[ "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
1,607
lean
/- Copyright (c) 2020 Bryan Gin-ge Chen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bryan Gin-ge Chen -/ /-! # Reserved notation This file is imported by `logic.basic` and `logic.relator` to place it at the top of the import graph. We place all of `mathlib`'s reserved notation in this file so that users will know not to use them as e.g. variable names without needing to import the specific file where they are defined. -/ -- used in `logic/relator.lean` reserve infixr ` ⇒ `:40 -- used in `tactic/core.lean` precedence `setup_tactic_parser`:0 reserve prefix `pformat! `:100 reserve prefix `fail! `:100 reserve prefix `trace! `:100 -- used in `tactic/localized.lean` reserve notation `localized` -- used in `tactic/lint/frontend.lean` reserve notation `#lint` reserve notation `#lint_mathlib` reserve notation `#lint_all` reserve notation `#list_linters` -- used in `tactic/where.lean` reserve prefix `#where`:max -- used in `tactic/simps.lean` reserve notation `initialize_simps_projections` reserve notation `as_prefix` -- used in `tactic/lift.lean` reserve notation `to` -- used in `tactic/rcases.lean` precedence `?`:max -- used in `tactic/induction.lean` precedence `fixing`:0 -- used in `order/lattice.lean` -- These priorities are chosen to be above `+`, `∑`, and `∏`, but below `*`. There is no particular -- reason for this choice. reserve infixl ` ⊓ `:69 reserve infixl ` ⊔ `:68 -- used in `algebra/module/linear_map.lean` reserve infix ` ≃ₗ `:25 -- used in `data/matrix/notation.lean` reserve notation `!![`
bac8bdd47f106caf7fde6ef11d1ead55b6aba60e
80746c6dba6a866de5431094bf9f8f841b043d77
/src/ring_theory/polynomial.lean
1f8b494ab15384ffab45712500a59201dd3eb64d
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
9,154
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Hilbert basis theorem: if a ring is noetherian then so is its polynomial ring. -/ import linear_algebra.multivariate_polynomial import data.polynomial import ring_theory.principal_ideal_domain import ring_theory.subring universes u v w namespace polynomial variables (R : Type u) [comm_ring R] [decidable_eq 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, _), 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 end polynomial variables {R : Type u} [comm_ring R] [decidable_eq 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, lattice.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⟩ }, { exact ⟨0⟩ }, 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 (hnr : is_noetherian_ring R) (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ hnr ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal /-- Hilbert basis theorem. -/ theorem is_noetherian_ring_polynomial (hnr : 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 hnr) (set.range I.leading_coeff_nth) (set.ne_empty_of_mem ⟨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 hnr 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 (is_noetherian_iff_well_founded.1 hnr) _ _ _; 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⟩
ca39ef32ec94f53881d36213f389960faf70905e
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/236.lean
6f6dc59f10274ed1cad166d7c73580fc6132e060
[ "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
214
lean
structure Foo where x : Nat b : Bool #check { x := 10, b := true : Foo } set_option pp.all true #check { x := 10, b := true : Foo } set_option pp.structure_instances true #check { x := 10, b := true : Foo }
608f415d8b67cea106b3796ea74eb1d63f21cfc6
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/sheaves/presheaf.lean
f0b55bd21d3df37b3b7e0723ba54c0910722b375
[ "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
11,945
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Mario Carneiro, Reid Barton, Andrew Yang -/ import category_theory.limits.kan_extension import category_theory.adjunction import topology.category.Top.opens /-! # Presheaves on a topological space We define `presheaf C X` simply as `(opens X)ᵒᵖ ⥤ C`, and inherit the category structure with natural transformations as morphisms. We define * `pushforward_obj {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) : Y.presheaf C` with notation `f _* ℱ` and for `ℱ : X.presheaf C` provide the natural isomorphisms * `pushforward.id : (𝟙 X) _* ℱ ≅ ℱ` * `pushforward.comp : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ)` along with their `@[simp]` lemmas. We also define the functors `pushforward` and `pullback` between the categories `X.presheaf C` and `Y.presheaf C`, and provide their adjunction at `pushforward_pullback_adjunction`. -/ universes v u open category_theory open topological_space open opposite variables (C : Type u) [category.{v} C] namespace Top /-- The category of `C`-valued presheaves on a (bundled) topological space `X`. -/ @[derive category, nolint has_inhabited_instance] def presheaf (X : Top.{v}) := (opens X)ᵒᵖ ⥤ C variables {C} namespace presheaf /-- Pushforward a presheaf on `X` along a continuous map `f : X ⟶ Y`, obtaining a presheaf on `Y`. -/ def pushforward_obj {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) : Y.presheaf C := (opens.map f).op ⋙ ℱ infix ` _* `: 80 := pushforward_obj @[simp] lemma pushforward_obj_obj {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) (U : (opens Y)ᵒᵖ) : (f _* ℱ).obj U = ℱ.obj ((opens.map f).op.obj U) := rfl @[simp] lemma pushforward_obj_map {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) {U V : (opens Y)ᵒᵖ} (i : U ⟶ V) : (f _* ℱ).map i = ℱ.map ((opens.map f).op.map i) := rfl /-- An equality of continuous maps induces a natural isomorphism between the pushforwards of a presheaf along those maps. -/ def pushforward_eq {X Y : Top.{v}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) : f _* ℱ ≅ g _* ℱ := iso_whisker_right (nat_iso.op (opens.map_iso f g h).symm) ℱ lemma pushforward_eq' {X Y : Top.{v}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) : f _* ℱ = g _* ℱ := by rw h @[simp] lemma pushforward_eq_hom_app {X Y : Top.{v}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) (U) : (pushforward_eq h ℱ).hom.app U = ℱ.map (begin dsimp [functor.op], apply quiver.hom.op, apply eq_to_hom, rw h, end) := by simp [pushforward_eq] lemma pushforward_eq'_hom_app {X Y : Top.{v}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) (U) : nat_trans.app (eq_to_hom (pushforward_eq' h ℱ)) U = ℱ.map (eq_to_hom (by rw h)) := by simpa @[simp] lemma pushforward_eq_rfl {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) (U) : (pushforward_eq (rfl : f = f) ℱ).hom.app (op U) = 𝟙 _ := begin dsimp [pushforward_eq], simp, end lemma pushforward_eq_eq {X Y : Top.{v}} {f g : X ⟶ Y} (h₁ h₂ : f = g) (ℱ : X.presheaf C) : ℱ.pushforward_eq h₁ = ℱ.pushforward_eq h₂ := rfl namespace pushforward variables {X : Top.{v}} (ℱ : X.presheaf C) /-- The natural isomorphism between the pushforward of a presheaf along the identity continuous map and the original presheaf. -/ def id : (𝟙 X) _* ℱ ≅ ℱ := (iso_whisker_right (nat_iso.op (opens.map_id X).symm) ℱ) ≪≫ functor.left_unitor _ lemma id_eq : (𝟙 X) _* ℱ = ℱ := by { unfold pushforward_obj, rw opens.map_id_eq, erw functor.id_comp } @[simp] lemma id_hom_app' (U) (p) : (id ℱ).hom.app (op ⟨U, p⟩) = ℱ.map (𝟙 (op ⟨U, p⟩)) := by { dsimp [id], simp, } local attribute [tidy] tactic.op_induction' @[simp, priority 990] lemma id_hom_app (U) : (id ℱ).hom.app U = ℱ.map (eq_to_hom (opens.op_map_id_obj U)) := by tidy @[simp] lemma id_inv_app' (U) (p) : (id ℱ).inv.app (op ⟨U, p⟩) = ℱ.map (𝟙 (op ⟨U, p⟩)) := by { dsimp [id], simp, } /-- The natural isomorphism between the pushforward of a presheaf along the composition of two continuous maps and the corresponding pushforward of a pushforward. -/ def comp {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ) := iso_whisker_right (nat_iso.op (opens.map_comp f g).symm) ℱ lemma comp_eq {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g) _* ℱ = g _* (f _* ℱ) := rfl @[simp] lemma comp_hom_app {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (comp ℱ f g).hom.app U = 𝟙 _ := by { dsimp [comp], tidy, } @[simp] lemma comp_inv_app {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (comp ℱ f g).inv.app U = 𝟙 _ := by { dsimp [comp], tidy, } end pushforward /-- A morphism of presheaves gives rise to a morphisms of the pushforwards of those presheaves. -/ @[simps] def pushforward_map {X Y : Top.{v}} (f : X ⟶ Y) {ℱ 𝒢 : X.presheaf C} (α : ℱ ⟶ 𝒢) : f _* ℱ ⟶ f _* 𝒢 := { app := λ U, α.app _, naturality' := λ U V i, by { erw α.naturality, refl, } } open category_theory.limits section pullback variable [has_colimits C] noncomputable theory /-- Pullback a presheaf on `Y` along a continuous map `f : X ⟶ Y`, obtaining a presheaf on `X`. This is defined in terms of left Kan extensions, which is just a fancy way of saying "take the colimits over the open sets whose preimage contains U". -/ @[simps] def pullback_obj {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : Y.presheaf C) : X.presheaf C := (Lan (opens.map f).op).obj ℱ /-- Pulling back along continuous maps is functorial. -/ def pullback_map {X Y : Top.{v}} (f : X ⟶ Y) {ℱ 𝒢 : Y.presheaf C} (α : ℱ ⟶ 𝒢) : pullback_obj f ℱ ⟶ pullback_obj f 𝒢 := (Lan (opens.map f).op).map α /-- If `f '' U` is open, then `f⁻¹ℱ U ≅ ℱ (f '' U)`. -/ @[simps] def pullback_obj_obj_of_image_open {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : Y.presheaf C) (U : opens X) (H : is_open (f '' U)) : (pullback_obj f ℱ).obj (op U) ≅ ℱ.obj (op ⟨_, H⟩) := begin let x : costructured_arrow (opens.map f).op (op U) := { left := op ⟨f '' U, H⟩, hom := ((@hom_of_le _ _ _ ((opens.map f).obj ⟨_, H⟩) (set.image_preimage.le_u_l _)).op : op ((opens.map f).obj (⟨⇑f '' ↑U, H⟩)) ⟶ op U) }, have hx : is_terminal x := { lift := λ s, begin fapply costructured_arrow.hom_mk, change op (unop _) ⟶ op (⟨_, H⟩ : opens _), refine (hom_of_le _).op, exact (set.image_subset f s.X.hom.unop.le).trans (set.image_preimage.l_u_le ↑(unop s.X.left)), simp end }, exact is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_terminal hx _), end namespace pullback variables {X Y : Top.{v}} (ℱ : Y.presheaf C) /-- The pullback along the identity is isomorphic to the original presheaf. -/ def id : pullback_obj (𝟙 _) ℱ ≅ ℱ := nat_iso.of_components (λ U, pullback_obj_obj_of_image_open (𝟙 _) ℱ (unop U) (by simpa using U.unop.2) ≪≫ ℱ.map_iso (eq_to_iso (by simp))) (λ U V i, begin ext, simp [-eq_to_hom_map,-eq_to_iso_map], erw colimit.pre_desc_assoc, erw colimit.ι_desc_assoc, erw colimit.ι_desc_assoc, dsimp, simp only [←ℱ.map_comp], congr end) lemma id_inv_app (U : opens Y) : (id ℱ).inv.app (op U) = colimit.ι (Lan.diagram (opens.map (𝟙 Y)).op ℱ (op U)) (@costructured_arrow.mk _ _ _ _ _ (op U) _ (eq_to_hom (by simp))) := begin dsimp[id], simp[-eq_to_hom_map,-eq_to_iso_map],dsimp[colimit_of_diagram_terminal], delta Lan.diagram, refine eq.trans _ (category.id_comp _), rw ← ℱ.map_id, congr, any_goals { apply subsingleton.helim }, all_goals { simp } end end pullback end pullback variable (C) /-- The pushforward functor. -/ def pushforward {X Y : Top.{v}} (f : X ⟶ Y) : X.presheaf C ⥤ Y.presheaf C := { obj := pushforward_obj f, map := @pushforward_map _ _ X Y f } @[simp] lemma pushforward_map_app' {X Y : Top.{v}} (f : X ⟶ Y) {ℱ 𝒢 : X.presheaf C} (α : ℱ ⟶ 𝒢) {U : (opens Y)ᵒᵖ} : ((pushforward C f).map α).app U = α.app (op $ (opens.map f).obj U.unop) := rfl lemma id_pushforward {X : Top.{v}} : pushforward C (𝟙 X) = 𝟭 (X.presheaf C) := begin apply category_theory.functor.ext, { intros, ext U, have h := f.congr, erw h (opens.op_map_id_obj U), simpa }, { intros, apply pushforward.id_eq }, end section iso /-- A homeomorphism of spaces gives an equivalence of categories of presheaves. -/ @[simps] def presheaf_equiv_of_iso {X Y : Top} (H : X ≅ Y) : X.presheaf C ≌ Y.presheaf C := equivalence.congr_left (opens.map_map_iso H).symm.op variable {C} /-- If `H : X ≅ Y` is a homeomorphism, then given an `H _* ℱ ⟶ 𝒢`, we may obtain an `ℱ ⟶ H ⁻¹ _* 𝒢`. -/ def to_pushforward_of_iso {X Y : Top} (H : X ≅ Y) {ℱ : X.presheaf C} {𝒢 : Y.presheaf C} (α : H.hom _* ℱ ⟶ 𝒢) : ℱ ⟶ H.inv _* 𝒢 := (presheaf_equiv_of_iso _ H).to_adjunction.hom_equiv ℱ 𝒢 α @[simp] lemma to_pushforward_of_iso_app {X Y : Top} (H₁ : X ≅ Y) {ℱ : X.presheaf C} {𝒢 : Y.presheaf C} (H₂ : H₁.hom _* ℱ ⟶ 𝒢) (U : (opens X)ᵒᵖ) : (to_pushforward_of_iso H₁ H₂).app U = ℱ.map (eq_to_hom (by simp [opens.map, set.preimage_preimage])) ≫ H₂.app (op ((opens.map H₁.inv).obj (unop U))) := begin delta to_pushforward_of_iso, simp only [equiv.to_fun_as_coe, nat_trans.comp_app, equivalence.equivalence_mk'_unit, eq_to_hom_map, presheaf_equiv_of_iso_unit_iso_hom_app_app, equivalence.to_adjunction, equivalence.equivalence_mk'_counit, presheaf_equiv_of_iso_inverse_map_app, adjunction.mk_of_unit_counit_hom_equiv_apply], congr end /-- If `H : X ≅ Y` is a homeomorphism, then given an `H _* ℱ ⟶ 𝒢`, we may obtain an `ℱ ⟶ H ⁻¹ _* 𝒢`. -/ def pushforward_to_of_iso {X Y : Top} (H₁ : X ≅ Y) {ℱ : Y.presheaf C} {𝒢 : X.presheaf C} (H₂ : ℱ ⟶ H₁.hom _* 𝒢) : H₁.inv _* ℱ ⟶ 𝒢 := ((presheaf_equiv_of_iso _ H₁.symm).to_adjunction.hom_equiv ℱ 𝒢).symm H₂ @[simp] lemma pushforward_to_of_iso_app {X Y : Top} (H₁ : X ≅ Y) {ℱ : Y.presheaf C} {𝒢 : X.presheaf C} (H₂ : ℱ ⟶ H₁.hom _* 𝒢) (U : (opens X)ᵒᵖ) : (pushforward_to_of_iso H₁ H₂).app U = H₂.app (op ((opens.map H₁.inv).obj (unop U))) ≫ 𝒢.map (eq_to_hom (by simp [opens.map, set.preimage_preimage])) := by simpa [pushforward_to_of_iso, equivalence.to_adjunction] end iso variables (C) [has_colimits C] /-- Pullback a presheaf on `Y` along a continuous map `f : X ⟶ Y`, obtaining a presheaf on `X`. -/ @[simps map_app] def pullback {X Y : Top.{v}} (f : X ⟶ Y) : Y.presheaf C ⥤ X.presheaf C := Lan (opens.map f).op @[simp] lemma pullback_obj_eq_pullback_obj {C} [category C] [has_colimits C] {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : Y.presheaf C) : (pullback C f).obj ℱ = pullback_obj f ℱ := rfl /-- The pullback and pushforward along a continuous map are adjoint to each other. -/ @[simps unit_app_app counit_app_app] def pushforward_pullback_adjunction {X Y : Top.{v}} (f : X ⟶ Y) : pullback C f ⊣ pushforward C f := Lan.adjunction _ _ /-- Pulling back along a homeomorphism is the same as pushing forward along its inverse. -/ def pullback_hom_iso_pushforward_inv {X Y : Top.{v}} (H : X ≅ Y) : pullback C H.hom ≅ pushforward C H.inv := adjunction.left_adjoint_uniq (pushforward_pullback_adjunction C H.hom) (presheaf_equiv_of_iso C H.symm).to_adjunction /-- Pulling back along the inverse of a homeomorphism is the same as pushing forward along it. -/ def pullback_inv_iso_pushforward_hom {X Y : Top.{v}} (H : X ≅ Y) : pullback C H.inv ≅ pushforward C H.hom := adjunction.left_adjoint_uniq (pushforward_pullback_adjunction C H.inv) (presheaf_equiv_of_iso C H).to_adjunction end presheaf end Top
26afcc2882629bb679962a581776c2774f7ddf61
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/ring_theory/noetherian.lean
39b930e2adafad6e8a0379d2b1ddd6a4ca5adf7e
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,653
lean
/- Copyright (c) 2018 Mario Carneiro, Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import algebraic_geometry.prime_spectrum import data.multiset.finset_ops import linear_algebra.linear_independent import order.order_iso_nat import order.compactly_generated import ring_theory.ideal.operations import group_theory.finiteness /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodules M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. (Note that we do not assume yet that our rings are commutative, so perhaps this should be called "left Noetherian". To avoid cumbersome names once we specialize to the commutative case, we don't make this explicit in the declaration names.) ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] * [samuel] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators pointwise namespace submodule variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ lemma fg_iff_add_submonoid_fg (P : submodule ℕ M) : P.fg ↔ P.to_add_submonoid.fg := ⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩, λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩⟩ lemma fg_iff_add_subgroup_fg {G : Type*} [add_comm_group G] (P : submodule ℤ G) : P.fg ↔ P.to_add_subgroup.fg := ⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩, λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩⟩ lemma fg_iff_exists_fin_generating_family {N : submodule R M} : N.fg ↔ ∃ (n : ℕ) (s : fin n → M), span R (range s) = N := begin rw fg_def, split, { rintros ⟨S, Sfin, hS⟩, obtain ⟨n, f, rfl⟩ := Sfin.fin_embedding, exact ⟨n, f, hS⟩, }, { rintros ⟨n, s, hs⟩, refine ⟨range s, finite_range s, hs⟩ }, end /-- **Nakayama's Lemma**. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, [Stacks 00DV](https://stacks.math.columbia.edu/tag/00DV) -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_span {s : set M} (hs : finite s) : fg (span R s) := ⟨hs.to_finset, by rw [hs.coe_to_finset]⟩ theorem fg_span_singleton (x : M) : fg (R ∙ x) := fg_span (finite_singleton x) theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_monoid P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M} (hfn : (N.map f).fg) : N.fg := let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, linear_map.ker_eq_bot.1 hf h, linear_map.map_injective hf $ by { rw [f.map_span, finset.coe_preimage, set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht], rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩ lemma fg_top {R M : Type*} [ring R] [add_comm_group M] [module R M] (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg := ⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ fg_map h, λ h, fg_of_fg_map N.subtype N.ker_subtype $ by rwa [map_top, range_subtype]⟩ lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) : (⊤ : submodule R M).fg := e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ fg_map h theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : M →ₗ[R] P) {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_image_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_image_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end /-- The image of a finitely generated ideal is finitely generated. -/ lemma map_fg_of_fg {R S : Type*} [comm_ring R] [comm_ring S] (I : ideal R) (h : I.fg) (f : R →+* S) : (I.map f).fg := begin obtain ⟨X, hXfin, hXgen⟩ := fg_def.1 h, apply fg_def.2, refine ⟨set.image f X, finite.image ⇑f hXfin, _⟩, rw [ideal.map, ideal.span, ← hXgen], refine le_antisymm (submodule.span_mono (image_subset _ ideal.subset_span)) _, rw [submodule.span_le, image_subset_iff], intros i hi, refine submodule.span_induction hi (λ x hx, _) _ (λ x y hx hy, _) (λ r x hx, _), { simp only [set_like.mem_coe, mem_preimage], suffices : f x ∈ f '' X, { exact ideal.subset_span this }, exact mem_image_of_mem ⇑f hx }, { simp only [set_like.mem_coe, ring_hom.map_zero, mem_preimage, zero_mem] }, { simp only [set_like.mem_coe, mem_preimage] at hx hy, simp only [ring_hom.map_add, set_like.mem_coe, mem_preimage], exact submodule.add_mem _ hx hy }, { simp only [set_like.mem_coe, mem_preimage] at hx, simp only [algebra.id.smul_eq_mul, set_like.mem_coe, mem_preimage, ring_hom.map_mul], exact submodule.smul_mem _ _ hx } end /-- The kernel of the composition of two linear maps is finitely generated if both kernels are and the first morphism is surjective. -/ lemma fg_ker_comp {R M N P : Type*} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] [add_comm_group P] [module R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf1 : f.ker.fg) (hf2 : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin rw linear_map.ker_comp, apply fg_of_fg_map_of_fg_inf_ker f, { rwa [submodule.map_comap_eq, linear_map.range_eq_top.2 hsur, top_inf_eq] }, { rwa [inf_of_le_right (show f.ker ≤ (comap f g.ker), from comap_mono (@bot_le _ _ g.ker))] } end lemma fg_restrict_scalars {R S M : Type*} [comm_ring R] [comm_ring S] [algebra R S] [add_comm_group M] [module S M] [module R M] [is_scalar_tower R S M] (N : submodule S M) (hfin : N.fg) (h : function.surjective (algebra_map R S)) : (submodule.restrict_scalars R N).fg := begin obtain ⟨X, rfl⟩ := hfin, use X, exact submodule.span_eq_restrict_scalars R S M X h end lemma fg_ker_ring_hom_comp {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A] (f : R →+* S) (g : S →+* A) (hf : f.ker.fg) (hg : g.ker.fg) (hsur : function.surjective f) : (g.comp f).ker.fg := begin letI : algebra R S := ring_hom.to_algebra f, letI : algebra R A := ring_hom.to_algebra (g.comp f), letI : algebra S A := ring_hom.to_algebra g, letI : is_scalar_tower R S A := is_scalar_tower.of_algebra_map_eq (λ _, rfl), let f₁ := algebra.linear_map R S, let g₁ := (is_scalar_tower.to_alg_hom R S A).to_linear_map, exact fg_ker_comp f₁ g₁ hf (fg_restrict_scalars g.ker hg hsur) hsur end /-- Finitely generated submodules are precisely compact elements in the submodule lattice. -/ theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s := begin classical, -- Introduce shorthand for span of an element let sp : M → submodule R M := λ a, span R {a}, -- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly. have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl, split, { rintro ⟨t, rfl⟩, rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)], apply complete_lattice.finset_sup_compact_of_compact, exact λ n _, singleton_span_is_compact_element n, }, { intro h, -- s is the Sup of the spans of its elements. have sSup : s = Sup (sp '' ↑s), by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq], -- by h, s is then below (and equal to) the sup of the spans of finitely many elements. obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup), have ssup : s = u.sup id, { suffices : u.sup id ≤ s, from le_antisymm husup this, rw [sSup, finset.sup_id_eq_Sup], exact Sup_le_Sup huspan, }, obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan, rw [finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw, ←span_eq_supr_of_singleton_spans, eq_comm] at ssup, exact ⟨t, ssup⟩, }, end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R /-- An R-module is Noetherian iff all its submodules are finitely-generated. -/ lemma is_noetherian_def : is_noetherian R M ↔ ∀ (s : submodule R M), s.fg := ⟨λ h, h.noetherian, is_noetherian.mk⟩ theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, submodule.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N := is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _ lemma is_noetherian_of_le {s t : submodule R M} [ht : is_noetherian R t] (h : s ≤ t) : is_noetherian R s := is_noetherian_submodule.mpr (λ s' hs', is_noetherian_submodule.mp ht _ (le_trans hs' h)) variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from submodule.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) : is_noetherian R M := is_noetherian_of_linear_equiv (linear_equiv.of_injective f $ linear_map.ker_eq_bot.mp hf).symm lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) : N.fg := @@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, submodule.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices on_finset : ∀ s : finset ι, is_noetherian R (Π i : s, M i), { let coe_e := equiv.subtype_univ_equiv finset.mem_univ, letI : is_noetherian R (Π i : finset.univ, M (coe_e i)) := on_finset finset.univ, exact is_noetherian_of_linear_equiv (linear_equiv.Pi_congr_left R M coe_e), }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ _ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), fconstructor, { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], } } end /-- A version of `is_noetherian_pi` for non-dependent functions. We need this instance because sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to prove that `ι → ℝ` is finite dimensional over `ℝ`). -/ instance is_noetherian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [fintype ι] [is_noetherian R M] : is_noetherian R (ι → M) := is_noetherian_pi end open is_noetherian submodule function section universe w variables {R M P : Type*} {N : Type w} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] [add_comm_group P] [module R P] theorem is_noetherian_iff_well_founded : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := begin rw (complete_lattice.well_founded_characterisations $ submodule R M).out 0 3, exact ⟨λ ⟨h⟩, λ k, (fg_iff_compact k).mp (h k), λ h, ⟨λ k, (fg_iff_compact k).mpr (h k)⟩⟩, end variables (R M) lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp variables {R M} lemma finite_of_linear_independent [nontrivial R] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, (rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M)).elim' _), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- A module is Noetherian iff every increasing chain of submodules stabilizes. -/ theorem monotone_stabilizes_iff_noetherian : (∀ (f : ℕ →ₘ submodule R M), ∃ n, ∀ m, n ≤ m → f n = f m) ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.monotone_chain_condition] /-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/ lemma is_noetherian.induction [is_noetherian R M] {P : submodule R M → Prop} (hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I := well_founded.recursion (well_founded_submodule_gt R M) I hgt /-- If the first and final modules in a short exact sequence are noetherian, then the middle module is also noetherian. -/ theorem is_noetherian_of_range_eq_ker [is_noetherian R M] [is_noetherian R P] (f : M →ₗ[R] N) (g : N →ₗ[R] P) (hf : function.injective f) (hg : function.surjective g) (h : f.range = g.ker) : is_noetherian R N := is_noetherian_iff_well_founded.2 $ well_founded_gt_exact_sequence (well_founded_submodule_gt R M) (well_founded_submodule_gt R P) f.range (submodule.map f) (submodule.comap f) (submodule.comap g) (submodule.map g) (submodule.gci_map_comap hf) (submodule.gi_map_comap hg) (by simp [submodule.map_comap_eq, inf_comm]) (by simp [submodule.comap_map_eq, h]) /-- For any endomorphism of a Noetherian module, there is some nontrivial iterate with disjoint kernel and range. -/ theorem is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot [I : is_noetherian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊓ (f ^ n).range = ⊥ := begin obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (f.iterate_ker.comp ⟨λ n, n+1, λ n m w, by linarith⟩), specialize w (2 * n + 1) (by linarith), dsimp at w, refine ⟨n+1, nat.succ_ne_zero _, _⟩, rw eq_bot_iff, rintros - ⟨h, ⟨y, rfl⟩⟩, rw [mem_bot, ←linear_map.mem_ker, w], erw linear_map.mem_ker at h ⊢, change ((f ^ (n + 1)) * (f ^ (n + 1))) y = 0 at h, rw ←pow_add at h, convert h using 3, linarith, end /-- Any surjective endomorphism of a Noetherian module is injective. -/ theorem is_noetherian.injective_of_surjective_endomorphism [is_noetherian R M] (f : M →ₗ[R] M) (s : surjective f) : injective f := begin obtain ⟨n, ne, w⟩ := is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot f, rw [linear_map.range_eq_top.mpr (linear_map.iterate_surjective s n), inf_top_eq, linear_map.ker_eq_bot] at w, exact linear_map.injective_of_iterate_injective ne w, end /-- Any surjective endomorphism of a Noetherian module is bijective. -/ theorem is_noetherian.bijective_of_surjective_endomorphism [is_noetherian R M] (f : M →ₗ[R] M) (s : surjective f) : bijective f := ⟨is_noetherian.injective_of_surjective_endomorphism f s, s⟩ /-- A sequence `f` of submodules of a noetherian module, with `f (n+1)` disjoint from the supremum of `f 0`, ..., `f n`, is eventually zero. -/ lemma is_noetherian.disjoint_partial_sups_eventually_bot [I : is_noetherian R M] (f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups f n) (f (n+1))) : ∃ n : ℕ, ∀ m, n ≤ m → f m = ⊥ := begin -- A little off-by-one cleanup first: suffices t : ∃ n : ℕ, ∀ m, n ≤ m → f (m+1) = ⊥, { obtain ⟨n, w⟩ := t, use n+1, rintros (_|m) p, { cases p, }, { apply w, exact nat.succ_le_succ_iff.mp p }, }, obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (partial_sups f), exact ⟨n, (λ m p, eq_bot_of_disjoint_absorbs (h m) ((eq.symm (w (m + 1) (le_add_right p))).trans (w m p)))⟩ end /-- If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial. -/ noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M] (f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} := begin apply nonempty.some, obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i) (f.tailings_disjoint_tailing i), specialize w n (le_refl n), apply nonempty.intro, refine (f.tailing_linear_equiv i n).symm ≪≫ₗ _, rw w, exact submodule.bot_equiv_punit, end end /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ class is_noetherian_ring (R) [ring R] extends is_noetherian R R : Prop theorem is_noetherian_ring_iff {R} [ring R] : is_noetherian_ring R ↔ is_noetherian R R := ⟨λ h, h.1, @is_noetherian_ring.mk _ _⟩ /-- A commutative ring is Noetherian if and only if all its ideals are finitely-generated. -/ lemma is_noetherian_ring_iff_ideal_fg (R : Type*) [comm_ring R] : is_noetherian_ring R ↔ ∀ I : ideal R, I.fg := is_noetherian_ring_iff.trans is_noetherian_def @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact is_noetherian_ring_iff.2 (ring.is_noetherian_of_fintype R R) theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end /-- If `M / S / R` is a scalar tower, and `M / R` is Noetherian, then `M / S` is also noetherian. -/ theorem is_noetherian_of_tower (R) {S M} [comm_ring R] [ring S] [add_comm_group M] [algebra R S] [module S M] [module R M] [is_scalar_tower R S M] (h : is_noetherian R M) : is_noetherian S M := begin rw is_noetherian_iff_well_founded at h ⊢, refine (submodule.restrict_scalars_embedding R S M).dual.well_founded h end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M := have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h, by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range f.range_restrict f.range_restrict_surjective theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule section primes variables {R : Type*} [comm_ring R] [is_noetherian_ring R] /--In a noetherian ring, every ideal contains a product of prime ideals ([samuel, § 3.3, Lemma 3])-/ lemma exists_prime_spectrum_prod_le (I : ideal R) : ∃ (Z : multiset (prime_spectrum R)), multiset.prod (Z.map (coe : subtype _ → ideal R)) ≤ I := begin refine is_noetherian.induction (λ (M : ideal R) hgt, _) I, by_cases h_prM : M.is_prime, { use {⟨M, h_prM⟩}, rw [multiset.map_singleton, multiset.prod_singleton, subtype.coe_mk], exact le_rfl }, by_cases htop : M = ⊤, { rw htop, exact ⟨0, le_top⟩ }, have lt_add : ∀ z ∉ M, M < M + span R {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨x, hx, y, hy, hxy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left htop, obtain ⟨Wx, h_Wx⟩ := hgt (M + span R {x}) (lt_add _ hx), obtain ⟨Wy, h_Wy⟩ := hgt (M + span R {y}) (lt_add _ hy), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], apply le_trans (submodule.mul_le_mul h_Wx h_Wy), rw add_mul, apply sup_le (show M * (M + span R {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span R {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem], end variables {A : Type*} [integral_domain A] [is_noetherian_ring A] /--In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as product or prime ideals ([samuel, § 3.3, Lemma 3]) -/ lemma exists_prime_spectrum_prod_le_and_ne_bot_of_domain (h_fA : ¬ is_field A) {I : ideal A} (h_nzI: I ≠ ⊥) : ∃ (Z : multiset (prime_spectrum A)), multiset.prod (Z.map (coe : subtype _ → ideal A)) ≤ I ∧ multiset.prod (Z.map (coe : subtype _ → ideal A)) ≠ ⊥ := begin revert h_nzI, refine is_noetherian.induction (λ (M : ideal A) hgt, _) I, intro h_nzM, have hA_nont : nontrivial A, apply is_integral_domain.to_nontrivial (integral_domain.to_is_integral_domain A), by_cases h_topM : M = ⊤, { rcases h_topM with rfl, obtain ⟨p_id, h_nzp, h_pp⟩ : ∃ (p : ideal A), p ≠ ⊥ ∧ p.is_prime, { apply ring.not_is_field_iff_exists_prime.mp h_fA }, use [({⟨p_id, h_pp⟩} : multiset (prime_spectrum A)), le_top], rwa [multiset.map_singleton, multiset.prod_singleton, subtype.coe_mk] }, by_cases h_prM : M.is_prime, { use ({⟨M, h_prM⟩} : multiset (prime_spectrum A)), rw [multiset.map_singleton, multiset.prod_singleton, subtype.coe_mk], exact ⟨le_rfl, h_nzM⟩ }, obtain ⟨x, hx, y, hy, h_xy⟩ := (ideal.not_is_prime_iff.mp h_prM).resolve_left h_topM, have lt_add : ∀ z ∉ M, M < M + span A {z}, { intros z hz, refine lt_of_le_of_ne le_sup_left (λ m_eq, hz _), rw m_eq, exact mem_sup_right (mem_span_singleton_self z) }, obtain ⟨Wx, h_Wx_le, h_Wx_ne⟩ := hgt (M + span A {x}) (lt_add _ hx) (ne_bot_of_gt (lt_add _ hx)), obtain ⟨Wy, h_Wy_le, h_Wx_ne⟩ := hgt (M + span A {y}) (lt_add _ hy) (ne_bot_of_gt (lt_add _ hy)), use Wx + Wy, rw [multiset.map_add, multiset.prod_add], refine ⟨le_trans (submodule.mul_le_mul h_Wx_le h_Wy_le) _, mt ideal.mul_eq_bot.mp _⟩, { rw add_mul, apply sup_le (show M * (M + span A {y}) ≤ M, from ideal.mul_le_right), rw mul_add, apply sup_le (show span A {x} * M ≤ M, from ideal.mul_le_left), rwa [span_mul_span, singleton_mul_singleton, span_singleton_le_iff_mem] }, { rintro (hx | hy); contradiction }, end end primes
078af4003db35ce81290ef610de4f5146eb6511c
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebraic_geometry/morphisms/quasi_compact.lean
ce3b7758ffb832e95c36878995d04ce4e4456f35
[ "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
10,442
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.morphisms.basic import topology.spectral.hom /-! # Quasi-compact morphisms A morphism of schemes is quasi-compact if the preimages of quasi-compact open sets are quasi-compact. It suffices to check that preimages of affine open sets are compact (`quasi_compact_iff_forall_affine`). -/ noncomputable theory open category_theory category_theory.limits opposite topological_space universe u namespace algebraic_geometry variables {X Y : Scheme.{u}} (f : X ⟶ Y) /-- A morphism is `quasi-compact` if the underlying map of topological spaces is, i.e. if the preimages of quasi-compact open sets are quasi-compact. -/ @[mk_iff] class quasi_compact (f : X ⟶ Y) : Prop := (is_compact_preimage : ∀ U : set Y.carrier, is_open U → is_compact U → is_compact (f.1.base ⁻¹' U)) lemma quasi_compact_iff_spectral : quasi_compact f ↔ is_spectral_map f.1.base := ⟨λ ⟨h⟩, ⟨by continuity, h⟩, λ h, ⟨h.2⟩⟩ /-- The `affine_target_morphism_property` corresponding to `quasi_compact`, asserting that the domain is a quasi-compact scheme. -/ def quasi_compact.affine_property : affine_target_morphism_property := λ X Y f hf, compact_space X.carrier @[priority 900] instance quasi_compact_of_is_iso {X Y : Scheme} (f : X ⟶ Y) [is_iso f] : quasi_compact f := begin constructor, intros U hU hU', convert hU'.image (inv f.1.base).continuous_to_fun using 1, rw set.image_eq_preimage_of_inverse, delta function.left_inverse, exacts [is_iso.inv_hom_id_apply f.1.base, is_iso.hom_inv_id_apply f.1.base] end instance quasi_compact_comp {X Y Z : Scheme} (f : X ⟶ Y) (g : Y ⟶ Z) [quasi_compact f] [quasi_compact g] : quasi_compact (f ≫ g) := begin constructor, intros U hU hU', rw [Scheme.comp_val_base, coe_comp, set.preimage_comp], apply quasi_compact.is_compact_preimage, { exact continuous.is_open_preimage (by continuity) _ hU }, apply quasi_compact.is_compact_preimage; assumption end lemma is_compact_open_iff_eq_finset_affine_union {X : Scheme} (U : set X.carrier) : is_compact U ∧ is_open U ↔ ∃ (s : set X.affine_opens), s.finite ∧ U = ⋃ (i : X.affine_opens) (h : i ∈ s), i := begin apply opens.is_compact_open_iff_eq_finite_Union_of_is_basis (coe : X.affine_opens → opens X.carrier), { rw subtype.range_coe, exact is_basis_affine_open X }, { intro i, exact i.2.is_compact } end lemma is_compact_open_iff_eq_basic_open_union {X : Scheme} [is_affine X] (U : set X.carrier) : is_compact U ∧ is_open U ↔ ∃ (s : set (X.presheaf.obj (op ⊤))), s.finite ∧ U = ⋃ (i : X.presheaf.obj (op ⊤)) (h : i ∈ s), X.basic_open i := begin apply opens.is_compact_open_iff_eq_finite_Union_of_is_basis, { exact is_basis_basic_open X }, { intro i, exact ((top_is_affine_open _).basic_open_is_affine _).is_compact } end lemma quasi_compact_iff_forall_affine : quasi_compact f ↔ ∀ U : opens Y.carrier, is_affine_open U → is_compact (f.1.base ⁻¹' (U : set Y.carrier)) := begin rw quasi_compact_iff, refine ⟨λ H U hU, H U U.prop hU.is_compact, _⟩, intros H U hU hU', obtain ⟨S, hS, rfl⟩ := (is_compact_open_iff_eq_finset_affine_union U).mp ⟨hU', hU⟩, simp only [set.preimage_Union, subtype.val_eq_coe], exact hS.compact_bUnion (λ i _, H i i.prop) end @[simp] lemma quasi_compact.affine_property_to_property {X Y : Scheme} (f : X ⟶ Y) : (quasi_compact.affine_property : _).to_property f ↔ is_affine Y ∧ compact_space X.carrier := by { delta affine_target_morphism_property.to_property quasi_compact.affine_property, simp } lemma quasi_compact_iff_affine_property : quasi_compact f ↔ target_affine_locally quasi_compact.affine_property f := begin rw quasi_compact_iff_forall_affine, transitivity (∀ U : Y.affine_opens, is_compact (f.1.base ⁻¹' (U : set Y.carrier))), { exact ⟨λ h U, h U U.prop, λ h U hU, h ⟨U, hU⟩⟩ }, apply forall_congr, exact λ _, is_compact_iff_compact_space, end lemma quasi_compact_eq_affine_property : @quasi_compact = target_affine_locally quasi_compact.affine_property := by { ext, exact quasi_compact_iff_affine_property _ } lemma is_compact_basic_open (X : Scheme) {U : opens X.carrier} (hU : is_compact (U : set X.carrier)) (f : X.presheaf.obj (op U)) : is_compact (X.basic_open f : set X.carrier) := begin classical, refine ((is_compact_open_iff_eq_finset_affine_union _).mpr _).1, obtain ⟨s, hs, e⟩ := (is_compact_open_iff_eq_finset_affine_union _).mp ⟨hU, U.prop⟩, let g : s → X.affine_opens, { intro V, use V.1 ∩ X.basic_open f, have : V.1.1 ⟶ U, { apply hom_of_le, change _ ⊆ (U : set X.carrier), rw e, convert @set.subset_Union₂ _ _ _ (λ (U : X.affine_opens) (h : U ∈ s), ↑U) V V.prop using 1, refl }, erw ← X.to_LocallyRingedSpace.to_RingedSpace.basic_open_res this.op, exact is_affine_open.basic_open_is_affine V.1.prop _ }, haveI : finite s := hs.to_subtype, refine ⟨set.range g, set.finite_range g, _⟩, refine (set.inter_eq_right_iff_subset.mpr (RingedSpace.basic_open_subset _ _)).symm.trans _, rw [e, set.Union₂_inter], apply le_antisymm; apply set.Union₂_subset, { intros i hi, refine set.subset.trans _ (set.subset_Union₂ _ (set.mem_range_self ⟨i, hi⟩)), exact set.subset.rfl }, { rintro ⟨i, hi⟩ ⟨⟨j, hj⟩, hj'⟩, rw ← hj', refine set.subset.trans _ (set.subset_Union₂ j hj), exact set.subset.rfl } end lemma quasi_compact.affine_property_is_local : (quasi_compact.affine_property : _).is_local := begin split, { apply affine_target_morphism_property.respects_iso_mk; rintros X Y Z _ _ _ H, exacts [@@homeomorph.compact_space _ _ H (Top.homeo_of_iso (as_iso e.inv.1.base)), H] }, { introv H, delta quasi_compact.affine_property at H ⊢, change compact_space ((opens.map f.val.base).obj (Y.basic_open r)), rw Scheme.preimage_basic_open f r, erw ← is_compact_iff_compact_space, rw ← is_compact_univ_iff at H, exact is_compact_basic_open X H _ }, { rintros X Y H f S hS hS', resetI, rw ← is_affine_open.basic_open_union_eq_self_iff at hS, delta quasi_compact.affine_property, rw ← is_compact_univ_iff, change is_compact ((opens.map f.val.base).obj ⊤).1, rw ← hS, dsimp [opens.map], simp only [opens.coe_supr, set.preimage_Union, subtype.val_eq_coe], exacts [compact_Union (λ i, is_compact_iff_compact_space.mpr (hS' i)), top_is_affine_open _] } end lemma quasi_compact.affine_open_cover_tfae {X Y : Scheme.{u}} (f : X ⟶ Y) : tfae [quasi_compact f, ∃ (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)], ∀ (i : 𝒰.J), compact_space (pullback f (𝒰.map i)).carrier, ∀ (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)] (i : 𝒰.J), compact_space (pullback f (𝒰.map i)).carrier, ∀ {U : Scheme} (g : U ⟶ Y) [is_affine U] [is_open_immersion g], compact_space (pullback f g).carrier, ∃ {ι : Type u} (U : ι → opens Y.carrier) (hU : supr U = ⊤) (hU' : ∀ i, is_affine_open (U i)), ∀ i, compact_space (f.1.base ⁻¹' (U i).1)] := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.affine_open_cover_tfae f lemma quasi_compact.open_cover_tfae {X Y : Scheme.{u}} (f : X ⟶ Y) : tfae [quasi_compact f, ∃ (𝒰 : Scheme.open_cover.{u} Y), ∀ (i : 𝒰.J), quasi_compact (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i), ∀ (𝒰 : Scheme.open_cover.{u} Y) (i : 𝒰.J), quasi_compact (pullback.snd : (𝒰.pullback_cover f).obj i ⟶ 𝒰.obj i), ∀ (U : opens Y.carrier), quasi_compact (f ∣_ U), ∀ {U : Scheme} (g : U ⟶ Y) [is_open_immersion g], quasi_compact (pullback.snd : pullback f g ⟶ _), ∃ {ι : Type u} (U : ι → opens Y.carrier) (hU : supr U = ⊤), ∀ i, quasi_compact (f ∣_ (U i))] := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.target_affine_locally_is_local.open_cover_tfae f lemma quasi_compact_over_affine_iff {X Y : Scheme} (f : X ⟶ Y) [is_affine Y] : quasi_compact f ↔ compact_space X.carrier := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.affine_target_iff f lemma quasi_compact.affine_open_cover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.open_cover.{u} Y) [∀ i, is_affine (𝒰.obj i)] (f : X ⟶ Y) : quasi_compact f ↔ ∀ i, compact_space (pullback f (𝒰.map i)).carrier := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.affine_open_cover_iff f 𝒰 lemma quasi_compact.open_cover_iff {X Y : Scheme.{u}} (𝒰 : Scheme.open_cover.{u} Y) (f : X ⟶ Y) : quasi_compact f ↔ ∀ i, quasi_compact (pullback.snd : pullback f (𝒰.map i) ⟶ _) := quasi_compact_eq_affine_property.symm ▸ quasi_compact.affine_property_is_local.target_affine_locally_is_local.open_cover_iff f 𝒰 lemma quasi_compact_respects_iso : morphism_property.respects_iso @quasi_compact := quasi_compact_eq_affine_property.symm ▸ target_affine_locally_respects_iso quasi_compact.affine_property_is_local.1 lemma quasi_compact_stable_under_composition : morphism_property.stable_under_composition @quasi_compact := λ _ _ _ _ _ _ _, by exactI infer_instance @[elab_as_eliminator] lemma compact_open_induction_on {P : opens X.carrier → Prop} (S : opens X.carrier) (hS : is_compact S.1) (h₁ : P ⊥) (h₂ : ∀ (S : opens X.carrier) (hS : is_compact S.1) (U : X.affine_opens), P S → P (S ⊔ U)) : P S := begin classical, obtain ⟨s, hs, hs'⟩ := (is_compact_open_iff_eq_finset_affine_union S.1).mp ⟨hS, S.2⟩, replace hs' : S = supr (λ i : s, (i : opens X.carrier)) := by { ext1, simpa using hs' }, subst hs', apply hs.induction_on, { convert h₁, rw supr_eq_bot, rintro ⟨_, h⟩, exact h.elim }, { intros x s h₃ hs h₄, have : is_compact (⨆ i : s, (i : opens X.carrier)).1, { refine ((is_compact_open_iff_eq_finset_affine_union _).mpr _).1, exact ⟨s, hs, by simp⟩ }, convert h₂ _ this x h₄, simp only [coe_coe], rw [supr_subtype, sup_comm], conv_rhs { rw supr_subtype }, exact supr_insert } end end algebraic_geometry
c4bc1883d2497b294ee0e7642dd825027595022c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/topology/sheaves/sheaf_condition/pairwise_intersections_auto.lean
558fd0f5c5289a248e4d73a13e7f2f2d0430fbde
[]
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
13,101
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.topology.sheaves.sheaf import Mathlib.category_theory.limits.preserves.basic import Mathlib.category_theory.category.pairwise import Mathlib.PostPort universes v u namespace Mathlib /-! # Equivalent formulations of the sheaf condition We give an equivalent formulation of the sheaf condition. Given any indexed type `ι`, we define `overlap ι`, a category with objects corresponding to * individual open sets, `single i`, and * intersections of pairs of open sets, `pair i j`, with morphisms from `pair i j` to both `single i` and `single j`. Any open cover `U : ι → opens X` provides a functor `diagram U : overlap ι ⥤ (opens X)ᵒᵖ`. There is a canonical cone over this functor, `cone U`, whose cone point is `supr U`, and in fact this is a limit cone. A presheaf `F : presheaf C X` is a sheaf precisely if it preserves this limit. We express this in two equivalent ways, as * `is_limit (F.map_cone (cone U))`, or * `preserves_limit (diagram U) F` -/ namespace Top.presheaf /-- An alternative formulation of the sheaf condition (which we prove equivalent to the usual one below as `sheaf_condition_equiv_sheaf_condition_pairwise_intersections`). A presheaf is a sheaf if `F` sends the cone `(pairwise.cocone U).op` to a limit cone. (Recall `pairwise.cocone U`, has cone point `supr U`, mapping down to the `U i` and the `U i ⊓ U j`.) -/ def sheaf_condition_pairwise_intersections {X : Top} {C : Type u} [category_theory.category C] (F : presheaf C X) := {ι : Type v} → (U : ι → topological_space.opens ↥X) → category_theory.limits.is_limit (category_theory.functor.map_cone F (category_theory.limits.cocone.op (category_theory.pairwise.cocone U))) /-- An alternative formulation of the sheaf condition (which we prove equivalent to the usual one below as `sheaf_condition_equiv_sheaf_condition_preserves_limit_pairwise_intersections`). A presheaf is a sheaf if `F` preserves the limit of `pairwise.diagram U`. (Recall `pairwise.diagram U` is the diagram consisting of the pairwise intersections `U i ⊓ U j` mapping into the open sets `U i`. This diagram has limit `supr U`.) -/ def sheaf_condition_preserves_limit_pairwise_intersections {X : Top} {C : Type u} [category_theory.category C] (F : presheaf C X) := {ι : Type v} → (U : ι → topological_space.opens ↥X) → category_theory.limits.preserves_limit (category_theory.functor.op (category_theory.pairwise.diagram U)) F /-! The remainder of this file shows that these conditions are equivalent to the usual sheaf condition. -/ namespace sheaf_condition_pairwise_intersections /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ def cone_equiv_functor_obj {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) (c : category_theory.limits.cone (category_theory.functor.op (category_theory.pairwise.diagram U) ⋙ F)) : category_theory.limits.cone (sheaf_condition_equalizer_products.diagram F U) := category_theory.limits.cone.mk (category_theory.limits.cone.X c) (category_theory.nat_trans.mk fun (Z : category_theory.limits.walking_parallel_pair) => category_theory.limits.walking_parallel_pair.cases_on Z (category_theory.limits.pi.lift fun (i : ι) => category_theory.nat_trans.app (category_theory.limits.cone.π c) (opposite.op (category_theory.pairwise.single i))) (category_theory.limits.pi.lift fun (b : ι × ι) => category_theory.nat_trans.app (category_theory.limits.cone.π c) (opposite.op (category_theory.pairwise.pair (prod.fst b) (prod.snd b))))) /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ def cone_equiv_functor {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) : category_theory.limits.cone (category_theory.functor.op (category_theory.pairwise.diagram U) ⋙ F) ⥤ category_theory.limits.cone (sheaf_condition_equalizer_products.diagram F U) := category_theory.functor.mk (fun (c : category_theory.limits.cone (category_theory.functor.op (category_theory.pairwise.diagram U) ⋙ F)) => cone_equiv_functor_obj F U c) fun (c c' : category_theory.limits.cone (category_theory.functor.op (category_theory.pairwise.diagram U) ⋙ F)) (f : c ⟶ c') => category_theory.limits.cone_morphism.mk (category_theory.limits.cone_morphism.hom f) /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simp] theorem cone_equiv_inverse_obj_π_app {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) (c : category_theory.limits.cone (sheaf_condition_equalizer_products.diagram F U)) (x : category_theory.pairwise ιᵒᵖ) : category_theory.nat_trans.app (category_theory.limits.cone.π (cone_equiv_inverse_obj F U c)) x = opposite.op_induction (fun (x : category_theory.pairwise ι) => category_theory.pairwise.cases_on x (fun (i : ι) => category_theory.nat_trans.app (category_theory.limits.cone.π c) category_theory.limits.walking_parallel_pair.zero ≫ category_theory.limits.pi.π (fun (i : ι) => category_theory.functor.obj F (opposite.op (U i))) i) fun (i j : ι) => category_theory.nat_trans.app (category_theory.limits.cone.π c) category_theory.limits.walking_parallel_pair.one ≫ category_theory.limits.pi.π (fun (p : ι × ι) => category_theory.functor.obj F (opposite.op (U (prod.fst p) ⊓ U (prod.snd p)))) (i, j)) x := Eq.refl (category_theory.nat_trans.app (category_theory.limits.cone.π (cone_equiv_inverse_obj F U c)) x) /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simp] theorem cone_equiv_inverse_map_hom {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) (c : category_theory.limits.cone (sheaf_condition_equalizer_products.diagram F U)) (c' : category_theory.limits.cone (sheaf_condition_equalizer_products.diagram F U)) (f : c ⟶ c') : category_theory.limits.cone_morphism.hom (category_theory.functor.map (cone_equiv_inverse F U) f) = category_theory.limits.cone_morphism.hom f := Eq.refl (category_theory.limits.cone_morphism.hom (category_theory.functor.map (cone_equiv_inverse F U) f)) /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ def cone_equiv_unit_iso_app {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) (c : category_theory.limits.cone (category_theory.functor.op (category_theory.pairwise.diagram U) ⋙ F)) : category_theory.functor.obj 𝟭 c ≅ category_theory.functor.obj (cone_equiv_functor F U ⋙ cone_equiv_inverse F U) c := category_theory.iso.mk (category_theory.limits.cone_morphism.mk 𝟙) (category_theory.limits.cone_morphism.mk 𝟙) /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simp] theorem cone_equiv_unit_iso_hom_app_hom {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) : ∀ (X_1 : category_theory.limits.cone (category_theory.functor.op (category_theory.pairwise.diagram U) ⋙ F)), category_theory.limits.cone_morphism.hom (category_theory.nat_trans.app (category_theory.iso.hom (cone_equiv_unit_iso F U)) X_1) = 𝟙 := fun (X_1 : category_theory.limits.cone (category_theory.functor.op (category_theory.pairwise.diagram U) ⋙ F)) => Eq.refl 𝟙 /-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/ @[simp] theorem cone_equiv_counit_iso_hom_app_hom {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) : ∀ (X_1 : category_theory.limits.cone (sheaf_condition_equalizer_products.diagram F U)), category_theory.limits.cone_morphism.hom (category_theory.nat_trans.app (category_theory.iso.hom (cone_equiv_counit_iso F U)) X_1) = 𝟙 := fun (X_1 : category_theory.limits.cone (sheaf_condition_equalizer_products.diagram F U)) => Eq.refl 𝟙 /-- Cones over `diagram U ⋙ F` are the same as a cones over the usual sheaf condition equalizer diagram. -/ @[simp] theorem cone_equiv_functor_2 {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) : category_theory.equivalence.functor (cone_equiv F U) = cone_equiv_functor F U := Eq.refl (category_theory.equivalence.functor (cone_equiv F U)) /-- If `sheaf_condition_equalizer_products.fork` is an equalizer, then `F.map_cone (cone U)` is a limit cone. -/ def is_limit_map_cone_of_is_limit_sheaf_condition_fork {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) (P : category_theory.limits.is_limit (sheaf_condition_equalizer_products.fork F U)) : category_theory.limits.is_limit (category_theory.functor.map_cone F (category_theory.limits.cocone.op (category_theory.pairwise.cocone U))) := category_theory.limits.is_limit.of_iso_limit (coe_fn (equiv.symm (category_theory.limits.is_limit.of_cone_equiv (category_theory.equivalence.symm (cone_equiv F U)))) P) (category_theory.iso.mk (category_theory.limits.cone_morphism.mk 𝟙) (category_theory.limits.cone_morphism.mk 𝟙)) /-- If `F.map_cone (cone U)` is a limit cone, then `sheaf_condition_equalizer_products.fork` is an equalizer. -/ def is_limit_sheaf_condition_fork_of_is_limit_map_cone {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) {ι : Type v} (U : ι → topological_space.opens ↥X) (Q : category_theory.limits.is_limit (category_theory.functor.map_cone F (category_theory.limits.cocone.op (category_theory.pairwise.cocone U)))) : category_theory.limits.is_limit (sheaf_condition_equalizer_products.fork F U) := category_theory.limits.is_limit.of_iso_limit (coe_fn (equiv.symm (category_theory.limits.is_limit.of_cone_equiv (cone_equiv F U))) Q) (category_theory.iso.mk (category_theory.limits.cone_morphism.mk 𝟙) (category_theory.limits.cone_morphism.mk 𝟙)) end sheaf_condition_pairwise_intersections /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of a limit diagram over `U i` and `U i ⊓ U j`. -/ def sheaf_condition_equiv_sheaf_condition_pairwise_intersections {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) : sheaf_condition F ≃ sheaf_condition_pairwise_intersections F := equiv.Pi_congr_right fun (i : Type v) => equiv.Pi_congr_right fun (U : i → topological_space.opens ↥X) => equiv_of_subsingleton_of_subsingleton (sheaf_condition_pairwise_intersections.is_limit_map_cone_of_is_limit_sheaf_condition_fork F U) (sheaf_condition_pairwise_intersections.is_limit_sheaf_condition_fork_of_is_limit_map_cone F U) /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of the presheaf preserving the limit of the diagram consisting of the `U i` and `U i ⊓ U j`. -/ def sheaf_condition_equiv_sheaf_condition_preserves_limit_pairwise_intersections {X : Top} {C : Type u} [category_theory.category C] [category_theory.limits.has_products C] (F : presheaf C X) : sheaf_condition F ≃ sheaf_condition_preserves_limit_pairwise_intersections F := sorry end Mathlib
efef72df67aa6e7d41072eeaf0428a90052ff03e
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
/src/locally_constant/analysis.lean
b96fc6b0ab56927d619c2c23e524e4703846daa2
[]
no_license
mr-infty/lean-liquid
3ff89d1f66244b434654c59bdbd6b77cb7de0109
a8db559073d2101173775ccbd85729d3a4f1ed4d
refs/heads/master
1,678,465,145,334
1,614,565,310,000
1,614,565,310,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,460
lean
import topology.locally_constant.algebra import for_mathlib.normed_group_hom /-! # Analysis of locally constant maps This file defines the normed group of locally constant maps into a normed group. ## Main construction * The instance `locally_constant.normed_group` * `locally_constant.map_hom`: push-forward of locally constant maps as a normed group hom * `locally_constant.comap_hom`: pull-back of locally constant maps as a normed group hom -/ noncomputable theory -- move this section for_mathlib lemma real.Sup_exists_of_finite (s : set ℝ) (hs : s.finite) : ∃ (x : ℝ), ∀ (y : ℝ), y ∈ s → y ≤ x := begin rcases hs.exists_finset with ⟨t, ht⟩, use t.fold max 0 id, intros y hy, exact (finset.fold_op_rel_iff_or (@le_max_iff _ _)).mpr (or.inr ⟨y, by rwa ht, le_rfl⟩) end -- feel free to golf!! lemma real.Sup_mul (r : ℝ) (s : set ℝ) (hr : 0 < r) : Sup ({x | ∃ y ∈ s, r * y = x}) = r * Sup s := begin let P₁ : Prop := (∃ (x : ℝ), x ∈ {x : ℝ | ∃ (y : ℝ) (H : y ∈ s), r * y = x}) ∧ ∃ (x : ℝ), ∀ (y : ℝ), y ∈ {x : ℝ | ∃ (y : ℝ) (H : y ∈ s), r * y = x} → y ≤ x, let P₂ : Prop := (∃ (x : ℝ), x ∈ s) ∧ ∃ (x : ℝ), ∀ (y : ℝ), y ∈ s → y ≤ x, have H : P₁ ↔ P₂ := _, { by_cases h : P₁, { apply le_antisymm, { rw real.Sup_le _ h.1 h.2, rintro _ ⟨x, hx, rfl⟩, apply mul_le_mul_of_nonneg_left _ hr.le, rw H at h, exact real.le_Sup _ h.2 hx }, { rw H at h, rw [← le_div_iff' hr, real.Sup_le _ h.1 h.2], intros x hx, rw le_div_iff' hr, rw ← H at h, exact real.le_Sup _ h.2 ⟨_, hx, rfl⟩ } }, { simp only [real.Sup_def], classical, rw [dif_neg, dif_neg, mul_zero], { rw H at h, exact h }, { exact h } } }, { apply and_congr, { simp only [exists_prop, set.mem_set_of_eq], rw exists_comm, simp only [and_comm, exists_eq_left'] }, { simp only [exists_prop, set.mem_set_of_eq, and_comm], simp only [exists_eq_left', mul_comm r, ← div_eq_iff_mul_eq hr.ne.symm], split; rintro ⟨x, hx⟩, { refine ⟨x / r, λ y hy, _⟩, rw ← mul_div_cancel y hr.ne.symm at hy, rw le_div_iff hr, exact hx _ hy }, { refine ⟨r * x, λ y hy, _⟩, rw ← div_le_iff' hr, exact hx _ hy } } }, end end for_mathlib namespace locally_constant variables {X Y Z V V₁ V₂ V₃ : Type*} [topological_space X] /-- The sup norm on locally constant function -/ protected def has_norm [has_norm Y] : has_norm (locally_constant X Y) := { norm := λ f, ⨆ x, ∥f x∥ } /-- The sup edist on locally constant function -/ protected def has_edist [has_edist Y] : has_edist (locally_constant X Y) := { edist := λ f g, ⨆ x, edist (f x) (g x) } /-- The sup edist on locally constant function -/ protected def has_dist [has_dist Y] : has_dist (locally_constant X Y) := { dist := λ f g, ⨆ x, dist (f x) (g x) } local attribute [instance] locally_constant.has_norm locally_constant.has_edist locally_constant.has_dist lemma edist_apply_le [has_edist Y] (f g : locally_constant X Y) (x : X) : edist (f x) (g x) ≤ edist f g := le_Sup (set.mem_range_self x) section compact_domain variables [compact_space X] lemma norm_apply_le [has_norm Y] (f : locally_constant X Y) (x : X) : ∥f x∥ ≤ ∥f∥ := begin refine real.le_Sup _ _ (set.mem_range_self _), apply real.Sup_exists_of_finite, rw set.range_comp, exact f.range_finite.image _ end lemma exists_ub_range_dist [has_dist Y] (f g : locally_constant X Y) : ∃ x : ℝ, ∀ y : ℝ, y ∈ set.range (λ (x : X), dist (f x) (g x)) → y ≤ x := begin apply real.Sup_exists_of_finite, simp only [← function.uncurry_apply_pair dist], rw set.range_comp, apply set.finite.image, apply (f.range_finite.prod g.range_finite).subset, rintro ⟨y₁, y₂⟩, simp only [set.mem_range, prod.mk.inj_iff], rintro ⟨y, rfl, rfl⟩, simp only [set.mem_range_self, set.prod_mk_mem_set_prod_eq, and_self] end lemma dist_apply_le [has_dist Y] (f g : locally_constant X Y) (x : X) : dist (f x) (g x) ≤ dist f g := real.le_Sup _ (exists_ub_range_dist _ _) (set.mem_range_self x) -- consider giving the `edist` and the `uniform_space` explicitly /-- The metric space on locally constant functions on a compact space, with sup distance. -/ protected def metric_space [metric_space Y] : metric_space (locally_constant X Y) := { dist_self := λ f, show (⨆ x, dist (f x) (f x)) = 0, begin simp only [dist_self, supr], by_cases H : nonempty X, swap, { rwa [set.range_eq_empty.mpr H, real.Sup_empty] }, resetI, simp only [set.range_const, cSup_singleton] end, eq_of_dist_eq_zero := begin intros f g h, ext x, apply eq_of_dist_eq_zero, apply le_antisymm _ dist_nonneg, rw ← h, exact dist_apply_le _ _ _ end, dist_comm := λ f g, show Sup _ = Sup _, by { simp only [dist_comm] }, dist_triangle := begin intros f g h, by_cases H : nonempty X, swap, { show Sup _ ≤ Sup _ + Sup _, simp only [set.range_eq_empty.mpr H, real.Sup_empty, add_zero] }, refine (real.Sup_le _ _ (exists_ub_range_dist _ _)).mpr _, { obtain ⟨x⟩ := H, exact ⟨_, set.mem_range_self x⟩ }, rintro r ⟨x, rfl⟩, calc dist (f x) (h x) ≤ dist (f x) (g x) + dist (g x) (h x) : dist_triangle _ _ _ ... ≤ dist f g + dist g h : add_le_add (dist_apply_le _ _ _) (dist_apply_le _ _ _) end, .. locally_constant.has_dist } /-- The metric space on locally constant functions on a compact space, with sup distance. -/ protected def normed_group {G : Type*} [normed_group G] : normed_group (locally_constant X G) := { dist_eq := λ f g, show Sup _ = Sup _, by simp only [normed_group.dist_eq, locally_constant.sub_apply], .. locally_constant.has_norm, .. locally_constant.add_comm_group, .. locally_constant.metric_space } local attribute [instance] locally_constant.normed_group section map_hom variables [normed_group V] [normed_group V₁] [normed_group V₂] [normed_group V₃] /-- Push-forward of locally constant maps under a normed group hom, as a normed group hom between types of locally constant functions. -/ @[simps] def map_hom (f : normed_group_hom V₁ V₂) : normed_group_hom (locally_constant X V₁) (locally_constant X V₂) := { to_fun := locally_constant.map f, map_zero' := by { ext, exact f.map_zero' }, map_add' := by { intros x y, ext s, apply f.map_add' }, bound' := begin obtain ⟨C, C_pos, hC⟩ := f.bound, use C, rintro (g : locally_constant _ _), calc Sup (set.range (λ x, ∥f (g x)∥)) ≤ Sup (set.range (λ x, C * ∥g x∥)) : _ ... = C * Sup (set.range (λ x, ∥g x∥)) : _, { by_cases H : nonempty X, swap, { simp only [set.range_eq_empty.mpr H, real.Sup_empty] }, apply real.Sup_le_ub, { obtain ⟨x⟩ := H, exact ⟨_, set.mem_range_self x⟩ }, rintro _ ⟨x, rfl⟩, calc ∥f (g x)∥ ≤ C * ∥g x∥ : hC _ ... ≤ Sup _ : real.le_Sup _ _ _, { apply real.Sup_exists_of_finite, rw [set.range_comp, set.range_comp], exact (g.range_finite.image _).image _ }, { exact set.mem_range_self _ } }, { convert real.Sup_mul C _ C_pos using 2, ext x, simp only [set.mem_range, exists_prop, set.set_of_mem_eq, exists_exists_eq_and], simp only [set.mem_set_of_eq] } end } @[simp] lemma map_hom_id : @map_hom X _ _ _ _ _ _ (@normed_group_hom.id V _) = normed_group_hom.id := by { ext, refl } @[simp] lemma map_hom_comp (g : normed_group_hom V₂ V₃) (f : normed_group_hom V₁ V₂) : (@map_hom X _ _ _ _ _ _ g).comp (map_hom f) = map_hom (g.comp f) := by { ext, refl } end map_hom section comap_hom /-! ### comapping as normed_group_hom -/ variables [topological_space Y] [compact_space Y] [topological_space Z] [compact_space Z] variables [normed_group V] /-- Pull-back of locally constant maps under a normed group hom, as a normed group hom between types of locally constant functions. -/ @[simps] def comap_hom (f : X → Y) (hf : continuous f) : normed_group_hom (locally_constant Y V) (locally_constant X V) := { to_fun := locally_constant.comap f, map_zero' := by { ext, simp only [hf, function.comp_app, coe_comap, zero_apply] }, map_add' := by { intros, ext, simp only [hf, add_apply, function.comp_app, coe_comap] }, bound' := begin use 1, assume g, rw one_mul, show Sup _ ≤ Sup _, simp only [hf, function.comp_app, coe_comap], by_cases hX : nonempty X, swap, { simp only [set.range_eq_empty.mpr hX, real.Sup_empty], by_cases hY : nonempty Y, swap, { simp only [set.range_eq_empty.mpr hY, real.Sup_empty] }, obtain ⟨y⟩ := hY, calc 0 ≤ ∥g y∥ : norm_nonneg _ ... ≤ _ : _, apply real.le_Sup, { apply real.Sup_exists_of_finite, rw set.range_comp, exact g.range_finite.image _ }, { exact set.mem_range_self _ } }, rw real.Sup_le, { rintro _ ⟨x, rfl⟩, apply real.le_Sup, { apply real.Sup_exists_of_finite, rw set.range_comp, exact g.range_finite.image _ }, { exact set.mem_range_self _ } }, { obtain ⟨x⟩ := hX, exact ⟨_, set.mem_range_self x⟩ }, { { apply real.Sup_exists_of_finite, rw [set.range_comp, set.range_comp], apply set.finite.image, apply g.range_finite.subset, apply set.image_subset_range } } end } @[simp] lemma comap_hom_id : @comap_hom X X V _ _ _ _ _ id continuous_id = normed_group_hom.id := begin ext, simp only [comap_id, comap_hom_to_fun, id.def, normed_group_hom.id_to_fun, add_monoid_hom.to_fun_eq_coe, add_monoid_hom.id_apply] end @[simp] lemma comap_hom_comp (f : X → Y) (g : Y → Z) (hf : continuous f) (hg : continuous g) : (@comap_hom _ _ V _ _ _ _ _ f hf).comp (comap_hom g hg) = (comap_hom (g ∘ f) (hg.comp hf)) := begin ext φ x, -- `[simps]` is producing bad lemmas... I don't know how to trick it into creating good ones -- so we use `show` instead, to get into a defeq shape that is usable show (comap_hom f hf) ((comap_hom g hg) φ) x = _, simp only [hg.comp hf, hf, hg, comap_hom_to_fun, coe_comap] end end comap_hom end compact_domain end locally_constant #lint- only unused_arguments def_lemma doc_blame
d198b4ddd18454b0b95e02b92e7c541f59b300ab
e2c1ee9c02c59b832eb48536755242ce5f9b2c3e
/src/t8.lean
10376127793d521fb1adde590391cb71f801282b
[]
no_license
yairgueta/Lean
cb5bb16d81674e8a07f85c9dbeb56dc2f543d4eb
af8a4fa24f76edfdd0dd33f013db194e611e6a86
refs/heads/master
1,676,275,529,938
1,610,289,661,000
1,610,289,661,000
328,405,309
0
0
null
null
null
null
UTF-8
Lean
false
false
2,371
lean
universe u inductive vector (α : Type u) : nat → Type u | nil {} : vector 0 | cons : Π {n}, α → vector n → vector (n+1) namespace vector local notation h :: t := cons h t def append_tail {α : Type*} : Π {n : ℕ}, vector α n → α → vector α (n+1) | 0 nil a := a :: nil | (n+1) (a::v) b := a::(append_tail v b) -- theorem simp_length {α : Type*} : ∀ {n m: ℕ}, vector α (n + 1 + m) = vector α (n + (m + 1)) -- := sorry def append {α : Type*} : Π {n m : ℕ}, vector α n → vector α m → vector α (n+m) | 0 0 nil nil := nil | (n+1) m (a::v) u := by repeat {rw nat.add_comm}; exact a::(append v u) | 0 (m+1) nil u := by repeat {rw nat.add_comm}; exact u end vector inductive aexpr : Type | const : ℕ → aexpr | var : ℕ → aexpr | plus : aexpr → aexpr → aexpr | times : aexpr → aexpr → aexpr open aexpr def sample_aexpr : aexpr := plus (times (var 0) (const 7)) (times (const 2) (var 1)) def aeval (v : ℕ → ℕ) : aexpr → ℕ | (const n) := n | (var n) := v n | (plus e₁ e₂) := aeval e₁ + aeval e₂ | (times e₁ e₂) := aeval e₁ * aeval e₂ def sample_val : ℕ → ℕ | 0 := 5 | 1 := 6 | _ := 0 #eval aeval sample_val sample_aexpr def simp_const : aexpr → aexpr | (plus (const n₁) (const n₂)) := const (n₁ + n₂) | (times (const n₁) (const n₂)) := const (n₁ * n₂) | e := e def sample_aexpr1 : aexpr := plus (times (const 0) (const 7)) (times (const 2) (const 1)) #reduce simp_const (times (const 0) (const 7)) #reduce simp_const (plus (times (const 0) (const 7)) (times (const 2) (const 1))) def fuse : aexpr → aexpr | (plus e₁ e₂) := simp_const (plus (simp_const e₁) (simp_const e₂)) | (times e₁ e₂) := simp_const (times (simp_const e₁) (simp_const e₂)) | e := simp_const e #reduce fuse (times (const 0) (const 7)) #reduce fuse (plus (times (const 0) (const 7)) (times (const 2) (const 1))) theorem simp_const_eq (v : ℕ → ℕ) : ∀ e : aexpr, aeval v (simp_const e) = aeval v e | e := have h: simp_const e = e, by simp [simp_const e], | (const _) := rfl | (var _) := rfl | (plus (const _) (const _)) := rfl | (times (const _) (const _)) := rfl theorem fuse_eq (v : ℕ → ℕ) : ∀ e : aexpr, aeval v (fuse e) = aeval v e := sorry
c9e324e4eea4fc1f6a6fa02a8cdf55b060372ef4
76df16d6c3760cb415f1294caee997cc4736e09b
/lean/src/interp/lang/thm.lean
a1a3d263a37dc49a1e19b36670e43320bdbf152a
[ "MIT" ]
permissive
uw-unsat/leanette-popl22-artifact
70409d9cbd8921d794d27b7992bf1d9a4087e9fe
80fea2519e61b45a283fbf7903acdf6d5528dbe7
refs/heads/master
1,681,592,449,670
1,637,037,431,000
1,637,037,431,000
414,331,908
6
1
null
null
null
null
UTF-8
Lean
false
false
9,904
lean
import ...cs.lang import .defs import ..tactic import ...basic.basic namespace interp section interp variables {D O : Type} {op : O → list (lang.val D O) → lang.result D O} open lang lemma interpVar_evalC {a : ℕ} {ε : env D O} {v : val D O} (h : ε.nth a = some v) : evalC op (exp.var a) ε (result.ans v) := begin simp only [list.nth_eq_some] at h, cases h with _ h', subst_vars, constructor, end -- The concrete interpreter is sound: -- if running `interpC` with `fuel` produces a concrete result `r` -- on a program `e` and a concrete environment `ε`, then -- `evalC` also produces `r` on `e` and `ε`. lemma interpC_soundness {e : exp D O} {ε : env D O} {r : lang.result D O} {fuel : ℕ} (h : interpC op fuel e ε = some r) : evalC op e ε r := begin induction fuel with fuel ih generalizing e ε r, case zero { contradiction }, case succ { cases e, all_goals { simp only [interpC] at h }, case [error, abort, bool, datum, lam] { all_goals { subst_vars, constructor }, }, case var : a { cases_on_interp h_a : ε.nth a : v, simp only [interpC] at h, subst_vars, apply interpVar_evalC, assumption, }, case call : a_f a_a { cases_on_interp h_f : ε.nth a_f : v_f, simp only [interpC] at h, cases_on_interp h_f : ε.nth a_a : v_a, cases v_f, case clos : x e_b ε_static { simp only [interpC] at h, constructor_c, case [h1, h2] { all_goals { apply interpVar_evalC, all_goals { assumption }, }, }, case h3 { apply ih, assumption }, }, all_goals { simp only [interpC] at h, subst_vars, apply_c evalC.call_halt, case [h1, h2] { all_goals { apply interpVar_evalC, all_goals { assumption }, }, }, case h3 { simp }, }, }, case app : o as { cases_on_interp h_as : mmap (λ (a : ℕ), ε.nth a) as : vs, simp only [interpC] at h, subst_vars, constructor_c, case h1 { apply mmap.length, assumption }, case h2 { intros i hi_a hi_v, apply interpVar_evalC, exact mmap.eq_some h_as i hi_a hi_v, }, }, case if0 : a_c e_t e_e { cases_on_interp h_c : ε.nth a_c : v_c, cases v_c, focus_case bool : b { cases b, case ff { cases_on_interp h_e : interpC op fuel e_e ε : r_e, simp only [interpC] at h, subst_vars, apply_c evalC.if0_false, case hc { apply interpVar_evalC, assumption }, case hv { simp }, case hr { apply ih, assumption }, }, }, all_goals { simp only [interpC] at h, cases_on_interp h_t : interpC op fuel e_t ε : r_t, simp only [interpC] at h, subst_vars, apply_c evalC.if0_true, case hc { apply interpVar_evalC, assumption }, case hv { simp }, case hr { apply ih, assumption }, }, }, case let0 : x e_v e_b { cases_on_interp h_v : interpC op fuel e_v ε : r_v, cases r_v, case halt { simp only [interpC] at h, subst_vars, apply evalC.let0_halt, apply ih, assumption, }, case ans { simp only [interpC] at h, apply_c evalC.let0, case [h1, h2] { all_goals { apply ih, assumption }, }, }, }, }, end lemma interpC_bump_fuel {e : exp D O} {ε : env D O} {r : lang.result D O} {fuel : ℕ} (h : interpC op fuel e ε = some r) : interpC op (fuel + 1) e ε = some r := begin induction fuel with fuel ih generalizing e ε r, case zero { contradiction }, case succ { cases e, all_goals { simp only [interpC] at h }, case [error, abort, bool, datum, lam] { all_goals { subst_vars, constructor_c, }, }, case var { simpa [interpC] }, case call : a_f a_a { cases_on_interp h_f : ε.nth a_f : v_f, simp only [interpC] at h, cases_on_interp h_a : ε.nth a_a : v_a, cases v_f, case clos { simp only [interpC] at h, simp only [interpC, h_f, h_a], exact ih h, }, all_goals { simp only [interpC] at h, simp [interpC, h_f, h_a, h], }, }, case app : o as { cases_on_interp h_as : mmap (λ (a : ℕ), ε.nth a) as : vs, simp [interpC, h_as, h], }, case if0 : a_c e_t e_e { cases_on_interp h_c : ε.nth a_c : v_c, cases v_c, focus_case bool : b { cases b }, focus_case [bool ff] { simp only [interpC] at h, cases_on_interp h_e : interpC op fuel e_e ε, }, focus_case [bool tt, clos, datum] { simp only [interpC] at h, cases_on_interp h_t : interpC op fuel e_t ε, }, all_goals { simp only [interpC] at h, subst_vars, simp only [interpC, h_c], apply ih, assumption, }, }, case let0 : x e_v e_b { cases_on_interp h_v : interpC op fuel e_v ε : r_v, replace h_v := ih h_v, cases r_v, case halt { simp only [interpC] at h h_v, simp only [interpC, h_v], assumption, }, case ans { simp only [interpC] at h h_v, simp only [interpC, h_v], exact ih h, }, }, }, end lemma interpC_bump_large_fuel {e : exp D O} {ε : env D O} {r : lang.result D O} {fuel : ℕ} (extra_fuel : ℕ) (h : interpC op fuel e ε = some r) : interpC op (fuel + extra_fuel) e ε = some r := begin induction extra_fuel, case zero { assumption }, case succ { apply interpC_bump_fuel, assumption }, end -- The concrete interpreter is complete: -- If `evalC` produces a concrete result `r` -- on a program `e` and a concrete environment `ε`, then -- there exists a `fuel` such that running `interpC` with `fuel` also -- produces `r` on `e` and `ε` lemma interpC_completeness {e : exp D O} {ε : env D O} {r : lang.result D O} (h : evalC op e ε r) : ∃ (fuel : ℕ), interpC op fuel e ε = some r := begin induction h, case [bool, error, abort, datum, lam] { all_goals { use 1, trivial, }, }, case call_halt : ε a_f a_a _ _ _ _ h_not_clos h_e_f h_e_a { use 1, cases h_e_f with _ h_e_f, replace h_e_f := interpC_bump_fuel h_e_f, cases h_e_a with _ h_e_a, replace h_e_a := interpC_bump_fuel h_e_a, simp only [interpC] at h_e_f h_e_a ⊢, cases_on_interp h_f : ε.nth a_f : v_f, cases_on_interp h_a : ε.nth a_a : v_a, simp only [interpC] at h_e_f h_e_a ⊢, subst_vars, cases v_f, case clos { contra [val.is_clos] at h_not_clos }, all_goals { simp [h_a, interpC] }, }, case call : ε a_f a_a _ _ _ _ _ _ _ _ h_e_f h_e_a h_e_b { cases h_e_b with the_fuel h_e_b, use (the_fuel + 1), cases h_e_f with _ h_e_f, replace h_e_f := interpC_bump_fuel h_e_f, cases h_e_a with _ h_e_a, replace h_e_a := interpC_bump_fuel h_e_a, simp only [interpC] at h_e_f h_e_a ⊢, cases_on_interp h_f : ε.nth a_f : v_f, cases_on_interp h_a : ε.nth a_a : v_a, simp only [interpC] at h_e_f h_e_a ⊢, subst_vars, simp [h_a, interpC, h_e_b], }, case var : ε' x h { use 1, generalize h' : ε'.nth_le x h = v, apply_fun some at h', simp only [← list.nth_le_nth] at h', simp [h', interpC], }, case app : ε o xs vs h_len h ih { use 1, simp only [interpC], cases h_map : mmap (λ (a : ℕ), ε.nth a) xs, case none { rcases mmap.eq_none h_map with ⟨i, hi, h_map'⟩, have hi' : i < vs.length := by { simp only [h_len] at hi, assumption }, specialize ih i hi hi', cases ih with _ ih, replace ih := interpC_bump_fuel ih, simp only at h_map', contra [interpC, h_map'] at ih, }, case some { simp only [interpC], have h_len_eq := mmap.length h_map, replace h_map := mmap.eq_some h_map, congr, apply_c list.ext_le, case hl { cc }, case h { intros i hi_a hi_v, have hi' : i < xs.length := by { simp only [← h_len] at hi_v, assumption }, specialize h_map i (by assumption) (by assumption), specialize ih i (by assumption) (by assumption), specialize h i (by assumption) (by assumption), cases ih with _ ih, replace ih := interpC_bump_fuel ih, simp only [interpC] at ih, cases_on_interp h_interp : ε.nth (xs.nth_le i hi') : v, simp only [interpC] at ih, subst_vars, simp only [h_interp] at h_map, simp [h_map], }, }, }, case let0 : ε x e_v e_b v_v r_b _ _ h_e_v h_e_b { cases h_e_v with fuel_v h_e_v, cases h_e_b with fuel_b h_e_b, use fuel_v + fuel_b + 1, simp only [ interpC, interpC_bump_large_fuel fuel_b h_e_v, ← interpC_bump_large_fuel fuel_v h_e_b ], congr' 1, linarith, }, case let0_halt : ε x e_v e_b _ _ h_e_v { cases h_e_v with fuel_v h_e_v, use fuel_v + 1, simp [interpC, h_e_v], }, case [if0_true : ε a_c e_t e_e _ _ _ h_c _ h_e_c h_e_b, if0_false : ε a_c e_t e_e _ _ _ h_c _ h_e_c h_e_b] { all_goals { cases h_e_c with _ h_e_c, cases h_e_b with fuel_b h_e_b, use fuel_b + 1, replace h_e_c := interpC_bump_fuel h_e_c, simp only [interpC] at ⊢ h_e_c, cases_on_interp h_interp : ε.nth a_c : v_c, simp only [interpC] at h_e_c, subst_vars, simp [h_e_b], }, case_c { cases v_c, focus_case bool : b { cases b, case ff { trivial }, }, all_goals { simp [interpC] }, }, case_c { simp [interpC] }, }, end end interp end interp
6dc47524c197c8d0ab06ec91872c7ccaa67eefb2
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/combinatorics/simple_graph/partition.lean
e1f70e32fbb2ab705d3388610775753fb26579ec
[ "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
5,105
lean
/- Copyright (c) 2021 Arthur Paulino. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Arthur Paulino, Kyle Miller -/ import combinatorics.simple_graph.coloring /-! # Graph partitions This module provides an interface for dealing with partitions on simple graphs. A partition of a graph `G`, with vertices `V`, is a set `P` of disjoint nonempty subsets of `V` such that: * The union of the subsets in `P` is `V`. * Each element of `P` is an independent set. (Each subset contains no pair of adjacent vertices.) Graph partitions are graph colorings that do not name their colors. They are adjoint in the following sense. Given a graph coloring, there is an associated partition from the set of color classes, and given a partition, there is an associated graph coloring from using the partition's subsets as colors. Going from graph colorings to partitions and back makes a coloring "canonical": all colors are given a canonical name and unused colors are removed. Going from partitions to graph colorings and back is the identity. ## Main definitions * `simple_graph.partition` is a structure to represent a partition of a simple graph * `simple_graph.partition.parts_card_le` is whether a given partition is an `n`-partition. (a partition with at most `n` parts). * `simple_graph.partitionable n` is whether a given graph is `n`-partite * `simple_graph.partition.to_coloring` creates colorings from partitions * `simple_graph.coloring.to_partition` creates partitions from colorings ## Main statements * `simple_graph.partitionable_iff_colorable` is that `n`-partitionability and `n`-colorability are equivalent. -/ universes u v namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- A `partition` of a simple graph `G` is a structure constituted by * `parts`: a set of subsets of the vertices `V` of `G` * `is_partition`: a proof that `parts` is a proper partition of `V` * `independent`: a proof that each element of `parts` doesn't have a pair of adjacent vertices -/ structure partition := (parts : set (set V)) (is_partition : setoid.is_partition parts) (independent : ∀ (s ∈ parts), is_antichain G.adj s) /-- Whether a partition `P` has at most `n` parts. A graph with a partition satisfying this predicate called `n`-partite. (See `simple_graph.partitionable`.) -/ def partition.parts_card_le {G : simple_graph V} (P : G.partition) (n : ℕ) : Prop := ∃ (h : P.parts.finite), h.to_finset.card ≤ n /-- Whether a graph is `n`-partite, which is whether its vertex set can be partitioned in at most `n` independent sets. -/ def partitionable (n : ℕ) : Prop := ∃ (P : G.partition), P.parts_card_le n namespace partition variables {G} (P : G.partition) /-- The part in the partition that `v` belongs to -/ def part_of_vertex (v : V) : set V := classical.some (P.is_partition.2 v) lemma part_of_vertex_mem (v : V) : P.part_of_vertex v ∈ P.parts := by { obtain ⟨h, -⟩ := (P.is_partition.2 v).some_spec.1, exact h, } lemma mem_part_of_vertex (v : V) : v ∈ P.part_of_vertex v := by { obtain ⟨⟨h1, h2⟩, h3⟩ := (P.is_partition.2 v).some_spec, exact h2.1 } lemma part_of_vertex_ne_of_adj {v w : V} (h : G.adj v w) : P.part_of_vertex v ≠ P.part_of_vertex w := begin intro hn, have hw := P.mem_part_of_vertex w, rw ←hn at hw, exact P.independent _ (P.part_of_vertex_mem v) (P.mem_part_of_vertex v) hw (G.ne_of_adj h) h, end /-- Create a coloring using the parts themselves as the colors. Each vertex is colored by the part it's contained in. -/ def to_coloring : G.coloring P.parts := coloring.mk (λ v, ⟨P.part_of_vertex v, P.part_of_vertex_mem v⟩) $ λ _ _ hvw, by { rw [ne.def, subtype.mk_eq_mk], exact P.part_of_vertex_ne_of_adj hvw } /-- Like `simple_graph.partition.to_coloring` but uses `set V` as the coloring type. -/ def to_coloring' : G.coloring (set V) := coloring.mk P.part_of_vertex $ λ _ _ hvw, P.part_of_vertex_ne_of_adj hvw lemma to_colorable [fintype P.parts] : G.colorable (fintype.card P.parts) := P.to_coloring.to_colorable end partition variables {G} /-- Creates a partition from a coloring. -/ @[simps] def coloring.to_partition {α : Type v} (C : G.coloring α) : G.partition := { parts := C.color_classes, is_partition := C.color_classes_is_partition, independent := begin rintros s ⟨c, rfl⟩, apply C.color_classes_independent, end } /-- The partition where every vertex is in its own part. -/ @[simps] instance : inhabited (partition G) := ⟨G.self_coloring.to_partition⟩ lemma partitionable_iff_colorable {n : ℕ} : G.partitionable n ↔ G.colorable n := begin split, { rintro ⟨P, hf, h⟩, haveI : fintype P.parts := hf.fintype, rw set.finite.card_to_finset at h, apply P.to_colorable.mono h, }, { rintro ⟨C⟩, refine ⟨C.to_partition, C.color_classes_finite, le_trans _ (fintype.card_fin n).le⟩, generalize_proofs h, haveI : fintype C.color_classes := C.color_classes_finite.fintype, rw h.card_to_finset, exact C.card_color_classes_le }, end end simple_graph
bf1c0d3edf2d039d58e62ebd9fd09f95f5935203
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/hom/complete_lattice.lean
872fcdd441fbfb8812f8cc66515bc2c149a6668d
[ "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
19,072
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.complete_lattice import order.hom.lattice /-! # Complete lattice homomorphisms This file defines frame homorphisms and complete lattice homomorphisms. We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. ## Types of morphisms * `Sup_hom`: Maps which preserve `⨆`. * `Inf_hom`: Maps which preserve `⨅`. * `frame_hom`: Frame homomorphisms. Maps which preserve `⨆` and `⊓`. * `complete_lattice_hom`: Complete lattice homomorphisms. Maps which preserve `⨆` and `⨅`. ## Typeclasses * `Sup_hom_class` * `Inf_hom_class` * `frame_hom_class` * `complete_lattice_hom_class` -/ open function variables {F α β γ δ : Type*} {ι : Sort*} {κ : ι → Sort*} /-- The type of `⨆`-preserving functions from `α` to `β`. -/ structure Sup_hom (α β : Type*) [has_Sup α] [has_Sup β] := (to_fun : α → β) (map_Sup' (s : set α) : to_fun (Sup s) = Sup (to_fun '' s)) /-- The type of `⨅`-preserving functions from `α` to `β`. -/ structure Inf_hom (α β : Type*) [has_Inf α] [has_Inf β] := (to_fun : α → β) (map_Inf' (s : set α) : to_fun (Inf s) = Inf (to_fun '' s)) /-- The type of frame homomorphisms from `α` to `β`. They preserve `⊓` and `⨆`. -/ structure frame_hom (α β : Type*) [complete_lattice α] [complete_lattice β] extends Sup_hom α β := (map_inf' (a b : α) : to_fun (a ⊓ b) = to_fun a ⊓ to_fun b) /-- The type of complete lattice homomorphisms from `α` to `β`. -/ structure complete_lattice_hom (α β : Type*) [complete_lattice α] [complete_lattice β] extends Sup_hom α β := (map_Inf' (s : set α) : to_fun (Inf s) = Inf (to_fun '' s)) /-- `Sup_hom_class F α β` states that `F` is a type of `⨆`-preserving morphisms. You should extend this class when you extend `Sup_hom`. -/ class Sup_hom_class (F : Type*) (α β : out_param $ Type*) [has_Sup α] [has_Sup β] extends fun_like F α (λ _, β) := (map_Sup (f : F) (s : set α) : f (Sup s) = Sup (f '' s)) /-- `Inf_hom_class F α β` states that `F` is a type of `⨅`-preserving morphisms. You should extend this class when you extend `Inf_hom`. -/ class Inf_hom_class (F : Type*) (α β : out_param $ Type*) [has_Inf α] [has_Inf β] extends fun_like F α (λ _, β) := (map_Inf (f : F) (s : set α) : f (Inf s) = Inf (f '' s)) /-- `frame_hom_class F α β` states that `F` is a type of frame morphisms. They preserve `⊓` and `⨆`. You should extend this class when you extend `frame_hom`. -/ class frame_hom_class (F : Type*) (α β : out_param $ Type*) [complete_lattice α] [complete_lattice β] extends Sup_hom_class F α β := (map_inf (f : F) (a b : α) : f (a ⊓ b) = f a ⊓ f b) /-- `complete_lattice_hom_class F α β` states that `F` is a type of complete lattice morphisms. You should extend this class when you extend `complete_lattice_hom`. -/ class complete_lattice_hom_class (F : Type*) (α β : out_param $ Type*) [complete_lattice α] [complete_lattice β] extends Sup_hom_class F α β := (map_Inf (f : F) (s : set α) : f (Inf s) = Inf (f '' s)) export Sup_hom_class (map_Sup) export Inf_hom_class (map_Inf) attribute [simp] map_Sup map_Inf lemma map_supr [has_Sup α] [has_Sup β] [Sup_hom_class F α β] (f : F) (g : ι → α) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, supr, map_Sup, set.range_comp] lemma map_supr₂ [has_Sup α] [has_Sup β] [Sup_hom_class F α β] (f : F) (g : Π i, κ i → α) : f (⨆ i j, g i j) = ⨆ i j, f (g i j) := by simp_rw map_supr lemma map_infi [has_Inf α] [has_Inf β] [Inf_hom_class F α β] (f : F) (g : ι → α) : f (⨅ i, g i) = ⨅ i, f (g i) := by rw [infi, infi, map_Inf, set.range_comp] lemma map_infi₂ [has_Inf α] [has_Inf β] [Inf_hom_class F α β] (f : F) (g : Π i, κ i → α) : f (⨅ i j, g i j) = ⨅ i j, f (g i j) := by simp_rw map_infi @[priority 100] -- See note [lower instance priority] instance Sup_hom_class.to_sup_hom_class [complete_lattice α] [complete_lattice β] [Sup_hom_class F α β] : sup_hom_class F α β := ⟨λ f a b, by rw [←Sup_pair, map_Sup, set.image_pair, Sup_pair]⟩ @[priority 100] -- See note [lower instance priority] instance Sup_hom_class.to_bot_hom_class [complete_lattice α] [complete_lattice β] [Sup_hom_class F α β] : bot_hom_class F α β := ⟨λ f, by rw [←Sup_empty, map_Sup, set.image_empty, Sup_empty]⟩ @[priority 100] -- See note [lower instance priority] instance Inf_hom_class.to_inf_hom_class [complete_lattice α] [complete_lattice β] [Inf_hom_class F α β] : inf_hom_class F α β := ⟨λ f a b, by rw [←Inf_pair, map_Inf, set.image_pair, Inf_pair]⟩ @[priority 100] -- See note [lower instance priority] instance Inf_hom_class.to_top_hom_class [complete_lattice α] [complete_lattice β] [Inf_hom_class F α β] : top_hom_class F α β := ⟨λ f, by rw [←Inf_empty, map_Inf, set.image_empty, Inf_empty]⟩ @[priority 100] -- See note [lower instance priority] instance frame_hom_class.to_lattice_hom_class [complete_lattice α] [complete_lattice β] [frame_hom_class F α β] : lattice_hom_class F α β := { .. ‹frame_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance complete_lattice_hom_class.to_Inf_hom_class [complete_lattice α] [complete_lattice β] [complete_lattice_hom_class F α β] : Inf_hom_class F α β := { .. ‹complete_lattice_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance complete_lattice_hom_class.to_frame_hom_class [complete_lattice α] [complete_lattice β] [complete_lattice_hom_class F α β] : frame_hom_class F α β := { .. ‹complete_lattice_hom_class F α β›, ..Inf_hom_class.to_inf_hom_class } @[priority 100] -- See note [lower instance priority] instance complete_lattice_hom_class.to_bounded_lattice_hom_class [complete_lattice α] [complete_lattice β] [complete_lattice_hom_class F α β] : bounded_lattice_hom_class F α β := { ..Sup_hom_class.to_bot_hom_class, ..Inf_hom_class.to_top_hom_class } instance [has_Sup α] [has_Sup β] [Sup_hom_class F α β] : has_coe_t F (Sup_hom α β) := ⟨λ f, ⟨f, map_Sup f⟩⟩ instance [has_Inf α] [has_Inf β] [Inf_hom_class F α β] : has_coe_t F (Inf_hom α β) := ⟨λ f, ⟨f, map_Inf f⟩⟩ instance [complete_lattice α] [complete_lattice β] [frame_hom_class F α β] : has_coe_t F (frame_hom α β) := ⟨λ f, { to_fun := f, map_Sup' := map_Sup f, map_inf' := map_inf f }⟩ instance [complete_lattice α] [complete_lattice β] [complete_lattice_hom_class F α β] : has_coe_t F (complete_lattice_hom α β) := ⟨λ f, { to_fun := f, map_Sup' := map_Sup f, map_Inf' := map_Inf f }⟩ /-! ### Supremum homomorphisms -/ namespace Sup_hom variables [has_Sup α] section has_Sup variables [has_Sup β] [has_Sup γ] [has_Sup δ] instance : Sup_hom_class (Sup_hom α β) α β := { coe := Sup_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_Sup := Sup_hom.map_Sup' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (Sup_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : Sup_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : Sup_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `Sup_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : Sup_hom α β) (f' : α → β) (h : f' = f) : Sup_hom α β := { to_fun := f', map_Sup' := h.symm ▸ f.map_Sup' } variables (α) /-- `id` as a `Sup_hom`. -/ protected def id : Sup_hom α α := ⟨id, λ s, by rw [id, set.image_id]⟩ instance : inhabited (Sup_hom α α) := ⟨Sup_hom.id α⟩ @[simp] lemma coe_id : ⇑(Sup_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : Sup_hom.id α a = a := rfl /-- Composition of `Sup_hom`s as a `Sup_hom`. -/ def comp (f : Sup_hom β γ) (g : Sup_hom α β) : Sup_hom α γ := { to_fun := f ∘ g, map_Sup' := λ s, by rw [comp_apply, map_Sup, map_Sup, set.image_image] } @[simp] lemma coe_comp (f : Sup_hom β γ) (g : Sup_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : Sup_hom β γ) (g : Sup_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : Sup_hom γ δ) (g : Sup_hom β γ) (h : Sup_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : Sup_hom α β) : f.comp (Sup_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : Sup_hom α β) : (Sup_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : Sup_hom β γ} {f : Sup_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : Sup_hom β γ} {f₁ f₂ : Sup_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end has_Sup variables [complete_lattice β] instance : partial_order (Sup_hom α β) := partial_order.lift _ fun_like.coe_injective instance : has_bot (Sup_hom α β) := ⟨⟨λ _, ⊥, λ s, begin obtain rfl | hs := s.eq_empty_or_nonempty, { rw [set.image_empty, Sup_empty] }, { rw [hs.image_const, Sup_singleton] } end⟩⟩ instance : order_bot (Sup_hom α β) := ⟨⊥, λ f a, bot_le⟩ @[simp] lemma coe_bot : ⇑(⊥ : Sup_hom α β) = ⊥ := rfl @[simp] lemma bot_apply (a : α) : (⊥ : Sup_hom α β) a = ⊥ := rfl end Sup_hom /-! ### Infimum homomorphisms -/ namespace Inf_hom variables [has_Inf α] section has_Inf variables [has_Inf β] [has_Inf γ] [has_Inf δ] instance : Inf_hom_class (Inf_hom α β) α β := { coe := Inf_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_Inf := Inf_hom.map_Inf' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (Inf_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : Inf_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : Inf_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `Inf_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : Inf_hom α β) (f' : α → β) (h : f' = f) : Inf_hom α β := { to_fun := f', map_Inf' := h.symm ▸ f.map_Inf' } variables (α) /-- `id` as an `Inf_hom`. -/ protected def id : Inf_hom α α := ⟨id, λ s, by rw [id, set.image_id]⟩ instance : inhabited (Inf_hom α α) := ⟨Inf_hom.id α⟩ @[simp] lemma coe_id : ⇑(Inf_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : Inf_hom.id α a = a := rfl /-- Composition of `Inf_hom`s as a `Inf_hom`. -/ def comp (f : Inf_hom β γ) (g : Inf_hom α β) : Inf_hom α γ := { to_fun := f ∘ g, map_Inf' := λ s, by rw [comp_apply, map_Inf, map_Inf, set.image_image] } @[simp] lemma coe_comp (f : Inf_hom β γ) (g : Inf_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : Inf_hom β γ) (g : Inf_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : Inf_hom γ δ) (g : Inf_hom β γ) (h : Inf_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : Inf_hom α β) : f.comp (Inf_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : Inf_hom α β) : (Inf_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : Inf_hom β γ} {f : Inf_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : Inf_hom β γ} {f₁ f₂ : Inf_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end has_Inf variables [complete_lattice β] instance : partial_order (Inf_hom α β) := partial_order.lift _ fun_like.coe_injective instance : has_top (Inf_hom α β) := ⟨⟨λ _, ⊤, λ s, begin obtain rfl | hs := s.eq_empty_or_nonempty, { rw [set.image_empty, Inf_empty] }, { rw [hs.image_const, Inf_singleton] } end⟩⟩ instance : order_top (Inf_hom α β) := ⟨⊤, λ f a, le_top⟩ @[simp] lemma coe_top : ⇑(⊤ : Inf_hom α β) = ⊤ := rfl @[simp] lemma top_apply (a : α) : (⊤ : Inf_hom α β) a = ⊤ := rfl end Inf_hom /-! ### Frame homomorphisms -/ namespace frame_hom variables [complete_lattice α] [complete_lattice β] [complete_lattice γ] [complete_lattice δ] instance : frame_hom_class (frame_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr', map_Sup := λ f, f.map_Sup', map_inf := λ f, f.map_inf' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (frame_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ /-- Reinterpret a `frame_hom` as a `lattice_hom`. -/ def to_lattice_hom (f : frame_hom α β) : lattice_hom α β := { to_fun := f, map_sup' := λ a b, by rw [←Sup_pair, map_Sup, set.image_pair, Sup_pair], ..f } @[simp] lemma to_fun_eq_coe {f : frame_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : frame_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `frame_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : frame_hom α β) (f' : α → β) (h : f' = f) : frame_hom α β := { .. f.to_Sup_hom.copy f' h, .. f.to_lattice_hom.copy f' h } variables (α) /-- `id` as a `frame_hom`. -/ protected def id : frame_hom α α := { ..Sup_hom.id α, ..inf_hom.id α } instance : inhabited (frame_hom α α) := ⟨frame_hom.id α⟩ @[simp] lemma coe_id : ⇑(frame_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : frame_hom.id α a = a := rfl /-- Composition of `frame_hom`s as a `frame_hom`. -/ def comp (f : frame_hom β γ) (g : frame_hom α β) : frame_hom α γ := { ..f.to_Sup_hom.comp g.to_Sup_hom, ..f.to_lattice_hom.comp g.to_lattice_hom } @[simp] lemma coe_comp (f : frame_hom β γ) (g : frame_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : frame_hom β γ) (g : frame_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : frame_hom γ δ) (g : frame_hom β γ) (h : frame_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : frame_hom α β) : f.comp (frame_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : frame_hom α β) : (frame_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : frame_hom β γ} {f : frame_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : frame_hom β γ} {f₁ f₂ : frame_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ instance : partial_order (frame_hom α β) := partial_order.lift _ fun_like.coe_injective instance : has_bot (frame_hom α β) := ⟨{ .. (inf_hom.const _ _), .. (⊥ : Sup_hom α β) }⟩ instance : order_bot (frame_hom α β) := ⟨⊥, λ f a, bot_le⟩ @[simp] lemma coe_bot : ⇑(⊥ : frame_hom α β) = ⊥ := rfl @[simp] lemma bot_apply (a : α) : (⊥ : frame_hom α β) a = ⊥ := rfl end frame_hom /-! ### Complete lattice homomorphisms -/ namespace complete_lattice_hom variables [complete_lattice α] [complete_lattice β] [complete_lattice γ] [complete_lattice δ] /-- Reinterpret a `complete_lattice_hom` as an `Inf_hom`. -/ def to_Inf_hom (f : complete_lattice_hom α β) : Inf_hom α β := { ..f } instance : complete_lattice_hom_class (complete_lattice_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr', map_Sup := λ f, f.map_Sup', map_Inf := λ f, f.map_Inf' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (complete_lattice_hom α β) (λ _, α → β) := ⟨λ f, f.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : complete_lattice_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : complete_lattice_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `complete_lattice_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : complete_lattice_hom α β) (f' : α → β) (h : f' = f) : complete_lattice_hom α β := { .. f.to_Sup_hom.copy f' h, .. f.to_Inf_hom.copy f' h } variables (α) /-- `id` as a `complete_lattice_hom`. -/ protected def id : complete_lattice_hom α α := { to_fun := id, ..Sup_hom.id α, ..Inf_hom.id α } instance : inhabited (complete_lattice_hom α α) := ⟨complete_lattice_hom.id α⟩ @[simp] lemma coe_id : ⇑(complete_lattice_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : complete_lattice_hom.id α a = a := rfl /-- Composition of `complete_lattice_hom`s as a `complete_lattice_hom`. -/ def comp (f : complete_lattice_hom β γ) (g : complete_lattice_hom α β) : complete_lattice_hom α γ := { ..f.to_Sup_hom.comp g.to_Sup_hom, ..f.to_Inf_hom.comp g.to_Inf_hom } @[simp] lemma coe_comp (f : complete_lattice_hom β γ) (g : complete_lattice_hom α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : complete_lattice_hom β γ) (g : complete_lattice_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : complete_lattice_hom γ δ) (g : complete_lattice_hom β γ) (h : complete_lattice_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : complete_lattice_hom α β) : f.comp (complete_lattice_hom.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : complete_lattice_hom α β) : (complete_lattice_hom.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : complete_lattice_hom β γ} {f : complete_lattice_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : complete_lattice_hom β γ} {f₁ f₂ : complete_lattice_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end complete_lattice_hom
5754803d12f026e040f463185e130f8dca70b9fd
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/123-1.lean
02988530129745b351e322d8694b43d30e1f0f58
[ "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
898
lean
/-- notation typeclass not in core. -/ class has_scalar (G : Type) (V : Type) := (smul : G → V → V) infixr ` • `:73 := has_scalar.smul structure Ring : Type. instance : has_coe_to_sort Ring Type := ⟨λ R, unit⟩ variables {G : Type} [has_mul G] {R : Ring} class distrib_mul_action' (G : Type) (V : Type) [has_mul G] extends has_scalar G V := (foo : ∀ (x y : G) (b : V), x • b = x • y • b) -- note that changing x • y • b to y • b fixes the violation -- and instead we get a different error. structure finsupp' (β : Type) : Type := (to_fun : β → β) def mas (r : R) : finsupp' ↥R := { to_fun := id, } variables (V : Type) instance foo : distrib_mul_action' G V := { smul := λ g v, (mas ()) • v, -- note that changing () to 37 also causes an assertion violation foo := λ g g' v, sorry }
5098c14bc3f6c2ed8afc86a061283e709dcf0520
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/rat/cast.lean
bf1b55d6fa78d47b4b8ac458c3e2e45e077e2c7f
[ "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
11,417
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.rat.order /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ namespace rat variable {α : Type*} open_locale rat section with_div_ring variable [division_ring α] /-- Construct the canonical injection from `ℚ` into an arbitrary division ring. If the field has positive characteristic `p`, we define `1 / p = 1 / 0 = 0` for consistency with our division by zero convention. -/ @[priority 10] instance cast_coe : has_coe ℚ α := ⟨λ r, r.1 / r.2⟩ @[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n := show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one] @[simp, squash_cast] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n := by rw [coe_int_eq_of_int, cast_of_int] @[simp, squash_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n @[simp, squash_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_of_int _).trans int.cast_zero @[simp, squash_cast] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_of_int _).trans int.cast_one theorem mul_cast_comm (a : α) : ∀ (n : ℚ), a * n = n * a | ⟨n, d, h, c⟩ := show a * (n * d⁻¹) = n * d⁻¹ * a, by rw [← mul_assoc, int.mul_cast_comm, mul_assoc, mul_assoc, ← show (d:α)⁻¹ * a = a * d⁻¹, from inv_comm_of_comm' (int.mul_cast_comm a d).symm] @[move_cast] theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b:α) ≠ 0) : (a /. b : α) = a / b := begin have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} }, cases e : a /. b with n d h c, have d0 : (d:α) ≠ 0, { intro d0, have dd := denom_dvd a b, cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke, have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl}, rw [d0, zero_mul] at this, contradiction }, rw [num_denom'] at e, have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e), rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this, symmetry, change (a * b⁻¹ : α) = n / d, rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, nat.mul_cast_comm, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] end @[move_cast] theorem cast_add_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', add_def d₁0' d₂0'], suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) + n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹, { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, left_distrib, right_distrib, mul_inv', d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul, ← nat.mul_cast_comm], simp [d₁0, mul_assoc] end @[simp, move_cast] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n | ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹), by rw [int.cast_neg, neg_mul_eq_neg_mul] @[move_cast] theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n := have ((-n).denom : α) ≠ 0, by cases n; exact n0, by simp [sub_eq_add_neg, (cast_add_of_ne_zero m0 this)] @[move_cast] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', mul_def d₁0' d₂0'], suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)), { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, mul_inv', d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [inv_comm_of_comm'], exact (nat.mul_cast_comm _ _).symm end @[move_cast] theorem cast_inv_of_ne_zero : ∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹ | ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl, have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl), rw [num_denom', inv_def], rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div]; simp [n0, d0] end @[move_cast] theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0) (nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := have (n⁻¹.denom : ℤ) ∣ n.num, by conv in n⁻¹.denom { rw [←(@num_denom n), inv_def] }; apply denom_dvd, have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from λ h, let ⟨k, e⟩ := this in by have := congr_arg (coe : ℤ → α) e; rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this, by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] @[simp, elim_cast] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin refine ⟨λ h, _, congr_arg _⟩, have d₁0 : d₁ ≠ 0 := ne_of_gt h₁, have d₂0 : d₂ ≠ 0 := ne_of_gt h₂, have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0, have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0, rw [num_denom', num_denom'] at h ⊢, rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢, rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc, inv_comm_of_comm', ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h, exact (nat.mul_cast_comm _ _) end theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero theorem eq_cast_of_ne_zero (f : ℚ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (Hmul : ∀ x y, f (x * y) = f x * f y) : ∀ n : ℚ, (n.denom : α) ≠ 0 → f n = n | ⟨n, d, h, c⟩ := λ (h₂ : ((d:ℤ):α) ≠ 0), show _ = (n / (d:ℤ) : α), begin rw [num_denom', mk_eq_div, eq_div_iff_mul_eq _ _ h₂], have : ∀ n : ℤ, f n = n, { apply int.eq_cast; simp [H1, Hadd] }, rw [← this, ← this, ← Hmul, div_mul_cancel], exact int.cast_ne_zero.2 (int.coe_nat_ne_zero.2 $ ne_of_gt h), end theorem eq_cast [char_zero α] (f : ℚ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (Hmul : ∀ x y, f (x * y) = f x * f y) (n : ℚ) : f n = n := eq_cast_of_ne_zero _ H1 Hadd Hmul _ $ nat.cast_ne_zero.2 $ ne_of_gt n.pos @[simp, move_cast] theorem cast_add [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, move_cast] theorem cast_sub [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, move_cast] theorem cast_mul [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, squash_cast, move_cast] theorem cast_bit0 [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _ @[simp, squash_cast, move_cast] theorem cast_bit1 [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl variable (α) /-- Coercion `ℚ → α` as a `ring_hom`. -/ def cast_hom [char_zero α] : ℚ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ variable {α} @[simp] lemma coe_cast_hom [char_zero α] : ⇑(cast_hom α) = coe := rfl @[simp, move_cast] theorem cast_inv [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ := (cast_hom α).map_inv @[simp, move_cast] theorem cast_div [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n := (cast_hom α).map_div @[move_cast] theorem cast_mk [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b := by simp only [mk_eq_div, cast_div, cast_coe_int] @[simp, move_cast] theorem cast_pow [char_zero α] (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k := (cast_hom α).map_pow q k end with_div_ring @[simp, elim_cast] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n | ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ), by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h), mul_nonneg_iff_right_nonneg_of_pos ((@inv_pos α _ _).2 (nat.cast_pos.2 h)), int.cast_nonneg] @[simp, elim_cast] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, elim_cast] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, squash_cast] theorem cast_id : ∀ n : ℚ, ↑n = n | ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div] @[simp, move_cast] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, move_cast] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, move_cast] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q := by simp [abs] end rat
e32d49e00e613827dbc4002cbb4520e52b0ad05b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/rat/order.lean
2157df0da1cf0082f1fc18e9fbf8ce9d48b01983
[ "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
8,207
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import algebra.order.field import data.rat.basic /-! # Order for Rational Numbers ## Summary We define the order on `ℚ`, prove that `ℚ` is a discrete, linearly ordered field, and define functions such as `abs` and `sqrt` that depend on this order. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, order, ordering, sqrt, abs -/ namespace rat variables (a b c : ℚ) open_locale rat /-- A rational number is called nonnegative if its numerator is nonnegative. -/ protected def nonneg (r : ℚ) : Prop := 0 ≤ r.num @[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : 0 < b) : (a /. b).nonneg ↔ 0 ≤ a := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, simp [rat.nonneg], have d0 := int.coe_nat_lt.2 h₁, have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha, constructor; intro h₂, { apply nonneg_of_mul_nonneg_left _ d0, rw this, exact mul_nonneg h₂ (le_of_lt h) }, { apply nonneg_of_mul_nonneg_left _ h, rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) }, end protected lemma nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : 0 < (d₁:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : 0 < (d₂:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], intros n₁0 n₂0, apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le}, end protected lemma nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : 0 < (d₁:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : 0 < (d₂:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0, mul_nonneg] { contextual := tt } end protected lemma nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 := num_denom_cases_on' a $ λ n d h, begin have d0 : 0 < (d:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h), simp [d0, h], exact λ h₁ h₂, le_antisymm h₂ h₁ end protected lemma nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) := by cases a with n; exact or.imp_right neg_nonneg_of_nonpos (le_total 0 n) instance decidable_nonneg : decidable (rat.nonneg a) := by cases a; unfold rat.nonneg; apply_instance /-- Relation `a ≤ b` on `ℚ` defined as `a ≤ b ↔ rat.nonneg (b - a)`. Use `a ≤ b` instead of `rat.le a b`. -/ protected def le (a b : ℚ) := rat.nonneg (b - a) instance : has_le ℚ := ⟨rat.le⟩ instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop) | a b := show decidable (rat.nonneg (b - a)), by apply_instance protected theorem le_def {a b c d : ℤ} (b0 : 0 < b) (d0 : 0 < d) : a /. b ≤ c /. d ↔ a * d ≤ c * b := begin show rat.nonneg _ ↔ _, rw ← sub_nonneg, simp [sub_eq_add_neg, ne_of_gt b0, ne_of_gt d0, mul_pos d0 b0] end protected theorem le_refl : a ≤ a := show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ) protected theorem le_total : a ≤ b ∨ b ≤ a := by have := rat.nonneg_total (b - a); rwa neg_sub at this protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b := by { have := eq_neg_of_add_eq_zero_left (rat.nonneg_antisymm hba $ by rwa [← sub_eq_add_neg, neg_sub]), rwa neg_neg at this } protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc, by simpa [sub_eq_add_neg, add_comm, add_left_comm] instance : linear_order ℚ := { le := rat.le, le_refl := rat.le_refl, le_trans := @rat.le_trans, le_antisymm := @rat.le_antisymm, le_total := rat.le_total, decidable_eq := by apply_instance, decidable_le := assume a b, rat.decidable_nonneg (b - a) } /- Extra instances to short-circuit type class resolution -/ instance : has_lt ℚ := by apply_instance instance : distrib_lattice ℚ := by apply_instance instance : lattice ℚ := by apply_instance instance : semilattice_inf ℚ := by apply_instance instance : semilattice_sup ℚ := by apply_instance instance : has_inf ℚ := by apply_instance instance : has_sup ℚ := by apply_instance instance : partial_order ℚ := by apply_instance instance : preorder ℚ := by apply_instance protected lemma le_def' {p q : ℚ} : p ≤ q ↔ p.num * q.denom ≤ q.num * p.denom := begin rw [←(@num_denom q), ←(@num_denom p)], conv_rhs { simp only [num_denom] }, exact rat.le_def (by exact_mod_cast p.pos) (by exact_mod_cast q.pos) end protected lemma lt_def {p q : ℚ} : p < q ↔ p.num * q.denom < q.num * p.denom := begin rw [lt_iff_le_and_ne, rat.le_def'], suffices : p ≠ q ↔ p.num * q.denom ≠ q.num * p.denom, by { split; intro h, { exact lt_iff_le_and_ne.elim_right ⟨h.left, (this.elim_left h.right)⟩ }, { have tmp := lt_iff_le_and_ne.elim_left h, exact ⟨tmp.left, this.elim_right tmp.right⟩ }}, exact (not_iff_not.elim_right eq_iff_mul_eq_mul) end theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a := show rat.nonneg a ↔ rat.nonneg (a - 0), by simp theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a | ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩ protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b := by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb instance : linear_ordered_field ℚ := { zero_le_one := dec_trivial, add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab, mul_pos := assume a b ha hb, lt_of_le_of_ne (rat.mul_nonneg (le_of_lt ha) (le_of_lt hb)) (mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm, ..rat.field, ..rat.linear_order, ..rat.semiring } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_comm_ring ℚ := by apply_instance instance : linear_ordered_ring ℚ := by apply_instance instance : ordered_ring ℚ := by apply_instance instance : linear_ordered_semiring ℚ := by apply_instance instance : ordered_semiring ℚ := by apply_instance instance : linear_ordered_add_comm_group ℚ := by apply_instance instance : ordered_add_comm_group ℚ := by apply_instance instance : ordered_cancel_add_comm_monoid ℚ := by apply_instance instance : ordered_add_comm_monoid ℚ := by apply_instance attribute [irreducible] rat.le theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a := lt_iff_lt_of_le_iff_le $ by simpa [(by cases a; refl : (-a).num = -a.num)] using @num_nonneg_iff_zero_le (-a) lemma div_lt_div_iff_mul_lt_mul {a b c d : ℤ} (b_pos : 0 < b) (d_pos : 0 < d) : (a : ℚ) / b < c / d ↔ a * d < c * b := begin simp only [lt_iff_le_not_le], apply and_congr, { simp [div_num_denom, (rat.le_def b_pos d_pos)] }, { apply not_iff_not_of_iff, simp [div_num_denom, (rat.le_def d_pos b_pos)] } end lemma lt_one_iff_num_lt_denom {q : ℚ} : q < 1 ↔ q.num < q.denom := by simp [rat.lt_def] theorem abs_def (q : ℚ) : |q| = q.num.nat_abs /. q.denom := begin cases le_total q 0 with hq hq, { rw [abs_of_nonpos hq], rw [←(@num_denom q), ← mk_zero_one, rat.le_def (int.coe_nat_pos.2 q.pos) zero_lt_one, mul_one, zero_mul] at hq, rw [int.of_nat_nat_abs_of_nonpos hq, ← neg_def, num_denom] }, { rw [abs_of_nonneg hq], rw [←(@num_denom q), ← mk_zero_one, rat.le_def zero_lt_one (int.coe_nat_pos.2 q.pos), mul_one, zero_mul] at hq, rw [int.nat_abs_of_nonneg hq, num_denom] } end end rat
684b3b1bea4049a306d86389cc2d28018b25bd3f
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/linear_algebra/dual.lean
75d34abe35868c1760da8c1e550e06280f0118d7
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
6,316
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Fabian Glöckle Dual vector spaces, the spaces of linear functionals to the base field, including the dual basis isomorphism and evaluation isomorphism in the finite-dimensional case. -/ import linear_algebra.dimension import linear_algebra.tensor_product noncomputable theory namespace module variables (R : Type*) (M : Type*) variables [comm_ring R] [add_comm_group M] [module R M] @[derive [add_comm_group, module R]] def dual := M →ₗ[R] R namespace dual instance : has_coe_to_fun (dual R M) := ⟨_, linear_map.to_fun⟩ def eval : M →ₗ[R] (dual R (dual R M)) := linear_map.id.flip lemma eval_apply (v : M) (a : dual R M) : (eval R M v) a = a v := begin dunfold eval, rw [linear_map.flip_apply, linear_map.id_apply] end end dual end module namespace is_basis universes u v w variables {K : Type u} {V : Type v} {ι : Type w} variables [discrete_field K] [add_comm_group V] [vector_space K V] open vector_space module module.dual submodule linear_map cardinal function instance dual.vector_space : vector_space K (dual K V) := { ..module.dual.inst K V } variables [decidable_eq ι] variables {B : ι → V} (h : is_basis K B) include h def to_dual : V →ₗ[K] module.dual K V := h.constr $ λ v, h.constr $ λ w, if w = v then 1 else 0 lemma to_dual_apply (i j : ι) : (h.to_dual (B i)) (B j) = if i = j then 1 else 0 := by erw [constr_basis h, constr_basis h]; ac_refl def to_dual_flip (v : V) : (V →ₗ[K] K) := (linear_map.flip h.to_dual).to_fun v omit h def eval_finsupp_at (i : ι) : (ι →₀ K) →ₗ[K] K := { to_fun := λ f, f i, add := by intros; rw finsupp.add_apply, smul := by intros; rw finsupp.smul_apply } include h set_option class.instance_max_depth 50 def coord_fun (i : ι) : (V →ₗ[K] K) := (eval_finsupp_at i).comp h.repr lemma coord_fun_eq_repr (v : V) (i : ι) : h.coord_fun i v = h.repr v i := rfl lemma to_dual_swap_eq_to_dual (v w : V) : h.to_dual_flip v w = h.to_dual w v := rfl lemma to_dual_eq_repr (v : V) (i : ι) : (h.to_dual v) (B i) = h.repr v i := begin rw [←coord_fun_eq_repr, ←to_dual_swap_eq_to_dual], apply congr_fun, dsimp, congr', apply h.ext, { intros, rw [to_dual_swap_eq_to_dual, to_dual_apply], { split_ifs with hx, { rwa [hx, coord_fun_eq_repr, repr_eq_single, finsupp.single_apply, if_pos rfl] }, { rw [coord_fun_eq_repr, repr_eq_single, finsupp.single_apply], symmetry, convert if_neg hx } } } end lemma to_dual_inj (v : V) (a : h.to_dual v = 0) : v = 0 := begin rw [← mem_bot K, ← h.repr_ker, mem_ker], apply finsupp.ext, intro b, rw [←to_dual_eq_repr _ _ _, a], refl end theorem to_dual_ker : h.to_dual.ker = ⊥ := ker_eq_bot'.mpr h.to_dual_inj theorem to_dual_range [fin : fintype ι] : h.to_dual.range = ⊤ := begin rw eq_top_iff', intro f, rw linear_map.mem_range, let lin_comb : ι →₀ K := finsupp.on_finset fin.elems (λ i, f.to_fun (B i)) _, --let emb := embedding.subtype B, { use finsupp.total ι V K B lin_comb, apply h.ext, { intros i, rw [h.to_dual_eq_repr _ i, repr_total h], { simpa }, { rw [finsupp.mem_supported], exact λ _ _, set.mem_univ _ } } }, { intros a _, apply fin.complete } end def dual_basis : ι → dual K V := λ i, h.to_dual (B i) theorem dual_lin_independent : linear_independent K h.dual_basis := begin apply linear_independent.image h.1, rw to_dual_ker, exact disjoint_bot_right end def to_dual_equiv [fintype ι] : V ≃ₗ[K] (dual K V) := linear_equiv.of_bijective h.to_dual h.to_dual_ker h.to_dual_range theorem dual_basis_is_basis [fintype ι] : is_basis K h.dual_basis := h.to_dual_equiv.is_basis h @[simp] lemma to_dual_to_dual [decidable_eq (dual K (dual K V))] [fintype ι] : (h.dual_basis_is_basis.to_dual).comp h.to_dual = eval K V := begin apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ h, intros i, apply @is_basis.ext _ _ _ _ _ _ _ _ _ _ _ _ h.dual_basis_is_basis, intros j, dunfold eval, rw [linear_map.flip_apply, linear_map.id_apply, linear_map.comp_apply], apply eq.trans (to_dual_apply h.dual_basis_is_basis i j), { dunfold dual_basis, rw to_dual_apply, split_ifs with h₁ h₂; try {refl}, { exfalso, apply h₂ h₁.symm }, { exfalso, apply ne.symm h₁ (by assumption) } } end theorem dual_dim_eq [fintype ι] : cardinal.lift.{v u} (dim K V) = dim K (dual K V) := begin have := linear_equiv.dim_eq_lift h.to_dual_equiv, simp only [cardinal.lift_umax] at this, rw [this, ← cardinal.lift_umax], apply cardinal.lift_id, end end is_basis namespace vector_space universes u v variables {K : Type u} {V : Type v} variables [discrete_field K] [add_comm_group V] [vector_space K V] open module module.dual submodule linear_map cardinal is_basis theorem eval_ker : (eval K V).ker = ⊥ := begin haveI := classical.dec_eq K, haveI := classical.dec_eq V, haveI := classical.dec_eq (dual K V), rw ker_eq_bot', intros v h, rw linear_map.ext_iff at h, by_contradiction H, rcases exists_subset_is_basis (linear_independent_singleton H) with ⟨b, hv, hb⟩, swap 4, assumption, have hv' : v = (λ (i : b), i.val) ⟨v, hv (set.mem_singleton v)⟩ := rfl, let hx := h (hb.to_dual v), erw [eval_apply, hv', to_dual_apply, if_pos rfl, zero_apply _] at hx, exact one_ne_zero hx end theorem dual_dim_eq (h : dim K V < omega) : cardinal.lift.{v u} (dim K V) = dim K (dual K V) := begin letI := classical.dec_eq (dual K V), letI := classical.dec_eq V, rcases exists_is_basis_fintype h with ⟨b, hb, ⟨hf⟩⟩, resetI, exact hb.dual_dim_eq end set_option class.instance_max_depth 70 lemma eval_range (h : dim K V < omega) : (eval K V).range = ⊤ := begin haveI := classical.dec_eq (dual K V), haveI := classical.dec_eq (dual K (dual K V)), letI := classical.dec_eq V, rcases exists_is_basis_fintype h with ⟨b, hb, ⟨hf⟩⟩, resetI, rw [← hb.to_dual_to_dual, range_comp, hb.to_dual_range, map_top, to_dual_range _], apply_instance end def eval_equiv (h : dim K V < omega) : V ≃ₗ[K] dual K (dual K V) := linear_equiv.of_bijective (eval K V) eval_ker (eval_range h) end vector_space
c763337bde33e79722baa313af2ad688f6df2bb8
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/topology/constructions.lean
43655cf79dd8255840351945fce30598b621946e
[ "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
30,225
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.maps /-! # Constructions of new topological spaces from old ones This file constructs products, sums, subtypes and quotients of topological spaces and sets up their basic theory, such as criteria for maps into or out of these constructions to be continuous; descriptions of the open sets, neighborhood filters, and generators of these constructions; and their behavior with respect to embeddings and other specific classes of maps. ## Implementation note The constructed topologies are defined using induced and coinduced topologies along with the complete lattice structure on topologies. Their universal properties (for example, a map `X → Y × Z` is continuous if and only if both projections `X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of continuity. With more work we can also extract descriptions of the open sets, neighborhood filters and so on. ## Tags product, sum, disjoint union, subspace, quotient space -/ noncomputable theory open topological_space set filter open_locale classical topological_space universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} section constructions instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) := induced coe t instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) := coinduced (quot.mk r) t instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) := coinduced quotient.mk t instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) := induced prod.fst t₁ ⊓ induced prod.snd t₂ instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) := coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂ instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) := ⨆a, coinduced (sigma.mk a) (t₂ a) instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (Πa, β a) := ⨅a, induced (λf, f a) (t₂ a) lemma quotient_dense_of_dense [setoid α] [topological_space α] {s : set α} (H : ∀ x, x ∈ closure s) : closure (quotient.mk '' s) = univ := eq_univ_of_forall $ λ x, begin rw mem_closure_iff, intros U U_op x_in_U, let V := quotient.mk ⁻¹' U, cases quotient.exists_rep x with y y_x, have y_in_V : y ∈ V, by simp only [mem_preimage, y_x, x_in_U], have V_op : is_open V := U_op, obtain ⟨w, w_in_V, w_in_range⟩ : (V ∩ s).nonempty := mem_closure_iff.1 (H y) V V_op y_in_V, exact ⟨_, w_in_V, mem_image_of_mem quotient.mk w_in_range⟩ end instance {p : α → Prop} [topological_space α] [discrete_topology α] : discrete_topology (subtype p) := ⟨bot_unique $ assume s hs, ⟨subtype.val '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.val_injective)⟩⟩ instance sum.discrete_topology [topological_space α] [topological_space β] [hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) := ⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩ instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)] [h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) := ⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩ section topα variable [topological_space α] /- The 𝓝 filter and the subspace topology. -/ theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 a.val, (@subtype.val α s) ⁻¹' u ⊆ t := mem_nhds_induced subtype.val a t theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) : 𝓝 a = comap subtype.val (𝓝 a.val) := nhds_induced subtype.val a end topα end constructions section prod open topological_space variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] lemma continuous_fst : continuous (@prod.fst α β) := continuous_inf_dom_left continuous_induced_dom lemma continuous_snd : continuous (@prod.snd α β) := continuous_inf_dom_right continuous_induced_dom lemma continuous.prod_mk {f : γ → α} {g : γ → β} (hf : continuous f) (hg : continuous g) : continuous (λx, prod.mk (f x) (g x)) := continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg) lemma continuous_swap : continuous (prod.swap : α × β → β × α) := continuous.prod_mk continuous_snd continuous_fst lemma is_open_prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) : is_open (set.prod s t) := is_open_inter (continuous_fst s hs) (continuous_snd t ht) lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = filter.prod (𝓝 a) (𝓝 b) := by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced] instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) := ⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩, by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩ lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β} (ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) := by rw [nhds_prod_eq]; exact prod_mem_prod ha hb lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap := by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β} (ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) : tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) := by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x := hf.prod_mk_nhds hg lemma prod_generate_from_generate_from_eq {α : Type*} {β : Type*} {s : set (set α)} {t : set (set β)} (hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) : @prod.topological_space α β (generate_from s) (generate_from t) = generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} := let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in le_antisymm (le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸ @is_open_prod _ _ (generate_from s) (generate_from t) _ _ (generate_open.basic _ hu) (generate_open.basic _ hv)) (le_inf (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu, have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u, from calc (⋃v∈t, set.prod u v) = set.prod u univ : set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt} ... = prod.fst ⁻¹' u : by simp [set.prod, preimage], show G.is_open (prod.fst ⁻¹' u), from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩) (coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv, have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v, from calc (⋃u∈s, set.prod u v) = set.prod univ v: set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt} ... = prod.snd ⁻¹' v : by simp [set.prod, preimage], show G.is_open (prod.snd ⁻¹' v), from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu, generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)) lemma prod_eq_generate_from : prod.topological_space = generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} := le_antisymm (le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ is_open_prod hs ht) (le_inf (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩) (ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩)) lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔ (∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) := begin rw [is_open_iff_nhds], simp [nhds_prod_eq, mem_prod_iff], simp [mem_nhds_sets_iff], exact forall_congr (assume a, ball_congr $ assume b h, ⟨assume ⟨u', ⟨u, us, uo, au⟩, v', ⟨v, vs, vo, bv⟩, h⟩, ⟨u, uo, v, vo, au, bv, subset.trans (set.prod_mono us vs) h⟩, assume ⟨u, uo, v, vo, au, bv, h⟩, ⟨u, ⟨u, subset.refl u, uo, au⟩, v, ⟨v, subset.refl v, vo, bv⟩, h⟩⟩) end /-- The first projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_fst : is_open_map (@prod.fst α β) := begin assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₁, refine ⟨o₁, _, o₁_open, yo₁⟩, assume z zs, rw mem_image_eq, exact ⟨(z, y₂), ho (by simp [zs, yo₂]), rfl⟩ end /-- The second projection in a product of topological spaces sends open sets to open sets. -/ lemma is_open_map_snd : is_open_map (@prod.snd α β) := begin /- This lemma could be proved by composing the fact that the first projection is open, and exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/ assume s hs, rw is_open_iff_forall_mem_open, assume x xs, rw mem_image_eq at xs, rcases xs with ⟨⟨y₁, y₂⟩, ys, yx⟩, rcases is_open_prod_iff.1 hs _ _ ys with ⟨o₁, o₂, o₁_open, o₂_open, yo₁, yo₂, ho⟩, simp at yx, rw yx at yo₂, refine ⟨o₂, _, o₂_open, yo₂⟩, assume z zs, rw mem_image_eq, exact ⟨(y₁, z), ho (by simp [zs, yo₁]), rfl⟩ end /-- A product set is open in a product space if and only if each factor is open, or one of them is empty -/ lemma is_open_prod_iff' {s : set α} {t : set β} : is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) := begin cases (set.prod s t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h, split, { assume H : is_open (set.prod s t), refine or.inl ⟨_, _⟩, show is_open s, { rw ← fst_image_prod s st.2, exact is_open_map_fst _ H }, show is_open t, { rw ← snd_image_prod st.1 t, exact is_open_map_snd _ H } }, { assume H, simp [st.1.ne_empty, st.2.ne_empty] at H, exact is_open_prod H.1 H.2 } } end lemma closure_prod_eq {s : set α} {t : set β} : closure (set.prod s t) = set.prod (closure s) (closure t) := set.ext $ assume ⟨a, b⟩, have filter.prod (𝓝 a) (𝓝 b) ⊓ principal (set.prod s t) = filter.prod (𝓝 a ⊓ principal s) (𝓝 b ⊓ principal t), by rw [←prod_inf_prod, prod_principal_principal], by simp [closure_eq_nhds, nhds_prod_eq, this]; exact prod_ne_bot lemma mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) : f a b ∈ closure u := have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩, show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb lemma is_closed_prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (set.prod s₁ s₂) := closure_eq_iff_is_closed.mp $ by simp [h₁, h₂, closure_prod_eq, closure_eq_of_is_closed] lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) : inducing (λx:α×γ, (f x.1, g x.2)) := ⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced, induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩ lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) : embedding (λx:α×γ, (f x.1, g x.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩, ..hf.to_inducing.prod_mk hg.to_inducing } protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) : is_open_map (λ p : α × γ, (f p.1, g p.2)) := begin rw [is_open_map_iff_nhds_le], rintros ⟨a, b⟩, rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq], exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b) end protected lemma open_embedding.prod {f : α → β} {g : γ → δ} (hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) := open_embedding_of_embedding_open (hf.1.prod_mk hg.1) (hf.is_open_map.prod hg.is_open_map) lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) := embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id end prod section sum variables [topological_space α] [topological_space β] [topological_space γ] lemma continuous_inl : continuous (@sum.inl α β) := continuous_sup_rng_left continuous_coinduced_rng lemma continuous_inr : continuous (@sum.inr α β) := continuous_sup_rng_right continuous_coinduced_rng lemma continuous_sum_rec {f : α → γ} {g : β → γ} (hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) := continuous_sup_dom hf hg lemma embedding_inl : embedding (@sum.inl α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_left }, { intros u hu, existsi (sum.inl '' u), change (is_open (sum.inl ⁻¹' (@sum.inl α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inl α β '' u))) ∧ sum.inl ⁻¹' (sum.inl '' u) = u, have : sum.inl ⁻¹' (@sum.inl α β '' u) = u := preimage_image_eq u (λ _ _, sum.inl.inj_iff.mp), rw this, have : sum.inr ⁻¹' (@sum.inl α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, sum.inl_ne_inr h), rw this, exact ⟨⟨hu, is_open_empty⟩, rfl⟩ } end, inj := λ _ _, sum.inl.inj_iff.mp } lemma embedding_inr : embedding (@sum.inr α β) := { induced := begin unfold sum.topological_space, apply le_antisymm, { rw ← coinduced_le_iff_le_induced, exact le_sup_right }, { intros u hu, existsi (sum.inr '' u), change (is_open (sum.inl ⁻¹' (@sum.inr α β '' u)) ∧ is_open (sum.inr ⁻¹' (@sum.inr α β '' u))) ∧ sum.inr ⁻¹' (sum.inr '' u) = u, have : sum.inl ⁻¹' (@sum.inr α β '' u) = ∅ := eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, sum.inr_ne_inl h), rw this, have : sum.inr ⁻¹' (@sum.inr α β '' u) = u := preimage_image_eq u (λ _ _, sum.inr.inj_iff.mp), rw this, exact ⟨⟨is_open_empty, hu⟩, rfl⟩ } end, inj := λ _ _, sum.inr.inj_iff.mp } end sum section subtype variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop} lemma embedding_subtype_val : embedding (@subtype.val α p) := ⟨⟨rfl⟩, subtype.val_injective⟩ lemma continuous_subtype_val : continuous (@subtype.val α p) := continuous_induced_dom lemma continuous_subtype_coe : continuous (coe : subtype p → α) := continuous_subtype_val lemma is_open.open_embedding_subtype_val {s : set α} (hs : is_open s) : open_embedding (subtype.val : s → α) := { induced := rfl, inj := subtype.val_injective, open_range := (subtype.val_range : range subtype.val = s).symm ▸ hs } lemma is_open.is_open_map_subtype_val {s : set α} (hs : is_open s) : is_open_map (subtype.val : s → α) := hs.open_embedding_subtype_val.is_open_map lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) : is_open_map (s.restrict f) := hf.comp hs.is_open_map_subtype_val lemma is_closed.closed_embedding_subtype_val {s : set α} (hs : is_closed s) : closed_embedding (subtype.val : {x // x ∈ s} → α) := { induced := rfl, inj := subtype.val_injective, closed_range := (subtype.val_range : range subtype.val = s).symm ▸ hs } lemma continuous_subtype_mk {f : β → α} (hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) := continuous_induced_rng h lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) := continuous_subtype_mk _ continuous_subtype_val lemma continuous_at_subtype_val {p : α → Prop} {a : subtype p} : continuous_at subtype.val a := continuous_iff_continuous_at.mp continuous_subtype_val _ lemma map_nhds_subtype_val_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) : map (@subtype.val α p) (𝓝 ⟨a, ha⟩) = 𝓝 a := map_nhds_induced_eq (by simp [subtype.val_image, h]) lemma nhds_subtype_eq_comap {a : α} {h : p a} : 𝓝 (⟨a, h⟩ : subtype p) = comap subtype.val (𝓝 a) := nhds_induced _ _ lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} : ∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, subtype.val (f x)) b (𝓝 a.val) | ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff] lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop} (c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_continuous_at.mpr $ assume x, let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in calc map f (𝓝 x) = map f (map subtype.val (𝓝 x')) : congr_arg (map f) (map_nhds_subtype_val_eq _ $ c_sets).symm ... = map (λx:subtype (c i), f x.val) (𝓝 x') : rfl ... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x' lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop) (h_lf : locally_finite (λi, {x | c i x})) (h_is_closed : ∀i, is_closed {x | c i x}) (h_cover : ∀x, ∃i, c i x) (f_cont : ∀i, continuous (λ(x : subtype (c i)), f x.val)) : continuous f := continuous_iff_is_closed.mpr $ assume s hs, have ∀i, is_closed (@subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from assume i, embedding_is_closed embedding_subtype_val (by simp [subtype.val_range]; exact h_is_closed i) (continuous_iff_is_closed.mp (f_cont i) _ hs), have is_closed (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), from is_closed_Union_of_locally_finite (locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx') this, have f ⁻¹' s = (⋃i, @subtype.val α {x | c i x} '' (f ∘ subtype.val ⁻¹' s)), begin apply set.ext, have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s := λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩, λ ⟨i, hi, hx⟩, hx⟩, simp [and.comm, and.left_comm], simpa [(∘)], end, by rwa [this] lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}: x ∈ closure s ↔ x.val ∈ closure (subtype.val '' s) := closure_induced $ assume x y, subtype.eq end subtype section quotient variables [topological_space α] [topological_space β] [topological_space γ] variables {r : α → α → Prop} {s : setoid α} lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) := ⟨quot.exists_rep, rfl⟩ lemma continuous_quot_mk : continuous (@quot.mk α r) := continuous_coinduced_rng lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b) (h : continuous f) : continuous (quot.lift f hr : quot r → β) := continuous_coinduced_dom h lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) := quotient_map_quot_mk lemma continuous_quotient_mk : continuous (@quotient.mk α s) := continuous_coinduced_rng lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b) (h : continuous f) : continuous (quotient.lift f hs : quotient s → β) := continuous_coinduced_dom h end quotient section pi variables {ι : Type*} {π : ι → Type*} open topological_space lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i} (h : ∀i, continuous (λa, f a i)) : continuous f := continuous_infi_rng $ assume i, continuous_induced_rng $ h i lemma continuous_apply [∀i, topological_space (π i)] (i : ι) : continuous (λp:Πi, π i, p i) := continuous_infi_dom continuous_induced_dom /-- Embedding a factor into a product space (by fixing arbitrarily all the other coordinates) is continuous. -/ lemma continuous_update [decidable_eq ι] [∀i, topological_space (π i)] {i : ι} {f : Πi:ι, π i} : continuous (λ x : π i, function.update f i x) := begin refine continuous_pi (λj, _), by_cases h : j = i, { rw h, simpa using continuous_id }, { simpa [h] using continuous_const } end lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} : 𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) := calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi ... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced] lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)} (hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) := by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, continuous_apply a _ $ hs a ha) lemma pi_eq_generate_from [∀a, topological_space (π a)] : Pi.topological_space = generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} := le_antisymm (le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi) (le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $ ⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩) lemma pi_generate_from_eq {g : Πa, set (set (π a))} : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} := let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in begin rw [pi_eq_generate_from], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩, { rintros s ⟨t, i, hi, rfl⟩, rw [pi_def], apply is_open_bInter (finset.finite_to_set _), assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a), refine le_generate_from _ _ (hi a ha), exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ } end lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) : @Pi.topological_space ι π (λa, generate_from (g a)) = generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} := let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in begin rw [pi_generate_from_eq], refine le_antisymm (generate_from_mono _) (le_generate_from _), exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩, { rintros s ⟨t, i, ht, rfl⟩, apply is_open_iff_forall_mem_open.2 _, assume f hf, choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s, { assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa }, refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩, { simp [pi_if] }, { refine generate_open.basic _ ⟨_, assume a, _, rfl⟩, by_cases a ∈ i; simp [*, pi] at * }, { have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * }, simpa [pi_if, hf] } } end end pi section sigma variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)] lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) := continuous_supr_rng continuous_coinduced_rng lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) := by simp only [is_open_supr_iff, is_open_coinduced] lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) := is_open_sigma_iff lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) := begin intros s hs, rw is_open_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ injective_sigma_mk }, { convert is_open_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ } lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) := begin intros s hs, rw is_closed_sigma_iff, intro j, classical, by_cases h : i = j, { subst j, convert hs, exact set.preimage_image_eq _ injective_sigma_mk }, { convert is_closed_empty, apply set.eq_empty_of_subset_empty, rintro x ⟨y, _, hy⟩, have : i = j, by cc, contradiction } end lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) := by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ } lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) := open_embedding_of_continuous_injective_open continuous_sigma_mk injective_sigma_mk is_open_map_sigma_mk lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) := closed_embedding_of_continuous_injective_closed continuous_sigma_mk injective_sigma_mk is_closed_map_sigma_mk lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) := closed_embedding_sigma_mk.1 /-- A map out of a sum type is continuous if its restriction to each summand is. -/ lemma continuous_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f := continuous_supr_dom (λ i, continuous_coinduced_dom (h i)) lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)] {f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) : continuous (sigma.map f₁ f₂) := continuous_sigma $ λ i, show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)), from continuous_sigma_mk.comp (hf i) lemma is_open_map_sigma [topological_space β] {f : sigma σ → β} (h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f := begin intros s hs, rw is_open_sigma_iff at hs, have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s), { rw Union_image_preimage_sigma_mk_eq_self }, rw this, rw [image_Union], apply is_open_Union, intro i, rw [image_image], exact h i _ (hs i) end /-- The sum of embeddings is an embedding. -/ lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)] {f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) := begin refine ⟨⟨_⟩, injective_sigma_map function.injective_id (λ i, (hf i).inj)⟩, refine le_antisymm (continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _, intros s hs, replace hs := is_open_sigma_iff.mp hs, have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s, { intro i, apply is_open_induced_iff.mp, convert hs i, exact (hf i).induced.symm }, choose t ht using this, apply is_open_induced_iff.mpr, refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩, ext p, rcases p with ⟨i, x⟩, change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s, rw [←(ht i).2, mem_Union], split, { rintro ⟨j, hj⟩, rw mem_image at hj, rcases hj with ⟨y, hy₁, hy₂⟩, rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩, replace hy := eq_of_heq hy, subst y, exact hy₁ }, { intro hx, use i, rw mem_image, exact ⟨f i x, hx, rfl⟩ } end end sigma lemma mem_closure_of_continuous [topological_space α] [topological_space β] {f : α → β} {a : α} {s : set α} {t : set β} (hf : continuous f) (ha : a ∈ closure s) (h : ∀a∈s, f a ∈ closure t) : f a ∈ closure t := calc f a ∈ f '' closure s : mem_image_of_mem _ ha ... ⊆ closure (f '' s) : image_closure_subset_closure_image hf ... ⊆ closure (closure t) : closure_mono $ image_subset_iff.mpr $ h ... ⊆ closure t : begin rw [closure_eq_of_is_closed], exact subset.refl _, exact is_closed_closure end lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ] {f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ} (hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t) (h : ∀a∈s, ∀b∈t, f a b ∈ closure u) : f a b ∈ closure u := have (a,b) ∈ closure (set.prod s t), by simp [closure_prod_eq, ha, hb], show f (a, b).1 (a, b).2 ∈ closure u, from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $ assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
8ad27badd922a09f65fbe9fa69a9540f104bd21c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/core.lean
8c55b963516401551495965273e58a2419a35fbb
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,002
lean
/- Copyright (c) 2019 Scott Morrison All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import control.equiv_functor import category_theory.groupoid import category_theory.whiskering import category_theory.types /-! # The core of a category The core of a category `C` is the (non-full) subcategory of `C` consisting of all objects, and all isomorphisms. We construct it as a `groupoid`. `core.inclusion : core C ⥤ C` gives the faithful inclusion into the original category. Any functor `F` from a groupoid `G` into `C` factors through `core C`, but this is not functorial with respect to `F`. -/ namespace category_theory universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. /-- The core of a category C is the groupoid whose morphisms are all the isomorphisms of C. -/ @[nolint has_nonempty_instance] def core (C : Type u₁) := C variables {C : Type u₁} [category.{v₁} C] instance core_category : groupoid.{v₁} (core C) := { hom := λ X Y : C, X ≅ Y, inv := λ X Y f, iso.symm f, id := λ X, iso.refl X, comp := λ X Y Z f g, iso.trans f g } namespace core @[simp] lemma id_hom (X : core C) : iso.hom (𝟙 X) = 𝟙 X := rfl @[simp] lemma comp_hom {X Y Z : core C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).hom = f.hom ≫ g.hom := rfl variables (C) /-- The core of a category is naturally included in the category. -/ def inclusion : core C ⥤ C := { obj := id, map := λ X Y f, f.hom } instance : faithful (inclusion C) := {} variables {C} {G : Type u₂} [groupoid.{v₂} G] /-- A functor from a groupoid to a category C factors through the core of C. -/ -- Note that this function is not functorial -- (consider the two functors from [0] to [1], and the natural transformation between them). noncomputable def functor_to_core (F : G ⥤ C) : G ⥤ core C := { obj := λ X, F.obj X, map := λ X Y f, ⟨F.map f, F.map (inv f)⟩ } /-- We can functorially associate to any functor from a groupoid to the core of a category `C`, a functor from the groupoid to `C`, simply by composing with the embedding `core C ⥤ C`. -/ def forget_functor_to_core : (G ⥤ core C) ⥤ (G ⥤ C) := (whiskering_right _ _ _).obj (inclusion C) end core /-- `of_equiv_functor m` lifts a type-level `equiv_functor` to a categorical functor `core (Type u₁) ⥤ core (Type u₂)`. -/ def of_equiv_functor (m : Type u₁ → Type u₂) [equiv_functor m] : core (Type u₁) ⥤ core (Type u₂) := { obj := m, map := λ α β f, (equiv_functor.map_equiv m f.to_equiv).to_iso, -- These are not very pretty. map_id' := λ α, begin ext, exact (congr_fun (equiv_functor.map_refl _) x), end, map_comp' := λ α β γ f g, begin ext, simp only [equiv_functor.map_equiv_apply, equiv.to_iso_hom, function.comp_app, core.comp_hom, types_comp], erw [iso.to_equiv_comp, equiv_functor.map_trans], end, } end category_theory
5cb9019778d01a07926a7902215a7ca1d09e0411
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Meta/InferType.lean
8377d68d74ad0cf3cc273c9dee4016d9d142bb0b
[ "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
17,294
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.LBool import Lean.Meta.Basic namespace Lean /- Auxiliary function for instantiating the loose bound variables in `e` with `args[start:stop]`. This function is similar to `instantiateRevRange`, but it applies beta-reduction when we instantiate a bound variable with a lambda expression. Example: Given the term `#0 a`, and `start := 0, stop := 1, args := #[fun x => x]` the result is `a` instead of `(fun x => x) a`. This reduction is useful when we are inferring the type of eliminator-like applications. For example, given `(n m : Nat) (f : Nat → Nat) (h : m = n)`, the type of `Eq.subst (motive := fun x => f m = f x) h rfl` is `motive n` which is `(fun (x : Nat) => f m = f x) n` This function reduces the new application to `f m = f n` We use it to implement `inferAppType` -/ partial def Expr.instantiateBetaRevRange (e : Expr) (start : Nat) (stop : Nat) (args : Array Expr) : Expr := if e.hasLooseBVars && stop > start then assert! stop ≤ args.size visit e 0 |>.run else e where visit (e : Expr) (offset : Nat) : MonadStateCacheT (ExprStructEq × Nat) Expr Id Expr := if offset >= e.looseBVarRange then -- `e` doesn't have free variables return e else checkCache ({ val := e : ExprStructEq }, offset) fun _ => do match e with | Expr.forallE _ d b _ => return e.updateForallE! (← visit d offset) (← visit b (offset+1)) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit d offset) (← visit b (offset+1)) | Expr.letE _ t v b _ => return e.updateLet! (← visit t offset) (← visit v offset) (← visit b (offset+1)) | Expr.mdata _ b _ => return e.updateMData! (← visit b offset) | Expr.proj _ _ b _ => return e.updateProj! (← visit b offset) | Expr.app f a _ => e.withAppRev fun f revArgs => do let fNew ← visit f offset let revArgs ← revArgs.mapM (visit · offset) if f.isBVar then -- try to beta reduce if `f` was a bound variable return fNew.betaRev revArgs else return mkAppRev fNew revArgs | Expr.bvar vidx _ => -- Recall that looseBVarRange for `Expr.bvar` is `vidx+1`. -- So, we must have offset ≤ vidx, since we are in the "else" branch of `if offset >= e.looseBVarRange` let n := stop - start if vidx < offset + n then return args[stop - (vidx - offset) - 1].liftLooseBVars 0 offset else return mkBVar (vidx - n) -- The following cases are unreachable because they never contain loose bound variables | Expr.const .. => unreachable! | Expr.fvar .. => unreachable! | Expr.mvar .. => unreachable! | Expr.sort .. => unreachable! | Expr.lit .. => unreachable! namespace Meta def throwFunctionExpected {α} (f : Expr) : MetaM α := throwError "function expected{indentExpr f}" private def inferAppType (f : Expr) (args : Array Expr) : MetaM Expr := do let mut fType ← inferType f let mut j := 0 /- TODO: check whether `instantiateBetaRevRange` is too expensive, and use it only when `args` contains a lambda expression. -/ for i in [:args.size] do match fType with | Expr.forallE _ _ b _ => fType := b | _ => match (← whnf <| fType.instantiateBetaRevRange j i args) with | Expr.forallE _ _ b _ => j := i; fType := b | _ => throwFunctionExpected <| mkAppRange f 0 (i+1) args return fType.instantiateBetaRevRange j args.size args def throwIncorrectNumberOfLevels {α} (constName : Name) (us : List Level) : MetaM α := throwError "incorrect number of universe levels {mkConst constName us}" private def inferConstType (c : Name) (us : List Level) : MetaM Expr := do let cinfo ← getConstInfo c if cinfo.levelParams.length == us.length then return cinfo.instantiateTypeLevelParams us else throwIncorrectNumberOfLevels c us private def inferProjType (structName : Name) (idx : Nat) (e : Expr) : MetaM Expr := do let failed {α} : Unit → MetaM α := fun _ => throwError "invalid projection{indentExpr (mkProj structName idx e)}" let structType ← inferType e let structType ← whnf structType matchConstStruct structType.getAppFn failed fun structVal structLvls ctorVal => let n := structVal.numParams let structParams := structType.getAppArgs if n != structParams.size then failed () else do let mut ctorType ← inferAppType (mkConst ctorVal.name structLvls) structParams for i in [:idx] do ctorType ← whnf ctorType match ctorType with | Expr.forallE _ _ body _ => if body.hasLooseBVars then ctorType := body.instantiate1 $ mkProj structName i e else ctorType := body | _ => failed () ctorType ← whnf ctorType match ctorType with | Expr.forallE _ d _ _ => pure d | _ => failed () def throwTypeExcepted {α} (type : Expr) : MetaM α := throwError "type expected{indentExpr type}" def getLevel (type : Expr) : MetaM Level := do let typeType ← inferType type let typeType ← whnfD typeType match typeType with | Expr.sort lvl _ => pure lvl | Expr.mvar mvarId _ => if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then throwTypeExcepted type else let lvl ← mkFreshLevelMVar assignExprMVar mvarId (mkSort lvl) pure lvl | _ => throwTypeExcepted type private def inferForallType (e : Expr) : MetaM Expr := forallTelescope e fun xs e => do let lvl ← getLevel e let lvl ← xs.foldrM (init := lvl) fun x lvl => do let xType ← inferType x let xTypeLvl ← getLevel xType pure $ mkLevelIMax' xTypeLvl lvl pure $ mkSort lvl.normalize /- Infer type of lambda and let expressions -/ private def inferLambdaType (e : Expr) : MetaM Expr := lambdaLetTelescope e fun xs e => do let type ← inferType e mkForallFVars xs type @[inline] private def withLocalDecl' {α} (name : Name) (bi : BinderInfo) (type : Expr) (x : Expr → MetaM α) : MetaM α := savingCache do let fvarId ← mkFreshId withReader (fun ctx => { ctx with lctx := ctx.lctx.mkLocalDecl fvarId name type bi }) do x (mkFVar fvarId) def throwUnknownMVar {α} (mvarId : MVarId) : MetaM α := throwError "unknown metavariable '?{mvarId}'" private def inferMVarType (mvarId : MVarId) : MetaM Expr := do match (← getMCtx).findDecl? mvarId with | some d => pure d.type | none => throwUnknownMVar mvarId private def inferFVarType (fvarId : FVarId) : MetaM Expr := do match (← getLCtx).find? fvarId with | some d => pure d.type | none => throwUnknownFVar fvarId @[inline] private def checkInferTypeCache (e : Expr) (inferType : MetaM Expr) : MetaM Expr := do match (← get).cache.inferType.find? e with | some type => pure type | none => let type ← inferType unless e.hasMVar || type.hasMVar do modifyInferTypeCache fun c => c.insert e type pure type def inferTypeImp (e : Expr) : MetaM Expr := let rec infer : Expr → MetaM Expr | Expr.const c [] _ => inferConstType c [] | Expr.const c us _ => checkInferTypeCache e (inferConstType c us) | e@(Expr.proj n i s _) => checkInferTypeCache e (inferProjType n i s) | e@(Expr.app f _ _) => checkInferTypeCache e (inferAppType f.getAppFn e.getAppArgs) | Expr.mvar mvarId _ => inferMVarType mvarId | Expr.fvar fvarId _ => inferFVarType fvarId | Expr.bvar bidx _ => throwError "unexpected bound variable {mkBVar bidx}" | Expr.mdata _ e _ => infer e | Expr.lit v _ => pure v.type | Expr.sort lvl _ => pure $ mkSort (mkLevelSucc lvl) | e@(Expr.forallE _ _ _ _) => checkInferTypeCache e (inferForallType e) | e@(Expr.lam _ _ _ _) => checkInferTypeCache e (inferLambdaType e) | e@(Expr.letE _ _ _ _ _) => checkInferTypeCache e (inferLambdaType e) withTransparency TransparencyMode.default (infer e) @[builtinInit] def setInferTypeRef : IO Unit := inferTypeRef.set inferTypeImp /-- Return `LBool.true` if given level is always equivalent to universe level zero. It is used to implement `isProp`. -/ private def isAlwaysZero : Level → Bool | Level.zero _ => true | Level.mvar _ _ => false | Level.param _ _ => false | Level.succ _ _ => false | Level.max u v _ => isAlwaysZero u && isAlwaysZero v | Level.imax _ u _ => isAlwaysZero u /-- `isArrowProp type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> Prop`. Remark: `type` can be a dependent arrow. -/ private partial def isArrowProp : Expr → Nat → MetaM LBool | Expr.sort u _, 0 => return isAlwaysZero (← instantiateLevelMVars u) |>.toLBool | Expr.forallE _ _ _ _, 0 => pure LBool.false | Expr.forallE _ _ b _, n+1 => isArrowProp b n | Expr.letE _ _ _ b _, n => isArrowProp b n | Expr.mdata _ e _, n => isArrowProp e n | _, _ => pure LBool.undef /-- `isPropQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a proposition. -/ private partial def isPropQuickApp : Expr → Nat → MetaM LBool | Expr.const c lvls _, arity => do let constType ← inferConstType c lvls; isArrowProp constType arity | Expr.fvar fvarId _, arity => do let fvarType ← inferFVarType fvarId; isArrowProp fvarType arity | Expr.mvar mvarId _, arity => do let mvarType ← inferMVarType mvarId; isArrowProp mvarType arity | Expr.app f _ _, arity => isPropQuickApp f (arity+1) | Expr.mdata _ e _, arity => isPropQuickApp e arity | Expr.letE _ _ _ b _, arity => isPropQuickApp b arity | Expr.lam _ _ _ _, 0 => pure LBool.false | Expr.lam _ _ b _, arity+1 => isPropQuickApp b arity | _, _ => pure LBool.undef /-- `isPropQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a proposition. -/ partial def isPropQuick : Expr → MetaM LBool | Expr.bvar _ _ => pure LBool.undef | Expr.lit _ _ => pure LBool.false | Expr.sort _ _ => pure LBool.false | Expr.lam _ _ _ _ => pure LBool.false | Expr.letE _ _ _ b _ => isPropQuick b | Expr.proj _ _ _ _ => pure LBool.undef | Expr.forallE _ _ b _ => isPropQuick b | Expr.mdata _ e _ => isPropQuick e | Expr.const c lvls _ => do let constType ← inferConstType c lvls; isArrowProp constType 0 | Expr.fvar fvarId _ => do let fvarType ← inferFVarType fvarId; isArrowProp fvarType 0 | Expr.mvar mvarId _ => do let mvarType ← inferMVarType mvarId; isArrowProp mvarType 0 | Expr.app f _ _ => isPropQuickApp f 1 /-- `isProp whnf e` return `true` if `e` is a proposition. If `e` contains metavariables, it may not be possible to decide whether is a proposition or not. We return `false` in this case. We considered using `LBool` and retuning `LBool.undef`, but we have no applications for it. -/ def isProp (e : Expr) : MetaM Bool := do let r ← isPropQuick e match r with | LBool.true => pure true | LBool.false => pure false | LBool.undef => let type ← inferType e let type ← whnfD type match type with | Expr.sort u _ => return isAlwaysZero (← instantiateLevelMVars u) | _ => pure false /-- `isArrowProposition type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> B`, where `B` is a proposition. Remark: `type` can be a dependent arrow. -/ private partial def isArrowProposition : Expr → Nat → MetaM LBool | Expr.forallE _ _ b _, n+1 => isArrowProposition b n | Expr.letE _ _ _ b _, n => isArrowProposition b n | Expr.mdata _ e _, n => isArrowProposition e n | type, 0 => isPropQuick type | _, _ => pure LBool.undef mutual /-- `isProofQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a proof. -/ private partial def isProofQuickApp : Expr → Nat → MetaM LBool | Expr.const c lvls _, arity => do let constType ← inferConstType c lvls; isArrowProposition constType arity | Expr.fvar fvarId _, arity => do let fvarType ← inferFVarType fvarId; isArrowProposition fvarType arity | Expr.mvar mvarId _, arity => do let mvarType ← inferMVarType mvarId; isArrowProposition mvarType arity | Expr.app f _ _, arity => isProofQuickApp f (arity+1) | Expr.mdata _ e _, arity => isProofQuickApp e arity | Expr.letE _ _ _ b _, arity => isProofQuickApp b arity | Expr.lam _ _ b _, 0 => isProofQuick b | Expr.lam _ _ b _, arity+1 => isProofQuickApp b arity | _, _ => pure LBool.undef /-- `isProofQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a proof. -/ partial def isProofQuick : Expr → MetaM LBool | Expr.bvar _ _ => pure LBool.undef | Expr.lit _ _ => pure LBool.false | Expr.sort _ _ => pure LBool.false | Expr.lam _ _ b _ => isProofQuick b | Expr.letE _ _ _ b _ => isProofQuick b | Expr.proj _ _ _ _ => pure LBool.undef | Expr.forallE _ _ b _ => pure LBool.false | Expr.mdata _ e _ => isProofQuick e | Expr.const c lvls _ => do let constType ← inferConstType c lvls; isArrowProposition constType 0 | Expr.fvar fvarId _ => do let fvarType ← inferFVarType fvarId; isArrowProposition fvarType 0 | Expr.mvar mvarId _ => do let mvarType ← inferMVarType mvarId; isArrowProposition mvarType 0 | Expr.app f _ _ => isProofQuickApp f 1 end def isProof (e : Expr) : MetaM Bool := do let r ← isProofQuick e match r with | LBool.true => pure true | LBool.false => pure false | LBool.undef => do let type ← inferType e Meta.isProp type /-- `isArrowType type n` is an "approximate" predicate which returns `LBool.true` if `type` is of the form `A_1 -> ... -> A_n -> Sort _`. Remark: `type` can be a dependent arrow. -/ private partial def isArrowType : Expr → Nat → MetaM LBool | Expr.sort u _, 0 => pure LBool.true | Expr.forallE _ _ _ _, 0 => pure LBool.false | Expr.forallE _ _ b _, n+1 => isArrowType b n | Expr.letE _ _ _ b _, n => isArrowType b n | Expr.mdata _ e _, n => isArrowType e n | _, _ => pure LBool.undef /-- `isTypeQuickApp f n` is an "approximate" predicate which returns `LBool.true` if `f` applied to `n` arguments is a type. -/ private partial def isTypeQuickApp : Expr → Nat → MetaM LBool | Expr.const c lvls _, arity => do let constType ← inferConstType c lvls; isArrowType constType arity | Expr.fvar fvarId _, arity => do let fvarType ← inferFVarType fvarId; isArrowType fvarType arity | Expr.mvar mvarId _, arity => do let mvarType ← inferMVarType mvarId; isArrowType mvarType arity | Expr.app f _ _, arity => isTypeQuickApp f (arity+1) | Expr.mdata _ e _, arity => isTypeQuickApp e arity | Expr.letE _ _ _ b _, arity => isTypeQuickApp b arity | Expr.lam _ _ _ _, 0 => pure LBool.false | Expr.lam _ _ b _, arity+1 => isTypeQuickApp b arity | _, _ => pure LBool.undef /-- `isTypeQuick e` is an "approximate" predicate which returns `LBool.true` if `e` is a type. -/ partial def isTypeQuick : Expr → MetaM LBool | Expr.bvar _ _ => pure LBool.undef | Expr.lit _ _ => pure LBool.false | Expr.sort _ _ => pure LBool.true | Expr.lam _ _ _ _ => pure LBool.false | Expr.letE _ _ _ b _ => isTypeQuick b | Expr.proj _ _ _ _ => pure LBool.undef | Expr.forallE _ _ b _ => pure LBool.true | Expr.mdata _ e _ => isTypeQuick e | Expr.const c lvls _ => do let constType ← inferConstType c lvls; isArrowType constType 0 | Expr.fvar fvarId _ => do let fvarType ← inferFVarType fvarId; isArrowType fvarType 0 | Expr.mvar mvarId _ => do let mvarType ← inferMVarType mvarId; isArrowType mvarType 0 | Expr.app f _ _ => isTypeQuickApp f 1 def isType (e : Expr) : MetaM Bool := do let r ← isTypeQuick e match r with | LBool.true => pure true | LBool.false => pure false | LBool.undef => let type ← inferType e let type ← whnfD type match type with | Expr.sort _ _ => pure true | _ => pure false partial def isTypeFormerType (type : Expr) : MetaM Bool := do let type ← whnfD type match type with | Expr.sort _ _ => pure true | Expr.forallE n d b c => withLocalDecl' n c.binderInfo d fun fvar => isTypeFormerType (b.instantiate1 fvar) | _ => pure false /-- Return true iff `e : Sort _` or `e : (forall As, Sort _)`. Remark: it subsumes `isType` -/ def isTypeFormer (e : Expr) : MetaM Bool := do let type ← inferType e isTypeFormerType type end Lean.Meta
e9f072f2a3e80389832351eb45bf314d8df361f9
ecad13897fdb44984cf1968424224d1750040236
/lean/lean/examples/example05.lean
5849a3932b1cd34c6c187561cefac84615f72108
[]
no_license
MetaBorgCube/sdf3-demo
4899159b1cfb0a95ae3af325035bbba8a1255477
e831606d5b404eba75b087916a1162923143b98a
refs/heads/master
1,609,472,086,310
1,553,380,857,000
1,553,380,857,000
59,577,395
0
0
null
null
null
null
UTF-8
Lean
false
false
37
lean
(z (a : b))(c : d) -> (e)(f : H) -> y
6a9045978a7a5e34edf50691848335df2f263ca9
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/NN.lean
4bb1fae26d20ed15464282d255861aca154605a6
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
8,545
lean
import data.rat tactic.norm_num .misc .string universes u v variables {α : Type} def N (α : Type) : Type := nat → α def NN (α : Type) : Type := nat → nat → α def N.eq (n : nat) (a b : N α) : Prop := ∀ j < n, a j = b j def NN.eq (m n : nat) (A B : NN α) : Prop := ∀ i < m, ∀ j < n, A i j = B i j def NN.mul_aux [ring α] (A B : NN α) (i j : nat) : nat → α | 0 := 0 | (m + 1) := NN.mul_aux m + (A i m * B m j) def NN.mul [ring α] (k m n : nat) (A B : NN α) : NN α | i j := NN.mul_aux A B i j m lemma N.eq_zero (a b : N α) : N.eq 0 a b := forall_lt_zero _ lemma N.eq_succ {n : nat} {a b : N α} : a n = b n → N.eq n a b → N.eq n.succ a b := forall_lt_succ _ n lemma NN.eq_zero {n : nat} {A B : NN α} : NN.eq 0 n A B := forall_lt_zero _ lemma NN.eq_succ {m n : nat} {A B : NN α} : N.eq n (A m) (B m) → NN.eq m n A B → NN.eq m.succ n A B := forall_lt_succ _ m lemma NN.eq_symm {m n : nat} {A B : NN α} : NN.eq m n A B → NN.eq m n B A := begin intros h1 i hi j hj, exact (h1 i hi j hj).symm end lemma NN.eq_trans {m n : nat} {A B C : NN α} : NN.eq m n A B → NN.eq m n B C → NN.eq m n A C := begin intros h1 h2 i hi j hj, apply eq.trans (h1 i hi j hj) (h2 i hi j hj) end def N.of_list [inhabited α] : list α → nat → α | [] _ := inhabited.default α | (a::as) 0 := a | (a::as) (j+1) := N.of_list as j def NN.of_lists (α : Type) [inhabited α] : list (list α) → NN α | [] _ _ := inhabited.default α | (l::ll) 0 j := N.of_list l j | (l::ll) (i+1) j := NN.of_lists ll i j instance N.eq.decidable [decidable_eq α] (n : nat) : decidable_rel (@N.eq α n) := by {intros A B, apply forall_lt.decidable} instance NN.eq.decidable [decidable_eq α] (m n : nat) : decidable_rel (@NN.eq α m n) := by {intros A B, apply forall_lt.decidable} /- repr -/ def N.cell_size [has_repr α] (b : N α) : nat → nat | 0 := 0 | (n+1) := max (N.cell_size n) (repr $ b n).length def NN.cell_size [has_repr α] (A : NN α) : nat → nat → nat | 0 n := 0 | (m+1) n := max (NN.cell_size m n) (N.cell_size (A m) n) def N.repr [has_repr α] (k : nat) (b : N α) : nat → string | 0 := "|" | (n+1) := N.repr n ++ " " ++ (repr $ b n).resize k ++ " |" def NN.repr_aux [has_repr α] (k : nat) (A : NN α) : nat → nat → string | 0 n := "" | (m+1) n := NN.repr_aux m n ++ "\n" ++ N.repr k (A m) n def NN.repr (m n : nat) [has_repr α] (A : NN α) : string := NN.repr_aux (NN.cell_size A m n) A m n def N.le [has_le α] (k : nat) (v w : N α) : Prop := ∀ x < k, v x ≤ w x instance N.le.decidable [has_le α] [decidable_rel ((≤) : α → α → Prop)] (k : nat) (v w : N α) : decidable (N.le k v w) := forall_lt.decidable _ _ def N.zero (α : Type) [has_zero α] : N α := λ _, 0 def N.sum [has_zero α] [has_add α] : ∀ k : nat, ∀ v : N α, α | 0 _ := 0 | (k + 1) v := v k + v.sum k def dot_prod [has_zero α] [has_add α] [has_mul α] (k : nat) (v w : N α) : α := N.sum k (λ m, v m * w m) def mul_vec [has_zero α] [has_add α] [has_mul α] (k : nat) (A : NN α) (x : N α) : N α := λ m, dot_prod k (A m) x /- norm -/ open tactic expr /- (N.mk_meta n) returns ⌜g : nat → α⌝, where ⌜f j⌝ is a unique metavariable for any j < n, and ⌜g j⌝ = x otherwise. -/ meta def N.mk_meta (τx tx : expr) : nat → tactic expr | 0 := to_expr ``(λ x : nat, (%%tx : %%τx)) | (n+1) := do gx ← N.mk_meta n, sx ← mk_meta_var τx, to_expr ``(update %%τx %%`(n) %%sx %%gx) /- (mk_meta m n) returns ⌜f : NN α⌝, where each ⌜f i j⌝ is a unique metavariable for any i < m and j < n, and ⌜f i j⌝ = x otherwise. -/ meta def NN.mk_meta (αx ax : expr) : nat → nat → tactic expr | 0 _ := to_expr ``(λ i j : nat, (%%ax : %%αx)) | (m+1) n := do fx ← NN.mk_meta m n, gx ← N.mk_meta αx ax n, to_expr ``(update (N %%αx) %%`(m) %%gx %%fx) meta def mul_simp_lemmas : list name := [`NN.mul, `NN.mul_aux, `N.of_list, `NN.of_lists] meta def get_simp_lemmas : list name → tactic simp_lemmas | [] := return simp_lemmas.mk | (n::ns) := do s ← get_simp_lemmas ns, s.add_simp n meta def simp_mul (x : expr) : tactic (expr × expr) := do s ← get_simp_lemmas mul_simp_lemmas, simplify s [] x /- Return ⌜h : t = s⌝ -/ meta def prove_eq (αx tx ux : expr) : tactic expr := do (sx,px) ← simp_mul tx, (rx,qx) ← norm_num.derive' sx, unify rx ux, to_expr ``(@eq.trans %%αx %%tx %%sx %%rx %%px %%qx) /- Return ⌜h : N.eq n a b⌝ -/ meta def N.prove_eq (αx ax bx : expr) : nat → tactic expr | 0 := return `(@N.eq_zero %%αx %%ax %%bx) | (n+1) := do px ← prove_eq αx (app ax `(n)) (app bx `(n)), qx ← N.prove_eq n, return `(@N.eq_succ %%αx %%`(n) %%ax %%bx %%px %%qx) /- Return ⌜h : NN.eq m n A B⌝ -/ meta def NN.prove_eq (αx Ax Bx : expr) : nat → nat → tactic expr | 0 n := return `(@NN.eq_zero %%αx %%`(n) %%Ax %%Bx) | (m+1) n := do px ← N.prove_eq αx (app Ax `(m)) (app Bx `(m)) n, qx ← NN.prove_eq m n, return `(@NN.eq_succ %%αx %%`(m) %%`(n) %%Ax %%Bx %%px %%qx) /- Return ⌜B : NN α⌝ and ⌜h : NN.eq m n A B⌝ -/ meta def NN.norm (αx ax Ax : expr) (m n : nat) : tactic (expr × expr) := do Bx ← NN.mk_meta αx ax m n, px ← NN.prove_eq αx Ax Bx m n, return (Bx,px) meta def NN.equate : tactic unit := do `(@NN.eq %%αx %%mx %%nx %%Ax %%Bx) ← target, ax ← get_default αx, m ← eval_expr nat mx, n ← eval_expr nat nx, (A'x, px) ← NN.norm αx ax Ax m n, (B'x, qx) ← NN.norm αx ax Bx m n, ( do is_def_eq A'x B'x, pq ← to_expr ``(@NN.eq_trans %%αx %%mx %%nx %%Ax %%A'x %%Bx %%px (@NN.eq_symm %%αx %%mx %%nx %%Bx %%B'x %%qx)), apply pq, skip ) <|> fail "Not definitionally equal" /- Tests -/ set_option profiler true lemma ex1 : NN.eq 2 2 ( NN.mul 2 2 2 ( NN.of_lists int [ [ 9 , -7 ], [ 18 , 4 ] ] ) ( NN.of_lists int [ [ -14 , 1 ], [ 5 , 22 ] ] ) ) ( NN.of_lists int [ [ -161 , -145 ], [ -232 , 106 ] ] ) := by NN.equate lemma ex2 : NN.eq 3 2 ( NN.mul 3 4 2 ( NN.of_lists rat [ [ 4.5 , -3.5 , 12.5 , 0.5 ], [ -1/2 , -3/2 , -2 , 0 ], [ 20 , 2 , 3 , 1 ] ] ) ( NN.of_lists rat [ [ 8 , 1/2 ], [ 5/2 , -13.5 ], [ 1/2 , 4 ], [ 21.5 , 11 ] ] ) ) ( NN.of_lists rat [ [ 177/4 , 105 ], [ -35/4 , 12 ], [ 188 , 6 ] ] ) := by NN.equate lemma ex3 : NN.eq 3 3 ( NN.mul 3 3 3 ( NN.of_lists rat [ [ 1/3 , -3.2 , 0.9 ], [ -1/2 , 3 - 5 , -2 ], [ 20 , 2 , 3.4 ] ] ) ( NN.of_lists rat [ [ 8 , 1/4 , 4/3 ], [ 5/3 , 3 , 4 * 7 ], [ 1/2 , 4 , 0 ] ] ) ) ( NN.of_lists rat [ [ -133/60 , -71/12 , -4012/45 ], [ -25/3 , -113/8 , -170/3 ], [ 4951/30 , 123/5 , 248/3 ] ] ) := by NN.equate lemma ex4 : NN.eq 4 4 ( NN.mul 4 4 4 ( NN.of_lists int [ [ 9 , -71 , 25 , 1 ], [ -1 , -3 , -4 , 92 ], [ 133 , -39 , -23 , 0 ], [ 40 , 26 , 366 , 28 ] ] ) ( NN.of_lists int [ [ 16 , 1 , 55 , -11 ], [ 512 , -27 , 219 , 129 ], [ 1 , 8 , -89 , 5 ], [ 43 , 22 , 4 , 42 ] ] ) ) ( NN.of_lists int [ [ -36140 , 2148 , -17275 , -9091 ], [ 2400 , 2072 , 12 , 3468 ], [ -17863 , 1002 , 821 , -6609 ], [ 15522 , 2882 , -24568 , 5920 ] ] ) := by NN.equate lemma ex5 : NN.eq 5 5 ( NN.mul 5 5 5 ( NN.of_lists int [ [ 9 , -71 , 25 , 1 , 910 ], [ -1 , -3 , -4 , 92 , 52 ], [ 133 , -39 , -23 , 0 , -20 ], [ -12 , 492 , 9 , 10 , 1929 ], [ 40 , 26 , 366 , 28 , 2 ] ] ) ( NN.of_lists int [ [ 16 , 1 , 55 , -11 , 13 ], [ 512 , -27 , 219 , 1921 , 212 ], [ 828 , 8 , -2 , 35 , 0 ], [ 1 , 4283 , -89 , 5 , 431 ], [ 43 , 22 , 4 , 42 , 880 ] ] ) ) ( NN.of_lists int [ [ 23623 , 26429 , -11553 , -97390 , 786296 ], [ -2536 , 395228 , -8684 , -3248 , 84763 ], [ -37744 , 562 , -1260 , -78027 , -24139 ], [ 342121 , 72044 , 113896 , 1026647 , 1805978 ], [ 317114 , 122234 , 4678 , 62540 , 19860 ] ] ) := by NN.equate
61f0161da746ca21a3fc7df73a0fe8d8ac590974
0c1546a496eccfb56620165cad015f88d56190c5
/library/data/list/basic.lean
a97e0973293d25b4495e1229a9caa0e78eb55e3c
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,043
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn Basic properties of lists. -/ import init.data.list.basic universe variables u v w namespace list open nat variables {α : Type u} {β : Type v} {φ : Type w} /- length theorems -/ @[simp] theorem length_append : ∀ (x y : list α), length (x ++ y) = length x + length y | [] l := eq.symm (nat.zero_add (length l)) | (a::s) l := calc succ (length (s ++ l)) = succ (length s + length l) : congr_arg nat.succ (length_append s l) ... = succ (length s) + length l : eq.symm (nat.succ_add (length s) (length l)) theorem length_concat (a : α) : ∀ (l : list α), length (concat l a) = succ (length l) | nil := rfl | (cons b l) := congr_arg succ (length_concat l) @[simp] theorem length_taken : ∀ (i : ℕ) (l : list α), length (taken i l) = min i (length l) | 0 l := eq.symm (nat.zero_min (length l)) | (succ n) [] := eq.symm (nat.min_zero (succ n)) | (succ n) (a::l) := calc succ (length (taken n l)) = succ (min n (length l)) : congr_arg succ (length_taken n l) ... = min (succ n) (succ (length l)) : eq.symm (nat.min_succ_succ n (length l)) @[simp] theorem length_dropn : ∀ (i : ℕ) (l : list α), length (dropn i l) = length l - i | 0 l := rfl | (succ i) [] := eq.symm (nat.zero_sub_eq_zero (succ i)) | (succ i) (x::l) := calc length (dropn (succ i) (x::l)) = length l - i : length_dropn i l ... = succ (length l) - succ i : nat.sub_eq_succ_sub_succ (length l) i @[simp] theorem length_map (f : α → β) : ∀ (a : list α), length (map f a) = length a | [] := rfl | (a :: l) := congr_arg succ (length_map l) @[simp] theorem length_repeat (a : α) : ∀ (n : ℕ), length (repeat a n) = n | 0 := eq.refl 0 | (succ i) := congr_arg succ (length_repeat i) end list
1b7cffc03c0b874449c2984e6656bdbbaaa34e45
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/12_Axioms.org.16.lean
5be853de4026b48d3e10517f460a82ad5b67a3ce
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
194
lean
import standard open subtype nonempty namespace hide -- BEGIN axiom strong_indefinite_description {A : Type} (P : A → Prop) (H : nonempty A) : { x | (∃ y : A, P y) → P x} -- END end hide
66f095d3e457d7a74b86783df7d3328e65d77258
076f5040b63237c6dd928c6401329ed5adcb0e44
/instructor-notes/2019.10.01..poly/boxed.lean
ac26e565a92647592f4843ead16bf91d20c35a77
[]
no_license
kevinsullivan/uva-cs-dm-f19
0f123689cf6cb078f263950b18382a7086bf30be
09a950752884bd7ade4be33e9e89a2c4b1927167
refs/heads/master
1,594,771,841,541
1,575,853,850,000
1,575,853,850,000
205,433,890
4
9
null
1,571,592,121,000
1,567,188,539,000
Lean
UTF-8
Lean
false
false
113
lean
inductive boxed (T : Type) : Type | box : T → boxed def unbox {T : Type} : boxed T → T | (boxed.box n) := n
c2d2d56d966cab9bcd531ea1c193622742c027d5
a7602958ab456501ff85db8cf5553f7bcab201d7
/Notes/Logic_and_Proof/Chapter4/4.31.lean
feb5e1312425df00e3658bde66bc713ccad747f5
[]
no_license
enlauren/math-logic
081e2e737c8afb28dbb337968df95ead47321ba0
086b6935543d1841f1db92d0e49add1124054c37
refs/heads/master
1,594,506,621,950
1,558,634,976,000
1,558,634,976,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
517
lean
-- Building Natural Deduction Proofs -- 4.31 Implication variables A B: Prop -- Implication introduction (by "assume" keyword). example: A /\ B -> B /\ A := assume h: A /\ B, show B /\ A, from and.intro (and.right h) (and.left h) -- (or another example); I actually do not know if this is a legitimate example. variable ht: A -> B example : A → B := assume h : A, show B, from ht h -- -- Implication elimination (by hypothesis application). variable h1: A -> B variable h2: A example: B := show B, from (h1 h2)
3fc6b1740ca331b1e461a022cc299b8d260b2100
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/const.lean
c86f45bf99cbc953a3edc3d5441c8c55bc5597d9
[ "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
301
lean
-- universe variables u definition foo {A : Type u} [H : inhabited A] : A := inhabited.rec (λa, a) H constant bla {A : Type u} [H : inhabited A] : Type 1 set_option pp.implicit true section variable A : Type u variable S : inhabited A variable B : @bla A S #check B #check @foo A S end
75985f60aea82530cfb1e14506e5f60d858ca282
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/uniform_space/separation.lean
8917cb88b5b68c9393cab55020133305e6acd2d4
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
13,808
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot Hausdorff properties of uniform spaces. Separation quotient. -/ import topology.uniform_space.basic open filter topological_space lattice set classical open_locale classical topological_space noncomputable theory set_option eqn_compiler.zeta true universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] open_locale uniformity /- 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 α] := ⋂₀ (𝓤 α).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 ∈ 𝓤 α, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ 𝓤 α), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ @[class] def separated (α : Type u) [uniform_space α] := separation_rel α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, (∀ r ∈ 𝓤 α, (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 ∈ 𝓤 α, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [classical.not_forall] @[priority 100] -- see Note [lower instance priority] 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'} ∈ 𝓝 x, from mem_nhds_left x hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ 𝓝 y, 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⟩⟩ @[priority 100] -- see Note [lower instance priority] instance separated_regular [separated α] : regular_space α := { regular := λs a hs ha, have -s ∈ 𝓝 a, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ -s} ∈ 𝓤 α, 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' ∈ 𝓤 α, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ -s, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ 𝓝 a, from (𝓝 a).sets_of_superset (mem_nhds_left a hd) subset_closure, have 𝓝 a ⊓ 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 } /- separation space -/ namespace uniform_space def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ local attribute [instance] separation_setoid instance separation_setoid.uniform_space {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_map.comp tendsto_swap_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) u.uniformity).lift' (λs, comp_rel s s) = u.uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ u.uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ 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⟧)) (u.uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, u.uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, u.uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : 𝓤 (quotient (separation_setoid α)) = (𝓤 α).map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ separation_rel α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ 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 comap_quotient_le_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ (𝓤 α) := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (𝓤 α).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = 𝓤 α := le_antisymm comap_quotient_le_uniformity le_comap_map instance separated_separation : separated (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (𝓤 $ quotient $ separation_setoid α).comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)), from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp [preimage], exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance [inhabited α] : inhabited (separation_quotient α) := by unfold separation_quotient; apply_instance def lift [separated β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (classical.inhabited_of_nonempty $ (nonempty_quotient_iff $ separation_setoid α).1 ⟨x⟩).default lemma lift_mk [separated β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (uniform_continuous_quotient_mk.comp h)] lemma uniform_continuous_map (f : α → β) : uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hg.comp hf) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact H ⟨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 uniform_space
7fa9d1f40b4219b789295c023bf721a50870f811
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/asymptotics/asymptotic_equivalent.lean
914c2fc6e3eacdccd96d8880f5952c2fd740d211
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
10,993
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import analysis.asymptotics.asymptotics import analysis.normed_space.ordered /-! # Asymptotic equivalence In this file, we define the relation `is_equivalent u v l`, which means that `u-v` is little o of `v` along the filter `l`. Unlike `is_[oO]` relations, this one requires `u` and `v` to have the same codomaine `β`. While the definition only requires `β` to be a `normed_group`, most interesting properties require it to be a `normed_field`. ## Notations We introduce the notation `u ~[l] v := is_equivalent u v l`, which you can use by opening the `asymptotics` locale. ## Main results If `β` is a `normed_group` : - `_ ~[l] _` is an equivalence relation - Equivalent statements for `u ~[l] const _ c` : - If `c ≠ 0`, this is true iff `tendsto u l (𝓝 c)` (see `is_equivalent_const_iff_tendsto`) - For `c = 0`, this is true iff `u =ᶠ[l] 0` (see `is_equivalent_zero_iff_eventually_zero`) If `β` is a `normed_field` : - Alternative characterization of the relation (see `is_equivalent_iff_exists_eq_mul`) : `u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v` - Provided some non-vanishing hypothesis, this can be seen as `u ~[l] v ↔ tendsto (u/v) l (𝓝 1)` (see `is_equivalent_iff_tendsto_one`) - For any constant `c`, `u ~[l] v` implies `tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c)` (see `is_equivalent.tendsto_nhds_iff`) - `*` and `/` are compatible with `_ ~[l] _` (see `is_equivalent.mul` and `is_equivalent.div`) If `β` is a `normed_linear_ordered_field` : - If `u ~[l] v`, we have `tendsto u l at_top ↔ tendsto v l at_top` (see `is_equivalent.tendsto_at_top_iff`) -/ namespace asymptotics open filter function open_locale topological_space section normed_group variables {α β : Type*} [normed_group β] /-- Two functions `u` and `v` are said to be asymptotically equivalent along a filter `l` when `u x - v x = o(v x)` as x converges along `l`. -/ def is_equivalent (u v : α → β) (l : filter α) := is_o (u - v) v l localized "notation u ` ~[`:50 l:50 `] `:0 v:50 := asymptotics.is_equivalent u v l" in asymptotics variables {u v w : α → β} {l : filter α} lemma is_equivalent.is_o (h : u ~[l] v) : is_o (u - v) v l := h lemma is_equivalent.is_O (h : u ~[l] v) : is_O u v l := (is_O.congr_of_sub h.is_O.symm).mp (is_O_refl _ _) lemma is_equivalent.is_O_symm (h : u ~[l] v) : is_O v u l := begin convert h.is_o.right_is_O_add, ext, simp end @[refl] lemma is_equivalent.refl : u ~[l] u := begin rw [is_equivalent, sub_self], exact is_o_zero _ _ end @[symm] lemma is_equivalent.symm (h : u ~[l] v) : v ~[l] u := (h.is_o.trans_is_O h.is_O_symm).symm @[trans] lemma is_equivalent.trans (huv : u ~[l] v) (hvw : v ~[l] w) : u ~[l] w := (huv.is_o.trans_is_O hvw.is_O).triangle hvw.is_o lemma is_equivalent.congr_left {u v w : α → β} {l : filter α} (huv : u ~[l] v) (huw : u =ᶠ[l] w) : w ~[l] v := is_o.congr' (huw.sub (eventually_eq.refl _ _)) (eventually_eq.refl _ _) huv lemma is_equivalent.congr_right {u v w : α → β} {l : filter α} (huv : u ~[l] v) (hvw : v =ᶠ[l] w) : u ~[l] w := (huv.symm.congr_left hvw).symm lemma is_equivalent_zero_iff_eventually_zero : u ~[l] 0 ↔ u =ᶠ[l] 0 := begin rw [is_equivalent, sub_zero], exact is_o_zero_right_iff end lemma is_equivalent_zero_iff_is_O_zero : u ~[l] 0 ↔ is_O u (0 : α → β) l := begin refine ⟨is_equivalent.is_O, λ h, _⟩, rw [is_equivalent_zero_iff_eventually_zero, eventually_eq_iff_exists_mem], exact ⟨{x : α | u x = 0}, is_O_zero_right_iff.mp h, λ x hx, hx⟩, end lemma is_equivalent_const_iff_tendsto {c : β} (h : c ≠ 0) : u ~[l] const _ c ↔ tendsto u l (𝓝 c) := begin rw [is_equivalent, is_o_const_iff h], split; intro h; [ { have := h.sub tendsto_const_nhds, rw zero_sub (-c) at this }, { have := h.sub tendsto_const_nhds, rw ← sub_self c} ]; convert this; try { ext }; simp end lemma is_equivalent.tendsto_const {c : β} (hu : u ~[l] const _ c) : tendsto u l (𝓝 c) := begin rcases (em $ c = 0) with ⟨rfl, h⟩, { exact (tendsto_congr' $ is_equivalent_zero_iff_eventually_zero.mp hu).mpr tendsto_const_nhds }, { exact (is_equivalent_const_iff_tendsto h).mp hu } end lemma is_equivalent.tendsto_nhds {c : β} (huv : u ~[l] v) (hu : tendsto u l (𝓝 c)) : tendsto v l (𝓝 c) := begin by_cases h : c = 0, { rw [h, ← is_o_one_iff ℝ] at *, convert (huv.symm.is_o.trans hu).add hu, simp }, { rw ← is_equivalent_const_iff_tendsto h at hu ⊢, exact huv.symm.trans hu } end lemma is_equivalent.tendsto_nhds_iff {c : β} (huv : u ~[l] v) : tendsto u l (𝓝 c) ↔ tendsto v l (𝓝 c) := ⟨huv.tendsto_nhds, huv.symm.tendsto_nhds⟩ lemma is_equivalent.add_is_o (huv : u ~[l] v) (hwv : is_o w v l) : (w + u) ~[l] v := begin rw is_equivalent at *, convert hwv.add huv, ext, simp [add_sub], end lemma is_o.is_equivalent (huv : is_o (u - v) v l) : u ~[l] v := huv lemma is_equivalent.neg (huv : u ~[l] v) : (λ x, - u x) ~[l] (λ x, - v x) := begin rw is_equivalent, convert huv.is_o.neg_left.neg_right, ext, simp, end end normed_group open_locale asymptotics section normed_field variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent_iff_exists_eq_mul : u ~[l] v ↔ ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := begin rw [is_equivalent, is_o_iff_exists_eq_mul], split; rintros ⟨φ, hφ, h⟩; [use (φ + 1), use (φ - 1)]; split, { conv in (𝓝 _) { rw ← zero_add (1 : β) }, exact hφ.add (tendsto_const_nhds) }, { convert h.add (eventually_eq.refl l v); ext; simp [add_mul] }, { conv in (𝓝 _) { rw ← sub_self (1 : β) }, exact hφ.sub (tendsto_const_nhds) }, { convert h.sub (eventually_eq.refl l v); ext; simp [sub_mul] } end lemma is_equivalent.exists_eq_mul (huv : u ~[l] v) : ∃ (φ : α → β) (hφ : tendsto φ l (𝓝 1)), u =ᶠ[l] φ * v := is_equivalent_iff_exists_eq_mul.mp huv lemma is_equivalent_of_tendsto_one (hz : ∀ᶠ x in l, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := begin rw is_equivalent_iff_exists_eq_mul, refine ⟨u/v, huv, hz.mono $ λ x hz', (div_mul_cancel_of_imp hz').symm⟩, end lemma is_equivalent_of_tendsto_one' (hz : ∀ x, v x = 0 → u x = 0) (huv : tendsto (u/v) l (𝓝 1)) : u ~[l] v := is_equivalent_of_tendsto_one (eventually_of_forall hz) huv lemma is_equivalent_iff_tendsto_one (hz : ∀ᶠ x in l, v x ≠ 0) : u ~[l] v ↔ tendsto (u/v) l (𝓝 1) := begin split, { intro hequiv, have := hequiv.is_o.tendsto_0, simp only [pi.sub_apply, sub_div] at this, have key : tendsto (λ x, v x / v x) l (𝓝 1), { exact (tendsto_congr' $ hz.mono $ λ x hnz, @div_self _ _ (v x) hnz).mpr tendsto_const_nhds }, convert this.add key, { ext, simp }, { norm_num } }, { exact is_equivalent_of_tendsto_one (hz.mono $ λ x hnvz hz, (hnvz hz).elim) } end end normed_field section smul lemma is_equivalent.smul {α E 𝕜 : Type*} [normed_field 𝕜] [normed_group E] [normed_space 𝕜 E] {a b : α → 𝕜} {u v : α → E} {l : filter α} (hab : a ~[l] b) (huv : u ~[l] v) : (λ x, a x • u x) ~[l] (λ x, b x • v x) := begin rcases hab.exists_eq_mul with ⟨φ, hφ, habφ⟩, have : (λ (x : α), a x • u x) - (λ (x : α), b x • v x) =ᶠ[l] λ x, b x • ((φ x • u x) - v x), { convert (habφ.comp₂ (•) $ eventually_eq.refl _ u).sub (eventually_eq.refl _ (λ x, b x • v x)), ext, rw [pi.mul_apply, mul_comm, mul_smul, ← smul_sub] }, refine (is_o_congr this.symm $ eventually_eq.rfl).mp ((is_O_refl b l).smul_is_o _), rcases huv.is_O.exists_pos with ⟨C, hC, hCuv⟩, rw is_equivalent at *, rw is_o_iff at *, rw is_O_with at hCuv, simp only [metric.tendsto_nhds, dist_eq_norm] at hφ, intros c hc, specialize hφ ((c/2)/C) (div_pos (by linarith) hC), specialize huv (show 0 < c/2, by linarith), refine hφ.mp (huv.mp $ hCuv.mono $ λ x hCuvx huvx hφx, _), have key := calc ∥φ x - 1∥ * ∥u x∥ ≤ (c/2) / C * ∥u x∥ : mul_le_mul_of_nonneg_right hφx.le (norm_nonneg $ u x) ... ≤ (c/2) / C * (C*∥v x∥) : mul_le_mul_of_nonneg_left hCuvx (div_pos (by linarith) hC).le ... = c/2 * ∥v x∥ : by {field_simp [hC.ne.symm], ring}, calc ∥((λ (x : α), φ x • u x) - v) x∥ = ∥(φ x - 1) • u x + (u x - v x)∥ : by simp [sub_smul, sub_add] ... ≤ ∥(φ x - 1) • u x∥ + ∥u x - v x∥ : norm_add_le _ _ ... = ∥φ x - 1∥ * ∥u x∥ + ∥u x - v x∥ : by rw norm_smul ... ≤ c / 2 * ∥v x∥ + ∥u x - v x∥ : add_le_add_right key _ ... ≤ c / 2 * ∥v x∥ + c / 2 * ∥v x∥ : add_le_add_left huvx _ ... = c * ∥v x∥ : by ring, end end smul section mul_inv variables {α β : Type*} [normed_field β] {t u v w : α → β} {l : filter α} lemma is_equivalent.mul (htu : t ~[l] u) (hvw : v ~[l] w) : t * v ~[l] u * w := htu.smul hvw lemma is_equivalent.inv (huv : u ~[l] v) : (λ x, (u x)⁻¹) ~[l] (λ x, (v x)⁻¹) := begin rw is_equivalent_iff_exists_eq_mul at *, rcases huv with ⟨φ, hφ, h⟩, rw ← inv_one, refine ⟨λ x, (φ x)⁻¹, tendsto.inv' hφ (by norm_num) , _⟩, convert h.inv, ext, simp [mul_inv'] end lemma is_equivalent.div (htu : t ~[l] u) (hvw : v ~[l] w) : (λ x, t x / v x) ~[l] (λ x, u x / w x) := by simpa only [div_eq_mul_inv] using htu.mul hvw.inv end mul_inv section normed_linear_ordered_field variables {α β : Type*} [normed_linear_ordered_field β] {u v : α → β} {l : filter α} lemma is_equivalent.tendsto_at_top [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_top) : tendsto v l at_top := let ⟨φ, hφ, h⟩ := huv.symm.exists_eq_mul in tendsto.congr' h.symm ((mul_comm u φ) ▸ (hu.at_top_mul zero_lt_one hφ)) lemma is_equivalent.tendsto_at_top_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_top ↔ tendsto v l at_top := ⟨huv.tendsto_at_top, huv.symm.tendsto_at_top⟩ lemma is_equivalent.tendsto_at_bot [order_topology β] (huv : u ~[l] v) (hu : tendsto u l at_bot) : tendsto v l at_bot := begin convert tendsto_neg_at_top_at_bot.comp (huv.neg.tendsto_at_top $ tendsto_neg_at_bot_at_top.comp hu), ext, simp end lemma is_equivalent.tendsto_at_bot_iff [order_topology β] (huv : u ~[l] v) : tendsto u l at_bot ↔ tendsto v l at_bot := ⟨huv.tendsto_at_bot, huv.symm.tendsto_at_bot⟩ end normed_linear_ordered_field end asymptotics open filter asymptotics open_locale asymptotics variables {α β : Type*} [normed_group β] lemma filter.eventually_eq.is_equivalent {u v : α → β} {l : filter α} (h : u =ᶠ[l] v) : u ~[l] v := is_o.congr' h.sub_eq.symm (eventually_eq.refl _ _) (is_o_zero v l)
f090bc3c963d7e6c0c76c0baf180da9b1f5ac1b8
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/metric_space/completion.lean
e801ac609b1e741f66903a2c765c9ee9107f9e6d
[ "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
8,574
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.uniform_space.completion topology.metric_space.isometry /-! # The completion of a metric space Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show here that the uniform space completion of a metric space inherits a metric space structure, by extending the distance to the completion and checking that it is indeed a distance, and that it defines the same uniformity as the already defined uniform structure on the completion -/ open set filter uniform_space uniform_space.completion noncomputable theory universes u variables {α : Type u} [metric_space α] namespace metric /-- The distance on the completion is obtained by extending the distance on the original space, by uniform continuity. -/ instance : has_dist (completion α) := ⟨completion.extension₂ dist⟩ /-- The new distance is uniformly continuous. -/ protected lemma completion.uniform_continuous_dist : uniform_continuous (λp:completion α × completion α, dist p.1 p.2) := uniform_continuous_extension₂ dist /-- The new distance is an extension of the original distance. -/ protected lemma completion.dist_eq (x y : α) : dist (x : completion α) y = dist x y := completion.extension₂_coe_coe uniform_continuous_dist' _ _ /- Let us check that the new distance satisfies the axioms of a distance, by starting from the properties on α and extending them to `completion α` by continuity. -/ protected lemma completion.dist_self (x : completion α) : dist x x = 0 := begin apply induction_on x, { refine is_closed_eq _ continuous_const, exact (completion.uniform_continuous_dist.continuous.comp (continuous.prod_mk continuous_id continuous_id) : _) }, { assume a, rw [completion.dist_eq, dist_self] } end protected lemma completion.dist_comm (x y : completion α) : dist x y = dist y x := begin apply induction_on₂ x y, { refine is_closed_eq completion.uniform_continuous_dist.continuous _, exact (completion.uniform_continuous_dist.continuous.comp continuous_swap : _) }, { assume a b, rw [completion.dist_eq, completion.dist_eq, dist_comm] } end protected lemma completion.dist_triangle (x y z : completion α) : dist x z ≤ dist x y + dist y z := begin apply induction_on₃ x y z, { refine is_closed_le _ (continuous.add _ _), { have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.2)) := continuous.prod_mk continuous_fst (continuous.comp continuous_snd continuous_snd), exact (completion.uniform_continuous_dist.continuous.comp this : _) }, { have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.1)) := continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd), exact (completion.uniform_continuous_dist.continuous.comp this : _) }, { have : continuous (λp : completion α × completion α × completion α, (p.2.1, p.2.2)) := continuous.prod_mk (continuous_fst.comp continuous_snd) (continuous.comp continuous_snd continuous_snd), exact (continuous.comp completion.uniform_continuous_dist.continuous this : _) } }, { assume a b c, rw [completion.dist_eq, completion.dist_eq, completion.dist_eq], exact dist_triangle a b c } end /-- Elements of the uniformity (defined generally for completions) can be characterized in terms of the distance. -/ protected lemma completion.mem_uniformity_dist (s : set (completion α × completion α)) : s ∈ uniformity (completion α) ↔ (∃ε>0, ∀{a b}, dist a b < ε → (a, b) ∈ s) := begin split, { /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in α is an entourage, so it contains an ε-neighborhood of the diagonal by definition of the entourages in metric spaces. Then `t` contains an ε-neighborhood of the diagonal in `completion α`, as closed properties pass to the completion. -/ assume hs, rcases mem_uniformity_is_closed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩, have A : {x : α × α | (coe (x.1), coe (x.2)) ∈ t} ∈ uniformity α := uniform_continuous_def.1 (uniform_continuous_coe α) t ht, rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩, refine ⟨ε, εpos, λx y hxy, _⟩, have : ε ≤ dist x y ∨ (x, y) ∈ t, { apply induction_on₂ x y, { have : {x : completion α × completion α | ε ≤ dist (x.fst) (x.snd) ∨ (x.fst, x.snd) ∈ t} = {p : completion α × completion α | ε ≤ dist p.1 p.2} ∪ t, by ext; simp, rw this, apply is_closed_union _ tclosed, exact is_closed_le continuous_const completion.uniform_continuous_dist.continuous }, { assume x y, rw completion.dist_eq, by_cases h : ε ≤ dist x y, { exact or.inl h }, { have Z := hε (not_le.1 h), simp only [set.mem_set_of_eq] at Z, exact or.inr Z }}}, simp only [not_le.mpr hxy, false_or, not_le] at this, exact ts this }, { /- Start from a set `s` containing an ε-neighborhood of the diagonal in `completion α`. To show that it is an entourage, we use the fact that `dist` is uniformly continuous on `completion α × completion α` (this is a general property of the extension of uniformly continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ is an entourage in `completion α × completion α`. Massaging this property, it follows that the ε-neighborhood of the diagonal is an entourage in `completion α`, and therefore this is also the case of `s`. -/ rintros ⟨ε, εpos, hε⟩, let r : set (ℝ × ℝ) := {p | dist p.1 p.2 < ε}, have : r ∈ uniformity ℝ := metric.dist_mem_uniformity εpos, have T := uniform_continuous_def.1 (@completion.uniform_continuous_dist α _) r this, simp only [uniformity_prod_eq_prod, mem_prod_iff, exists_prop, filter.mem_map, set.mem_set_of_eq] at T, rcases T with ⟨t1, ht1, t2, ht2, ht⟩, refine mem_sets_of_superset ht1 _, have A : ∀a b : completion α, (a, b) ∈ t1 → dist a b < ε, { assume a b hab, have : ((a, b), (a, a)) ∈ set.prod t1 t2 := ⟨hab, refl_mem_uniformity ht2⟩, have I := ht this, simp [completion.dist_self, real.dist_eq, completion.dist_comm] at I, exact lt_of_le_of_lt (le_abs_self _) I }, show t1 ⊆ s, { rintros ⟨a, b⟩ hp, have : dist a b < ε := A a b hp, exact hε this }} end /-- If two points are at distance 0, then they coincide. -/ protected lemma completion.eq_of_dist_eq_zero (x y : completion α) (h : dist x y = 0) : x = y := begin /- This follows from the separation of `completion α` and from the description of entourages in terms of the distance. -/ have : separated (completion α) := by apply_instance, refine separated_def.1 this x y (λs hs, _), rcases (completion.mem_uniformity_dist s).1 hs with ⟨ε, εpos, hε⟩, rw ← h at εpos, exact hε εpos end /- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition of the metric space structure. -/ protected lemma completion.uniformity_dist' : uniformity (completion α) = (⨅ε:{ε:ℝ // ε>0}, principal {p | dist p.1 p.2 < ε.val}) := begin ext s, rw mem_infi, { simp [completion.mem_uniformity_dist, subset_def] }, { rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩, simp [lt_min_iff, (≥)] {contextual := tt} }, { exact ⟨⟨1, zero_lt_one⟩⟩ } end protected lemma completion.uniformity_dist : uniformity (completion α) = (⨅ ε>0, principal {p | dist p.1 p.2 < ε}) := by simpa [infi_subtype] using @completion.uniformity_dist' α _ /-- Metric space structure on the completion of a metric space. -/ instance completion.metric_space : metric_space (completion α) := { dist_self := completion.dist_self, eq_of_dist_eq_zero := completion.eq_of_dist_eq_zero, dist_comm := completion.dist_comm, dist_triangle := completion.dist_triangle, to_uniform_space := by apply_instance, uniformity_dist := completion.uniformity_dist } /-- The embedding of a metric space in its completion is an isometry. -/ lemma completion.coe_isometry : isometry (coe : α → completion α) := isometry_emetric_iff_metric.2 completion.dist_eq end metric
e6a0f4b783541e72a772f472b2a3f53bf95ab264
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/monotone/basic.lean
9ca070071a7ca93fe28a09050a195cd6b584fe20
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
39,308
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Yaël Dillies -/ import order.compare import order.max import order.rel_classes /-! # Monotonicity > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines (strictly) monotone/antitone functions. Contrary to standard mathematical usage, "monotone"/"mono" here means "increasing", not "increasing or decreasing". We use "antitone"/"anti" to mean "decreasing". ## Definitions * `monotone f`: A function `f` between two preorders is monotone if `a ≤ b` implies `f a ≤ f b`. * `antitone f`: A function `f` between two preorders is antitone if `a ≤ b` implies `f b ≤ f a`. * `monotone_on f s`: Same as `monotone f`, but for all `a, b ∈ s`. * `antitone_on f s`: Same as `antitone f`, but for all `a, b ∈ s`. * `strict_mono f` : A function `f` between two preorders is strictly monotone if `a < b` implies `f a < f b`. * `strict_anti f` : A function `f` between two preorders is strictly antitone if `a < b` implies `f b < f a`. * `strict_mono_on f s`: Same as `strict_mono f`, but for all `a, b ∈ s`. * `strict_anti_on f s`: Same as `strict_anti f`, but for all `a, b ∈ s`. ## Main theorems * `monotone_nat_of_le_succ`, `monotone_int_of_le_succ`: If `f : ℕ → α` or `f : ℤ → α` and `f n ≤ f (n + 1)` for all `n`, then `f` is monotone. * `antitone_nat_of_succ_le`, `antitone_int_of_succ_le`: If `f : ℕ → α` or `f : ℤ → α` and `f (n + 1) ≤ f n` for all `n`, then `f` is antitone. * `strict_mono_nat_of_lt_succ`, `strict_mono_int_of_lt_succ`: If `f : ℕ → α` or `f : ℤ → α` and `f n < f (n + 1)` for all `n`, then `f` is strictly monotone. * `strict_anti_nat_of_succ_lt`, `strict_anti_int_of_succ_lt`: If `f : ℕ → α` or `f : ℤ → α` and `f (n + 1) < f n` for all `n`, then `f` is strictly antitone. ## Implementation notes Some of these definitions used to only require `has_le α` or `has_lt α`. The advantage of this is unclear and it led to slight elaboration issues. Now, everything requires `preorder α` and seems to work fine. Related Zulip discussion: https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/Order.20diamond/near/254353352. ## TODO The above theorems are also true in `ℕ+`, `fin n`... To make that work, we need `succ_order α` and `succ_archimedean α`. ## Tags monotone, strictly monotone, antitone, strictly antitone, increasing, strictly increasing, decreasing, strictly decreasing -/ open function order_dual universes u v w variables {ι : Type*} {α : Type u} {β : Type v} {γ : Type w} {δ : Type*} {π : ι → Type*} {r : α → α → Prop} section monotone_def variables [preorder α] [preorder β] /-- A function `f` is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) : Prop := ∀ ⦃a b⦄, a ≤ b → f a ≤ f b /-- A function `f` is antitone if `a ≤ b` implies `f b ≤ f a`. -/ def antitone (f : α → β) : Prop := ∀ ⦃a b⦄, a ≤ b → f b ≤ f a /-- A function `f` is monotone on `s` if, for all `a, b ∈ s`, `a ≤ b` implies `f a ≤ f b`. -/ def monotone_on (f : α → β) (s : set α) : Prop := ∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a ≤ b → f a ≤ f b /-- A function `f` is antitone on `s` if, for all `a, b ∈ s`, `a ≤ b` implies `f b ≤ f a`. -/ def antitone_on (f : α → β) (s : set α) : Prop := ∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a ≤ b → f b ≤ f a /-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/ def strict_mono (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f a < f b /-- A function `f` is strictly antitone if `a < b` implies `f b < f a`. -/ def strict_anti (f : α → β) : Prop := ∀ ⦃a b⦄, a < b → f b < f a /-- A function `f` is strictly monotone on `s` if, for all `a, b ∈ s`, `a < b` implies `f a < f b`. -/ def strict_mono_on (f : α → β) (s : set α) : Prop := ∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a < b → f a < f b /-- A function `f` is strictly antitone on `s` if, for all `a, b ∈ s`, `a < b` implies `f b < f a`. -/ def strict_anti_on (f : α → β) (s : set α) : Prop := ∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a < b → f b < f a end monotone_def section decidable variables [preorder α] [preorder β] {f : α → β} {s : set α} instance [i : decidable (∀ a b, a ≤ b → f a ≤ f b)] : decidable (monotone f) := i instance [i : decidable (∀ a b, a ≤ b → f b ≤ f a)] : decidable (antitone f) := i instance [i : decidable (∀ a b ∈ s, a ≤ b → f a ≤ f b)] : decidable (monotone_on f s) := i instance [i : decidable (∀ a b ∈ s, a ≤ b → f b ≤ f a)] : decidable (antitone_on f s) := i instance [i : decidable (∀ a b, a < b → f a < f b)] : decidable (strict_mono f) := i instance [i : decidable (∀ a b, a < b → f b < f a)] : decidable (strict_anti f) := i instance [i : decidable (∀ a b ∈ s, a < b → f a < f b)] : decidable (strict_mono_on f s) := i instance [i : decidable (∀ a b ∈ s, a < b → f b < f a)] : decidable (strict_anti_on f s) := i end decidable /-! ### Monotonicity on the dual order Strictly, many of the `*_on.dual` lemmas in this section should use `of_dual ⁻¹' s` instead of `s`, but right now this is not possible as `set.preimage` is not defined yet, and importing it creates an import cycle. Often, you should not need the rewriting lemmas. Instead, you probably want to add `.dual`, `.dual_left` or `.dual_right` to your `monotone`/`antitone` hypothesis. -/ section order_dual variables [preorder α] [preorder β] {f : α → β} {s : set α} @[simp] lemma monotone_comp_of_dual_iff : monotone (f ∘ of_dual) ↔ antitone f := forall_swap @[simp] lemma antitone_comp_of_dual_iff : antitone (f ∘ of_dual) ↔ monotone f := forall_swap @[simp] lemma monotone_to_dual_comp_iff : monotone (to_dual ∘ f) ↔ antitone f := iff.rfl @[simp] lemma antitone_to_dual_comp_iff : antitone (to_dual ∘ f) ↔ monotone f := iff.rfl @[simp] lemma monotone_on_comp_of_dual_iff : monotone_on (f ∘ of_dual) s ↔ antitone_on f s := forall₂_swap @[simp] lemma antitone_on_comp_of_dual_iff : antitone_on (f ∘ of_dual) s ↔ monotone_on f s := forall₂_swap @[simp] lemma monotone_on_to_dual_comp_iff : monotone_on (to_dual ∘ f) s ↔ antitone_on f s := iff.rfl @[simp] lemma antitone_on_to_dual_comp_iff : antitone_on (to_dual ∘ f) s ↔ monotone_on f s := iff.rfl @[simp] lemma strict_mono_comp_of_dual_iff : strict_mono (f ∘ of_dual) ↔ strict_anti f := forall_swap @[simp] lemma strict_anti_comp_of_dual_iff : strict_anti (f ∘ of_dual) ↔ strict_mono f := forall_swap @[simp] lemma strict_mono_to_dual_comp_iff : strict_mono (to_dual ∘ f) ↔ strict_anti f := iff.rfl @[simp] lemma strict_anti_to_dual_comp_iff : strict_anti (to_dual ∘ f) ↔ strict_mono f := iff.rfl @[simp] lemma strict_mono_on_comp_of_dual_iff : strict_mono_on (f ∘ of_dual) s ↔ strict_anti_on f s := forall₂_swap @[simp] lemma strict_anti_on_comp_of_dual_iff : strict_anti_on (f ∘ of_dual) s ↔ strict_mono_on f s := forall₂_swap @[simp] lemma strict_mono_on_to_dual_comp_iff : strict_mono_on (to_dual ∘ f) s ↔ strict_anti_on f s := iff.rfl @[simp] lemma strict_anti_on_to_dual_comp_iff : strict_anti_on (to_dual ∘ f) s ↔ strict_mono_on f s := iff.rfl protected lemma monotone.dual (hf : monotone f) : monotone (to_dual ∘ f ∘ of_dual) := swap hf protected lemma antitone.dual (hf : antitone f) : antitone (to_dual ∘ f ∘ of_dual) := swap hf protected lemma monotone_on.dual (hf : monotone_on f s) : monotone_on (to_dual ∘ f ∘ of_dual) s := swap₂ hf protected lemma antitone_on.dual (hf : antitone_on f s) : antitone_on (to_dual ∘ f ∘ of_dual) s := swap₂ hf protected lemma strict_mono.dual (hf : strict_mono f) : strict_mono (to_dual ∘ f ∘ of_dual) := swap hf protected lemma strict_anti.dual (hf : strict_anti f) : strict_anti (to_dual ∘ f ∘ of_dual) := swap hf protected lemma strict_mono_on.dual (hf : strict_mono_on f s) : strict_mono_on (to_dual ∘ f ∘ of_dual) s := swap₂ hf protected lemma strict_anti_on.dual (hf : strict_anti_on f s) : strict_anti_on (to_dual ∘ f ∘ of_dual) s := swap₂ hf alias antitone_comp_of_dual_iff ↔ _ monotone.dual_left alias monotone_comp_of_dual_iff ↔ _ antitone.dual_left alias antitone_to_dual_comp_iff ↔ _ monotone.dual_right alias monotone_to_dual_comp_iff ↔ _ antitone.dual_right alias antitone_on_comp_of_dual_iff ↔ _ monotone_on.dual_left alias monotone_on_comp_of_dual_iff ↔ _ antitone_on.dual_left alias antitone_on_to_dual_comp_iff ↔ _ monotone_on.dual_right alias monotone_on_to_dual_comp_iff ↔ _ antitone_on.dual_right alias strict_anti_comp_of_dual_iff ↔ _ strict_mono.dual_left alias strict_mono_comp_of_dual_iff ↔ _ strict_anti.dual_left alias strict_anti_to_dual_comp_iff ↔ _ strict_mono.dual_right alias strict_mono_to_dual_comp_iff ↔ _ strict_anti.dual_right alias strict_anti_on_comp_of_dual_iff ↔ _ strict_mono_on.dual_left alias strict_mono_on_comp_of_dual_iff ↔ _ strict_anti_on.dual_left alias strict_anti_on_to_dual_comp_iff ↔ _ strict_mono_on.dual_right alias strict_mono_on_to_dual_comp_iff ↔ _ strict_anti_on.dual_right end order_dual /-! ### Monotonicity in function spaces -/ section preorder variables [preorder α] theorem monotone.comp_le_comp_left [preorder β] {f : β → α} {g h : γ → β} (hf : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := λ x, hf (le_gh x) variables [preorder γ] theorem monotone_lam {f : α → β → γ} (hf : ∀ b, monotone (λ a, f a b)) : monotone f := λ a a' h b, hf b h theorem monotone_app (f : β → α → γ) (b : β) (hf : monotone (λ a b, f b a)) : monotone (f b) := λ a a' h, hf h b theorem antitone_lam {f : α → β → γ} (hf : ∀ b, antitone (λ a, f a b)) : antitone f := λ a a' h b, hf b h theorem antitone_app (f : β → α → γ) (b : β) (hf : antitone (λ a b, f b a)) : antitone (f b) := λ a a' h, hf h b end preorder lemma function.monotone_eval {ι : Type u} {α : ι → Type v} [∀ i, preorder (α i)] (i : ι) : monotone (function.eval i : (Π i, α i) → α i) := λ f g H, H i /-! ### Monotonicity hierarchy -/ section preorder variables [preorder α] section preorder variables [preorder β] {f : α → β} {s : set α} {a b : α} /-! These four lemmas are there to strip off the semi-implicit arguments `⦃a b : α⦄`. This is useful when you do not want to apply a `monotone` assumption (i.e. your goal is `a ≤ b → f a ≤ f b`). However if you find yourself writing `hf.imp h`, then you should have written `hf h` instead. -/ lemma monotone.imp (hf : monotone f) (h : a ≤ b) : f a ≤ f b := hf h lemma antitone.imp (hf : antitone f) (h : a ≤ b) : f b ≤ f a := hf h lemma strict_mono.imp (hf : strict_mono f) (h : a < b) : f a < f b := hf h lemma strict_anti.imp (hf : strict_anti f) (h : a < b) : f b < f a := hf h protected lemma monotone.monotone_on (hf : monotone f) (s : set α) : monotone_on f s := λ a _ b _, hf.imp protected lemma antitone.antitone_on (hf : antitone f) (s : set α) : antitone_on f s := λ a _ b _, hf.imp @[simp] lemma monotone_on_univ : monotone_on f set.univ ↔ monotone f := ⟨λ h a b, h trivial trivial, λ h, h.monotone_on _⟩ @[simp] lemma antitone_on_univ : antitone_on f set.univ ↔ antitone f := ⟨λ h a b, h trivial trivial, λ h, h.antitone_on _⟩ protected lemma strict_mono.strict_mono_on (hf : strict_mono f) (s : set α) : strict_mono_on f s := λ a _ b _, hf.imp protected lemma strict_anti.strict_anti_on (hf : strict_anti f) (s : set α) : strict_anti_on f s := λ a _ b _, hf.imp @[simp] lemma strict_mono_on_univ : strict_mono_on f set.univ ↔ strict_mono f := ⟨λ h a b, h trivial trivial, λ h, h.strict_mono_on _⟩ @[simp] lemma strict_anti_on_univ : strict_anti_on f set.univ ↔ strict_anti f := ⟨λ h a b, h trivial trivial, λ h, h.strict_anti_on _⟩ end preorder section partial_order variables [partial_order β] {f : α → β} lemma monotone.strict_mono_of_injective (h₁ : monotone f) (h₂ : injective f) : strict_mono f := λ a b h, (h₁ h.le).lt_of_ne (λ H, h.ne $ h₂ H) lemma antitone.strict_anti_of_injective (h₁ : antitone f) (h₂ : injective f) : strict_anti f := λ a b h, (h₁ h.le).lt_of_ne (λ H, h.ne $ h₂ H.symm) end partial_order end preorder section partial_order variables [partial_order α] [preorder β] {f : α → β} {s : set α} lemma monotone_iff_forall_lt : monotone f ↔ ∀ ⦃a b⦄, a < b → f a ≤ f b := forall₂_congr $ λ a b, ⟨λ hf h, hf h.le, λ hf h, h.eq_or_lt.elim (λ H, (congr_arg _ H).le) hf⟩ lemma antitone_iff_forall_lt : antitone f ↔ ∀ ⦃a b⦄, a < b → f b ≤ f a := forall₂_congr $ λ a b, ⟨λ hf h, hf h.le, λ hf h, h.eq_or_lt.elim (λ H, (congr_arg _ H).ge) hf⟩ lemma monotone_on_iff_forall_lt : monotone_on f s ↔ ∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a < b → f a ≤ f b := ⟨λ hf a ha b hb h, hf ha hb h.le, λ hf a ha b hb h, h.eq_or_lt.elim (λ H, (congr_arg _ H).le) (hf ha hb)⟩ lemma antitone_on_iff_forall_lt : antitone_on f s ↔ ∀ ⦃a⦄ (ha : a ∈ s) ⦃b⦄ (hb : b ∈ s), a < b → f b ≤ f a := ⟨λ hf a ha b hb h, hf ha hb h.le, λ hf a ha b hb h, h.eq_or_lt.elim (λ H, (congr_arg _ H).ge) (hf ha hb)⟩ -- `preorder α` isn't strong enough: if the preorder on `α` is an equivalence relation, -- then `strict_mono f` is vacuously true. protected lemma strict_mono_on.monotone_on (hf : strict_mono_on f s) : monotone_on f s := monotone_on_iff_forall_lt.2 $ λ a ha b hb h, (hf ha hb h).le protected lemma strict_anti_on.antitone_on (hf : strict_anti_on f s) : antitone_on f s := antitone_on_iff_forall_lt.2 $ λ a ha b hb h, (hf ha hb h).le protected lemma strict_mono.monotone (hf : strict_mono f) : monotone f := monotone_iff_forall_lt.2 $ λ a b h, (hf h).le protected lemma strict_anti.antitone (hf : strict_anti f) : antitone f := antitone_iff_forall_lt.2 $ λ a b h, (hf h).le end partial_order /-! ### Monotonicity from and to subsingletons -/ namespace subsingleton variables [preorder α] [preorder β] protected lemma monotone [subsingleton α] (f : α → β) : monotone f := λ a b _, (congr_arg _ $ subsingleton.elim _ _).le protected lemma antitone [subsingleton α] (f : α → β) : antitone f := λ a b _, (congr_arg _ $ subsingleton.elim _ _).le lemma monotone' [subsingleton β] (f : α → β) : monotone f := λ a b _, (subsingleton.elim _ _).le lemma antitone' [subsingleton β] (f : α → β) : antitone f := λ a b _, (subsingleton.elim _ _).le protected lemma strict_mono [subsingleton α] (f : α → β) : strict_mono f := λ a b h, (h.ne $ subsingleton.elim _ _).elim protected lemma strict_anti [subsingleton α] (f : α → β) : strict_anti f := λ a b h, (h.ne $ subsingleton.elim _ _).elim end subsingleton /-! ### Miscellaneous monotonicity results -/ lemma monotone_id [preorder α] : monotone (id : α → α) := λ a b, id lemma monotone_on_id [preorder α] {s : set α} : monotone_on id s := λ a ha b hb, id lemma strict_mono_id [preorder α] : strict_mono (id : α → α) := λ a b, id lemma strict_mono_on_id [preorder α] {s : set α} : strict_mono_on id s := λ a ha b hb, id theorem monotone_const [preorder α] [preorder β] {c : β} : monotone (λ (a : α), c) := λ a b _, le_rfl theorem monotone_on_const [preorder α] [preorder β] {c : β} {s : set α} : monotone_on (λ (a : α), c) s := λ a _ b _ _, le_rfl theorem antitone_const [preorder α] [preorder β] {c : β} : antitone (λ (a : α), c) := λ a b _, le_refl c theorem antitone_on_const [preorder α] [preorder β] {c : β} {s : set α} : antitone_on (λ (a : α), c) s := λ a _ b _ _, le_rfl lemma strict_mono_of_le_iff_le [preorder α] [preorder β] {f : α → β} (h : ∀ x y, x ≤ y ↔ f x ≤ f y) : strict_mono f := λ a b, (lt_iff_lt_of_le_iff_le' (h _ _) (h _ _)).1 lemma strict_anti_of_le_iff_le [preorder α] [preorder β] {f : α → β} (h : ∀ x y, x ≤ y ↔ f y ≤ f x) : strict_anti f := λ a b, (lt_iff_lt_of_le_iff_le' (h _ _) (h _ _)).1 lemma injective_of_lt_imp_ne [linear_order α] {f : α → β} (h : ∀ x y, x < y → f x ≠ f y) : injective f := begin intros x y hxy, contrapose hxy, cases ne.lt_or_lt hxy with hxy hxy, exacts [h _ _ hxy, (h _ _ hxy).symm] end lemma injective_of_le_imp_le [partial_order α] [preorder β] (f : α → β) (h : ∀ {x y}, f x ≤ f y → x ≤ y) : injective f := λ x y hxy, (h hxy.le).antisymm (h hxy.ge) section preorder variables [preorder α] [preorder β] {f g : α → β} {a : α} lemma strict_mono.is_max_of_apply (hf : strict_mono f) (ha : is_max (f a)) : is_max a := of_not_not $ λ h, let ⟨b, hb⟩ := not_is_max_iff.1 h in (hf hb).not_is_max ha lemma strict_mono.is_min_of_apply (hf : strict_mono f) (ha : is_min (f a)) : is_min a := of_not_not $ λ h, let ⟨b, hb⟩ := not_is_min_iff.1 h in (hf hb).not_is_min ha lemma strict_anti.is_max_of_apply (hf : strict_anti f) (ha : is_min (f a)) : is_max a := of_not_not $ λ h, let ⟨b, hb⟩ := not_is_max_iff.1 h in (hf hb).not_is_min ha lemma strict_anti.is_min_of_apply (hf : strict_anti f) (ha : is_max (f a)) : is_min a := of_not_not $ λ h, let ⟨b, hb⟩ := not_is_min_iff.1 h in (hf hb).not_is_max ha protected lemma strict_mono.ite' (hf : strict_mono f) (hg : strict_mono g) {p : α → Prop} [decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ ⦃x y⦄, p x → ¬p y → x < y → f x < g y) : strict_mono (λ x, if p x then f x else g x) := begin intros x y h, by_cases hy : p y, { have hx : p x := hp h hy, simpa [hx, hy] using hf h }, by_cases hx : p x, { simpa [hx, hy] using hfg hx hy h }, { simpa [hx, hy] using hg h} end protected lemma strict_mono.ite (hf : strict_mono f) (hg : strict_mono g) {p : α → Prop} [decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ x, f x ≤ g x) : strict_mono (λ x, if p x then f x else g x) := hf.ite' hg hp $ λ x y hx hy h, (hf h).trans_le (hfg y) protected lemma strict_anti.ite' (hf : strict_anti f) (hg : strict_anti g) {p : α → Prop} [decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ ⦃x y⦄, p x → ¬p y → x < y → g y < f x) : strict_anti (λ x, if p x then f x else g x) := (strict_mono.ite' hf.dual_right hg.dual_right hp hfg).dual_right protected lemma strict_anti.ite (hf : strict_anti f) (hg : strict_anti g) {p : α → Prop} [decidable_pred p] (hp : ∀ ⦃x y⦄, x < y → p y → p x) (hfg : ∀ x, g x ≤ f x) : strict_anti (λ x, if p x then f x else g x) := hf.ite' hg hp $ λ x y hx hy h, (hfg y).trans_lt (hf h) end preorder /-! ### Monotonicity under composition -/ section composition variables [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} protected lemma monotone.comp (hg : monotone g) (hf : monotone f) : monotone (g ∘ f) := λ a b h, hg (hf h) lemma monotone.comp_antitone (hg : monotone g) (hf : antitone f) : antitone (g ∘ f) := λ a b h, hg (hf h) protected lemma antitone.comp (hg : antitone g) (hf : antitone f) : monotone (g ∘ f) := λ a b h, hg (hf h) lemma antitone.comp_monotone (hg : antitone g) (hf : monotone f) : antitone (g ∘ f) := λ a b h, hg (hf h) protected lemma monotone.iterate {f : α → α} (hf : monotone f) (n : ℕ) : monotone (f^[n]) := nat.rec_on n monotone_id (λ n h, h.comp hf) protected lemma monotone.comp_monotone_on (hg : monotone g) (hf : monotone_on f s) : monotone_on (g ∘ f) s := λ a ha b hb h, hg (hf ha hb h) lemma monotone.comp_antitone_on (hg : monotone g) (hf : antitone_on f s) : antitone_on (g ∘ f) s := λ a ha b hb h, hg (hf ha hb h) protected lemma antitone.comp_antitone_on (hg : antitone g) (hf : antitone_on f s) : monotone_on (g ∘ f) s := λ a ha b hb h, hg (hf ha hb h) lemma antitone.comp_monotone_on (hg : antitone g) (hf : monotone_on f s) : antitone_on (g ∘ f) s := λ a ha b hb h, hg (hf ha hb h) protected lemma strict_mono.comp (hg : strict_mono g) (hf : strict_mono f) : strict_mono (g ∘ f) := λ a b h, hg (hf h) lemma strict_mono.comp_strict_anti (hg : strict_mono g) (hf : strict_anti f) : strict_anti (g ∘ f) := λ a b h, hg (hf h) protected lemma strict_anti.comp (hg : strict_anti g) (hf : strict_anti f) : strict_mono (g ∘ f) := λ a b h, hg (hf h) lemma strict_anti.comp_strict_mono (hg : strict_anti g) (hf : strict_mono f) : strict_anti (g ∘ f) := λ a b h, hg (hf h) protected lemma strict_mono.iterate {f : α → α} (hf : strict_mono f) (n : ℕ) : strict_mono (f^[n]) := nat.rec_on n strict_mono_id (λ n h, h.comp hf) protected lemma strict_mono.comp_strict_mono_on (hg : strict_mono g) (hf : strict_mono_on f s) : strict_mono_on (g ∘ f) s := λ a ha b hb h, hg (hf ha hb h) lemma strict_mono.comp_strict_anti_on (hg : strict_mono g) (hf : strict_anti_on f s) : strict_anti_on (g ∘ f) s := λ a ha b hb h, hg (hf ha hb h) protected lemma strict_anti.comp_strict_anti_on (hg : strict_anti g) (hf : strict_anti_on f s) : strict_mono_on (g ∘ f) s := λ a ha b hb h, hg (hf ha hb h) lemma strict_anti.comp_strict_mono_on (hg : strict_anti g) (hf : strict_mono_on f s) : strict_anti_on (g ∘ f) s := λ a ha b hb h, hg (hf ha hb h) end composition namespace list section fold theorem foldl_monotone [preorder α] {f : α → β → α} (H : ∀ b, monotone (λ a, f a b)) (l : list β) : monotone (λ a, l.foldl f a) := list.rec_on l (λ _ _, id) (λ i l hl _ _ h, hl (H _ h)) theorem foldr_monotone [preorder β] {f : α → β → β} (H : ∀ a, monotone (f a)) (l : list α) : monotone (λ b, l.foldr f b) := λ _ _ h, list.rec_on l h (λ i l hl, H i hl) theorem foldl_strict_mono [preorder α] {f : α → β → α} (H : ∀ b, strict_mono (λ a, f a b)) (l : list β) : strict_mono (λ a, l.foldl f a) := list.rec_on l (λ _ _, id) (λ i l hl _ _ h, hl (H _ h)) theorem foldr_strict_mono [preorder β] {f : α → β → β} (H : ∀ a, strict_mono (f a)) (l : list α) : strict_mono (λ b, l.foldr f b) := λ _ _ h, list.rec_on l h (λ i l hl, H i hl) end fold end list /-! ### Monotonicity in linear orders -/ section linear_order variables [linear_order α] section preorder variables [preorder β] {f : α → β} {s : set α} open ordering lemma monotone.reflect_lt (hf : monotone f) {a b : α} (h : f a < f b) : a < b := lt_of_not_ge (λ h', h.not_le (hf h')) lemma antitone.reflect_lt (hf : antitone f) {a b : α} (h : f a < f b) : b < a := lt_of_not_ge (λ h', h.not_le (hf h')) lemma monotone_on.reflect_lt (hf : monotone_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) (h : f a < f b) : a < b := lt_of_not_ge $ λ h', h.not_le $ hf hb ha h' lemma antitone_on.reflect_lt (hf : antitone_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) (h : f a < f b) : b < a := lt_of_not_ge $ λ h', h.not_le $ hf ha hb h' lemma strict_mono_on.le_iff_le (hf : strict_mono_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : f a ≤ f b ↔ a ≤ b := ⟨λ h, le_of_not_gt $ λ h', (hf hb ha h').not_le h, λ h, h.lt_or_eq_dec.elim (λ h', (hf ha hb h').le) (λ h', h' ▸ le_rfl)⟩ lemma strict_anti_on.le_iff_le (hf : strict_anti_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : f a ≤ f b ↔ b ≤ a := hf.dual_right.le_iff_le hb ha lemma strict_mono_on.eq_iff_eq (hf : strict_mono_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : f a = f b ↔ a = b := ⟨λ h, le_antisymm ((hf.le_iff_le ha hb).mp h.le) ((hf.le_iff_le hb ha).mp h.ge), by { rintro rfl, refl, }⟩ lemma strict_anti_on.eq_iff_eq (hf : strict_anti_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : f a = f b ↔ b = a := (hf.dual_right.eq_iff_eq ha hb).trans eq_comm lemma strict_mono_on.lt_iff_lt (hf : strict_mono_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : f a < f b ↔ a < b := by rw [lt_iff_le_not_le, lt_iff_le_not_le, hf.le_iff_le ha hb, hf.le_iff_le hb ha] lemma strict_anti_on.lt_iff_lt (hf : strict_anti_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : f a < f b ↔ b < a := hf.dual_right.lt_iff_lt hb ha lemma strict_mono.le_iff_le (hf : strict_mono f) {a b : α} : f a ≤ f b ↔ a ≤ b := (hf.strict_mono_on set.univ).le_iff_le trivial trivial lemma strict_anti.le_iff_le (hf : strict_anti f) {a b : α} : f a ≤ f b ↔ b ≤ a := (hf.strict_anti_on set.univ).le_iff_le trivial trivial lemma strict_mono.lt_iff_lt (hf : strict_mono f) {a b : α} : f a < f b ↔ a < b := (hf.strict_mono_on set.univ).lt_iff_lt trivial trivial lemma strict_anti.lt_iff_lt (hf : strict_anti f) {a b : α} : f a < f b ↔ b < a := (hf.strict_anti_on set.univ).lt_iff_lt trivial trivial protected theorem strict_mono_on.compares (hf : strict_mono_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : ∀ {o : ordering}, o.compares (f a) (f b) ↔ o.compares a b | ordering.lt := hf.lt_iff_lt ha hb | ordering.eq := ⟨λ h, ((hf.le_iff_le ha hb).1 h.le).antisymm ((hf.le_iff_le hb ha).1 h.symm.le), congr_arg _⟩ | ordering.gt := hf.lt_iff_lt hb ha protected theorem strict_anti_on.compares (hf : strict_anti_on f s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) {o : ordering} : o.compares (f a) (f b) ↔ o.compares b a := to_dual_compares_to_dual.trans $ hf.dual_right.compares hb ha protected theorem strict_mono.compares (hf : strict_mono f) {a b : α} {o : ordering} : o.compares (f a) (f b) ↔ o.compares a b := (hf.strict_mono_on set.univ).compares trivial trivial protected theorem strict_anti.compares (hf : strict_anti f) {a b : α} {o : ordering} : o.compares (f a) (f b) ↔ o.compares b a := (hf.strict_anti_on set.univ).compares trivial trivial lemma strict_mono.injective (hf : strict_mono f) : injective f := λ x y h, show compares eq x y, from hf.compares.1 h lemma strict_anti.injective (hf : strict_anti f) : injective f := λ x y h, show compares eq x y, from hf.compares.1 h.symm lemma strict_mono.maximal_of_maximal_image (hf : strict_mono f) {a} (hmax : ∀ p, p ≤ f a) (x : α) : x ≤ a := hf.le_iff_le.mp (hmax (f x)) lemma strict_mono.minimal_of_minimal_image (hf : strict_mono f) {a} (hmin : ∀ p, f a ≤ p) (x : α) : a ≤ x := hf.le_iff_le.mp (hmin (f x)) lemma strict_anti.minimal_of_maximal_image (hf : strict_anti f) {a} (hmax : ∀ p, p ≤ f a) (x : α) : a ≤ x := hf.le_iff_le.mp (hmax (f x)) lemma strict_anti.maximal_of_minimal_image (hf : strict_anti f) {a} (hmin : ∀ p, f a ≤ p) (x : α) : x ≤ a := hf.le_iff_le.mp (hmin (f x)) end preorder section partial_order variables [partial_order β] {f : α → β} lemma monotone.strict_mono_iff_injective (hf : monotone f) : strict_mono f ↔ injective f := ⟨λ h, h.injective, hf.strict_mono_of_injective⟩ lemma antitone.strict_anti_iff_injective (hf : antitone f) : strict_anti f ↔ injective f := ⟨λ h, h.injective, hf.strict_anti_of_injective⟩ end partial_order variables [linear_order β] {f : α → β} {s : set α} {x y : α} /-- A function between linear orders which is neither monotone nor antitone makes a dent upright or downright. -/ lemma not_monotone_not_antitone_iff_exists_le_le : ¬ monotone f ∧ ¬ antitone f ↔ ∃ a b c, a ≤ b ∧ b ≤ c ∧ (f a < f b ∧ f c < f b ∨ f b < f a ∧ f b < f c) := begin simp_rw [monotone, antitone, not_forall, not_le], refine iff.symm ⟨_, _⟩, { rintro ⟨a, b, c, hab, hbc, ⟨hfab, hfcb⟩ | ⟨hfba, hfbc⟩⟩, exacts [⟨⟨_, _, hbc, hfcb⟩, _, _, hab, hfab⟩, ⟨⟨_, _, hab, hfba⟩, _, _, hbc, hfbc⟩] }, rintro ⟨⟨a, b, hab, hfba⟩, c, d, hcd, hfcd⟩, obtain hda | had := le_total d a, { obtain hfad | hfda := le_total (f a) (f d), { exact ⟨c, d, b, hcd, hda.trans hab, or.inl ⟨hfcd, hfba.trans_le hfad⟩⟩ }, { exact ⟨c, a, b, hcd.trans hda, hab, or.inl ⟨hfcd.trans_le hfda, hfba⟩⟩ } }, obtain hac | hca := le_total a c, { obtain hfdb | hfbd := le_or_lt (f d) (f b), { exact ⟨a, c, d, hac, hcd, or.inr ⟨hfcd.trans $ hfdb.trans_lt hfba, hfcd⟩⟩ }, obtain hfca | hfac := lt_or_le (f c) (f a), { exact ⟨a, c, d, hac, hcd, or.inr ⟨hfca, hfcd⟩⟩ }, obtain hbd | hdb := le_total b d, { exact ⟨a, b, d, hab, hbd, or.inr ⟨hfba, hfbd⟩⟩ }, { exact ⟨a, d, b, had, hdb, or.inl ⟨hfac.trans_lt hfcd, hfbd⟩⟩ } }, { obtain hfdb | hfbd := le_or_lt (f d) (f b), { exact ⟨c, a, b, hca, hab, or.inl ⟨hfcd.trans $ hfdb.trans_lt hfba, hfba⟩⟩ }, obtain hfca | hfac := lt_or_le (f c) (f a), { exact ⟨c, a, b, hca, hab, or.inl ⟨hfca, hfba⟩⟩ }, obtain hbd | hdb := le_total b d, { exact ⟨a, b, d, hab, hbd, or.inr ⟨hfba, hfbd⟩⟩ }, { exact ⟨a, d, b, had, hdb, or.inl ⟨hfac.trans_lt hfcd, hfbd⟩⟩ } } end /-- A function between linear orders which is neither monotone nor antitone makes a dent upright or downright. -/ lemma not_monotone_not_antitone_iff_exists_lt_lt : ¬ monotone f ∧ ¬ antitone f ↔ ∃ a b c, a < b ∧ b < c ∧ (f a < f b ∧ f c < f b ∨ f b < f a ∧ f b < f c) := begin simp_rw [not_monotone_not_antitone_iff_exists_le_le, ←and_assoc], refine exists₃_congr (λ a b c, and_congr_left $ λ h, (ne.le_iff_lt _).and $ ne.le_iff_lt _); rintro rfl; simpa using h, end /-! ### Strictly monotone functions and `cmp` -/ lemma strict_mono_on.cmp_map_eq (hf : strict_mono_on f s) (hx : x ∈ s) (hy : y ∈ s) : cmp (f x) (f y) = cmp x y := ((hf.compares hx hy).2 (cmp_compares x y)).cmp_eq lemma strict_mono.cmp_map_eq (hf : strict_mono f) (x y : α) : cmp (f x) (f y) = cmp x y := (hf.strict_mono_on set.univ).cmp_map_eq trivial trivial lemma strict_anti_on.cmp_map_eq (hf : strict_anti_on f s) (hx : x ∈ s) (hy : y ∈ s) : cmp (f x) (f y) = cmp y x := hf.dual_right.cmp_map_eq hy hx lemma strict_anti.cmp_map_eq (hf : strict_anti f) (x y : α) : cmp (f x) (f y) = cmp y x := (hf.strict_anti_on set.univ).cmp_map_eq trivial trivial end linear_order /-! ### Monotonicity in `ℕ` and `ℤ` -/ section preorder variables [preorder α] lemma nat.rel_of_forall_rel_succ_of_le_of_lt (r : β → β → Prop) [is_trans β r] {f : ℕ → β} {a : ℕ} (h : ∀ n, a ≤ n → r (f n) (f (n + 1))) ⦃b c : ℕ⦄ (hab : a ≤ b) (hbc : b < c) : r (f b) (f c) := begin induction hbc with k b_lt_k r_b_k, exacts [h _ hab, trans r_b_k (h _ (hab.trans_lt b_lt_k).le)] end lemma nat.rel_of_forall_rel_succ_of_le_of_le (r : β → β → Prop) [is_refl β r] [is_trans β r] {f : ℕ → β} {a : ℕ} (h : ∀ n, a ≤ n → r (f n) (f (n + 1))) ⦃b c : ℕ⦄ (hab : a ≤ b) (hbc : b ≤ c) : r (f b) (f c) := hbc.eq_or_lt.elim (λ h, h ▸ refl _) (nat.rel_of_forall_rel_succ_of_le_of_lt r h hab) lemma nat.rel_of_forall_rel_succ_of_lt (r : β → β → Prop) [is_trans β r] {f : ℕ → β} (h : ∀ n, r (f n) (f (n + 1))) ⦃a b : ℕ⦄ (hab : a < b) : r (f a) (f b) := nat.rel_of_forall_rel_succ_of_le_of_lt r (λ n _, h n) le_rfl hab lemma nat.rel_of_forall_rel_succ_of_le (r : β → β → Prop) [is_refl β r] [is_trans β r] {f : ℕ → β} (h : ∀ n, r (f n) (f (n + 1))) ⦃a b : ℕ⦄ (hab : a ≤ b) : r (f a) (f b) := nat.rel_of_forall_rel_succ_of_le_of_le r (λ n _, h n) le_rfl hab lemma monotone_nat_of_le_succ {f : ℕ → α} (hf : ∀ n, f n ≤ f (n + 1)) : monotone f := nat.rel_of_forall_rel_succ_of_le (≤) hf lemma antitone_nat_of_succ_le {f : ℕ → α} (hf : ∀ n, f (n + 1) ≤ f n) : antitone f := @monotone_nat_of_le_succ αᵒᵈ _ _ hf lemma strict_mono_nat_of_lt_succ {f : ℕ → α} (hf : ∀ n, f n < f (n + 1)) : strict_mono f := nat.rel_of_forall_rel_succ_of_lt (<) hf lemma strict_anti_nat_of_succ_lt {f : ℕ → α} (hf : ∀ n, f (n + 1) < f n) : strict_anti f := @strict_mono_nat_of_lt_succ αᵒᵈ _ f hf namespace nat /-- If `α` is a preorder with no maximal elements, then there exists a strictly monotone function `ℕ → α` with any prescribed value of `f 0`. -/ lemma exists_strict_mono' [no_max_order α] (a : α) : ∃ f : ℕ → α, strict_mono f ∧ f 0 = a := begin have := (λ x : α, exists_gt x), choose g hg, exact ⟨λ n, nat.rec_on n a (λ _, g), strict_mono_nat_of_lt_succ $ λ n, hg _, rfl⟩ end /-- If `α` is a preorder with no maximal elements, then there exists a strictly antitone function `ℕ → α` with any prescribed value of `f 0`. -/ lemma exists_strict_anti' [no_min_order α] (a : α) : ∃ f : ℕ → α, strict_anti f ∧ f 0 = a := exists_strict_mono' (order_dual.to_dual a) variable (α) /-- If `α` is a nonempty preorder with no maximal elements, then there exists a strictly monotone function `ℕ → α`. -/ lemma exists_strict_mono [nonempty α] [no_max_order α] : ∃ f : ℕ → α, strict_mono f := let ⟨a⟩ := ‹nonempty α›, ⟨f, hf, hfa⟩ := exists_strict_mono' a in ⟨f, hf⟩ /-- If `α` is a nonempty preorder with no minimal elements, then there exists a strictly antitone function `ℕ → α`. -/ lemma exists_strict_anti [nonempty α] [no_min_order α] : ∃ f : ℕ → α, strict_anti f := exists_strict_mono αᵒᵈ end nat lemma int.rel_of_forall_rel_succ_of_lt (r : β → β → Prop) [is_trans β r] {f : ℤ → β} (h : ∀ n, r (f n) (f (n + 1))) ⦃a b : ℤ⦄ (hab : a < b) : r (f a) (f b) := begin rcases hab.dest with ⟨n, rfl⟩, clear hab, induction n with n ihn, { rw int.coe_nat_one, apply h }, { rw [int.coe_nat_succ, ← int.add_assoc], exact trans ihn (h _) } end lemma int.rel_of_forall_rel_succ_of_le (r : β → β → Prop) [is_refl β r] [is_trans β r] {f : ℤ → β} (h : ∀ n, r (f n) (f (n + 1))) ⦃a b : ℤ⦄ (hab : a ≤ b) : r (f a) (f b) := hab.eq_or_lt.elim (λ h, h ▸ refl _) (λ h', int.rel_of_forall_rel_succ_of_lt r h h') lemma monotone_int_of_le_succ {f : ℤ → α} (hf : ∀ n, f n ≤ f (n + 1)) : monotone f := int.rel_of_forall_rel_succ_of_le (≤) hf lemma antitone_int_of_succ_le {f : ℤ → α} (hf : ∀ n, f (n + 1) ≤ f n) : antitone f := int.rel_of_forall_rel_succ_of_le (≥) hf lemma strict_mono_int_of_lt_succ {f : ℤ → α} (hf : ∀ n, f n < f (n + 1)) : strict_mono f := int.rel_of_forall_rel_succ_of_lt (<) hf lemma strict_anti_int_of_succ_lt {f : ℤ → α} (hf : ∀ n, f (n + 1) < f n) : strict_anti f := int.rel_of_forall_rel_succ_of_lt (>) hf namespace int variables (α) [nonempty α] [no_min_order α] [no_max_order α] /-- If `α` is a nonempty preorder with no minimal or maximal elements, then there exists a strictly monotone function `f : ℤ → α`. -/ lemma exists_strict_mono : ∃ f : ℤ → α, strict_mono f := begin inhabit α, rcases nat.exists_strict_mono' (default : α) with ⟨f, hf, hf₀⟩, rcases nat.exists_strict_anti' (default : α) with ⟨g, hg, hg₀⟩, refine ⟨λ n, int.cases_on n f (λ n, g (n + 1)), strict_mono_int_of_lt_succ _⟩, rintro (n|_|n), { exact hf n.lt_succ_self }, { show g 1 < f 0, rw [hf₀, ← hg₀], exact hg nat.zero_lt_one }, { exact hg (nat.lt_succ_self _) } end /-- If `α` is a nonempty preorder with no minimal or maximal elements, then there exists a strictly antitone function `f : ℤ → α`. -/ lemma exists_strict_anti : ∃ f : ℤ → α, strict_anti f := exists_strict_mono αᵒᵈ end int -- TODO@Yael: Generalize the following four to succ orders /-- If `f` is a monotone function from `ℕ` to a preorder such that `x` lies between `f n` and `f (n + 1)`, then `x` doesn't lie in the range of `f`. -/ lemma monotone.ne_of_lt_of_lt_nat {f : ℕ → α} (hf : monotone f) (n : ℕ) {x : α} (h1 : f n < x) (h2 : x < f (n + 1)) (a : ℕ) : f a ≠ x := by { rintro rfl, exact (hf.reflect_lt h1).not_le (nat.le_of_lt_succ $ hf.reflect_lt h2) } /-- If `f` is an antitone function from `ℕ` to a preorder such that `x` lies between `f (n + 1)` and `f n`, then `x` doesn't lie in the range of `f`. -/ lemma antitone.ne_of_lt_of_lt_nat {f : ℕ → α} (hf : antitone f) (n : ℕ) {x : α} (h1 : f (n + 1) < x) (h2 : x < f n) (a : ℕ) : f a ≠ x := by { rintro rfl, exact (hf.reflect_lt h2).not_le (nat.le_of_lt_succ $ hf.reflect_lt h1) } /-- If `f` is a monotone function from `ℤ` to a preorder and `x` lies between `f n` and `f (n + 1)`, then `x` doesn't lie in the range of `f`. -/ lemma monotone.ne_of_lt_of_lt_int {f : ℤ → α} (hf : monotone f) (n : ℤ) {x : α} (h1 : f n < x) (h2 : x < f (n + 1)) (a : ℤ) : f a ≠ x := by { rintro rfl, exact (hf.reflect_lt h1).not_le (int.le_of_lt_add_one $ hf.reflect_lt h2) } /-- If `f` is an antitone function from `ℤ` to a preorder and `x` lies between `f (n + 1)` and `f n`, then `x` doesn't lie in the range of `f`. -/ lemma antitone.ne_of_lt_of_lt_int {f : ℤ → α} (hf : antitone f) (n : ℤ) {x : α} (h1 : f (n + 1) < x) (h2 : x < f n) (a : ℤ) : f a ≠ x := by { rintro rfl, exact (hf.reflect_lt h2).not_le (int.le_of_lt_add_one $ hf.reflect_lt h1) } lemma strict_mono.id_le {φ : ℕ → ℕ} (h : strict_mono φ) : ∀ n, n ≤ φ n := λ n, nat.rec_on n (nat.zero_le _) (λ n hn, nat.succ_le_of_lt (hn.trans_lt $ h $ nat.lt_succ_self n)) end preorder lemma subtype.mono_coe [preorder α] (t : set α) : monotone (coe : (subtype t) → α) := λ x y, id lemma subtype.strict_mono_coe [preorder α] (t : set α) : strict_mono (coe : (subtype t) → α) := λ x y, id section preorder variables [preorder α] [preorder β] [preorder γ] [preorder δ] {f : α → γ} {g : β → δ} {a b : α} lemma monotone_fst : monotone (@prod.fst α β) := λ a b, and.left lemma monotone_snd : monotone (@prod.snd α β) := λ a b, and.right lemma monotone.prod_map (hf : monotone f) (hg : monotone g) : monotone (prod.map f g) := λ a b h, ⟨hf h.1, hg h.2⟩ lemma antitone.prod_map (hf : antitone f) (hg : antitone g) : antitone (prod.map f g) := λ a b h, ⟨hf h.1, hg h.2⟩ end preorder section partial_order variables [partial_order α] [partial_order β] [preorder γ] [preorder δ] {f : α → γ} {g : β → δ} lemma strict_mono.prod_map (hf : strict_mono f) (hg : strict_mono g) : strict_mono (prod.map f g) := λ a b, by { simp_rw prod.lt_iff, exact or.imp (and.imp hf.imp hg.monotone.imp) (and.imp hf.monotone.imp hg.imp) } lemma strict_anti.prod_map (hf : strict_anti f) (hg : strict_anti g) : strict_anti (prod.map f g) := λ a b, by { simp_rw prod.lt_iff, exact or.imp (and.imp hf.imp hg.antitone.imp) (and.imp hf.antitone.imp hg.imp) } end partial_order /-! ### Pi types -/ namespace function variables [preorder α] [decidable_eq ι] [Π i, preorder (π i)] {f : Π i, π i} {i : ι} lemma update_mono : monotone (f.update i) := λ a b, update_le_update_iff'.2 lemma update_strict_mono : strict_mono (f.update i) := λ a b, update_lt_update_iff.2 lemma const_mono : monotone (const β : α → β → α) := λ a b h i, h lemma const_strict_mono [nonempty β] : strict_mono (const β : α → β → α) := λ a b, const_lt_const.2 end function
b060042ce7df5058955844e92ae9659335000228
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/nested1.lean
050763629964568492a7d6d394d5813838808685
[ "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
267
lean
import data.nat open nat namespace test constant foo (a : nat) : a > 0 → nat definition bla (a : nat) := foo (succ (succ a)) abstract as foo.prf [irreducible] lt.step (zero_lt_succ a) end print foo.prf print bla end test print test.bla print test.foo.prf
123b43f839c6a01ab1377a8a2b9c6f01814758ce
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/algebra/ordered_smul.lean
bc2dec9084d7dc676662f848a7397f09df583042
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,340
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis -/ import algebra.ordered_pi import algebra.smul_with_zero import group_theory.group_action.group /-! # Ordered scalar product In this file we define * `ordered_smul R M` : an ordered additive commutative monoid `M` is an `ordered_smul` over an `ordered_semiring` `R` if the scalar product respects the order relation on the monoid and on the ring. There is a correspondence between this structure and convex cones, which is proven in `analysis/convex/cone.lean`. ## Implementation notes * We choose to define `ordered_smul` as a `Prop`-valued mixin, so that it can be used for actions, modules, and algebras (the axioms for an "ordered algebra" are exactly that the algebra is ordered as a module). * To get ordered modules and ordered vector spaces, it suffices to replace the `order_add_comm_monoid` and the `ordered_semiring` as desired. ## References * https://en.wikipedia.org/wiki/Ordered_module ## Tags ordered module, ordered scalar, ordered smul, ordered action, ordered vector space -/ /-- The ordered scalar product property is when an ordered additive commutative monoid with a partial order has a scalar multiplication which is compatible with the order. -/ @[protect_proj] class ordered_smul (R M : Type*) [ordered_semiring R] [ordered_add_comm_monoid M] [smul_with_zero R M] : Prop := (smul_lt_smul_of_pos : ∀ {a b : M}, ∀ {c : R}, a < b → 0 < c → c • a < c • b) (lt_of_smul_lt_smul_of_pos : ∀ {a b : M}, ∀ {c : R}, c • a < c • b → 0 < c → a < b) section ordered_smul variables {R M : Type*} [ordered_semiring R] [ordered_add_comm_monoid M] [smul_with_zero R M] [ordered_smul R M] {a b : M} {c : R} lemma smul_lt_smul_of_pos : a < b → 0 < c → c • a < c • b := ordered_smul.smul_lt_smul_of_pos lemma smul_le_smul_of_nonneg (h₁ : a ≤ b) (h₂ : 0 ≤ c) : c • a ≤ c • b := begin by_cases H₁ : c = 0, { simp [H₁, zero_smul] }, { by_cases H₂ : a = b, { rw H₂ }, { exact le_of_lt (smul_lt_smul_of_pos (lt_of_le_of_ne h₁ H₂) (lt_of_le_of_ne h₂ (ne.symm H₁))), } } end lemma eq_of_smul_eq_smul_of_pos_of_le (h₁ : c • a = c • b) (hc : 0 < c) (hle : a ≤ b) : a = b := hle.lt_or_eq.resolve_left $ λ hlt, (smul_lt_smul_of_pos hlt hc).ne h₁ lemma lt_of_smul_lt_smul_of_nonneg (h : c • a < c • b) (hc : 0 ≤ c) : a < b := hc.eq_or_lt.elim (λ hc, false.elim $ lt_irrefl (0:M) $ by rwa [← hc, zero_smul, zero_smul] at h) (ordered_smul.lt_of_smul_lt_smul_of_pos h) lemma smul_lt_smul_iff_of_pos (hc : 0 < c) : c • a < c • b ↔ a < b := ⟨λ h, lt_of_smul_lt_smul_of_nonneg h hc.le, λ h, smul_lt_smul_of_pos h hc⟩ lemma smul_pos_iff_of_pos (hc : 0 < c) : 0 < c • a ↔ 0 < a := calc 0 < c • a ↔ c • 0 < c • a : by rw smul_zero' ... ↔ 0 < a : smul_lt_smul_iff_of_pos hc end ordered_smul /-- If `R` is a linear ordered semifield, then it suffices to verify only the first axiom of `ordered_smul`. Moreover, it suffices to verify that `a < b` and `0 < c` imply `c • a ≤ c • b`. We have no semifields in `mathlib`, so we use the assumption `∀ c ≠ 0, is_unit c` instead. -/ lemma ordered_smul.mk'' {R M : Type*} [linear_ordered_semiring R] [ordered_add_comm_monoid M] [mul_action_with_zero R M] (hR : ∀ {c : R}, c ≠ 0 → is_unit c) (hlt : ∀ ⦃a b : M⦄ ⦃c : R⦄, a < b → 0 < c → c • a ≤ c • b) : ordered_smul R M := begin have hlt' : ∀ ⦃a b : M⦄ ⦃c : R⦄, a < b → 0 < c → c • a < c • b, { refine λ a b c hab hc, (hlt hab hc).lt_of_ne _, rw [ne.def, (hR hc.ne').smul_left_cancel], exact hab.ne }, refine { smul_lt_smul_of_pos := hlt', .. }, intros a b c h hc, rcases (hR hc.ne') with ⟨c, rfl⟩, rw [← inv_smul_smul c a, ← inv_smul_smul c b], refine hlt' h (pos_of_mul_pos_left _ hc.le), simp only [c.mul_inv, zero_lt_one] end /-- If `R` is a linear ordered field, then it suffices to verify only the first axiom of `ordered_smul`. -/ lemma ordered_smul.mk' {k M : Type*} [linear_ordered_field k] [ordered_add_comm_monoid M] [mul_action_with_zero k M] (hlt : ∀ ⦃a b : M⦄ ⦃c : k⦄, a < b → 0 < c → c • a ≤ c • b) : ordered_smul k M := ordered_smul.mk'' (λ c hc, is_unit.mk0 _ hc) hlt instance linear_ordered_semiring.to_ordered_smul {R : Type*} [linear_ordered_semiring R] : ordered_smul R R := { smul_lt_smul_of_pos := ordered_semiring.mul_lt_mul_of_pos_left, lt_of_smul_lt_smul_of_pos := λ _ _ _ h hc, lt_of_mul_lt_mul_left h hc.le } section field variables {k M : Type*} [linear_ordered_field k] [ordered_add_comm_group M] [mul_action_with_zero k M] [ordered_smul k M] {a b : M} {c : k} lemma smul_le_smul_iff_of_pos (hc : 0 < c) : c • a ≤ c • b ↔ a ≤ b := ⟨λ h, inv_smul_smul' hc.ne' a ▸ inv_smul_smul' hc.ne' b ▸ smul_le_smul_of_nonneg h (inv_nonneg.2 hc.le), λ h, smul_le_smul_of_nonneg h hc.le⟩ lemma smul_lt_iff_of_pos (hc : 0 < c) : c • a < b ↔ a < c⁻¹ • b := calc c • a < b ↔ c • a < c • c⁻¹ • b : by rw [smul_inv_smul' hc.ne'] ... ↔ a < c⁻¹ • b : smul_lt_smul_iff_of_pos hc lemma lt_smul_iff_of_pos (hc : 0 < c) : a < c • b ↔ c⁻¹ • a < b := calc a < c • b ↔ c • c⁻¹ • a < c • b : by rw [smul_inv_smul' hc.ne'] ... ↔ c⁻¹ • a < b : smul_lt_smul_iff_of_pos hc lemma smul_le_iff_of_pos (hc : 0 < c) : c • a ≤ b ↔ a ≤ c⁻¹ • b := calc c • a ≤ b ↔ c • a ≤ c • c⁻¹ • b : by rw [smul_inv_smul' hc.ne'] ... ↔ a ≤ c⁻¹ • b : smul_le_smul_iff_of_pos hc lemma le_smul_iff_of_pos (hc : 0 < c) : a ≤ c • b ↔ c⁻¹ • a ≤ b := calc a ≤ c • b ↔ c • c⁻¹ • a ≤ c • b : by rw [smul_inv_smul' hc.ne'] ... ↔ c⁻¹ • a ≤ b : smul_le_smul_iff_of_pos hc end field namespace order_dual variables {R M : Type*} instance [has_scalar R M] : has_scalar R (order_dual M) := { smul := λ k x, order_dual.rec (λ x', (k • x' : M)) x } instance [has_zero R] [add_zero_class M] [h : smul_with_zero R M] : smul_with_zero R (order_dual M) := { zero_smul := λ m, order_dual.rec (zero_smul _) m, smul_zero := λ r, order_dual.rec (smul_zero' _) r, ..order_dual.has_scalar } instance [monoid R] [mul_action R M] : mul_action R (order_dual M) := { one_smul := λ m, order_dual.rec (one_smul _) m, mul_smul := λ r, order_dual.rec mul_smul r, ..order_dual.has_scalar } instance [monoid_with_zero R] [add_monoid M] [mul_action_with_zero R M] : mul_action_with_zero R (order_dual M) := { ..order_dual.mul_action, ..order_dual.smul_with_zero } instance [monoid_with_zero R] [add_monoid M] [distrib_mul_action R M] : distrib_mul_action R (order_dual M) := { smul_add := λ k a, order_dual.rec (λ a' b, order_dual.rec (smul_add _ _) b) a, smul_zero := λ r, order_dual.rec smul_zero r } instance [ordered_semiring R] [ordered_add_comm_monoid M] [smul_with_zero R M] [ordered_smul R M] : ordered_smul R (order_dual M) := { smul_lt_smul_of_pos := λ a b, @ordered_smul.smul_lt_smul_of_pos R M _ _ _ _ b a, lt_of_smul_lt_smul_of_pos := λ a b, @ordered_smul.lt_of_smul_lt_smul_of_pos R M _ _ _ _ b a } end order_dual
cf9ea946079c9965ada5884c7db6c2ba6d54588d
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Lean/Util/FindLevelMVar.lean
e84186b7d31b5fcf939fb80f8758c070f33e5bff
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,619
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Lean.Expr namespace Lean namespace FindLevelMVar abbrev Visitor := Option MVarId → Option MVarId mutual partial def visit (p : MVarId → Bool) (e : Expr) : Visitor := fun s => if s.isSome || !e.hasLevelMVar then s else main p e s @[specialize] partial def main (p : MVarId → Bool) : Expr → Visitor | Expr.sort l _ => visitLevel p l | Expr.const _ ls _ => ls.foldr (init := id) fun l acc => visitLevel p l ∘ acc | Expr.forallE _ d b _ => visit p b ∘ visit p d | Expr.lam _ d b _ => visit p b ∘ visit p d | Expr.letE _ t v b _ => visit p b ∘ visit p v ∘ visit p t | Expr.app f a _ => visit p a ∘ visit p f | Expr.mdata _ b _ => visit p b | Expr.proj _ _ e _ => visit p e | _ => id partial def visitLevel (p : MVarId → Bool) (l : Level) : Visitor := fun s => if s.isSome || !l.hasMVar then s else mainLevel p l s @[specialize] partial def mainLevel (p : MVarId → Bool) : Level → Visitor | Level.zero _ => id | Level.succ l _ => visitLevel p l | Level.max l₁ l₂ _ => visitLevel p l₁ ∘ visitLevel p l₂ | Level.imax l₁ l₂ _ => visitLevel p l₁ ∘ visitLevel p l₂ | Level.param n _ => id | Level.mvar mvarId _ => fun s => if p mvarId then some mvarId else s end end FindLevelMVar @[inline] def Expr.findLevelMVar? (e : Expr) (p : MVarId → Bool) : Option MVarId := FindLevelMVar.main p e none end Lean
1683e6145d7633f8cdb354aac99b94061775a6fb
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/l_series.lean
ab291a985295f7de05778775baddb507db7a9361
[ "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
4,844
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import analysis.p_series import number_theory.arithmetic_function import topology.algebra.infinite_sum /-! # L-series Given an arithmetic function, we define the corresponding L-series. ## Main Definitions * `nat.arithmetic_function.l_series` is the `l_series` with a given arithmetic function as its coefficients. This is not the analytic continuation, just the infinite series. * `nat.arithmetic_function.l_series_summable` indicates that the `l_series` converges at a given point. ## Main Results * `nat.arithmetic_function.l_series_summable_of_bounded_of_one_lt_re`: the `l_series` of a bounded arithmetic function converges when `1 < z.re`. * `nat.arithmetic_function.zeta_l_series_summable_iff_one_lt_re`: the `l_series` of `ζ` (whose analytic continuation is the Riemann ζ) converges iff `1 < z.re`. -/ noncomputable theory open_locale big_operators namespace nat namespace arithmetic_function /-- The L-series of an `arithmetic_function`. -/ def l_series (f : arithmetic_function ℂ) (z : ℂ) : ℂ := ∑'n, (f n) / (n ^ z) /-- `f.l_series_summable z` indicates that the L-series of `f` converges at `z`. -/ def l_series_summable (f : arithmetic_function ℂ) (z : ℂ) : Prop := summable (λ n, (f n) / (n ^ z)) lemma l_series_eq_zero_of_not_l_series_summable (f : arithmetic_function ℂ) (z : ℂ) : ¬ f.l_series_summable z → f.l_series z = 0 := tsum_eq_zero_of_not_summable @[simp] lemma l_series_summable_zero {z : ℂ} : l_series_summable 0 z := by simp [l_series_summable, summable_zero] theorem l_series_summable_of_bounded_of_one_lt_real {f : arithmetic_function ℂ} {m : ℝ} (h : ∀ (n : ℕ), complex.abs (f n) ≤ m) {z : ℝ} (hz : 1 < z) : f.l_series_summable z := begin by_cases h0 : m = 0, { subst h0, have hf : f = 0 := arithmetic_function.ext (λ n, complex.abs_eq_zero.1 (le_antisymm (h n) (complex.abs_nonneg _))), simp [hf] }, refine summable_of_norm_bounded (λ (n : ℕ), m / (n ^ z)) _ _, { simp_rw [div_eq_mul_inv], exact (summable_mul_left_iff h0).1 (real.summable_nat_rpow_inv.2 hz) }, { intro n, have hm : 0 ≤ m := le_trans (complex.abs_nonneg _) (h 0), cases n, { simp [hm, real.zero_rpow (ne_of_gt (lt_trans real.zero_lt_one hz))] }, simp only [complex.abs_div, complex.norm_eq_abs], apply div_le_div hm (h _) (real.rpow_pos_of_pos (nat.cast_pos.2 n.succ_pos) _) (le_of_eq _), rw [complex.abs_cpow_real, complex.abs_cast_nat] } end theorem l_series_summable_iff_of_re_eq_re {f : arithmetic_function ℂ} {w z : ℂ} (h : w.re = z.re) : f.l_series_summable w ↔ f.l_series_summable z := begin suffices h : ∀ n : ℕ, complex.abs (f n) / complex.abs (↑n ^ w) = complex.abs (f n) / complex.abs (↑n ^ z), { simp [l_series_summable, ← summable_norm_iff, h, complex.norm_eq_abs] }, intro n, cases n, { simp }, apply congr rfl, have h0 : (n.succ : ℂ) ≠ 0, { rw [ne.def, nat.cast_eq_zero], apply n.succ_ne_zero }, rw [complex.cpow_def, complex.cpow_def, if_neg h0, if_neg h0, complex.abs_exp_eq_iff_re_eq], simp only [h, complex.mul_re, mul_eq_mul_left_iff, sub_right_inj], right, rw [complex.log_im, ← complex.of_real_nat_cast], exact complex.arg_of_real_of_nonneg (le_of_lt (cast_pos.2 n.succ_pos)), end theorem l_series_summable_of_bounded_of_one_lt_re {f : arithmetic_function ℂ} {m : ℝ} (h : ∀ (n : ℕ), complex.abs (f n) ≤ m) {z : ℂ} (hz : 1 < z.re) : f.l_series_summable z := begin rw ← l_series_summable_iff_of_re_eq_re (complex.of_real_re z.re), apply l_series_summable_of_bounded_of_one_lt_real h, exact hz, end open_locale arithmetic_function theorem zeta_l_series_summable_iff_one_lt_re {z : ℂ} : l_series_summable ζ z ↔ 1 < z.re := begin rw [← l_series_summable_iff_of_re_eq_re (complex.of_real_re z.re), l_series_summable, ← summable_norm_iff, ← real.summable_one_div_nat_rpow, iff_iff_eq], by_cases h0 : z.re = 0, { rw [h0, ← summable_nat_add_iff 1], swap, { apply_instance }, apply congr rfl, ext n, simp [n.succ_ne_zero] }, { apply congr rfl, ext n, cases n, { simp [h0] }, simp only [n.succ_ne_zero, one_div, cast_one, nat_coe_apply, complex.abs_cpow_real, inv_inj₀, complex.abs_inv, if_false, zeta_apply, complex.norm_eq_abs, complex.abs_of_nat] } end @[simp] theorem l_series_add {f g : arithmetic_function ℂ} {z : ℂ} (hf : f.l_series_summable z) (hg : g.l_series_summable z) : (f + g).l_series z = f.l_series z + g.l_series z := begin simp only [l_series, add_apply], rw ← tsum_add hf hg, apply congr rfl (funext (λ n, _)), apply _root_.add_div, end end arithmetic_function end nat
e87f9af3093375a2dbe4c631c352fe2ae7452b79
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/ring_theory/polynomial/basic.lean
6006fb7de02c0f6174c5ef40cd79dc25afc1c030
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
41,836
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.char_p.basic import data.mv_polynomial.comm_ring import data.mv_polynomial.equiv import data.polynomial.field_division import ring_theory.principal_ideal_domain import ring_theory.polynomial.content /-! # Ring-theoretic supplement of data.polynomial. ## Main results * `mv_polynomial.integral_domain`: If a ring is an integral domain, then so is its polynomial ring over finitely many variables. * `polynomial.is_noetherian_ring`: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring. * `polynomial.wf_dvd_monoid`: If an integral domain is a `wf_dvd_monoid`, then so is its polynomial ring. * `polynomial.unique_factorization_monoid`: If an integral domain is a `unique_factorization_monoid`, then so is its polynomial ring. -/ noncomputable theory open_locale classical big_operators universes u v w namespace polynomial instance {R : Type u} [semiring R] (p : ℕ) [h : char_p R p] : char_p (polynomial R) p := let ⟨h⟩ := h in ⟨λ n, by rw [← C.map_nat_cast, ← C_0, C_inj, h]⟩ 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 /-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/ def degree_lt (n : ℕ) : 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 @[mono] 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 : polynomial R)^n)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← polynomial.sum_monomial_eq p, polynomial.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [monomial_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, exact (degree_X_pow_le _).trans (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end theorem mem_degree_lt {n : ℕ} {f : polynomial R} : f ∈ degree_lt R n ↔ degree f < n := by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl } @[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) : degree_lt R m ≤ degree_lt R n := λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H) theorem degree_lt_eq_span_X_pow {n : ℕ} : degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_lt.1 hp, rw [← polynomial.sum_monomial_eq p, polynomial.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk), rw [monomial_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 this, rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_lt.2, exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk) end /-- The first `n` coefficients on `degree_lt n` form a linear equivalence with `fin n → F`. -/ def degree_lt_equiv (F : Type*) [field F] (n : ℕ) : degree_lt F n ≃ₗ[F] (fin n → F) := { to_fun := λ p n, (↑p : polynomial F).coeff n, inv_fun := λ f, ⟨∑ i : fin n, monomial i (f i), (degree_lt F n).sum_mem (λ i _, mem_degree_lt.mpr (lt_of_le_of_lt (degree_monomial_le i (f i)) (with_bot.coe_lt_coe.mpr i.is_lt)))⟩, map_add' := λ p q, by { ext, rw [submodule.coe_add, coeff_add], refl }, map_smul' := λ x p, by { ext, rw [submodule.coe_smul, coeff_smul], refl }, left_inv := begin rintro ⟨p, hp⟩, ext1, simp only [submodule.coe_mk], by_cases hp0 : p = 0, { subst hp0, simp only [coeff_zero, linear_map.map_zero, finset.sum_const_zero] }, rw [mem_degree_lt, degree_eq_nat_degree hp0, with_bot.coe_lt_coe] at hp, conv_rhs { rw [p.as_sum_range' n hp, ← fin.sum_univ_eq_sum_range] }, end, right_inv := begin intro f, ext i, simp only [finset_sum_coeff, submodule.coe_mk], rw [finset.sum_eq_single i, coeff_monomial, if_pos rfl], { rintro j - hji, rw [coeff_monomial, if_neg], rwa [← subtype.ext_iff] }, { intro h, exact (h (finset.mem_univ _)).elim } end } local attribute [instance] subset.ring /-- The finset of nonzero coefficients of a polynomial. -/ def frange (p : polynomial R) : finset R := finset.image (λ n, p.coeff n) p.support lemma frange_zero : frange (0 : polynomial R) = ∅ := rfl lemma mem_frange_iff {p : polynomial R} {c : R} : c ∈ p.frange ↔ ∃ n ∈ p.support, c = p.coeff n := by simp [frange, eq_comm] lemma frange_one : frange (1 : polynomial R) ⊆ {1} := begin simp [frange, finset.image_subset_iff], simp only [← C_1, coeff_C], assume n hn, simp only [exists_prop, ite_eq_right_iff, not_forall] at hn, simp [hn], end lemma coeff_mem_frange (p : polynomial R) (n : ℕ) (h : p.coeff n ≠ 0) : p.coeff n ∈ p.frange := begin simp only [frange, exists_prop, mem_support_iff, finset.mem_image, ne.def], exact ⟨n, h, rfl⟩, 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)) := ∑ i in p.support, monomial i (⟨p.coeff i, if H : p.coeff i = 0 then H.symm ▸ is_add_submonoid.zero_mem else ring.subset_closure (p.coeff_mem_frange _ H)⟩ : (ring.closure (↑p.frange : set R))) @[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := begin simp only [restriction, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ne.def, ite_not], split_ifs, { rw h, refl }, { refl } end @[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := coeff_restriction @[simp] lemma support_restriction (p : polynomial R) : support (restriction p) = support p := begin ext i, simp only [mem_support_iff, not_iff_not, ne.def], conv_rhs { rw [← coeff_restriction] }, exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end section local attribute [instance] algebra.of_is_subring subring.domain subset.comm_ring @[simp] theorem map_restriction (p : polynomial R) : p.restriction.map (algebra_map _ _) = p := ext $ λ n, by rw [coeff_map, algebra.is_subring_algebra_map_apply, coeff_restriction] end @[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := by simp [degree] @[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := by simp [nat_degree] @[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p := begin simp_rw [monic, leading_coeff, nat_degree_restriction, ← coeff_restriction], exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end @[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := by simp only [restriction, finset.sum_empty, support_zero] @[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} [ring S] {f : R →+* S} {x : S} theorem eval₂_restriction {p : polynomial R} : eval₂ f x p = eval₂ (f.comp (is_subring.subtype _)) x p.restriction := begin simp_rw [eval₂_eq_sum, sum, support_restriction, ← coeff_restriction], refl end 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 := ∑ i in p.support, monomial i (⟨p.coeff i, if H : p.coeff i = 0 then H.symm ▸ is_add_submonoid.zero_mem else hp (p.coeff_mem_frange _ H)⟩ : T) variables (hp : ↑p.frange ⊆ T) include hp @[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := begin simp only [to_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ne.def, ite_not], split_ifs, { rw h, refl }, { refl } end @[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := coeff_to_subring _ _ hp @[simp] lemma support_to_subring : support (to_subring p T hp) = support p := begin ext i, simp only [mem_support_iff, not_iff_not, ne.def], conv_rhs { rw [← coeff_to_subring p T hp] }, exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end @[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := by simp [degree] @[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := by simp [nat_degree] @[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p := begin simp_rw [monic, leading_coeff, nat_degree_to_subring, ← coeff_to_subring p T hp], exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end omit hp @[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (by simp [frange_zero]) = 0 := by { ext i, simp } @[simp] theorem to_subring_one : to_subring (1 : polynomial R) T (set.subset.trans frange_one $finset.singleton_subset_set_iff.2 is_submonoid.one_mem) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl @[simp] theorem map_to_subring : (p.to_subring T hp).map (is_subring.subtype T) = p := by { ext n, simp [coeff_map] } end to_subring variables (T : set R) [is_subring T] /-- Given a polynomial whose coefficients are in some subring, return the corresponding polynomial whose coefficients are in the ambient ring. -/ def of_subring (p : polynomial T) : polynomial R := ∑ i in p.support, monomial i (p.coeff i : R) lemma coeff_of_subring (p : polynomial T) (n : ℕ) : coeff (of_subring T p) n = (coeff p n : T) := begin simp only [of_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ite_eq_right_iff, ne.def, ite_not, not_not, ite_eq_left_iff], assume h, rw h, refl end @[simp] theorem frange_of_subring {p : polynomial T} : ↑(p.of_subring T).frange ⊆ T := begin assume i hi, simp only [frange, set.mem_image, mem_support_iff, ne.def, finset.mem_coe, finset.coe_image] at hi, rcases hi with ⟨n, hn, h'n⟩, rw [← h'n, coeff_of_subring], exact subtype.mem (coeff p n) end end polynomial variables {R : Type u} {σ : Type v} {M : Type w} [comm_ring R] [add_comm_group M] [module R M] namespace ideal open polynomial /-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself -/ lemma polynomial_mem_ideal_of_coeff_mem_ideal (I : ideal (polynomial R)) (p : polynomial R) (hp : ∀ (n : ℕ), (p.coeff n) ∈ I.comap C) : p ∈ I := sum_C_mul_X_eq p ▸ submodule.sum_mem I (λ n hn, I.mul_mem_right _ (hp n)) /-- The push-forward of an ideal `I` of `R` to `polynomial R` via inclusion is exactly the set of polynomials whose coefficients are in `I` -/ theorem mem_map_C_iff {I : ideal R} {f : polynomial R} : f ∈ (ideal.map C I : ideal (polynomial R)) ↔ ∀ n : ℕ, f.coeff n ∈ I := begin split, { intros hf, apply submodule.span_induction hf, { intros f hf n, cases (set.mem_image _ _ _).mp hf with x hx, rw [← hx.right, coeff_C], by_cases (n = 0), { simpa [h] using hx.left }, { simp [h] } }, { simp }, { exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] }, { refine λ f g hg n, _, rw [smul_eq_mul, coeff_mul], exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } }, { intros hf, rw ← sum_monomial_eq f, refine (I.map C : ideal (polynomial R)).sum_mem (λ n hn, _), simp [monomial_eq_C_mul_X], rw mul_comm, exact (I.map C : ideal (polynomial R)).mul_mem_left _ (mem_map_of_mem _ (hf n)) } end lemma quotient_map_C_eq_zero {I : ideal R} : ∀ a ∈ I, ((quotient.mk (map C I : ideal (polynomial R))).comp C) a = 0 := begin intros a ha, rw [ring_hom.comp_apply, quotient.eq_zero_iff_mem], exact mem_map_of_mem _ ha, end lemma eval₂_C_mk_eq_zero {I : ideal R} : ∀ f ∈ (map C I : ideal (polynomial R)), eval₂_ring_hom (C.comp (quotient.mk I)) X f = 0 := begin intros a ha, rw ← sum_monomial_eq a, dsimp, rw eval₂_sum, refine finset.sum_eq_zero (λ n hn, _), dsimp, rw eval₂_monomial (C.comp (quotient.mk I)) X, refine mul_eq_zero_of_left (polynomial.ext (λ m, _)) (X ^ n), erw coeff_C, by_cases h : m = 0, { simpa [h] using quotient.eq_zero_iff_mem.2 ((mem_map_C_iff.1 ha) n) }, { simp [h] } end /-- If `I` is an ideal of `R`, then the ring polynomials over the quotient ring `I.quotient` is isomorphic to the quotient of `polynomial R` by the ideal `map C I`, where `map C I` contains exactly the polynomials whose coefficients all lie in `I` -/ def polynomial_quotient_equiv_quotient_polynomial (I : ideal R) : polynomial (I.quotient) ≃+* (map C I : ideal (polynomial R)).quotient := { to_fun := eval₂_ring_hom (quotient.lift I ((quotient.mk (map C I : ideal (polynomial R))).comp C) quotient_map_C_eq_zero) ((quotient.mk (map C I : ideal (polynomial R)) X)), inv_fun := quotient.lift (map C I : ideal (polynomial R)) (eval₂_ring_hom (C.comp (quotient.mk I)) X) eval₂_C_mk_eq_zero, map_mul' := λ f g, by simp, map_add' := λ f g, by simp, left_inv := begin intro f, apply polynomial.induction_on' f, { simp_intros p q hp hq, rw [hp, hq] }, { rintros n ⟨x⟩, simp [monomial_eq_smul_X, C_mul'] } end, right_inv := begin rintro ⟨f⟩, apply polynomial.induction_on' f, { simp_intros p q hp hq, rw [hp, hq] }, { intros n a, simp [monomial_eq_smul_X, ← C_mul' a (X ^ n)] }, end, } /-- If `P` is a prime ideal of `R`, then `R[x]/(P)` is an integral domain. -/ lemma is_integral_domain_map_C_quotient {P : ideal R} (H : is_prime P) : is_integral_domain (quotient (map C P : ideal (polynomial R))) := ring_equiv.is_integral_domain (polynomial (quotient P)) (integral_domain.to_is_integral_domain (polynomial (quotient P))) (polynomial_quotient_equiv_quotient_polynomial P).symm /-- If `P` is a prime ideal of `R`, then `P.R[x]` is a prime ideal of `R[x]`. -/ lemma is_prime_map_C_of_is_prime {P : ideal R} (H : is_prime P) : is_prime (map C P : ideal (polynomial R)) := (quotient.is_integral_domain_iff_prime (map C P : ideal (polynomial R))).mp (is_integral_domain_map_C_quotient H) /-- Given any ring `R` and an ideal `I` of `polynomial R`, we get a map `R → R[x] → R[x]/I`. If we let `R` be the image of `R` in `R[x]/I` then we also have a map `R[x] → R'[x]`. In particular we can map `I` across this map, to get `I'` and a new map `R' → R'[x] → R'[x]/I`. This theorem shows `I'` will not contain any non-zero constant polynomials -/ lemma eq_zero_of_polynomial_mem_map_range (I : ideal (polynomial R)) (x : ((quotient.mk I).comp C).range) (hx : C x ∈ (I.map (polynomial.map_ring_hom ((quotient.mk I).comp C).range_restrict))) : x = 0 := begin let i := ((quotient.mk I).comp C).range_restrict, have hi' : (polynomial.map_ring_hom i).ker ≤ I, { refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _), rw [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply], rw [ring_hom.mem_ker, coe_map_ring_hom] at hf, replace hf := congr_arg (λ (f : polynomial _), f.coeff n) hf, simp only [coeff_map, coeff_zero] at hf, rwa [subtype.ext_iff, ring_hom.coe_range_restrict] at hf }, obtain ⟨x, hx'⟩ := x, obtain ⟨y, rfl⟩ := (ring_hom.mem_range).1 hx', refine subtype.eq _, simp only [ring_hom.comp_apply, quotient.eq_zero_iff_mem, subring.coe_zero, subtype.val_eq_coe], suffices : C (i y) ∈ (I.map (polynomial.map_ring_hom i)), { obtain ⟨f, hf⟩ := mem_image_of_mem_map_of_surjective (polynomial.map_ring_hom i) (polynomial.map_surjective _ (((quotient.mk I).comp C).range_restrict_surjective)) this, refine sub_add_cancel (C y) f ▸ I.add_mem (hi' _ : (C y - f) ∈ I) hf.1, rw [ring_hom.mem_ker, ring_hom.map_sub, hf.2, sub_eq_zero, coe_map_ring_hom, map_C] }, exact hx, end /-- `polynomial R` is never a field for any ring `R`. -/ lemma polynomial_not_is_field : ¬ is_field (polynomial R) := begin by_contradiction hR, by_cases hR' : ∃ (x y : R), x ≠ y, { haveI : nontrivial R := let ⟨x, y, hxy⟩ := hR' in nontrivial_of_ne x y hxy, obtain ⟨p, hp⟩ := hR.mul_inv_cancel X_ne_zero, by_cases hp0 : p = 0, { replace hp := congr_arg degree hp, rw [hp0, mul_zero, degree_zero, degree_one] at hp, contradiction }, { have : p.degree < (X * p).degree := (mul_comm p X) ▸ degree_lt_degree_mul_X hp0, rw [congr_arg degree hp, degree_one, nat.with_bot.lt_zero_iff, degree_eq_bot] at this, exact hp0 this } }, { push_neg at hR', exact let ⟨x, y, hxy⟩ := hR.exists_pair_ne in hxy (polynomial.ext (λ n, hR' _ _)) } end /-- The only constant in a maximal ideal over a field is `0`. -/ lemma eq_zero_of_constant_mem_of_maximal (hR : is_field R) (I : ideal (polynomial R)) [hI : I.is_maximal] (x : R) (hx : C x ∈ I) : x = 0 := begin refine classical.by_contradiction (λ hx0, hI.ne_top ((eq_top_iff_one I).2 _)), obtain ⟨y, hy⟩ := hR.mul_inv_cancel hx0, convert I.smul_mem (C y) hx, rw [smul_eq_mul, ← C.map_mul, mul_comm y x, hy, ring_hom.map_one], end /-- 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_mem' := I.zero_mem, add_mem' := λ _ _, I.add_mem, smul_mem' := λ c x H, by { rw [← C_mul'], exact I.mul_mem_left _ 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 [set_like.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 namespace polynomial @[priority 100] instance {R : Type*} [integral_domain R] [wf_dvd_monoid R] : wf_dvd_monoid (polynomial R) := { well_founded_dvd_not_unit := begin classical, refine rel_hom.well_founded ⟨λ p, (if p = 0 then ⊤ else ↑p.degree, p.leading_coeff), _⟩ (prod.lex_wf (with_top.well_founded_lt $ with_bot.well_founded_lt nat.lt_wf) _inst_5.well_founded_dvd_not_unit), rintros a b ⟨ane0, ⟨c, ⟨not_unit_c, rfl⟩⟩⟩, rw [polynomial.degree_mul, if_neg ane0], split_ifs with hac, { rw [hac, polynomial.leading_coeff_zero], apply prod.lex.left, exact lt_of_le_of_ne le_top with_top.coe_ne_top }, have cne0 : c ≠ 0 := right_ne_zero_of_mul hac, simp only [cne0, ane0, polynomial.leading_coeff_mul], by_cases hdeg : c.degree = 0, { simp only [hdeg, add_zero], refine prod.lex.right _ ⟨_, ⟨c.leading_coeff, (λ unit_c, not_unit_c _), rfl⟩⟩, { rwa [ne, polynomial.leading_coeff_eq_zero] }, rw [polynomial.is_unit_iff, polynomial.eq_C_of_degree_eq_zero hdeg], use [c.leading_coeff, unit_c], rw [polynomial.leading_coeff, polynomial.nat_degree_eq_of_degree_eq_some hdeg] }, { apply prod.lex.left, rw polynomial.degree_eq_nat_degree cne0 at *, rw [with_top.coe_lt_coe, polynomial.degree_eq_nat_degree ane0, ← with_bot.coe_add, with_bot.coe_lt_coe], exact lt_add_of_pos_right _ (nat.pos_of_ne_zero (λ h, hdeg (h.symm ▸ with_bot.coe_zero))) }, end } end polynomial /-- 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) := is_noetherian_ring_iff.2 ⟨assume I : ideal (polynomial R), 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 have : submodule.span (polynomial R) ↑s = ideal.span ↑s, by refl, rw this, 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 }, haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩, 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', 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 polynomial theorem exists_irreducible_of_degree_pos {R : Type u} [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : 0 < f.degree) : ∃ g, irreducible g ∧ g ∣ f := wf_dvd_monoid.exists_irreducible_factor (λ huf, ne_of_gt hf $ degree_eq_zero_of_is_unit huf) (λ hf0, not_lt_of_lt hf $ hf0.symm ▸ (@degree_zero R _).symm ▸ with_bot.bot_lt_coe _) theorem exists_irreducible_of_nat_degree_pos {R : Type u} [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : 0 < f.nat_degree) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_degree_pos $ by { contrapose! hf, exact nat_degree_le_of_degree_le hf } theorem exists_irreducible_of_nat_degree_ne_zero {R : Type u} [integral_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : f.nat_degree ≠ 0) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_nat_degree_pos $ nat.pos_of_ne_zero hf lemma linear_independent_powers_iff_aeval (f : M →ₗ[R] M) (v : M) : linear_independent R (λ n : ℕ, (f ^ n) v) ↔ ∀ (p : polynomial R), aeval f p v = 0 → p = 0 := begin rw linear_independent_iff, simp only [finsupp.total_apply, aeval_endomorphism, forall_iff_forall_finsupp, sum, support, coeff, ← zero_to_finsupp], exact iff.rfl, end lemma disjoint_ker_aeval_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : disjoint (aeval f p).ker (aeval f q).ker := begin intros v hv, rcases hpq with ⟨p', q', hpq'⟩, simpa [linear_map.mem_ker.1 (submodule.mem_inf.1 hv).1, linear_map.mem_ker.1 (submodule.mem_inf.1 hv).2] using congr_arg (λ p : polynomial R, aeval f p v) hpq'.symm, end lemma sup_aeval_range_eq_top_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : (aeval f p).range ⊔ (aeval f q).range = ⊤ := begin rw eq_top_iff, intros v hv, rw submodule.mem_sup, rcases hpq with ⟨p', q', hpq'⟩, use aeval f (p * p') v, use linear_map.mem_range.2 ⟨aeval f p' v, by simp only [linear_map.mul_apply, aeval_mul]⟩, use aeval f (q * q') v, use linear_map.mem_range.2 ⟨aeval f q' v, by simp only [linear_map.mul_apply, aeval_mul]⟩, simpa only [mul_comm p p', mul_comm q q', aeval_one, aeval_add] using congr_arg (λ p : polynomial R, aeval f p v) hpq' end lemma sup_ker_aeval_le_ker_aeval_mul {f : M →ₗ[R] M} {p q : polynomial R} : (aeval f p).ker ⊔ (aeval f q).ker ≤ (aeval f (p * q)).ker := begin intros v hv, rcases submodule.mem_sup.1 hv with ⟨x, hx, y, hy, hxy⟩, have h_eval_x : aeval f (p * q) x = 0, { rw [mul_comm, aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hx, linear_map.map_zero] }, have h_eval_y : aeval f (p * q) y = 0, { rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hy, linear_map.map_zero] }, rw [linear_map.mem_ker, ←hxy, linear_map.map_add, h_eval_x, h_eval_y, add_zero], end lemma sup_ker_aeval_eq_ker_aeval_mul_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : (aeval f p).ker ⊔ (aeval f q).ker = (aeval f (p * q)).ker := begin apply le_antisymm sup_ker_aeval_le_ker_aeval_mul, intros v hv, rw submodule.mem_sup, rcases hpq with ⟨p', q', hpq'⟩, have h_eval₂_qpp' := calc aeval f (q * (p * p')) v = aeval f (p' * (p * q)) v : by rw [mul_comm, mul_assoc, mul_comm, mul_assoc, mul_comm q p] ... = 0 : by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero], have h_eval₂_pqq' := calc aeval f (p * (q * q')) v = aeval f (q' * (p * q)) v : by rw [←mul_assoc, mul_comm] ... = 0 : by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero], rw aeval_mul at h_eval₂_qpp' h_eval₂_pqq', refine ⟨aeval f (q * q') v, linear_map.mem_ker.1 h_eval₂_pqq', aeval f (p * p') v, linear_map.mem_ker.1 h_eval₂_qpp', _⟩, rw [add_comm, mul_comm p p', mul_comm q q'], simpa using congr_arg (λ p : polynomial R, aeval f p v) hpq' end end polynomial 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 (rename_equiv R fin_zero_equiv'.symm).to_ring_equiv) 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).to_ring_equiv.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) := @is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _ (rename_equiv R (fintype.equiv_fin σ).symm).to_ring_equiv 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 ((rename_equiv R fin_zero_equiv').to_ring_equiv.trans (mv_polynomial.pempty_ring_equiv R)) /-- Auxiliary 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).to_ring_equiv 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) := @ring_equiv.is_integral_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _ (mv_polynomial.is_integral_domain_fin _ hR _) (rename_equiv R (fintype.equiv_fin σ)).to_ring_equiv /-- Auxiliary 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 : rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) p * rename (subtype.map id (finset.subset_union_right s t) : {x // x ∈ t} → {x // x ∈ s ∪ t}) q = 0, { apply rename_injective _ 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, exists_pair_ne := ⟨0, 1, λ H, begin have : eval₂ (ring_hom.id _) (λ s, (0:R)) (0 : mv_polynomial σ R) = eval₂ (ring_hom.id _) (λ s, (0:R)) (1 : mv_polynomial σ R), { congr, exact H }, simpa, end⟩, .. (by apply_instance : comm_ring (mv_polynomial σ R)) } lemma map_mv_polynomial_eq_eval₂ {S : Type*} [comm_ring S] [fintype σ] (ϕ : mv_polynomial σ R →+* S) (p : mv_polynomial σ R) : ϕ p = mv_polynomial.eval₂ (ϕ.comp mv_polynomial.C) (λ s, ϕ (mv_polynomial.X s)) p := begin refine trans (congr_arg ϕ (mv_polynomial.as_sum p)) _, rw [mv_polynomial.eval₂_eq', ϕ.map_sum], congr, ext, simp only [monomial_eq, ϕ.map_pow, ϕ.map_prod, ϕ.comp_apply, ϕ.map_mul, finsupp.prod_pow], end lemma quotient_map_C_eq_zero {I : ideal R} {i : R} (hi : i ∈ I) : (ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C i = 0 := begin simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient.eq_zero_iff_mem], exact ideal.mem_map_of_mem _ hi end /-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself, multivariate version. -/ lemma mem_ideal_of_coeff_mem_ideal (I : ideal (mv_polynomial σ R)) (p : mv_polynomial σ R) (hcoe : ∀ (m : σ →₀ ℕ), p.coeff m ∈ I.comap C) : p ∈ I := begin rw as_sum p, suffices : ∀ m ∈ p.support, monomial m (mv_polynomial.coeff m p) ∈ I, { exact submodule.sum_mem I this }, intros m hm, rw [← mul_one (coeff m p), ← C_mul_monomial], suffices : C (coeff m p) ∈ I, { exact ideal.mul_mem_right I (monomial m 1) this }, simpa [ideal.mem_comap] using hcoe m end /-- The push-forward of an ideal `I` of `R` to `mv_polynomial σ R` via inclusion is exactly the set of polynomials whose coefficients are in `I` -/ theorem mem_map_C_iff {I : ideal R} {f : mv_polynomial σ R} : f ∈ (ideal.map C I : ideal (mv_polynomial σ R)) ↔ ∀ (m : σ →₀ ℕ), f.coeff m ∈ I := begin split, { intros hf, apply submodule.span_induction hf, { intros f hf n, cases (set.mem_image _ _ _).mp hf with x hx, rw [← hx.right, coeff_C], by_cases (n = 0), { simpa [h] using hx.left }, { simp [ne.symm h] } }, { simp }, { exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] }, { refine λ f g hg n, _, rw [smul_eq_mul, coeff_mul], exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } }, { intros hf, rw as_sum f, suffices : ∀ m ∈ f.support, monomial m (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)), { exact submodule.sum_mem _ this }, intros m hm, rw [← mul_one (coeff m f), ← C_mul_monomial], suffices : C (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)), { exact ideal.mul_mem_right _ _ this }, apply ideal.mem_map_of_mem _, exact hf m } end lemma eval₂_C_mk_eq_zero {I : ideal R} {a : mv_polynomial σ R} (ha : a ∈ (ideal.map C I : ideal (mv_polynomial σ R))) : eval₂_hom (C.comp (ideal.quotient.mk I)) X a = 0 := begin rw as_sum a, rw [coe_eval₂_hom, eval₂_sum], refine finset.sum_eq_zero (λ n hn, _), simp only [eval₂_monomial, function.comp_app, ring_hom.coe_comp], refine mul_eq_zero_of_left _ _, suffices : coeff n a ∈ I, { rw [← @ideal.mk_ker R _ I, ring_hom.mem_ker] at this, simp only [this, C_0] }, exact mem_map_C_iff.1 ha n end /-- If `I` is an ideal of `R`, then the ring `mv_polynomial σ I.quotient` is isomorphic as an `R`-algebra to the quotient of `mv_polynomial σ R` by the ideal generated by `I`. -/ def quotient_equiv_quotient_mv_polynomial (I : ideal R) : mv_polynomial σ I.quotient ≃ₐ[R] (ideal.map C I : ideal (mv_polynomial σ R)).quotient := { to_fun := eval₂_hom (ideal.quotient.lift I ((ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C) (λ i hi, quotient_map_C_eq_zero hi)) (λ i, ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R)) (X i)), inv_fun := ideal.quotient.lift (ideal.map C I : ideal (mv_polynomial σ R)) (eval₂_hom (C.comp (ideal.quotient.mk I)) X) (λ a ha, eval₂_C_mk_eq_zero ha), map_mul' := ring_hom.map_mul _, map_add' := ring_hom.map_add _, left_inv := begin intro f, apply induction_on f, { rintro ⟨r⟩, rw [coe_eval₂_hom, eval₂_C], simp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_C_right, ring_hom.coe_comp] }, { simp_intros p q hp hq only [ring_hom.map_add, mv_polynomial.coe_eval₂_hom, coe_eval₂_hom, mv_polynomial.eval₂_add, mv_polynomial.eval₂_hom_eq_bind₂, eval₂_hom_eq_bind₂], rw [hp, hq] }, { simp_intros p i hp only [eval₂_hom_eq_bind₂, coe_eval₂_hom], simp only [hp, eval₂_hom_eq_bind₂, coe_eval₂_hom, ideal.quotient.lift_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul, eval₂_X] } end, right_inv := begin rintro ⟨f⟩, apply induction_on f, { intros r, simp only [submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, ring_hom.coe_comp, eval₂_hom_C] }, { simp_intros p q hp hq only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, eval₂_add, ring_hom.map_add, coe_eval₂_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk], rw [hp, hq] }, { simp_intros p i hp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, coe_eval₂_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul, eval₂_X], simp only [hp] } end, commutes' := λ r, eval₂_hom_C _ _ (ideal.quotient.mk I r) } end mv_polynomial namespace polynomial open unique_factorization_monoid variables {D : Type u} [integral_domain D] [unique_factorization_monoid D] @[priority 100] instance unique_factorization_monoid : unique_factorization_monoid (polynomial D) := begin haveI := arbitrary (normalization_monoid D), haveI := to_gcd_monoid D, exact ufm_of_gcd_of_wf_dvd_monoid end end polynomial
4f82ecb77ea898fcbe55d02555fc58d2080d5759
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/category/applicative.lean
b8fa963f28dd48509d50d2122b04b59d6cfb98ec
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
3,086
lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Instances for identity and composition functors -/ import category.functor universe variables u v w section lemmas open function variables {f : Type u → Type v} variables [applicative f] [is_lawful_applicative f] variables {α β γ σ : Type u} attribute [functor_norm] seq_assoc pure_seq_eq_map map_pure seq_map_assoc map_seq lemma applicative.map_seq_map (g : α → β → γ) (h : σ → β) (x : f α) (y : f σ) : (g <$> x) <*> (h <$> y) = (flip (∘) h ∘ g) <$> x <*> y := by simp [flip] with functor_norm lemma applicative.pure_seq_eq_map' (g : α → β) : (<*>) (pure g : f (α → β)) = (<$>) g := by ext; simp with functor_norm end lemmas namespace comp open function (hiding comp) open functor variables {f : Type u → Type w} {g : Type v → Type u} variables [applicative f] [applicative g] protected def seq {α β : Type v} : comp f g (α → β) → comp f g α → comp f g β | ⟨h⟩ ⟨x⟩ := ⟨has_seq.seq <$> h <*> x⟩ instance : has_pure (comp f g) := ⟨λ _ x, ⟨pure $ pure x⟩⟩ instance : has_seq (comp f g) := ⟨λ _ _ f x, comp.seq f x⟩ @[simp] protected lemma run_pure {α : Type v} : ∀ x : α, (pure x : comp f g α).run = pure (pure x) | _ := rfl @[simp] protected lemma run_seq {α β : Type v} : ∀ (h : comp f g (α → β)) (x : comp f g α), (h <*> x).run = (<*>) <$> h.run <*> x.run | ⟨_⟩ ⟨_⟩ := rfl variables [is_lawful_applicative f] [is_lawful_applicative g] variables {α β γ : Type v} lemma map_pure (h : α → β) (x : α) : (h <$> pure x : comp f g β) = pure (h x) := by ext; simp lemma seq_pure (h : comp f g (α → β)) (x : α) : h <*> pure x = (λ g : α → β, g x) <$> h := by ext; simp [(∘)] with functor_norm lemma seq_assoc (x : comp f g α) (h₀ : comp f g (α → β)) (h₁ : comp f g (β → γ)) : h₁ <*> (h₀ <*> x) = (@function.comp α β γ <$> h₁) <*> h₀ <*> x := by ext; simp [(∘)] with functor_norm lemma pure_seq_eq_map (h : α → β) (x : comp f g α) : pure h <*> x = h <$> x := by ext; simp [applicative.pure_seq_eq_map'] with functor_norm instance {f : Type u → Type w} {g : Type v → Type u} [applicative f] [applicative g] : applicative (comp f g) := { map := @comp.map f g _ _, seq := @comp.seq f g _ _, ..comp.has_pure } instance {f : Type u → Type w} {g : Type v → Type u} [applicative f] [applicative g] [is_lawful_applicative f] [is_lawful_applicative g] : is_lawful_applicative (comp f g) := { pure_seq_eq_map := @comp.pure_seq_eq_map f g _ _ _ _, map_pure := @comp.map_pure f g _ _ _ _, seq_pure := @comp.seq_pure f g _ _ _ _, seq_assoc := @comp.seq_assoc f g _ _ _ _ } end comp open functor @[functor_norm] lemma comp.seq_mk {α β : Type w} {f : Type u → Type v} {g : Type w → Type u} [applicative f] [applicative g] (h : f (g (α → β))) (x : f (g α)) : comp.mk h <*> comp.mk x = comp.mk (has_seq.seq <$> h <*> x) := rfl
ebfedb84c10d455a956d2f610d2f433612c8163b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/measure/hausdorff.lean
40b9e7863e06fcebd5214371814484c8cb712d25
[ "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
53,579
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.convex.between import measure_theory.constructions.borel_space.basic import measure_theory.measure.haar.inner_product_space import measure_theory.measure.lebesgue.basic import topology.metric_space.holder import topology.metric_space.metric_separated /-! # Hausdorff measure and metric (outer) measures > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define the `d`-dimensional Hausdorff measure on an (extended) metric space `X` and the Hausdorff dimension of a set in an (extended) metric space. Let `μ d δ` be the maximal outer measure such that `μ d δ s ≤ (emetric.diam s) ^ d` for every set of diameter less than `δ`. Then the Hausdorff measure `μH[d] s` of `s` is defined as `⨆ δ > 0, μ d δ s`. By Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, this is a Borel measure on `X`. The value of `μH[d]`, `d > 0`, on a set `s` (measurable or not) is given by ``` μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, emetric.diam (t n) ^ d ``` For every set `s` for any `d < d'` we have either `μH[d] s = ∞` or `μH[d'] s = 0`, see `measure_theory.measure.hausdorff_measure_zero_or_top`. In `topology.metric_space.hausdorff_dimension` we use this fact to define the Hausdorff dimension `dimH` of a set in an (extended) metric space. We also define two generalizations of the Hausdorff measure. In one generalization (see `measure_theory.measure.mk_metric`) we take any function `m (diam s)` instead of `(diam s) ^ d`. In an even more general definition (see `measure_theory.measure.mk_metric'`) we use any function of `m : set X → ℝ≥0∞`. Some authors start with a partial function `m` defined only on some sets `s : set X` (e.g., only on balls or only on measurable sets). This is equivalent to our definition applied to `measure_theory.extend m`. We also define a predicate `measure_theory.outer_measure.is_metric` which says that an outer measure is additive on metric separated pairs of sets: `μ (s ∪ t) = μ s + μ t` provided that `⨅ (x ∈ s) (y ∈ t), edist x y ≠ 0`. This is the property required for the Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, so we prove this theorem for any metric outer measure, then prove that outer measures constructed using `mk_metric'` are metric outer measures. ## Main definitions * `measure_theory.outer_measure.is_metric`: an outer measure `μ` is called *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s` and `t`. A metric outer measure in a Borel extended metric space is guaranteed to satisfy the Caratheodory condition, see `measure_theory.outer_measure.is_metric.borel_le_caratheodory`. * `measure_theory.outer_measure.mk_metric'` and its particular case `measure_theory.outer_measure.mk_metric`: a construction of an outer measure that is guaranteed to be metric. Both constructions are generalizations of the Hausdorff measure. The same measures interpreted as Borel measures are called `measure_theory.measure.mk_metric'` and `measure_theory.measure.mk_metric`. * `measure_theory.measure.hausdorff_measure` a.k.a. `μH[d]`: the `d`-dimensional Hausdorff measure. There are many definitions of the Hausdorff measure that differ from each other by a multiplicative constant. We put `μH[d] s = ⨆ r > 0, ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬set.subsingleton (t n)), (emetric.diam (t n)) ^ d`, see `measure_theory.measure.hausdorff_measure_apply'`. In the most interesting case `0 < d` one can omit the `⨆ (ht : ¬set.subsingleton (t n))` part. ## Main statements ### Basic properties * `measure_theory.outer_measure.is_metric.borel_le_caratheodory`: if `μ` is a metric outer measure on an extended metric space `X` (that is, it is additive on pairs of metric separated sets), then every Borel set is Caratheodory measurable (hence, `μ` defines an actual `measure_theory.measure`). See also `measure_theory.measure.mk_metric`. * `measure_theory.measure.hausdorff_measure_mono`: `μH[d] s` is an antitone function of `d`. * `measure_theory.measure.hausdorff_measure_zero_or_top`: if `d₁ < d₂`, then for any `s`, either `μH[d₂] s = 0` or `μH[d₁] s = ∞`. Together with the previous lemma, this means that `μH[d] s` is equal to infinity on some ray `(-∞, D)` and is equal to zero on `(D, +∞)`, where `D` is a possibly infinite number called the *Hausdorff dimension* of `s`; `μH[D] s` can be zero, infinity, or anything in between. * `measure_theory.measure.no_atoms_hausdorff`: Hausdorff measure has no atoms. ### Hausdorff measure in `ℝⁿ` * `measure_theory.hausdorff_measure_pi_real`: for a nonempty `ι`, `μH[card ι]` on `ι → ℝ` equals Lebesgue measure. ## Notations We use the following notation localized in `measure_theory`. - `μH[d]` : `measure_theory.measure.hausdorff_measure d` ## Implementation notes There are a few similar constructions called the `d`-dimensional Hausdorff measure. E.g., some sources only allow coverings by balls and use `r ^ d` instead of `(diam s) ^ d`. While these construction lead to different Hausdorff measures, they lead to the same notion of the Hausdorff dimension. ## References * [Herbert Federer, Geometric Measure Theory, Chapter 2.10][Federer1996] ## Tags Hausdorff measure, measure, metric measure -/ open_locale nnreal ennreal topology big_operators open emetric set function filter encodable finite_dimensional topological_space noncomputable theory variables {ι X Y : Type*} [emetric_space X] [emetric_space Y] namespace measure_theory namespace outer_measure /-! ### Metric outer measures In this section we define metric outer measures and prove Caratheodory theorem: a metric outer measure has the Caratheodory property. -/ /-- We say that an outer measure `μ` in an (e)metric space is *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s`, `t`. -/ def is_metric (μ : outer_measure X) : Prop := ∀ (s t : set X), is_metric_separated s t → μ (s ∪ t) = μ s + μ t namespace is_metric variables {μ : outer_measure X} /-- A metric outer measure is additive on a finite set of pairwise metric separated sets. -/ lemma finset_Union_of_pairwise_separated (hm : is_metric μ) {I : finset ι} {s : ι → set X} (hI : ∀ (i ∈ I) (j ∈ I), i ≠ j → is_metric_separated (s i) (s j)) : μ (⋃ i ∈ I, s i) = ∑ i in I, μ (s i) := begin classical, induction I using finset.induction_on with i I hiI ihI hI, { simp }, simp only [finset.mem_insert] at hI, rw [finset.set_bUnion_insert, hm, ihI, finset.sum_insert hiI], exacts [λ i hi j hj hij, (hI i (or.inr hi) j (or.inr hj) hij), is_metric_separated.finset_Union_right (λ j hj, hI i (or.inl rfl) j (or.inr hj) (ne_of_mem_of_not_mem hj hiI).symm)] end /-- Caratheodory theorem. If `m` is a metric outer measure, then every Borel measurable set `t` is Caratheodory measurable: for any (not necessarily measurable) set `s` we have `μ (s ∩ t) + μ (s \ t) = μ s`. -/ lemma borel_le_caratheodory (hm : is_metric μ) : borel X ≤ μ.caratheodory := begin rw [borel_eq_generate_from_is_closed], refine measurable_space.generate_from_le (λ t ht, μ.is_caratheodory_iff_le.2 $ λ s, _), set S : ℕ → set X := λ n, {x ∈ s | (↑n)⁻¹ ≤ inf_edist x t}, have n0 : ∀ {n : ℕ}, (n⁻¹ : ℝ≥0∞) ≠ 0, from λ n, ennreal.inv_ne_zero.2 (ennreal.nat_ne_top _), have Ssep : ∀ n, is_metric_separated (S n) t, from λ n, ⟨n⁻¹, n0, λ x hx y hy, hx.2.trans $ inf_edist_le_edist_of_mem hy⟩, have Ssep' : ∀ n, is_metric_separated (S n) (s ∩ t), from λ n, (Ssep n).mono subset.rfl (inter_subset_right _ _), have S_sub : ∀ n, S n ⊆ s \ t, from λ n, subset_inter (inter_subset_left _ _) (Ssep n).subset_compl_right, have hSs : ∀ n, μ (s ∩ t) + μ (S n) ≤ μ s, from λ n, calc μ (s ∩ t) + μ (S n) = μ (s ∩ t ∪ S n) : eq.symm $ hm _ _ $ (Ssep' n).symm ... ≤ μ (s ∩ t ∪ s \ t) : by { mono*, exact le_rfl } ... = μ s : by rw [inter_union_diff], have Union_S : (⋃ n, S n) = s \ t, { refine subset.antisymm (Union_subset S_sub) _, rintro x ⟨hxs, hxt⟩, rw mem_iff_inf_edist_zero_of_closed ht at hxt, rcases ennreal.exists_inv_nat_lt hxt with ⟨n, hn⟩, exact mem_Union.2 ⟨n, hxs, hn.le⟩ }, /- Now we have `∀ n, μ (s ∩ t) + μ (S n) ≤ μ s` and we need to prove `μ (s ∩ t) + μ (⋃ n, S n) ≤ μ s`. We can't pass to the limit because `μ` is only an outer measure. -/ by_cases htop : μ (s \ t) = ∞, { rw [htop, add_top, ← htop], exact μ.mono (diff_subset _ _) }, suffices : μ (⋃ n, S n) ≤ ⨆ n, μ (S n), calc μ (s ∩ t) + μ (s \ t) = μ (s ∩ t) + μ (⋃ n, S n) : by rw Union_S ... ≤ μ (s ∩ t) + ⨆ n, μ (S n) : add_le_add le_rfl this ... = ⨆ n, μ (s ∩ t) + μ (S n) : ennreal.add_supr ... ≤ μ s : supr_le hSs, /- It suffices to show that `∑' k, μ (S (k + 1) \ S k) ≠ ∞`. Indeed, if we have this, then for all `N` we have `μ (⋃ n, S n) ≤ μ (S N) + ∑' k, m (S (N + k + 1) \ S (N + k))` and the second term tends to zero, see `outer_measure.Union_nat_of_monotone_of_tsum_ne_top` for details. -/ have : ∀ n, S n ⊆ S (n + 1), from λ n x hx, ⟨hx.1, le_trans (ennreal.inv_le_inv.2 $ nat.cast_le.2 n.le_succ) hx.2⟩, refine (μ.Union_nat_of_monotone_of_tsum_ne_top this _).le, clear this, /- While the sets `S (k + 1) \ S k` are not pairwise metric separated, the sets in each subsequence `S (2 * k + 1) \ S (2 * k)` and `S (2 * k + 2) \ S (2 * k)` are metric separated, so `m` is additive on each of those sequences. -/ rw [← tsum_even_add_odd ennreal.summable ennreal.summable, ennreal.add_ne_top], suffices : ∀ a, (∑' (k : ℕ), μ (S (2 * k + 1 + a) \ S (2 * k + a))) ≠ ∞, from ⟨by simpa using this 0, by simpa using this 1⟩, refine λ r, ne_top_of_le_ne_top htop _, rw [← Union_S, ennreal.tsum_eq_supr_nat, supr_le_iff], intro n, rw [← hm.finset_Union_of_pairwise_separated], { exact μ.mono (Union_subset $ λ i, Union_subset $ λ hi x hx, mem_Union.2 ⟨_, hx.1⟩) }, suffices : ∀ i j, i < j → is_metric_separated (S (2 * i + 1 + r)) (s \ S (2 * j + r)), from λ i _ j _ hij, hij.lt_or_lt.elim (λ h, (this i j h).mono (inter_subset_left _ _) (λ x hx, ⟨hx.1.1, hx.2⟩)) (λ h, (this j i h).symm.mono (λ x hx, ⟨hx.1.1, hx.2⟩) (inter_subset_left _ _)), intros i j hj, have A : ((↑(2 * j + r))⁻¹ : ℝ≥0∞) < (↑(2 * i + 1 + r))⁻¹, by { rw [ennreal.inv_lt_inv, nat.cast_lt], linarith }, refine ⟨(↑(2 * i + 1 + r))⁻¹ - (↑(2 * j + r))⁻¹, by simpa using A, λ x hx y hy, _⟩, have : inf_edist y t < (↑(2 * j + r))⁻¹, from not_le.1 (λ hle, hy.2 ⟨hy.1, hle⟩), rcases inf_edist_lt_iff.mp this with ⟨z, hzt, hyz⟩, have hxz : (↑(2 * i + 1 + r))⁻¹ ≤ edist x z, from le_inf_edist.1 hx.2 _ hzt, apply ennreal.le_of_add_le_add_right hyz.ne_top, refine le_trans _ (edist_triangle _ _ _), refine (add_le_add le_rfl hyz.le).trans (eq.trans_le _ hxz), rw [tsub_add_cancel_of_le A.le] end lemma le_caratheodory [measurable_space X] [borel_space X] (hm : is_metric μ) : ‹measurable_space X› ≤ μ.caratheodory := by { rw @borel_space.measurable_eq X _ _, exact hm.borel_le_caratheodory } end is_metric /-! ### Constructors of metric outer measures In this section we provide constructors `measure_theory.outer_measure.mk_metric'` and `measure_theory.outer_measure.mk_metric` and prove that these outer measures are metric outer measures. We also prove basic lemmas about `map`/`comap` of these measures. -/ /-- Auxiliary definition for `outer_measure.mk_metric'`: given a function on sets `m : set X → ℝ≥0∞`, returns the maximal outer measure `μ` such that `μ s ≤ m s` for any set `s` of diameter at most `r`.-/ def mk_metric'.pre (m : set X → ℝ≥0∞) (r : ℝ≥0∞) : outer_measure X := bounded_by $ extend (λ s (hs : diam s ≤ r), m s) /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `mk_metric'.pre m r` over `r > 0`. Equivalently, it is the limit of `mk_metric'.pre m r` as `r` tends to zero from the right. -/ def mk_metric' (m : set X → ℝ≥0∞) : outer_measure X := ⨆ r > 0, mk_metric'.pre m r /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞` and `r > 0`, let `μ r` be the maximal outer measure such that `μ s ≤ m (emetric.diam s)` whenever `emetric.diam s < r`. Then `mk_metric m = ⨆ r > 0, μ r`. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : outer_measure X := mk_metric' (λ s, m (diam s)) namespace mk_metric' variables {m : set X → ℝ≥0∞} {r : ℝ≥0∞} {μ : outer_measure X} {s : set X} lemma le_pre : μ ≤ pre m r ↔ ∀ s : set X, diam s ≤ r → μ s ≤ m s := by simp only [pre, le_bounded_by, extend, le_infi_iff] lemma pre_le (hs : diam s ≤ r) : pre m r s ≤ m s := (bounded_by_le _).trans $ infi_le _ hs lemma mono_pre (m : set X → ℝ≥0∞) {r r' : ℝ≥0∞} (h : r ≤ r') : pre m r' ≤ pre m r := le_pre.2 $ λ s hs, pre_le (hs.trans h) lemma mono_pre_nat (m : set X → ℝ≥0∞) : monotone (λ k : ℕ, pre m k⁻¹) := λ k l h, le_pre.2 $ λ s hs, pre_le (hs.trans $ by simpa) lemma tendsto_pre (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ r, pre m r s) (𝓝[>] 0) (𝓝 $ mk_metric' m s) := begin rw [← map_coe_Ioi_at_bot, tendsto_map'_iff], simp only [mk_metric', outer_measure.supr_apply, supr_subtype'], exact tendsto_at_bot_supr (λ r r' hr, mono_pre _ hr _) end lemma tendsto_pre_nat (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ n : ℕ, pre m n⁻¹ s) at_top (𝓝 $ mk_metric' m s) := begin refine (tendsto_pre m s).comp (tendsto_inf.2 ⟨ennreal.tendsto_inv_nat_nhds_zero, _⟩), refine tendsto_principal.2 (eventually_of_forall $ λ n, _), simp end lemma eq_supr_nat (m : set X → ℝ≥0∞) : mk_metric' m = ⨆ n : ℕ, mk_metric'.pre m n⁻¹ := begin ext1 s, rw supr_apply, refine tendsto_nhds_unique (mk_metric'.tendsto_pre_nat m s) (tendsto_at_top_supr $ λ k l hkl, mk_metric'.mono_pre_nat m hkl s) end /-- `measure_theory.outer_measure.mk_metric'.pre m r` is a trimmed measure provided that `m (closure s) = m s` for any set `s`. -/ lemma trim_pre [measurable_space X] [opens_measurable_space X] (m : set X → ℝ≥0∞) (hcl : ∀ s, m (closure s) = m s) (r : ℝ≥0∞) : (pre m r).trim = pre m r := begin refine le_antisymm (le_pre.2 $ λ s hs, _) (le_trim _), rw trim_eq_infi, refine (infi_le_of_le (closure s) $ infi_le_of_le subset_closure $ infi_le_of_le measurable_set_closure ((pre_le _).trans_eq (hcl _))), rwa diam_closure end end mk_metric' /-- An outer measure constructed using `outer_measure.mk_metric'` is a metric outer measure. -/ lemma mk_metric'_is_metric (m : set X → ℝ≥0∞) : (mk_metric' m).is_metric := begin rintros s t ⟨r, r0, hr⟩, refine tendsto_nhds_unique_of_eventually_eq (mk_metric'.tendsto_pre _ _) ((mk_metric'.tendsto_pre _ _).add (mk_metric'.tendsto_pre _ _)) _, rw [← pos_iff_ne_zero] at r0, filter_upwards [Ioo_mem_nhds_within_Ioi ⟨le_rfl, r0⟩], rintro ε ⟨ε0, εr⟩, refine bounded_by_union_of_top_of_nonempty_inter _, rintro u ⟨x, hxs, hxu⟩ ⟨y, hyt, hyu⟩, have : ε < diam u, from εr.trans_le ((hr x hxs y hyt).trans $ edist_le_diam_of_mem hxu hyu), exact infi_eq_top.2 (λ h, (this.not_le h).elim) end /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[≥] 0] c • m₂) : (mk_metric m₁ : outer_measure X) ≤ c • mk_metric m₂ := begin classical, rcases (mem_nhds_within_Ici_iff_exists_Ico_subset' zero_lt_one).1 hle with ⟨r, hr0, hr⟩, refine λ s, le_of_tendsto_of_tendsto (mk_metric'.tendsto_pre _ s) (ennreal.tendsto.const_mul (mk_metric'.tendsto_pre _ s) (or.inr hc)) (mem_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_rfl, hr0⟩) (λ r' hr', _)), simp only [mem_set_of_eq, mk_metric'.pre, ring_hom.id_apply], rw [←smul_eq_mul, ← smul_apply, smul_bounded_by hc], refine le_bounded_by.2 (λ t, (bounded_by_le _).trans _) _, simp only [smul_eq_mul, pi.smul_apply, extend, infi_eq_if], split_ifs with ht ht, { apply hr, exact ⟨zero_le _, ht.trans_lt hr'.2⟩ }, { simp [h0] } end @[simp] lemma mk_metric_top : (mk_metric (λ _, ∞ : ℝ≥0∞ → ℝ≥0∞) : outer_measure X) = ⊤ := begin simp_rw [mk_metric, mk_metric', mk_metric'.pre, extend_top, bounded_by_top, eq_top_iff], rw le_supr_iff, intros b hb, simpa using hb ⊤, end /-- If `m₁ d ≤ m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[≥] 0] m₂) : (mk_metric m₁ : outer_measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top one_ne_zero _; simp * } lemma isometry_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone m ∨ surjective f) : comap f (mk_metric m) = mk_metric m := begin simp only [mk_metric, mk_metric', mk_metric'.pre, induced_outer_measure, comap_supr], refine surjective_id.supr_congr id (λ ε, surjective_id.supr_congr id $ λ hε, _), rw comap_bounded_by _ (H.imp (λ h_mono, _) id), { congr' with s : 1, apply extend_congr, { simp [hf.ediam_image] }, { intros, simp [hf.injective.subsingleton_image_iff, hf.ediam_image] } }, { assume s t hst, simp only [extend, le_infi_iff], assume ht, apply le_trans _ (h_mono (diam_mono hst)), simp only [(diam_mono hst).trans ht, le_refl, cinfi_pos] } end lemma mk_metric_smul (m : ℝ≥0∞ → ℝ≥0∞) {c : ℝ≥0∞} (hc : c ≠ ∞) (hc' : c ≠ 0) : (mk_metric (c • m) : outer_measure X) = c • mk_metric m := begin simp only [mk_metric, mk_metric', mk_metric'.pre, induced_outer_measure, ennreal.smul_supr], simp_rw [smul_supr, smul_bounded_by hc, smul_extend _ hc', pi.smul_apply], end lemma mk_metric_nnreal_smul (m : ℝ≥0∞ → ℝ≥0∞) {c : ℝ≥0} (hc : c ≠ 0) : (mk_metric (c • m) : outer_measure X) = c • mk_metric m := by rw [ennreal.smul_def, ennreal.smul_def, mk_metric_smul m (ennreal.coe_ne_top) (ennreal.coe_ne_zero.mpr hc)] lemma isometry_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone m ∨ surjective f) : map f (mk_metric m) = restrict (range f) (mk_metric m) := by rw [← isometry_comap_mk_metric _ hf H, map_comap] lemma isometry_equiv_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : comap f (mk_metric m) = mk_metric m := isometry_comap_mk_metric _ f.isometry (or.inr f.surjective) lemma isometry_equiv_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : map f (mk_metric m) = mk_metric m := by rw [← isometry_equiv_comap_mk_metric _ f, map_comap_of_surjective f.surjective] lemma trim_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : outer_measure X).trim = mk_metric m := begin simp only [mk_metric, mk_metric'.eq_supr_nat, trim_supr], congr' 1 with n : 1, refine mk_metric'.trim_pre _ (λ s, _) _, simp end lemma le_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (μ : outer_measure X) (r : ℝ≥0∞) (h0 : 0 < r) (hr : ∀ s, diam s ≤ r → μ s ≤ m (diam s)) : μ ≤ mk_metric m := le_supr₂_of_le r h0 $ mk_metric'.le_pre.2 $ λ s hs, hr _ hs end outer_measure /-! ### Metric measures In this section we use `measure_theory.outer_measure.to_measure` and theorems about `measure_theory.outer_measure.mk_metric'`/`measure_theory.outer_measure.mk_metric` to define `measure_theory.measure.mk_metric'`/`measure_theory.measure.mk_metric`. We also restate some lemmas about metric outer measures for metric measures. -/ namespace measure variables [measurable_space X] [borel_space X] /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all `s`. While each `μ r` is an *outer* measure, the supremum is a measure. -/ def mk_metric' (m : set X → ℝ≥0∞) : measure X := (outer_measure.mk_metric' m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞`, `mk_metric m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all sets `s` that contain at least two points. While each `mk_metric'.pre` is an *outer* measure, the supremum is a measure. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : measure X := (outer_measure.mk_metric m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory @[simp] lemma mk_metric'_to_outer_measure (m : set X → ℝ≥0∞) : (mk_metric' m).to_outer_measure = (outer_measure.mk_metric' m).trim := rfl @[simp] lemma mk_metric_to_outer_measure (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : measure X).to_outer_measure = outer_measure.mk_metric m := outer_measure.trim_mk_metric m end measure lemma outer_measure.coe_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : ⇑(outer_measure.mk_metric m : outer_measure X) = measure.mk_metric m := by rw [← measure.mk_metric_to_outer_measure, coe_to_outer_measure] namespace measure variables [measurable_space X] [borel_space X] /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[≥] 0] c • m₂) : (mk_metric m₁ : measure X) ≤ c • mk_metric m₂ := begin intros s hs, rw [← outer_measure.coe_mk_metric, coe_smul, ← outer_measure.coe_mk_metric], exact outer_measure.mk_metric_mono_smul hc h0 hle s end @[simp] lemma mk_metric_top : (mk_metric (λ _, ∞ : ℝ≥0∞ → ℝ≥0∞) : measure X) = ⊤ := begin apply to_outer_measure_injective, rw [mk_metric_to_outer_measure, outer_measure.mk_metric_top, to_outer_measure_top], end /-- If `m₁ d ≤ m₂ d` for `d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[≥] 0]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[≥] 0] m₂) : (mk_metric m₁ : measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top one_ne_zero _; simp * } /-- A formula for `measure_theory.measure.mk_metric`. -/ lemma mk_metric_apply (m : ℝ≥0∞ → ℝ≥0∞) (s : set X) : mk_metric m s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (h : s ⊆ Union t) (h' : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (h : (t n).nonempty), m (diam (t n)) := begin -- We mostly unfold the definitions but we need to switch the order of `∑'` and `⨅` classical, simp only [← outer_measure.coe_mk_metric, outer_measure.mk_metric, outer_measure.mk_metric', outer_measure.supr_apply, outer_measure.mk_metric'.pre, outer_measure.bounded_by_apply, extend], refine surjective_id.supr_congr (λ r, r) (λ r, supr_congr_Prop iff.rfl $ λ hr, surjective_id.infi_congr _ $ λ t, infi_congr_Prop iff.rfl $ λ ht, _), dsimp, by_cases htr : ∀ n, diam (t n) ≤ r, { rw [infi_eq_if, if_pos htr], congr' 1 with n : 1, simp only [infi_eq_if, htr n, id, if_true, supr_and'] }, { rw [infi_eq_if, if_neg htr], push_neg at htr, rcases htr with ⟨n, hn⟩, refine ennreal.tsum_eq_top_of_eq_top ⟨n, _⟩, rw [supr_eq_if, if_pos, infi_eq_if, if_neg], exact hn.not_le, rcases diam_pos_iff.1 ((zero_le r).trans_lt hn) with ⟨x, hx, -⟩, exact ⟨x, hx⟩ } end lemma le_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (μ : measure X) (ε : ℝ≥0∞) (h₀ : 0 < ε) (h : ∀ s : set X, diam s ≤ ε → μ s ≤ m (diam s)) : μ ≤ mk_metric m := begin rw [← to_outer_measure_le, mk_metric_to_outer_measure], exact outer_measure.le_mk_metric m μ.to_outer_measure ε h₀ h end /-- To bound the Hausdorff measure (or, more generally, for a measure defined using `measure_theory.measure.mk_metric`) of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of countable types. -/ lemma mk_metric_le_liminf_tsum {β : Type*} {ι : β → Type*} [∀ n, countable (ι n)] (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) (m : ℝ≥0∞ → ℝ≥0∞) : mk_metric m s ≤ liminf (λ n, ∑' i, m (diam (t n i))) l := begin haveI : Π n, encodable (ι n) := λ n, encodable.of_countable _, simp only [mk_metric_apply], refine supr₂_le (λ ε hε, _), refine le_of_forall_le_of_dense (λ c hc, _), rcases ((frequently_lt_of_liminf_lt (by apply_auto_param) hc).and_eventually ((hr.eventually (gt_mem_nhds hε)).and (ht.and hst))).exists with ⟨n, hn, hrn, htn, hstn⟩, set u : ℕ → set X := λ j, ⋃ b ∈ decode₂ (ι n) j, t n b, refine infi₂_le_of_le u (by rwa Union_decode₂) _, refine infi_le_of_le (λ j, _) _, { rw emetric.diam_Union_mem_option, exact supr₂_le (λ _ _, (htn _).trans hrn.le) }, { calc (∑' (j : ℕ), ⨆ (h : (u j).nonempty), m (diam (u j))) = _ : tsum_Union_decode₂ (λ t : set X, ⨆ (h : t.nonempty), m (diam t)) (by simp) _ ... ≤ ∑' (i : ι n), m (diam (t n i)) : ennreal.tsum_le_tsum (λ b, supr_le $ λ htb, le_rfl) ... ≤ c : hn.le } end /-- To bound the Hausdorff measure (or, more generally, for a measure defined using `measure_theory.measure.mk_metric`) of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of finite types. -/ lemma mk_metric_le_liminf_sum {β : Type*} {ι : β → Type*} [hι : ∀ n, fintype (ι n)] (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) (m : ℝ≥0∞ → ℝ≥0∞) : mk_metric m s ≤ liminf (λ n, ∑ i, m (diam (t n i))) l := by simpa only [tsum_fintype] using mk_metric_le_liminf_tsum s r hr t ht hst m /-! ### Hausdorff measure and Hausdorff dimension -/ /-- Hausdorff measure on an (e)metric space. -/ def hausdorff_measure (d : ℝ) : measure X := mk_metric (λ r, r ^ d) localized "notation (name := hausdorff_measure) `μH[` d `]` := measure_theory.measure.hausdorff_measure d" in measure_theory lemma le_hausdorff_measure (d : ℝ) (μ : measure X) (ε : ℝ≥0∞) (h₀ : 0 < ε) (h : ∀ s : set X, diam s ≤ ε → μ s ≤ diam s ^ d) : μ ≤ μH[d] := le_mk_metric _ μ ε h₀ h /-- A formula for `μH[d] s`. -/ lemma hausdorff_measure_apply (d : ℝ) (s : set X) : μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (h : (t n).nonempty), (diam (t n)) ^ d := mk_metric_apply _ _ /-- To bound the Hausdorff measure of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of countable types. -/ lemma hausdorff_measure_le_liminf_tsum {β : Type*} {ι : β → Type*} [hι : ∀ n, countable (ι n)] (d : ℝ) (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) : μH[d] s ≤ liminf (λ n, ∑' i, diam (t n i) ^ d) l := mk_metric_le_liminf_tsum s r hr t ht hst _ /-- To bound the Hausdorff measure of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of finite types. -/ lemma hausdorff_measure_le_liminf_sum {β : Type*} {ι : β → Type*} [hι : ∀ n, fintype (ι n)] (d : ℝ) (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) : μH[d] s ≤ liminf (λ n, ∑ i, diam (t n i) ^ d) l := mk_metric_le_liminf_sum s r hr t ht hst _ /-- If `d₁ < d₂`, then for any set `s` we have either `μH[d₂] s = 0`, or `μH[d₁] s = ∞`. -/ lemma hausdorff_measure_zero_or_top {d₁ d₂ : ℝ} (h : d₁ < d₂) (s : set X) : μH[d₂] s = 0 ∨ μH[d₁] s = ∞ := begin by_contra' H, suffices : ∀ (c : ℝ≥0), c ≠ 0 → μH[d₂] s ≤ c * μH[d₁] s, { rcases ennreal.exists_nnreal_pos_mul_lt H.2 H.1 with ⟨c, hc0, hc⟩, exact hc.not_le (this c (pos_iff_ne_zero.1 hc0)) }, intros c hc, refine le_iff'.1 (mk_metric_mono_smul ennreal.coe_ne_top (by exact_mod_cast hc) _) s, have : 0 < (c ^ (d₂ - d₁)⁻¹ : ℝ≥0∞), { rw [ennreal.coe_rpow_of_ne_zero hc, pos_iff_ne_zero, ne.def, ennreal.coe_eq_zero, nnreal.rpow_eq_zero_iff], exact mt and.left hc }, filter_upwards [Ico_mem_nhds_within_Ici ⟨le_rfl, this⟩], rintro r ⟨hr₀, hrc⟩, lift r to ℝ≥0 using ne_top_of_lt hrc, rw [pi.smul_apply, smul_eq_mul, ← ennreal.div_le_iff_le_mul (or.inr ennreal.coe_ne_top) (or.inr $ mt ennreal.coe_eq_zero.1 hc)], rcases eq_or_ne r 0 with rfl|hr₀, { rcases lt_or_le 0 d₂ with h₂|h₂, { simp only [h₂, ennreal.zero_rpow_of_pos, zero_le, ennreal.zero_div, ennreal.coe_zero] }, { simp only [h.trans_le h₂, ennreal.div_top, zero_le, ennreal.zero_rpow_of_neg, ennreal.coe_zero] } }, { have : (r : ℝ≥0∞) ≠ 0, by simpa only [ennreal.coe_eq_zero, ne.def] using hr₀, rw [← ennreal.rpow_sub _ _ this ennreal.coe_ne_top], refine (ennreal.rpow_lt_rpow hrc (sub_pos.2 h)).le.trans _, rw [← ennreal.rpow_mul, inv_mul_cancel (sub_pos.2 h).ne', ennreal.rpow_one], exact le_rfl } end /-- Hausdorff measure `μH[d] s` is monotone in `d`. -/ lemma hausdorff_measure_mono {d₁ d₂ : ℝ} (h : d₁ ≤ d₂) (s : set X) : μH[d₂] s ≤ μH[d₁] s := begin rcases h.eq_or_lt with rfl|h, { exact le_rfl }, cases hausdorff_measure_zero_or_top h s with hs hs, { rw hs, exact zero_le _ }, { rw hs, exact le_top } end variables (X) lemma no_atoms_hausdorff {d : ℝ} (hd : 0 < d) : has_no_atoms (hausdorff_measure d : measure X) := begin refine ⟨λ x, _⟩, rw [← nonpos_iff_eq_zero, hausdorff_measure_apply], refine supr₂_le (λ ε ε0, infi₂_le_of_le (λ n, {x}) _ $ infi_le_of_le (λ n, _) _), { exact subset_Union (λ n, {x} : ℕ → set X) 0 }, { simp only [emetric.diam_singleton, zero_le] }, { simp [hd] } end variables {X} @[simp] lemma hausdorff_measure_zero_singleton (x : X) : μH[0] ({x} : set X) = 1 := begin apply le_antisymm, { let r : ℕ → ℝ≥0∞ := λ _, 0, let t : ℕ → unit → set X := λ n _, {x}, have ht : ∀ᶠ n in at_top, ∀ i, diam (t n i) ≤ r n, by simp only [implies_true_iff, eq_self_iff_true, diam_singleton, eventually_at_top, nonpos_iff_eq_zero, exists_const], simpa [liminf_const] using hausdorff_measure_le_liminf_sum 0 {x} r tendsto_const_nhds t ht }, { rw hausdorff_measure_apply, suffices : (1 : ℝ≥0∞) ≤ ⨅ (t : ℕ → set X) (hts : {x} ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ 1), ∑' n, ⨆ (h : (t n).nonempty), (diam (t n)) ^ (0 : ℝ), { apply le_trans this _, convert le_supr₂ (1 : ℝ≥0∞) zero_lt_one, refl }, simp only [ennreal.rpow_zero, le_infi_iff], assume t hst h't, rcases mem_Union.1 (hst (mem_singleton x)) with ⟨m, hm⟩, have A : (t m).nonempty := ⟨x, hm⟩, calc (1 : ℝ≥0∞) = ⨆ (h : (t m).nonempty), 1 : by simp only [A, csupr_pos] ... ≤ ∑' n, ⨆ (h : (t n).nonempty), 1 : ennreal.le_tsum _ } end lemma one_le_hausdorff_measure_zero_of_nonempty {s : set X} (h : s.nonempty) : 1 ≤ μH[0] s := begin rcases h with ⟨x, hx⟩, calc (1 : ℝ≥0∞) = μH[0] ({x} : set X) : (hausdorff_measure_zero_singleton x).symm ... ≤ μH[0] s : measure_mono (singleton_subset_iff.2 hx) end lemma hausdorff_measure_le_one_of_subsingleton {s : set X} (hs : s.subsingleton) {d : ℝ} (hd : 0 ≤ d) : μH[d] s ≤ 1 := begin rcases eq_empty_or_nonempty s with rfl|⟨x, hx⟩, { simp only [measure_empty, zero_le] }, { rw (subsingleton_iff_singleton hx).1 hs, rcases eq_or_lt_of_le hd with rfl|dpos, { simp only [le_refl, hausdorff_measure_zero_singleton] }, { haveI := no_atoms_hausdorff X dpos, simp only [zero_le, measure_singleton] } } end end measure end measure_theory /-! ### Hausdorff measure, Hausdorff dimension, and Hölder or Lipschitz continuous maps -/ open_locale measure_theory open measure_theory measure_theory.measure variables [measurable_space X] [borel_space X] [measurable_space Y] [borel_space Y] namespace holder_on_with variables {C r : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f : X → Y` is Hölder continuous on `s` with a positive exponent `r`, then `μH[d] (f '' s) ≤ C ^ d * μH[r * d] s`. -/ lemma hausdorff_measure_image_le (h : holder_on_with C r f s) (hr : 0 < r) {d : ℝ} (hd : 0 ≤ d) : μH[d] (f '' s) ≤ C ^ d * μH[r * d] s := begin -- We start with the trivial case `C = 0` rcases (zero_le C).eq_or_lt with rfl|hC0, { rcases eq_empty_or_nonempty s with rfl|⟨x, hx⟩, { simp only [measure_empty, nonpos_iff_eq_zero, mul_zero, image_empty] }, have : f '' s = {f x}, { have : (f '' s).subsingleton, by simpa [diam_eq_zero_iff] using h.ediam_image_le, exact (subsingleton_iff_singleton (mem_image_of_mem f hx)).1 this }, rw this, rcases eq_or_lt_of_le hd with rfl|h'd, { simp only [ennreal.rpow_zero, one_mul, mul_zero], rw hausdorff_measure_zero_singleton, exact one_le_hausdorff_measure_zero_of_nonempty ⟨x, hx⟩ }, { haveI := no_atoms_hausdorff Y h'd, simp only [zero_le, measure_singleton] } }, -- Now assume `C ≠ 0` { have hCd0 : (C : ℝ≥0∞) ^ d ≠ 0, by simp [hC0.ne'], have hCd : (C : ℝ≥0∞) ^ d ≠ ∞, by simp [hd], simp only [hausdorff_measure_apply, ennreal.mul_supr, ennreal.mul_infi_of_ne hCd0 hCd, ← ennreal.tsum_mul_left], refine supr_le (λ R, supr_le $ λ hR, _), have : tendsto (λ d : ℝ≥0∞, (C : ℝ≥0∞) * d ^ (r : ℝ)) (𝓝 0) (𝓝 0), from ennreal.tendsto_const_mul_rpow_nhds_zero_of_pos ennreal.coe_ne_top hr, rcases ennreal.nhds_zero_basis_Iic.eventually_iff.1 (this.eventually (gt_mem_nhds hR)) with ⟨δ, δ0, H⟩, refine le_supr₂_of_le δ δ0 (infi₂_mono' $ λ t hst, ⟨λ n, f '' (t n ∩ s), _, infi_mono' $ λ htδ, ⟨λ n, (h.ediam_image_inter_le (t n)).trans (H (htδ n)).le, _⟩⟩), { rw [← image_Union, ← Union_inter], exact image_subset _ (subset_inter hst subset.rfl) }, { apply ennreal.tsum_le_tsum (λ n, _), simp only [supr_le_iff, nonempty_image_iff], assume hft, simp only [nonempty.mono ((t n).inter_subset_left s) hft, csupr_pos], rw [ennreal.rpow_mul, ← ennreal.mul_rpow_of_nonneg _ _ hd], exact ennreal.rpow_le_rpow (h.ediam_image_inter_le _) hd } } end end holder_on_with namespace lipschitz_on_with variables {K : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f : X → Y` is `K`-Lipschitz on `s`, then `μH[d] (f '' s) ≤ K ^ d * μH[d] s`. -/ lemma hausdorff_measure_image_le (h : lipschitz_on_with K f s) {d : ℝ} (hd : 0 ≤ d) : μH[d] (f '' s) ≤ K ^ d * μH[d] s := by simpa only [nnreal.coe_one, one_mul] using h.holder_on_with.hausdorff_measure_image_le zero_lt_one hd end lipschitz_on_with namespace lipschitz_with variables {K : ℝ≥0} {f : X → Y} /-- If `f` is a `K`-Lipschitz map, then it increases the Hausdorff `d`-measures of sets at most by the factor of `K ^ d`.-/ lemma hausdorff_measure_image_le (h : lipschitz_with K f) {d : ℝ} (hd : 0 ≤ d) (s : set X) : μH[d] (f '' s) ≤ K ^ d * μH[d] s := (h.lipschitz_on_with s).hausdorff_measure_image_le hd end lipschitz_with open_locale pointwise lemma measure_theory.measure.hausdorff_measure_smul₀ {𝕜 E : Type*} [normed_add_comm_group E] [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space E] [borel_space E] {d : ℝ} (hd : 0 ≤ d) {r : 𝕜} (hr : r ≠ 0) (s : set E) : μH[d] (r • s) = ‖r‖₊ ^ d • μH[d] s := begin suffices : ∀ {r : 𝕜}, r ≠ 0 → ∀ s : set E, μH[d] (r • s) ≤ ‖r‖₊ ^ d • μH[d] s, { refine le_antisymm (this hr s) _, rw [←ennreal.le_inv_smul_iff, ←nnreal.inv_rpow, ←nnnorm_inv], { refine eq.trans_le _ (this (inv_ne_zero hr) (r • s)), rw inv_smul_smul₀ hr }, { simp [hr] } }, intros r hr s, simpa only [ennreal.smul_def, smul_eq_mul, ← ennreal.coe_rpow_of_nonneg _ hd] using (@lipschitz_with_smul _ E _ _ _ _ r).hausdorff_measure_image_le hd s, end /-! ### Antilipschitz maps do not decrease Hausdorff measures and dimension -/ namespace antilipschitz_with variables {f : X → Y} {K : ℝ≥0} {d : ℝ} lemma hausdorff_measure_preimage_le (hf : antilipschitz_with K f) (hd : 0 ≤ d) (s : set Y) : μH[d] (f ⁻¹' s) ≤ K ^ d * μH[d] s := begin rcases eq_or_ne K 0 with rfl|h0, { rcases eq_empty_or_nonempty (f ⁻¹' s) with hs|⟨x, hx⟩, { simp only [hs, measure_empty, zero_le], }, have : f ⁻¹' s = {x}, { haveI : subsingleton X := hf.subsingleton, have : (f ⁻¹' s).subsingleton, from subsingleton_univ.anti (subset_univ _), exact (subsingleton_iff_singleton hx).1 this }, rw this, rcases eq_or_lt_of_le hd with rfl|h'd, { simp only [ennreal.rpow_zero, one_mul, mul_zero], rw hausdorff_measure_zero_singleton, exact one_le_hausdorff_measure_zero_of_nonempty ⟨f x, hx⟩ }, { haveI := no_atoms_hausdorff X h'd, simp only [zero_le, measure_singleton] } }, have hKd0 : (K : ℝ≥0∞) ^ d ≠ 0, by simp [h0], have hKd : (K : ℝ≥0∞) ^ d ≠ ∞, by simp [hd], simp only [hausdorff_measure_apply, ennreal.mul_supr, ennreal.mul_infi_of_ne hKd0 hKd, ← ennreal.tsum_mul_left], refine supr₂_le (λ ε ε0, _), refine le_supr₂_of_le (ε / K) (by simp [ε0.ne']) _, refine le_infi₂ (λ t hst, le_infi $ λ htε, _), replace hst : f ⁻¹' s ⊆ _ := preimage_mono hst, rw preimage_Union at hst, refine infi₂_le_of_le _ hst (infi_le_of_le (λ n, _) _), { exact (hf.ediam_preimage_le _).trans (ennreal.mul_le_of_le_div' $ htε n) }, { refine ennreal.tsum_le_tsum (λ n, supr_le_iff.2 (λ hft, _)), simp only [nonempty_of_nonempty_preimage hft, csupr_pos], rw [← ennreal.mul_rpow_of_nonneg _ _ hd], exact ennreal.rpow_le_rpow (hf.ediam_preimage_le _) hd } end lemma le_hausdorff_measure_image (hf : antilipschitz_with K f) (hd : 0 ≤ d) (s : set X) : μH[d] s ≤ K ^ d * μH[d] (f '' s) := calc μH[d] s ≤ μH[d] (f ⁻¹' (f '' s)) : measure_mono (subset_preimage_image _ _) ... ≤ K ^ d * μH[d] (f '' s) : hf.hausdorff_measure_preimage_le hd (f '' s) end antilipschitz_with /-! ### Isometries preserve the Hausdorff measure and Hausdorff dimension -/ namespace isometry variables {f : X → Y} {d : ℝ} lemma hausdorff_measure_image (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) (s : set X) : μH[d] (f '' s) = μH[d] s := begin simp only [hausdorff_measure, ← outer_measure.coe_mk_metric, ← outer_measure.comap_apply], rw [outer_measure.isometry_comap_mk_metric _ hf (hd.imp_left _)], exact λ hd x y hxy, ennreal.rpow_le_rpow hxy hd end lemma hausdorff_measure_preimage (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) (s : set Y) : μH[d] (f ⁻¹' s) = μH[d] (s ∩ range f) := by rw [← hf.hausdorff_measure_image hd, image_preimage_eq_inter_range] lemma map_hausdorff_measure (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) : measure.map f μH[d] = (μH[d]).restrict (range f) := begin ext1 s hs, rw [map_apply hf.continuous.measurable hs, restrict_apply hs, hf.hausdorff_measure_preimage hd] end end isometry namespace isometry_equiv @[simp] lemma hausdorff_measure_image (e : X ≃ᵢ Y) (d : ℝ) (s : set X) : μH[d] (e '' s) = μH[d] s := e.isometry.hausdorff_measure_image (or.inr e.surjective) s @[simp] lemma hausdorff_measure_preimage (e : X ≃ᵢ Y) (d : ℝ) (s : set Y) : μH[d] (e ⁻¹' s) = μH[d] s := by rw [← e.image_symm, e.symm.hausdorff_measure_image] @[simp] lemma map_hausdorff_measure (e : X ≃ᵢ Y) (d : ℝ) : measure.map e μH[d] = μH[d] := by rw [e.isometry.map_hausdorff_measure (or.inr e.surjective), e.surjective.range_eq, restrict_univ] lemma measure_preserving_hausdorff_measure (e : X ≃ᵢ Y) (d : ℝ) : measure_preserving e μH[d] μH[d] := ⟨e.continuous.measurable, map_hausdorff_measure _ _⟩ end isometry_equiv namespace measure_theory @[to_additive] lemma hausdorff_measure_smul {α : Type*} [has_smul α X] [has_isometric_smul α X] {d : ℝ} (c : α) (h : 0 ≤ d ∨ surjective ((•) c : X → X)) (s : set X) : μH[d] (c • s) = μH[d] s := (isometry_smul X c).hausdorff_measure_image h _ @[to_additive] instance {d : ℝ} [group X] [has_isometric_smul X X] : is_mul_left_invariant (μH[d] : measure X) := { map_mul_left_eq_self := λ x, (isometry_equiv.const_smul x).map_hausdorff_measure _ } @[to_additive] instance {d : ℝ} [group X] [has_isometric_smul Xᵐᵒᵖ X] : is_mul_right_invariant (μH[d] : measure X) := { map_mul_right_eq_self := λ x, (isometry_equiv.const_smul (mul_opposite.op x)).map_hausdorff_measure _ } /-! ### Hausdorff measure and Lebesgue measure -/ /-- In the space `ι → ℝ`, the Hausdorff measure coincides exactly with the Lebesgue measure. -/ @[simp] theorem hausdorff_measure_pi_real {ι : Type*} [fintype ι] : (μH[fintype.card ι] : measure (ι → ℝ)) = volume := begin classical, -- it suffices to check that the two measures coincide on products of rational intervals refine (pi_eq_generate_from (λ i, real.borel_eq_generate_from_Ioo_rat.symm) (λ i, real.is_pi_system_Ioo_rat) (λ i, real.finite_spanning_sets_in_Ioo_rat _) _).symm, simp only [mem_Union, mem_singleton_iff], -- fix such a product `s` of rational intervals, of the form `Π (a i, b i)`. intros s hs, choose a b H using hs, obtain rfl : s = λ i, Ioo (a i) (b i), from funext (λ i, (H i).2), replace H := λ i, (H i).1, apply le_antisymm _, -- first check that `volume s ≤ μH s` { have Hle : volume ≤ (μH[fintype.card ι] : measure (ι → ℝ)), { refine le_hausdorff_measure _ _ ∞ ennreal.coe_lt_top (λ s _, _), rw [ennreal.rpow_nat_cast], exact real.volume_pi_le_diam_pow s }, rw [← volume_pi_pi (λ i, Ioo (a i : ℝ) (b i))], exact measure.le_iff'.1 Hle _ }, /- For the other inequality `μH s ≤ volume s`, we use a covering of `s` by sets of small diameter `1/n`, namely cubes with left-most point of the form `a i + f i / n` with `f i` ranging between `0` and `⌈(b i - a i) * n⌉`. Their number is asymptotic to `n^d * Π (b i - a i)`. -/ have I : ∀ i, 0 ≤ (b i : ℝ) - a i := λ i, by simpa only [sub_nonneg, rat.cast_le] using (H i).le, let γ := λ (n : ℕ), (Π (i : ι), fin ⌈((b i : ℝ) - a i) * n⌉₊), let t : Π (n : ℕ), γ n → set (ι → ℝ) := λ n f, set.pi univ (λ i, Icc (a i + f i / n) (a i + (f i + 1) / n)), have A : tendsto (λ (n : ℕ), 1/(n : ℝ≥0∞)) at_top (𝓝 0), by simp only [one_div, ennreal.tendsto_inv_nat_nhds_zero], have B : ∀ᶠ n in at_top, ∀ (i : γ n), diam (t n i) ≤ 1 / n, { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, assume f, apply diam_pi_le_of_le (λ b, _), simp only [real.ediam_Icc, add_div, ennreal.of_real_div_of_pos (nat.cast_pos.mpr hn), le_refl, add_sub_add_left_eq_sub, add_sub_cancel', ennreal.of_real_one, ennreal.of_real_coe_nat] }, have C : ∀ᶠ n in at_top, set.pi univ (λ (i : ι), Ioo (a i : ℝ) (b i)) ⊆ ⋃ (i : γ n), t n i, { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, have npos : (0 : ℝ) < n := nat.cast_pos.2 hn, assume x hx, simp only [mem_Ioo, mem_univ_pi] at hx, simp only [mem_Union, mem_Ioo, mem_univ_pi, coe_coe], let f : γ n := λ i, ⟨⌊(x i - a i) * n⌋₊, begin apply nat.floor_lt_ceil_of_lt_of_pos, { refine (mul_lt_mul_right npos).2 _, simp only [(hx i).right, sub_lt_sub_iff_right] }, { refine mul_pos _ npos, simpa only [rat.cast_lt, sub_pos] using H i } end⟩, refine ⟨f, λ i, ⟨_, _⟩⟩, { calc (a i : ℝ) + ⌊(x i - a i) * n⌋₊ / n ≤ (a i : ℝ) + ((x i - a i) * n) / n : begin refine add_le_add le_rfl ((div_le_div_right npos).2 _), exact nat.floor_le (mul_nonneg (sub_nonneg.2 (hx i).1.le) npos.le), end ... = x i : by field_simp [npos.ne'] }, { calc x i = (a i : ℝ) + ((x i - a i) * n) / n : by field_simp [npos.ne'] ... ≤ (a i : ℝ) + (⌊(x i - a i) * n⌋₊ + 1) / n : add_le_add le_rfl ((div_le_div_right npos).2 (nat.lt_floor_add_one _).le) } }, calc μH[fintype.card ι] (set.pi univ (λ (i : ι), Ioo (a i : ℝ) (b i))) ≤ liminf (λ (n : ℕ), ∑ (i : γ n), diam (t n i) ^ ↑(fintype.card ι)) at_top : hausdorff_measure_le_liminf_sum _ (set.pi univ (λ i, Ioo (a i : ℝ) (b i))) (λ (n : ℕ), 1/(n : ℝ≥0∞)) A t B C ... ≤ liminf (λ (n : ℕ), ∑ (i : γ n), (1/n) ^ (fintype.card ι)) at_top : begin refine liminf_le_liminf _ (by is_bounded_default), filter_upwards [B] with _ hn, apply finset.sum_le_sum (λ i _, _), rw ennreal.rpow_nat_cast, exact pow_le_pow_of_le_left' (hn i) _, end ... = liminf (λ (n : ℕ), ∏ (i : ι), (⌈((b i : ℝ) - a i) * n⌉₊ : ℝ≥0∞) / n) at_top : begin simp only [finset.card_univ, nat.cast_prod, one_mul, fintype.card_fin, finset.sum_const, nsmul_eq_mul, fintype.card_pi, div_eq_mul_inv, finset.prod_mul_distrib, finset.prod_const] end ... = ∏ (i : ι), volume (Ioo (a i : ℝ) (b i)) : begin simp only [real.volume_Ioo], apply tendsto.liminf_eq, refine ennreal.tendsto_finset_prod_of_ne_top _ (λ i hi, _) (λ i hi, _), { apply tendsto.congr' _ ((ennreal.continuous_of_real.tendsto _).comp ((tendsto_nat_ceil_mul_div_at_top (I i)).comp tendsto_coe_nat_at_top_at_top)), apply eventually_at_top.2 ⟨1, λ n hn, _⟩, simp only [ennreal.of_real_div_of_pos (nat.cast_pos.mpr hn), comp_app, ennreal.of_real_coe_nat] }, { simp only [ennreal.of_real_ne_top, ne.def, not_false_iff] } end end variables (ι X) theorem hausdorff_measure_measure_preserving_fun_unique [unique ι] [topological_space.second_countable_topology X] (d : ℝ) : measure_preserving (measurable_equiv.fun_unique ι X) μH[d] μH[d] := (isometry_equiv.fun_unique ι X).measure_preserving_hausdorff_measure _ theorem hausdorff_measure_measure_preserving_pi_fin_two (α : fin 2 → Type*) [Π i, measurable_space (α i)] [Π i, emetric_space (α i)] [Π i, borel_space (α i)] [Π i, topological_space.second_countable_topology (α i)] (d : ℝ) : measure_preserving (measurable_equiv.pi_fin_two α) μH[d] μH[d] := (isometry_equiv.pi_fin_two α).measure_preserving_hausdorff_measure _ /-- In the space `ℝ`, the Hausdorff measure coincides exactly with the Lebesgue measure. -/ @[simp] theorem hausdorff_measure_real : (μH[1] : measure ℝ) = volume := by rw [←(volume_preserving_fun_unique unit ℝ).map_eq, ←(hausdorff_measure_measure_preserving_fun_unique unit ℝ 1).map_eq, ←hausdorff_measure_pi_real, fintype.card_unit, nat.cast_one] /-- In the space `ℝ × ℝ`, the Hausdorff measure coincides exactly with the Lebesgue measure. -/ @[simp] theorem hausdorff_measure_prod_real : (μH[2] : measure (ℝ × ℝ)) = volume := by rw [←(volume_preserving_pi_fin_two (λ i, ℝ)).map_eq, ←(hausdorff_measure_measure_preserving_pi_fin_two (λ i, ℝ) _).map_eq, ←hausdorff_measure_pi_real, fintype.card_fin, nat.cast_two] /-! ### Geometric results in affine spaces -/ section geometric variables {𝕜 E P : Type*} lemma hausdorff_measure_smul_right_image [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] (v : E) (s : set ℝ) : μH[1] ((λ r, r • v) '' s) = ‖v‖₊ • μH[1] s := begin obtain rfl | hv := eq_or_ne v 0, { haveI := no_atoms_hausdorff E one_pos, obtain rfl | hs := s.eq_empty_or_nonempty, { simp }, simp [hs] }, have hn : ‖v‖ ≠ 0 := norm_ne_zero_iff.mpr hv, -- break line_map into pieces suffices : μH[1] ( ((•) ‖v‖) '' (linear_map.to_span_singleton ℝ E (‖v‖⁻¹ • v) '' s)) = ‖v‖₊ • μH[1] s, { simpa only [set.image_image, smul_comm (norm _), inv_smul_smul₀ hn, linear_map.to_span_singleton_apply] using this }, have iso_smul : isometry (linear_map.to_span_singleton ℝ E (‖v‖⁻¹ • v)), { refine add_monoid_hom_class.isometry_of_norm _ (λ x, (norm_smul _ _).trans _), rw [norm_smul, norm_inv, norm_norm, inv_mul_cancel hn, mul_one, linear_map.id_apply] }, rw [set.image_smul, measure.hausdorff_measure_smul₀ zero_le_one hn, nnnorm_norm, nnreal.rpow_one, iso_smul.hausdorff_measure_image (or.inl $ zero_le_one' ℝ)], end section normed_field_affine variables [normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [measurable_space P] variables [metric_space P] [normed_add_torsor E P] [borel_space P] include E /-- Scaling by `c` around `x` scales the measure by `‖c‖₊ ^ d`. -/ lemma hausdorff_measure_homothety_image {d : ℝ} (hd : 0 ≤ d) (x : P) {c : 𝕜} (hc : c ≠ 0) (s : set P) : μH[d] (affine_map.homothety x c '' s) = ‖c‖₊ ^ d • μH[d] s := begin suffices : μH[d] (isometry_equiv.vadd_const x '' (((•) c) '' ((isometry_equiv.vadd_const x).symm '' s))) = ‖c‖₊ ^ d • μH[d] s, { simpa only [set.image_image] }, borelize E, rw [isometry_equiv.hausdorff_measure_image, set.image_smul, measure.hausdorff_measure_smul₀ hd hc, isometry_equiv.hausdorff_measure_image], end lemma hausdorff_measure_homothety_preimage {d : ℝ} (hd : 0 ≤ d) (x : P) {c : 𝕜} (hc : c ≠ 0) (s : set P) : μH[d] (affine_map.homothety x c ⁻¹' s) = ‖c‖₊⁻¹ ^ d • μH[d] s := begin change μH[d] (affine_equiv.homothety_units_mul_hom x (units.mk0 c hc) ⁻¹' s) = _, rw [←affine_equiv.image_symm, affine_equiv.coe_homothety_units_mul_hom_apply_symm, hausdorff_measure_homothety_image hd x (_ : 𝕜ˣ).is_unit.ne_zero, units.coe_inv, units.coe_mk0, nnnorm_inv], end /-! TODO: prove `measure.map (affine_map.homothety x c) μH[d] = ‖c‖₊⁻¹ ^ d • μH[d]`, which needs a more general version of `affine_map.homothety_continuous` -/ end normed_field_affine section real_affine variables [normed_add_comm_group E] [normed_space ℝ E] [measurable_space P] variables [metric_space P] [normed_add_torsor E P] [borel_space P] include E /-- Mapping a set of reals along a line segment scales the measure by the length of a segment. This is an auxiliary result used to prove `hausdorff_measure_affine_segment`. -/ lemma hausdorff_measure_line_map_image (x y : P) (s : set ℝ) : μH[1] (affine_map.line_map x y '' s) = nndist x y • μH[1] s := begin suffices : μH[1] (isometry_equiv.vadd_const x '' ((• y -ᵥ x) '' s)) = nndist x y • μH[1] s, { simpa only [set.image_image] }, borelize E, rw [isometry_equiv.hausdorff_measure_image, hausdorff_measure_smul_right_image, nndist_eq_nnnorm_vsub' E], end /-- The measure of a segment is the distance between its endpoints. -/ @[simp] lemma hausdorff_measure_affine_segment (x y : P) : μH[1] (affine_segment ℝ x y) = edist x y := begin rw [affine_segment, hausdorff_measure_line_map_image, hausdorff_measure_real, real.volume_Icc, sub_zero, ennreal.of_real_one, ← algebra.algebra_map_eq_smul_one], exact (edist_nndist _ _).symm, end end real_affine /-- The measure of a segment is the distance between its endpoints. -/ @[simp] lemma hausdorff_measure_segment {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] (x y : E) : μH[1] (segment ℝ x y) = edist x y := by rw [←affine_segment_eq_segment, hausdorff_measure_affine_segment] end geometric end measure_theory
231890b8478f18e0041a4d37c0e5b5eb5054c8d3
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/algebra/module/basic.lean
a0302427d97425e521ab60a6930fd7823b255295
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
22,883
lean
/- Copyright (c) 2015 Nathaniel Thomas. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro -/ import group_theory.group_action import tactic.nth_rewrite /-! # Modules over a ring In this file we define * `semimodule R M` : an additive commutative monoid `M` is a `semimodule` over a `semiring` `R` if for `r : R` and `x : M` their "scalar multiplication `r • x : M` is defined, and the operation `•` satisfies some natural associativity and distributivity axioms similar to those on a ring. * `module R M` : same as `semimodule R M` but assumes that `R` is a `ring` and `M` is an additive commutative group. * `vector_space k M` : same as `semimodule k M` and `module k M` but assumes that `k` is a `field` and `M` is an additive commutative group. * `linear_map R M M₂`, `M →ₗ[R] M₂` : a linear map between two R-`semimodule`s. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. ## Implementation notes * `vector_space` and `module` are abbreviations for `semimodule R M`. ## Tags semimodule, module, vector space, linear map -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type u} {k : Type u'} {S : Type v} {M : Type w} {M₂ : Type x} {M₃ : Type y} {ι : Type z} /-- A semimodule is a generalization of vector spaces to a scalar semiring. It consists of a scalar semiring `R` and an additive monoid of "vectors" `M`, connected by a "scalar multiplication" operation `r • x : M` (where `r : R` and `x : M`) with some natural associativity and distributivity axioms similar to those on a ring. -/ @[protect_proj] class semimodule (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] extends distrib_mul_action R M := (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (zero_smul : ∀x : M, (0 : R) • x = 0) section add_comm_monoid variables [semiring R] [add_comm_monoid M] [semimodule R M] (r s : R) (x y : M) theorem add_smul : (r + s) • x = r • x + s • x := semimodule.add_smul r s x variables (R) @[simp] theorem zero_smul : (0 : R) • x = 0 := semimodule.zero_smul x theorem two_smul : (2 : R) • x = x + x := by rw [bit0, add_smul, one_smul] /-- Pullback a `semimodule` structure along an injective additive monoid homomorphism. -/ protected def function.injective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M₂ →+ M) (hf : injective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : semimodule R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, hf $ by simp only [smul, f.map_add, add_smul], zero_smul := λ x, hf $ by simp only [smul, zero_smul, f.map_zero], .. hf.distrib_mul_action f smul } /-- Pushforward a `semimodule` structure along a surjective additive monoid homomorphism. -/ protected def function.surjective.semimodule [add_comm_monoid M₂] [has_scalar R M₂] (f : M →+ M₂) (hf : surjective f) (smul : ∀ (c : R) x, f (c • x) = c • f x) : semimodule R M₂ := { smul := (•), add_smul := λ c₁ c₂ x, by { rcases hf x with ⟨x, rfl⟩, simp only [add_smul, ← smul, ← f.map_add] }, zero_smul := λ x, by { rcases hf x with ⟨x, rfl⟩, simp only [← f.map_zero, ← smul, zero_smul] }, .. hf.distrib_mul_action f smul } variable (M) /-- `(•)` as an `add_monoid_hom`. -/ def smul_add_hom : R →+ M →+ M := { to_fun := const_smul_hom M, map_zero' := add_monoid_hom.ext $ λ r, by simp, map_add' := λ x y, add_monoid_hom.ext $ λ r, by simp [add_smul] } variables {R M} @[simp] lemma smul_add_hom_apply (r : R) (x : M) : smul_add_hom R M r x = r • x := rfl lemma semimodule.eq_zero_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : x = 0 := by rw [←one_smul R x, ←zero_eq_one, zero_smul] lemma list.sum_smul {l : list R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_list_sum l lemma multiset.sum_smul {l : multiset R} {x : M} : l.sum • x = (l.map (λ r, r • x)).sum := ((smul_add_hom R M).flip x).map_multiset_sum l lemma finset.sum_smul {f : ι → R} {s : finset ι} {x : M} : (∑ i in s, f i) • x = (∑ i in s, (f i) • x) := ((smul_add_hom R M).flip x).map_sum f s end add_comm_monoid variables (R) /-- An `add_comm_monoid` that is a `semimodule` over a `ring` carries a natural `add_comm_group` structure. -/ def semimodule.add_comm_monoid_to_add_comm_group [ring R] [add_comm_monoid M] [semimodule R M] : add_comm_group M := { neg := λ a, (-1 : R) • a, add_left_neg := λ a, by { nth_rewrite 1 ← one_smul _ a, rw [← add_smul, add_left_neg, zero_smul], }, ..(infer_instance : add_comm_monoid M), } variables {R} section add_comm_group variables (R M) [semiring R] [add_comm_group M] /-- A structure containing most informations as in a semimodule, except the fields `zero_smul` and `smul_zero`. As these fields can be deduced from the other ones when `M` is an `add_comm_group`, this provides a way to construct a semimodule structure by checking less properties, in `semimodule.of_core`. -/ @[nolint has_inhabited_instance] structure semimodule.core extends has_scalar R M := (smul_add : ∀(r : R) (x y : M), r • (x + y) = r • x + r • y) (add_smul : ∀(r s : R) (x : M), (r + s) • x = r • x + s • x) (mul_smul : ∀(r s : R) (x : M), (r * s) • x = r • s • x) (one_smul : ∀x : M, (1 : R) • x = x) variables {R M} /-- Define `semimodule` without proving `zero_smul` and `smul_zero` by using an auxiliary structure `semimodule.core`, when the underlying space is an `add_comm_group`. -/ def semimodule.of_core (H : semimodule.core R M) : semimodule R M := by letI := H.to_has_scalar; exact { zero_smul := λ x, (add_monoid_hom.mk' (λ r : R, r • x) (λ r s, H.add_smul r s x)).map_zero, smul_zero := λ r, (add_monoid_hom.mk' ((•) r) (H.smul_add r)).map_zero, ..H } end add_comm_group /-- Modules are defined as an `abbreviation` for semimodules, if the base semiring is a ring. (A previous definition made `module` a structure defined to be `semimodule`.) This has as advantage that modules are completely transparent for type class inference, which means that all instances for semimodules are immediately picked up for modules as well. A cosmetic disadvantage is that one can not extend modules as such, in definitions such as `normed_space`. The solution is to extend `semimodule` instead. -/ library_note "module definition" /-- A module is the same as a semimodule, except the scalar semiring is actually a ring. This is the traditional generalization of spaces like `ℤ^n`, which have a natural addition operation and a way to multiply them by elements of a ring, but no multiplication operation between vectors. -/ abbreviation module (R : Type u) (M : Type v) [ring R] [add_comm_group M] := semimodule R M /-- To prove two module structures on a fixed `add_comm_group` agree, it suffices to check the scalar multiplications agree. -/ -- We'll later use this to show `module ℤ M` is a subsingleton. @[ext] lemma module_ext {R : Type*} [ring R] {M : Type*} [add_comm_group M] (P Q : module R M) (w : ∀ (r : R) (m : M), by { haveI := P, exact r • m } = by { haveI := Q, exact r • m }) : P = Q := begin unfreezingI { rcases P with ⟨⟨⟨⟨P⟩⟩⟩⟩, rcases Q with ⟨⟨⟨⟨Q⟩⟩⟩⟩ }, congr, funext r m, exact w r m, all_goals { apply proof_irrel_heq }, end section module variables [ring R] [add_comm_group M] [module R M] (r s : R) (x y : M) @[simp] theorem neg_smul : -r • x = - (r • x) := eq_neg_of_add_eq_zero (by rw [← add_smul, add_left_neg, zero_smul]) variables (R) theorem neg_one_smul (x : M) : (-1 : R) • x = -x := by simp variables {R} theorem sub_smul (r s : R) (y : M) : (r - s) • y = r • y - s • y := by simp [add_smul, sub_eq_add_neg] theorem smul_eq_zero {R E : Type*} [division_ring R] [add_comm_group E] [module R E] {c : R} {x : E} : c • x = 0 ↔ c = 0 ∨ x = 0 := ⟨λ h, or_iff_not_imp_left.2 $ λ hc, (units.mk0 c hc).smul_eq_zero.1 h, λ h, h.elim (λ hc, hc.symm ▸ zero_smul R x) (λ hx, hx.symm ▸ smul_zero c)⟩ end module @[priority 910] -- see Note [lower instance priority] instance semiring.to_semimodule [semiring R] : semimodule R R := { smul := (*), smul_add := mul_add, add_smul := add_mul, mul_smul := mul_assoc, one_smul := one_mul, zero_smul := zero_mul, smul_zero := mul_zero } @[simp] lemma smul_eq_mul [semiring R] {a a' : R} : a • a' = a * a' := rfl /-- A ring homomorphism `f : R →+* M` defines a module structure by `r • x = f r * x`. -/ def ring_hom.to_semimodule [semiring R] [semiring S] (f : R →+* S) : semimodule R S := { smul := λ r x, f r * x, smul_add := λ r x y, by unfold has_scalar.smul; rw [mul_add], add_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_add, add_mul], mul_smul := λ r s x, by unfold has_scalar.smul; rw [f.map_mul, mul_assoc], one_smul := λ x, show f 1 * x = _, by rw [f.map_one, one_mul], zero_smul := λ x, show f 0 * x = 0, by rw [f.map_zero, zero_mul], smul_zero := λ r, mul_zero (f r) } /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) /-- A map `f` between semimodules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. Elements of `linear_map R M M₂` (available under the notation `M →ₗ[R] M₂`) are bundled versions of such maps. An unbundled version is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map (R : Type u) (M : Type v) (M₂ : Type w) [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] := (to_fun : M → M₂) (map_add' : ∀x y, to_fun (x + y) = to_fun x + to_fun y) (map_smul' : ∀(c : R) x, to_fun (c • x) = c • to_fun x) infixr ` →ₗ `:25 := linear_map _ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map R M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] section variables [semimodule R M] [semimodule R M₂] instance : has_coe_to_fun (M →ₗ[R] M₂) := ⟨_, to_fun⟩ @[simp] lemma coe_mk (f : M → M₂) (h₁ h₂) : ((linear_map.mk f h₁ h₂ : M →ₗ[R] M₂) : M → M₂) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := ⟨id, λ _ _, rfl, λ _ _, rfl⟩ lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section -- We can infer the module structure implicitly from the linear maps, -- rather than via typeclass resolution. variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f g : M →ₗ[R] M₂) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R f := ⟨f.2, f.3⟩ variables {f g} theorem coe_inj (h : (f : M → M₂) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_inj $ funext H lemma coe_fn_congr : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl } , ext⟩ /-- If two linear maps are equal, they are equal at each point. -/ lemma lcongr_fun (h : f = g) (m : M) : f m = g m := congr_fun (congr_arg linear_map.to_fun h) m variables (f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smul (c : R) (x : M) : f (c • x) = c • f x := f.map_smul' c x @[simp] lemma map_zero : f 0 = 0 := by rw [← zero_smul R, map_smul f 0 0, zero_smul] instance : is_add_monoid_hom f := { map_add := map_add f, map_zero := map_zero f } /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₂ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : ((f.to_add_monoid_hom) : M → M₂) = f := rfl @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective [semimodule R M] [semimodule R M₂] : function.injective (to_add_monoid_hom : (M →ₗ[R] M₂) → (M →+ M₂)) := λ f g h, coe_inj $ funext $ add_monoid_hom.congr_fun h end section variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} {semimodule_M₃ : semimodule R M₃} variables (f : M₂ →ₗ[R] M₃) (g : M →ₗ[R] M₂) /-- Composition of two linear maps is a linear map -/ def comp : M →ₗ[R] M₃ := ⟨f ∘ g, by simp, by simp⟩ @[simp] lemma comp_apply (x : M) : f.comp g x = f (g x) := rfl @[norm_cast] lemma comp_coe : (f : M₂ → M₃) ∘ (g : M → M₂) = f.comp g := rfl end end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables {semimodule_M : semimodule R M} {semimodule_M₂ : semimodule R M₂} variables (f : M →ₗ[R] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance : is_add_group_hom f := { map_add := map_add f} end add_comm_group end linear_map namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [semimodule R M] [semimodule R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ M₂ := ⟨f, H.1, H.2⟩ @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [semimodule R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end --TODO: move lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [semimodule R M] [semimodule R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Ring of linear endomorphismsms of a module. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [semimodule R M] := M →ₗ[R] M /-- Vector spaces are defined as an `abbreviation` for semimodules, if the base ring is a field. (A previous definition made `vector_space` a structure defined to be `module`.) This has as advantage that vector spaces are completely transparent for type class inference, which means that all instances for semimodules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend vector spaces as such, in definitions such as `normed_space`. The solution is to extend `semimodule` instead. -/ library_note "vector space definition" /-- A vector space is the same as a module, except the scalar ring is actually a field. (This adds commutativity of the multiplication and existence of inverses.) This is the traditional generalization of spaces like `ℝ^n`, which have a natural addition operation and a way to multiply them by real numbers, but no multiplication operation between vectors. -/ abbreviation vector_space (R : Type u) (M : Type v) [field R] [add_comm_group M] := semimodule R M namespace add_comm_monoid open add_monoid variables [add_comm_monoid M] /-- The natural ℕ-semimodule structure on any `add_comm_monoid`. -/ -- We don't make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℕ`. def nat_semimodule : semimodule ℕ M := { smul := nsmul, smul_add := λ _ _ _, nsmul_add _ _ _, add_smul := λ _ _ _, add_nsmul _ _ _, mul_smul := λ _ _ _, mul_nsmul _ _ _, one_smul := one_nsmul, zero_smul := zero_nsmul, smul_zero := nsmul_zero } end add_comm_monoid namespace add_comm_group variables [add_comm_group M] /-- The natural ℤ-module structure on any `add_comm_group`. -/ -- We don't immediately make this a global instance, as it results in too many instances, -- and confusing ambiguity in the notation `n • x` when `n : ℤ`. -- We do turn it into a global instance, but only at the end of this file, -- and I remain dubious whether this is a good idea. def int_module : module ℤ M := { smul := gsmul, smul_add := λ _ _ _, gsmul_add _ _ _, add_smul := λ _ _ _, add_gsmul _ _ _, mul_smul := λ _ _ _, gsmul_mul _ _ _, one_smul := one_gsmul, zero_smul := zero_gsmul, smul_zero := gsmul_zero } instance : subsingleton (module ℤ M) := begin split, intros P Q, ext, -- isn't that lovely: `r • m = r • m` have one_smul : by { haveI := P, exact (1 : ℤ) • m } = by { haveI := Q, exact (1 : ℤ) • m }, begin rw [@one_smul ℤ _ _ (by { haveI := P, apply_instance, }) m], rw [@one_smul ℤ _ _ (by { haveI := Q, apply_instance, }) m], end, have nat_smul : ∀ n : ℕ, by { haveI := P, exact (n : ℤ) • m } = by { haveI := Q, exact (n : ℤ) • m }, begin intro n, induction n with n ih, { erw [zero_smul, zero_smul], }, { rw [int.coe_nat_succ, add_smul, add_smul], erw ih, rw [one_smul], } end, cases r, { rw [int.of_nat_eq_coe, nat_smul], }, { rw [int.neg_succ_of_nat_coe, neg_smul, neg_smul, nat_smul], } end end add_comm_group section local attribute [instance] add_comm_monoid.nat_semimodule lemma semimodule.smul_eq_smul (R : Type*) [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) : n • b = (n : R) • b := begin induction n with n ih, { rw [nat.cast_zero, zero_smul, zero_smul] }, { change (n + 1) • b = (n + 1 : R) • b, rw [add_smul, add_smul, one_smul, ih, one_smul] } end lemma semimodule.nsmul_eq_smul (R : Type*) [semiring R] {M : Type*} [add_comm_monoid M] [semimodule R M] (n : ℕ) (b : M) : n •ℕ b = (n : R) • b := semimodule.smul_eq_smul R n b lemma nat.smul_def {M : Type*} [add_comm_monoid M] (n : ℕ) (x : M) : n • x = n •ℕ x := rfl end section local attribute [instance] add_comm_group.int_module lemma gsmul_eq_smul {M : Type*} [add_comm_group M] (n : ℤ) (x : M) : gsmul n x = n • x := rfl lemma module.gsmul_eq_smul_cast (R : Type*) [ring R] {M : Type*} [add_comm_group M] [module R M] (n : ℤ) (b : M) : gsmul n b = (n : R) • b := begin cases n, { apply semimodule.nsmul_eq_smul, }, { dsimp, rw semimodule.nsmul_eq_smul R, push_cast, rw neg_smul, } end lemma module.gsmul_eq_smul {M : Type*} [add_comm_group M] [module ℤ M] (n : ℤ) (b : M) : gsmul n b = n • b := by rw [module.gsmul_eq_smul_cast ℤ, int.cast_id] end -- We prove this without using the `add_comm_group.int_module` instance, so the `•`s here -- come from whatever the local `module ℤ` structure actually is. lemma add_monoid_hom.map_int_module_smul [add_comm_group M] [add_comm_group M₂] [module ℤ M] [module ℤ M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f (x • a) = x • f a := by simp only [← module.gsmul_eq_smul, f.map_gsmul] lemma add_monoid_hom.map_int_cast_smul [ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂] (f : M →+ M₂) (x : ℤ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [← module.gsmul_eq_smul_cast, f.map_gsmul] lemma add_monoid_hom.map_nat_cast_smul [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [semimodule R M] [semimodule R M₂] (f : M →+ M₂) (x : ℕ) (a : M) : f ((x : R) • a) = (x : R) • f a := by simp only [← semimodule.nsmul_eq_smul, f.map_nsmul] lemma add_monoid_hom.map_rat_cast_smul {R : Type*} [division_ring R] [char_zero R] {E : Type*} [add_comm_group E] [module R E] {F : Type*} [add_comm_group F] [module R F] (f : E →+ F) (c : ℚ) (x : E) : f ((c : R) • x) = (c : R) • f x := begin have : ∀ (x : E) (n : ℕ), 0 < n → f (((n⁻¹ : ℚ) : R) • x) = ((n⁻¹ : ℚ) : R) • f x, { intros x n hn, replace hn : (n : R) ≠ 0 := nat.cast_ne_zero.2 (ne_of_gt hn), conv_rhs { congr, skip, rw [← one_smul R x, ← mul_inv_cancel hn, mul_smul] }, rw [f.map_nat_cast_smul, smul_smul, rat.cast_inv, rat.cast_coe_nat, inv_mul_cancel hn, one_smul] }, refine c.num_denom_cases_on (λ m n hn hmn, _), rw [rat.mk_eq_div, div_eq_mul_inv, rat.cast_mul, int.cast_coe_nat, mul_smul, mul_smul, rat.cast_coe_int, f.map_int_cast_smul, this _ n hn] end lemma add_monoid_hom.map_rat_module_smul {E : Type*} [add_comm_group E] [vector_space ℚ E] {F : Type*} [add_comm_group F] [module ℚ F] (f : E →+ F) (c : ℚ) (x : E) : f (c • x) = c • f x := rat.cast_id c ▸ f.map_rat_cast_smul c x -- We finally turn on these instances globally: attribute [instance] add_comm_monoid.nat_semimodule add_comm_group.int_module /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := ⟨f, f.map_add, f.map_int_module_smul⟩ /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [vector_space ℚ M] [add_comm_group M₂] [vector_space ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := ⟨f, f.map_add, f.map_rat_module_smul⟩
f2684aac5c71cb551b79173845a3692d58b78fc9
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/category/preorder.lean
b5ce286ec310621688689bfadcbb042b560423b4
[ "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,382
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton -/ import category_theory.adjunction.basic import order.galois_connection /-! # Preorders as categories We install a category instance on any preorder. This is not to be confused with the category _of_ preorders, defined in `order/category/Preorder`. We show that monotone functions between preorders correspond to functors of the associated categories. Furthermore, galois connections correspond to adjoint functors. ## Main definitions * `hom_of_le` and `le_of_hom` provide translations between inequalities in the preorder, and morphisms in the associated category. * `monotone.functor` is the functor associated to a monotone function. * `galois_connection.adjunction` is the adjunction associated to a galois connection. * `Preorder_to_Cat` is the functor embedding the category of preorders into `Cat`. -/ universes u v namespace preorder open category_theory /-- The category structure coming from a preorder. There is a morphism `X ⟶ Y` if and only if `X ≤ Y`. Because we don't allow morphisms to live in `Prop`, we have to define `X ⟶ Y` as `ulift (plift (X ≤ Y))`. See `category_theory.hom_of_le` and `category_theory.le_of_hom`. See <https://stacks.math.columbia.edu/tag/00D3>. -/ @[priority 100] -- see Note [lower instance priority] instance small_category (α : Type u) [preorder α] : small_category α := { hom := λ U V, ulift (plift (U ≤ V)), id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩, comp := λ X Y Z f g, ⟨ ⟨ le_trans _ _ _ f.down.down g.down.down ⟩ ⟩ } end preorder namespace category_theory open opposite variables {X : Type u} [preorder X] /-- Express an inequality as a morphism in the corresponding preorder category. -/ def hom_of_le {x y : X} (h : x ≤ y) : x ⟶ y := ulift.up (plift.up h) alias hom_of_le ← has_le.le.hom @[simp] lemma hom_of_le_refl {x : X} : (le_refl x).hom = 𝟙 x := rfl @[simp] lemma hom_of_le_comp {x y z : X} (h : x ≤ y) (k : y ≤ z) : h.hom ≫ k.hom = (h.trans k).hom := rfl /-- Extract the underlying inequality from a morphism in a preorder category. -/ lemma le_of_hom {x y : X} (h : x ⟶ y) : x ≤ y := h.down.down alias le_of_hom ← quiver.hom.le @[simp] lemma le_of_hom_hom_of_le {x y : X} (h : x ≤ y) : h.hom.le = h := rfl @[simp] lemma hom_of_le_le_of_hom {x y : X} (h : x ⟶ y) : h.le.hom = h := by { cases h, cases h, refl, } /-- Construct a morphism in the opposite of a preorder category from an inequality. -/ def op_hom_of_le {x y : Xᵒᵖ} (h : unop x ≤ unop y) : y ⟶ x := h.hom.op lemma le_of_op_hom {x y : Xᵒᵖ} (h : x ⟶ y) : unop y ≤ unop x := h.unop.le instance unique_to_top [order_top X] {x : X} : unique (x ⟶ ⊤) := by tidy instance unique_from_bot [order_bot X] {x : X} : unique (⊥ ⟶ x) := by tidy end category_theory section variables {X : Type u} {Y : Type v} [preorder X] [preorder Y] /-- A monotone function between preorders induces a functor between the associated categories. -/ def monotone.functor {f : X → Y} (h : monotone f) : X ⥤ Y := { obj := f, map := λ x₁ x₂ g, (h g.le).hom } @[simp] lemma monotone.functor_obj {f : X → Y} (h : monotone f) : h.functor.obj = f := rfl /-- A galois connection between preorders induces an adjunction between the associated categories. -/ def galois_connection.adjunction {l : X → Y} {u : Y → X} (gc : galois_connection l u) : gc.monotone_l.functor ⊣ gc.monotone_u.functor := category_theory.adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, ⟨λ f, (gc.le_u f.le).hom, λ f, (gc.l_le f.le).hom, by tidy, by tidy⟩ } end namespace category_theory section preorder variables {X : Type u} {Y : Type v} [preorder X] [preorder Y] /-- A functor between preorder categories is monotone. -/ @[mono] lemma functor.monotone (f : X ⥤ Y) : monotone f.obj := λ x y hxy, (f.map hxy.hom).le /-- An adjunction between preorder categories induces a galois connection. -/ lemma adjunction.gc {L : X ⥤ Y} {R : Y ⥤ X} (adj : L ⊣ R) : galois_connection L.obj R.obj := λ x y, ⟨λ h, ((adj.hom_equiv x y).to_fun h.hom).le, λ h, ((adj.hom_equiv x y).inv_fun h.hom).le⟩ end preorder section partial_order variables {X : Type u} {Y : Type v} [partial_order X] [partial_order Y] lemma iso.to_eq {x y : X} (f : x ≅ y) : x = y := le_antisymm f.hom.le f.inv.le /-- A categorical equivalence between partial orders is just an order isomorphism. -/ def equivalence.to_order_iso (e : X ≌ Y) : X ≃o Y := { to_fun := e.functor.obj, inv_fun := e.inverse.obj, left_inv := λ a, (e.unit_iso.app a).to_eq.symm, right_inv := λ b, (e.counit_iso.app b).to_eq, map_rel_iff' := λ a a', ⟨λ h, ((equivalence.unit e).app a ≫ e.inverse.map h.hom ≫ (equivalence.unit_inv e).app a').le, λ (h : a ≤ a'), (e.functor.map h.hom).le⟩, } -- `@[simps]` on `equivalence.to_order_iso` produces lemmas that fail the `simp_nf` linter, -- so we provide them by hand: @[simp] lemma equivalence.to_order_iso_apply (e : X ≌ Y) (x : X) : e.to_order_iso x = e.functor.obj x := rfl @[simp] lemma equivalence.to_order_iso_symm_apply (e : X ≌ Y) (y : Y) : e.to_order_iso.symm y = e.inverse.obj y := rfl end partial_order end category_theory
f7048df4b36f1aeaee6f1a1863d8203aade4ceeb
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed/group/controlled_closure.lean
e43218e83efbb08ebec339721385064b86610bff
[ "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,745
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import analysis.normed.group.hom import analysis.specific_limits.normed /-! # Extending a backward bound on a normed group homomorphism from a dense set > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Possible TODO (from the PR's review, https://github.com/leanprover-community/mathlib/pull/8498 ): "This feels a lot like the second step in the proof of the Banach open mapping theorem (`exists_preimage_norm_le`) ... wonder if it would be possible to refactor it using one of [the lemmas in this file]." -/ open filter finset open_locale topology big_operators variables {G : Type*} [normed_add_comm_group G] [complete_space G] variables {H : Type*} [normed_add_comm_group H] /-- Given `f : normed_add_group_hom G H` for some complete `G` and a subgroup `K` of `H`, if every element `x` of `K` has a preimage under `f` whose norm is at most `C*‖x‖` then the same holds for elements of the (topological) closure of `K` with constant `C+ε` instead of `C`, for any positive `ε`. -/ lemma controlled_closure_of_complete {f : normed_add_group_hom G H} {K : add_subgroup H} {C ε : ℝ} (hC : 0 < C) (hε : 0 < ε) (hyp : f.surjective_on_with K C) : f.surjective_on_with K.topological_closure (C + ε) := begin rintros (h : H) (h_in : h ∈ K.topological_closure), /- We first get rid of the easy case where `h = 0`.-/ by_cases hyp_h : h = 0, { rw hyp_h, use 0, simp }, /- The desired preimage will be constructed as the sum of a series. Convergence of the series will be guaranteed by completeness of `G`. We first write `h` as the sum of a sequence `v` of elements of `K` which starts close to `h` and then quickly goes to zero. The sequence `b` below quantifies this. -/ set b : ℕ → ℝ := λ i, (1/2)^i*(ε*‖h‖/2)/C, have b_pos : ∀ i, 0 < b i, { intro i, field_simp [b, hC], exact div_pos (mul_pos hε (norm_pos_iff.mpr hyp_h)) (mul_pos (by norm_num : (0 : ℝ) < 2^i*2) hC) }, obtain ⟨v : ℕ → H, lim_v : tendsto (λ (n : ℕ), ∑ k in range (n + 1), v k) at_top (𝓝 h), v_in : ∀ n, v n ∈ K, hv₀ : ‖v 0 - h‖ < b 0, hv : ∀ n > 0, ‖v n‖ < b n⟩ := controlled_sum_of_mem_closure h_in b_pos, /- The controlled surjectivity assumption on `f` allows to build preimages `u n` for all elements `v n` of the `v` sequence.-/ have : ∀ n, ∃ m' : G, f m' = v n ∧ ‖m'‖ ≤ C * ‖v n‖ := λ (n : ℕ), hyp (v n) (v_in n), choose u hu hnorm_u using this, /- The desired series `s` is then obtained by summing `u`. We then check our choice of `b` ensures `s` is Cauchy. -/ set s : ℕ → G := λ n, ∑ k in range (n+1), u k, have : cauchy_seq s, { apply normed_add_comm_group.cauchy_series_of_le_geometric'' (by norm_num) one_half_lt_one, rintro n (hn : n ≥ 1), calc ‖u n‖ ≤ C*‖v n‖ : hnorm_u n ... ≤ C * b n : mul_le_mul_of_nonneg_left (hv _ $ nat.succ_le_iff.mp hn).le hC.le ... = (1/2)^n * (ε * ‖h‖/2) : by simp [b, mul_div_cancel' _ hC.ne.symm] ... = (ε * ‖h‖/2) * (1/2)^n : mul_comm _ _ }, /- We now show that the limit `g` of `s` is the desired preimage. -/ obtain ⟨g : G, hg⟩ := cauchy_seq_tendsto_of_complete this, refine ⟨g, _, _⟩, { /- We indeed get a preimage. First note: -/ have : f ∘ s = λ n, ∑ k in range (n + 1), v k, { ext n, simp [map_sum, hu] }, /- In the above equality, the left-hand-side converges to `f g` by continuity of `f` and definition of `g` while the right-hand-side converges to `h` by construction of `v` so `g` is indeed a preimage of `h`. -/ rw ← this at lim_v, exact tendsto_nhds_unique ((f.continuous.tendsto g).comp hg) lim_v }, { /- Then we need to estimate the norm of `g`, using our careful choice of `b`. -/ suffices : ∀ n, ‖s n‖ ≤ (C + ε) * ‖h‖, from le_of_tendsto' (continuous_norm.continuous_at.tendsto.comp hg) this, intros n, have hnorm₀ : ‖u 0‖ ≤ C*b 0 + C*‖h‖, { have := calc ‖v 0‖ ≤ ‖h‖ + ‖v 0 - h‖ : norm_le_insert' _ _ ... ≤ ‖h‖ + b 0 : by apply add_le_add_left hv₀.le, calc ‖u 0‖ ≤ C*‖v 0‖ : hnorm_u 0 ... ≤ C*(‖h‖ + b 0) : mul_le_mul_of_nonneg_left this hC.le ... = C * b 0 + C * ‖h‖ : by rw [add_comm, mul_add] }, have : ∑ k in range (n + 1), C * b k ≤ ε * ‖h‖ := calc ∑ k in range (n + 1), C * b k = (∑ k in range (n + 1), (1 / 2) ^ k) * (ε * ‖h‖ / 2) : by simp only [b, mul_div_cancel' _ hC.ne.symm, ← sum_mul] ... ≤ 2 * (ε * ‖h‖ / 2) : mul_le_mul_of_nonneg_right (sum_geometric_two_le _) (by nlinarith [hε, norm_nonneg h]) ... = ε * ‖h‖ : mul_div_cancel' _ two_ne_zero, calc ‖s n‖ ≤ ∑ k in range (n+1), ‖u k‖ : norm_sum_le _ _ ... = ∑ k in range n, ‖u (k + 1)‖ + ‖u 0‖ : sum_range_succ' _ _ ... ≤ ∑ k in range n, C*‖v (k + 1)‖ + ‖u 0‖ : add_le_add_right (sum_le_sum (λ _ _, hnorm_u _)) _ ... ≤ ∑ k in range n, C*b (k+1) + (C*b 0 + C*‖h‖) : add_le_add (sum_le_sum (λ k _, mul_le_mul_of_nonneg_left (hv _ k.succ_pos).le hC.le)) hnorm₀ ... = ∑ k in range (n+1), C*b k + C*‖h‖ : by rw [← add_assoc, sum_range_succ'] ... ≤ (C+ε)*‖h‖ : by { rw [add_comm, add_mul], apply add_le_add_left this } } end /-- Given `f : normed_add_group_hom G H` for some complete `G`, if every element `x` of the image of an isometric immersion `j : normed_add_group_hom K H` has a preimage under `f` whose norm is at most `C*‖x‖` then the same holds for elements of the (topological) closure of this image with constant `C+ε` instead of `C`, for any positive `ε`. This is useful in particular if `j` is the inclusion of a normed group into its completion (in this case the closure is the full target group). -/ lemma controlled_closure_range_of_complete {f : normed_add_group_hom G H} {K : Type*} [seminormed_add_comm_group K] {j : normed_add_group_hom K H} (hj : ∀ x, ‖j x‖ = ‖x‖) {C ε : ℝ} (hC : 0 < C) (hε : 0 < ε) (hyp : ∀ k, ∃ g, f g = j k ∧ ‖g‖ ≤ C*‖k‖) : f.surjective_on_with j.range.topological_closure (C + ε) := begin replace hyp : ∀ h ∈ j.range, ∃ g, f g = h ∧ ‖g‖ ≤ C*‖h‖, { intros h h_in, rcases (j.mem_range _).mp h_in with ⟨k, rfl⟩, rw hj, exact hyp k }, exact controlled_closure_of_complete hC hε hyp end
fae5230fd9f3e88810cc3ec405cc2165e2ad2378
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Util/FindExpr.lean
48086e85dbc25c51e13183a8d2016cb7e6d7972b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
2,273
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean namespace Expr namespace FindImpl abbrev cacheSize : USize := 8192 structure State where keys : Array Expr -- Remark: our "unsafe" implementation relies on the fact that `()` is not a valid Expr abbrev FindM := StateT State Id unsafe def visited (e : Expr) (size : USize) : FindM Bool := do let s ← get let h := ptrAddrUnsafe e let i := h % size let k := s.keys.uget i lcProof if ptrAddrUnsafe k == h then pure true else modify fun s => { keys := s.keys.uset i e lcProof } pure false @[specialize] unsafe def findM? (p : Expr → Bool) (size : USize) (e : Expr) : OptionT FindM Expr := let rec visit (e : Expr) := do if (← visited e size) then failure else if p e then pure e else match e with | Expr.forallE _ d b _ => visit d <|> visit b | Expr.lam _ d b _ => visit d <|> visit b | Expr.mdata _ b _ => visit b | Expr.letE _ t v b _ => visit t <|> visit v <|> visit b | Expr.app f a _ => visit f <|> visit a | Expr.proj _ _ b _ => visit b | e => failure visit e unsafe def initCache : State := { keys := mkArray cacheSize.toNat (cast lcProof ()) } @[inline] unsafe def findUnsafe? (p : Expr → Bool) (e : Expr) : Option Expr := Id.run <| findM? p cacheSize e |>.run' initCache end FindImpl @[implementedBy FindImpl.findUnsafe?] partial def find? (p : Expr → Bool) (e : Expr) : Option Expr := /- This is a reference implementation for the unsafe one above -/ if p e then some e else match e with | Expr.forallE _ d b _ => find? p d <|> find? p b | Expr.lam _ d b _ => find? p d <|> find? p b | Expr.mdata _ b _ => find? p b | Expr.letE _ t v b _ => find? p t <|> find? p v <|> find? p b | Expr.app f a _ => find? p f <|> find? p a | Expr.proj _ _ b _ => find? p b | e => none /-- Return true if `e` occurs in `t` -/ def occurs (e : Expr) (t : Expr) : Bool := (t.find? fun s => s == e).isSome end Expr end Lean
e499104df7c19c4d3fa0431ceadab7e82dc5da6e
437dc96105f48409c3981d46fb48e57c9ac3a3e4
/src/data/setoid.lean
9617ade69025f970aa6a8f86394592638b635b73
[ "Apache-2.0" ]
permissive
dan-c-k/mathlib
08efec79bd7481ee6da9cc44c24a653bff4fbe0d
96efc220f6225bc7a5ed8349900391a33a38cc56
refs/heads/master
1,658,082,847,093
1,589,013,201,000
1,589,013,201,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,445
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston, Bryan Gin-ge Chen -/ import data.set.lattice /-! # Equivalence relations The first section of the file defines the complete lattice of equivalence relations on a type, results about the inductively defined equivalence closure of a binary relation, and the analogues of some isomorphism theorems for quotients of arbitrary types. The second section comprises properties of equivalence relations viewed as partitions. ## Implementation notes The function `rel` and lemmas ending in ' make it easier to talk about different equivalence relations on the same type. The complete lattice instance for equivalence relations could have been defined by lifting the Galois insertion of equivalence relations on α into binary relations on α, and then using `complete_lattice.copy` to define a complete lattice instance with more appropriate definitional equalities (a similar example is `filter.complete_lattice` in `order/filter/basic.lean`). This does not save space, however, and is less clear. Partitions are not defined as a separate structure here; users are encouraged to reason about them using the existing `setoid` and its infrastructure. ## Tags setoid, equivalence, iseqv, relation, equivalence relation, partition, equivalence class -/ variables {α : Type*} {β : Type*} /-- A version of `setoid.r` that takes the equivalence relation as an explicit argument. -/ def setoid.rel (r : setoid α) : α → α → Prop := @setoid.r _ r /-- A version of `quotient.eq'` compatible with `setoid.rel`, to make rewriting possible. -/ lemma quotient.eq_rel {r : setoid α} {x y} : ⟦x⟧ = ⟦y⟧ ↔ r.rel x y := quotient.eq' namespace setoid @[ext] lemma ext' {r s : setoid α} (H : ∀ a b, r.rel a b ↔ s.rel a b) : r = s := ext H lemma ext_iff {r s : setoid α} : r = s ↔ ∀ a b, r.rel a b ↔ s.rel a b := ⟨λ h a b, h ▸ iff.rfl, ext'⟩ /-- Two equivalence relations are equal iff their underlying binary operations are equal. -/ theorem eq_iff_rel_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.rel = r₂.rel := ⟨λ h, h ▸ rfl, λ h, setoid.ext' $ λ x y, h ▸ iff.rfl⟩ /-- Defining `≤` for equivalence relations. -/ instance : has_le (setoid α) := ⟨λ r s, ∀ ⦃x y⦄, r.rel x y → s.rel x y⟩ theorem le_def {r s : setoid α} : r ≤ s ↔ ∀ {x y}, r.rel x y → s.rel x y := iff.rfl @[refl] lemma refl' (r : setoid α) (x) : r.rel x x := r.2.1 x @[symm] lemma symm' (r : setoid α) : ∀ {x y}, r.rel x y → r.rel y x := λ _ _ h, r.2.2.1 h @[trans] lemma trans' (r : setoid α) : ∀ {x y z}, r.rel x y → r.rel y z → r.rel x z := λ _ _ _ hx, r.2.2.2 hx /-- The kernel of a function is an equivalence relation. -/ def ker (f : α → β) : setoid α := ⟨λ x y, f x = f y, ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h, h.trans⟩⟩ /-- The kernel of the quotient map induced by an equivalence relation r equals r. -/ @[simp] lemma ker_mk_eq (r : setoid α) : ker (@quotient.mk _ r) = r := ext' $ λ x y, quotient.eq /-- Given types `α, β`, the product of two equivalence relations `r` on `α` and `s` on `β`: `(x₁, x₂), (y₁, y₂) ∈ α × β` are related by `r.prod s` iff `x₁` is related to `y₁` by `r` and `x₂` is related to `y₂` by `s`. -/ protected def prod (r : setoid α) (s : setoid β) : setoid (α × β) := { r := λ x y, r.rel x.1 y.1 ∧ s.rel x.2 y.2, iseqv := ⟨λ x, ⟨r.refl' x.1, s.refl' x.2⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩, λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩ } /-- The infimum of two equivalence relations. -/ instance : has_inf (setoid α) := ⟨λ r s, ⟨λ x y, r.rel x y ∧ s.rel x y, ⟨λ x, ⟨r.refl' x, s.refl' x⟩, λ _ _ h, ⟨r.symm' h.1, s.symm' h.2⟩, λ _ _ _ h1 h2, ⟨r.trans' h1.1 h2.1, s.trans' h1.2 h2.2⟩⟩⟩⟩ /-- The infimum of 2 equivalence relations r and s is the same relation as the infimum of the underlying binary operations. -/ lemma inf_def {r s : setoid α} : (r ⊓ s).rel = r.rel ⊓ s.rel := rfl theorem inf_iff_and {r s : setoid α} {x y} : (r ⊓ s).rel x y ↔ r.rel x y ∧ s.rel x y := iff.rfl /-- The infimum of a set of equivalence relations. -/ instance : has_Inf (setoid α) := ⟨λ S, ⟨λ x y, ∀ r ∈ S, rel r x y, ⟨λ x r hr, r.refl' x, λ _ _ h r hr, r.symm' $ h r hr, λ _ _ _ h1 h2 r hr, r.trans' (h1 r hr) $ h2 r hr⟩⟩⟩ /-- The underlying binary operation of the infimum of a set of equivalence relations is the infimum of the set's image under the map to the underlying binary operation. -/ theorem Inf_def {s : set (setoid α)} : (Inf s).rel = Inf (rel '' s) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } instance : partial_order (setoid α) := { le := (≤), lt := λ r s, r ≤ s ∧ ¬s ≤ r, le_refl := λ _ _ _, id, le_trans := λ _ _ _ hr hs _ _ h, hs $ hr h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ r s h1 h2, setoid.ext' $ λ x y, ⟨λ h, h1 h, λ h, h2 h⟩ } /-- The complete lattice of equivalence relations on a type, with bottom element `=` and top element the trivial equivalence relation. -/ instance complete_lattice : complete_lattice (setoid α) := { inf := has_inf.inf, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ h1 h2 _ _ h, ⟨h1 h, h2 h⟩, top := ⟨λ _ _, true, ⟨λ _, trivial, λ _ _ h, h, λ _ _ _ h1 h2, h1⟩⟩, le_top := λ _ _ _ _, trivial, bot := ⟨(=), ⟨λ _, rfl, λ _ _ h, h.symm, λ _ _ _ h1 h2, h1.trans h2⟩⟩, bot_le := λ r x y h, h ▸ r.2.1 x, .. complete_lattice_of_Inf (setoid α) $ assume s, ⟨λ r hr x y h, h _ hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The inductively defined equivalence closure of a binary relation r is the infimum of the set of all equivalence relations containing r. -/ theorem eqv_gen_eq (r : α → α → Prop) : eqv_gen.setoid r = Inf {s : setoid α | ∀ ⦃x y⦄, r x y → s.rel x y} := le_antisymm (λ _ _ H, eqv_gen.rec (λ _ _ h _ hs, hs h) (refl' _) (λ _ _ _, symm' _) (λ _ _ _ _ _, trans' _) H) (Inf_le $ λ _ _ h, eqv_gen.rel _ _ h) /-- The supremum of two equivalence relations r and s is the equivalence closure of the binary relation `x is related to y by r or s`. -/ lemma sup_eq_eqv_gen (r s : setoid α) : r ⊔ s = eqv_gen.setoid (λ x y, r.rel x y ∨ s.rel x y) := begin rw eqv_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of 2 equivalence relations r and s is the equivalence closure of the supremum of the underlying binary operations. -/ lemma sup_def {r s : setoid α} : r ⊔ s = eqv_gen.setoid (r.rel ⊔ s.rel) := by rw sup_eq_eqv_gen; refl /-- The supremum of a set S of equivalence relations is the equivalence closure of the binary relation `there exists r ∈ S relating x and y`. -/ lemma Sup_eq_eqv_gen (S : set (setoid α)) : Sup S = eqv_gen.setoid (λ x y, ∃ r : setoid α, r ∈ S ∧ r.rel x y) := begin rw eqv_gen_eq, apply congr_arg Inf, simp only [upper_bounds, le_def, and_imp, exists_imp_distrib], ext, exact ⟨λ H x y r hr, H hr, λ H r hr x y, H r hr⟩ end /-- The supremum of a set of equivalence relations is the equivalence closure of the supremum of the set's image under the map to the underlying binary operation. -/ lemma Sup_def {s : set (setoid α)} : Sup s = eqv_gen.setoid (Sup (rel '' s)) := begin rw Sup_eq_eqv_gen, congr, ext x y, erw [Sup_image, supr_apply, supr_apply, supr_Prop_eq], simp only [Sup_image, supr_Prop_eq, supr_apply, supr_Prop_eq, exists_prop] end /-- The equivalence closure of an equivalence relation r is r. -/ @[simp] lemma eqv_gen_of_setoid (r : setoid α) : eqv_gen.setoid r.r = r := le_antisymm (by rw eqv_gen_eq; exact Inf_le (λ _ _, id)) eqv_gen.rel /-- Equivalence closure is idempotent. -/ @[simp] lemma eqv_gen_idem (r : α → α → Prop) : eqv_gen.setoid (eqv_gen.setoid r).rel = eqv_gen.setoid r := eqv_gen_of_setoid _ /-- The equivalence closure of a binary relation r is contained in any equivalence relation containing r. -/ theorem eqv_gen_le {r : α → α → Prop} {s : setoid α} (h : ∀ x y, r x y → s.rel x y) : eqv_gen.setoid r ≤ s := by rw eqv_gen_eq; exact Inf_le h /-- Equivalence closure of binary relations is monotonic. -/ theorem eqv_gen_mono {r s : α → α → Prop} (h : ∀ x y, r x y → s x y) : eqv_gen.setoid r ≤ eqv_gen.setoid s := eqv_gen_le $ λ _ _ hr, eqv_gen.rel _ _ $ h _ _ hr /-- There is a Galois insertion of equivalence relations on α into binary relations on α, with equivalence closure the lower adjoint. -/ def gi : @galois_insertion (α → α → Prop) (setoid α) _ _ eqv_gen.setoid rel := { choice := λ r h, eqv_gen.setoid r, gc := λ r s, ⟨λ H _ _ h, H $ eqv_gen.rel _ _ h, λ H, eqv_gen_of_setoid s ▸ eqv_gen_mono H⟩, le_l_u := λ x, (eqv_gen_of_setoid x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } open function /-- A function from α to β is injective iff its kernel is the bottom element of the complete lattice of equivalence relations on α. -/ theorem injective_iff_ker_bot (f : α → β) : injective f ↔ ker f = ⊥ := ⟨λ hf, setoid.ext' $ λ x y, ⟨λ h, hf h, λ h, h ▸ rfl⟩, λ hk x y h, show rel ⊥ x y, from hk ▸ (show (ker f).rel x y, from h)⟩ /-- The elements related to x ∈ α by the kernel of f are those in the preimage of f(x) under f. -/ lemma ker_apply_eq_preimage (f : α → β) (x) : (ker f).rel x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 (set.mem_singleton_iff.2 h.symm), λ h, (set.mem_singleton_iff.1 (set.mem_preimage.1 h)).symm⟩ /-- The uniqueness part of the universal property for quotients of an arbitrary type. -/ theorem lift_unique {r : setoid α} {f : α → β} (H : r ≤ ker f) (g : quotient r → β) (Hg : f = g ∘ quotient.mk) : quotient.lift f H = g := begin ext, rcases x, erw [quotient.lift_beta f H, Hg], refl end /-- Given a map f from α to β, the natural map from the quotient of α by the kernel of f is injective. -/ lemma injective_ker_lift (f : α → β) : injective (@quotient.lift _ _ (ker f) f (λ _ _ h, h)) := λ x y, quotient.induction_on₂' x y $ λ a b h, quotient.sound' h /-- Given a map f from α to β, the kernel of f is the unique equivalence relation on α whose induced map from the quotient of α to β is injective. -/ lemma ker_eq_lift_of_injective {r : setoid α} (f : α → β) (H : ∀ x y, r.rel x y → f x = f y) (h : injective (quotient.lift f H)) : ker f = r := le_antisymm (λ x y hk, quotient.exact $ h $ show quotient.lift f H ⟦x⟧ = quotient.lift f H ⟦y⟧, from hk) H variables (r : setoid α) (f : α → β) /-- The first isomorphism theorem for sets: the quotient of α by the kernel of a function f bijects with f's image. -/ noncomputable def quotient_ker_equiv_range : quotient (ker f) ≃ set.range f := @equiv.of_bijective _ (set.range f) (@quotient.lift _ (set.range f) (ker f) (λ x, ⟨f x, set.mem_range_self x⟩) $ λ _ _ h, subtype.eq' h) ⟨λ x y h, injective_ker_lift f $ by rcases x; rcases y; injections, λ ⟨w, z, hz⟩, ⟨@quotient.mk _ (ker f) z, by rw quotient.lift_beta; exact subtype.ext.2 hz⟩⟩ /-- The quotient of α by the kernel of a surjective function f bijects with f's codomain. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : surjective f) : quotient (ker f) ≃ β := @equiv.of_bijective _ _ (@quotient.lift _ _ (ker f) f (λ _ _, id)) ⟨injective_ker_lift f, λ y, exists.elim (hf y) $ λ w hw, ⟨quotient.mk' w, hw⟩⟩ variables {r f} /-- Given a function `f : α → β` and equivalence relation `r` on `α`, the equivalence closure of the relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `r`.' -/ def map (r : setoid α) (f : α → β) : setoid β := eqv_gen.setoid $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b /-- Given a surjective function f whose kernel is contained in an equivalence relation r, the equivalence relation on f's codomain defined by x ≈ y ↔ the elements of f⁻¹(x) are related to the elements of f⁻¹(y) by r. -/ def map_of_surjective (r) (f : α → β) (h : ker f ≤ r) (hf : surjective f) : setoid β := ⟨λ x y, ∃ a b, f a = x ∧ f b = y ∧ r.rel a b, ⟨λ x, let ⟨y, hy⟩ := hf x in ⟨y, y, hy, hy, r.refl' y⟩, λ _ _ ⟨x, y, hx, hy, h⟩, ⟨y, x, hy, hx, r.symm' h⟩, λ _ _ _ ⟨x, y, hx, hy, h₁⟩ ⟨y', z, hy', hz, h₂⟩, ⟨x, z, hx, hz, r.trans' h₁ $ r.trans' (h $ by rwa ←hy' at hy) h₂⟩⟩⟩ /-- A special case of the equivalence closure of an equivalence relation r equalling r. -/ lemma map_of_surjective_eq_map (h : ker f ≤ r) (hf : surjective f) : map r f = map_of_surjective r f h hf := by rw ←eqv_gen_of_setoid (map_of_surjective r f h hf); refl /-- Given a function `f : α → β`, an equivalence relation `r` on `β` induces an equivalence relation on `α` defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `r`'. -/ def comap (f : α → β) (r : setoid β) : setoid α := ⟨λ x y, r.rel (f x) (f y), ⟨λ _, r.refl' _, λ _ _ h, r.symm' h, λ _ _ _ h1, r.trans' h1⟩⟩ /-- Given a map `f : N → M` and an equivalence relation `r` on `β`, the equivalence relation induced on `α` by `f` equals the kernel of `r`'s quotient map composed with `f`. -/ lemma comap_eq {f : α → β} {r : setoid β} : comap f r = ker (@quotient.mk _ r ∘ f) := ext $ λ x y, show _ ↔ ⟦_⟧ = ⟦_⟧, by rw quotient.eq; refl /-- The second isomorphism theorem for sets. -/ noncomputable def comap_quotient_equiv (f : α → β) (r : setoid β) : quotient (comap f r) ≃ set.range (@quotient.mk _ r ∘ f) := (quotient.congr_right $ ext_iff.1 comap_eq).trans $ quotient_ker_equiv_range $ quotient.mk ∘ f variables (r f) /-- The third isomorphism theorem for sets. -/ def quotient_quotient_equiv_quotient (s : setoid α) (h : r ≤ s) : quotient (ker (quot.map_right h)) ≃ quotient s := { to_fun := λ x, quotient.lift_on' x (λ w, quotient.lift_on' w (@quotient.mk _ s) $ λ x y H, quotient.sound $ h H) $ λ x y, quotient.induction_on₂' x y $ λ w z H, show @quot.mk _ _ _ = @quot.mk _ _ _, from H, inv_fun := λ x, quotient.lift_on' x (λ w, @quotient.mk _ (ker $ quot.map_right h) $ @quotient.mk _ r w) $ λ x y H, quotient.sound' $ show @quot.mk _ _ _ = @quot.mk _ _ _, from quotient.sound H, left_inv := λ x, quotient.induction_on' x $ λ y, quotient.induction_on' y $ λ w, by show ⟦_⟧ = _; refl, right_inv := λ x, quotient.induction_on' x $ λ y, by show ⟦_⟧ = _; refl } variables {r f} section open quotient /-- Given an equivalence relation r on α, the order-preserving bijection between the set of equivalence relations containing r and the equivalence relations on the quotient of α by r. -/ def correspondence (r : setoid α) : ((≤) : {s // r ≤ s} → {s // r ≤ s} → Prop) ≃o ((≤) : setoid (quotient r) → setoid (quotient r) → Prop) := { to_fun := λ s, map_of_surjective s.1 quotient.mk ((ker_mk_eq r).symm ▸ s.2) exists_rep, inv_fun := λ s, ⟨comap quotient.mk s, λ x y h, show s.rel ⟦x⟧ ⟦y⟧, by rw eq_rel.2 h⟩, left_inv := λ s, subtype.ext.2 $ ext' $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in s.1.trans' (s.1.symm' $ s.2 $ eq_rel.1 hx) $ s.1.trans' H $ s.2 $ eq_rel.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ s, let Hm : ker quotient.mk ≤ comap quotient.mk s := λ x y h, show s.rel ⟦x⟧ ⟦y⟧, by rw (@eq_rel _ r x y).2 ((ker_mk_eq r) ▸ h) in ext' $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, quotient.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, ord := λ s t, ⟨λ h x y hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩, λ h x y hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨x, y, rfl, rfl, hs⟩ in t.1.trans' (t.1.symm' $ t.2 $ eq_rel.1 hx) $ t.1.trans' ht $ t.2 $ eq_rel.1 hy⟩ } end /-! ### Partitions -/ /-- If x ∈ α is in 2 elements of a set of sets partitioning α, those 2 sets are equal. -/ lemma eq_of_mem_eqv_class {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {x b b'} (hc : b ∈ c) (hb : x ∈ b) (hc' : b' ∈ c) (hb' : x ∈ b') : b = b' := (H x).unique2 hc hb hc' hb' /-- Makes an equivalence relation from a set of sets partitioning α. -/ def mk_classes (c : set (set α)) (H : ∀ a, ∃! b ∈ c, a ∈ b) : setoid α := ⟨λ x y, ∀ s ∈ c, x ∈ s → y ∈ s, ⟨λ _ _ _ hx, hx, λ x y h s hs hy, (H x).elim2 $ λ t ht hx _, have s = t, from eq_of_mem_eqv_class H hs hy ht (h t ht hx), this.symm ▸ hx, λ x y z h1 h2 s hs hx, (H y).elim2 $ λ t ht hy _, (H z).elim2 $ λ t' ht' hz _, have hst : s = t, from eq_of_mem_eqv_class H hs (h1 _ hs hx) ht hy, have htt' : t = t', from eq_of_mem_eqv_class H ht (h2 _ ht hy) ht' hz, (hst.trans htt').symm ▸ hz⟩⟩ /-- Makes the equivalence classes of an equivalence relation. -/ def classes (r : setoid α) : set (set α) := {s | ∃ y, s = {x | r.rel x y}} lemma mem_classes (r : setoid α) (y) : {x | r.rel x y} ∈ r.classes := ⟨y, rfl⟩ /-- Two equivalence relations are equal iff all their equivalence classes are equal. -/ lemma eq_iff_classes_eq {r₁ r₂ : setoid α} : r₁ = r₂ ↔ ∀ x, {y | r₁.rel x y} = {y | r₂.rel x y} := ⟨λ h x, h ▸ rfl, λ h, ext' $ λ x, set.ext_iff.1 $ h x⟩ lemma rel_iff_exists_classes (r : setoid α) {x y} : r.rel x y ↔ ∃ c ∈ r.classes, x ∈ c ∧ y ∈ c := ⟨λ h, ⟨_, r.mem_classes y, h, r.refl' y⟩, λ ⟨c, ⟨z, hz⟩, hx, hy⟩, by { subst c, exact r.trans' hx (r.symm' hy) }⟩ /-- Two equivalence relations are equal iff their equivalence classes are equal. -/ lemma classes_inj {r₁ r₂ : setoid α} : r₁ = r₂ ↔ r₁.classes = r₂.classes := ⟨λ h, h ▸ rfl, λ h, ext' $ λ a b, by simp only [rel_iff_exists_classes, exists_prop, h] ⟩ /-- The empty set is not an equivalence class. -/ lemma empty_not_mem_classes {r : setoid α} : ∅ ∉ r.classes := λ ⟨y, hy⟩, set.not_mem_empty y $ hy.symm ▸ r.refl' y /-- Equivalence classes partition the type. -/ lemma classes_eqv_classes {r : setoid α} (a) : ∃! b ∈ r.classes, a ∈ b := exists_unique.intro2 {x | r.rel x a} (r.mem_classes a) (r.refl' _) $ begin rintros _ ⟨y, rfl⟩ ha, ext x, exact ⟨λ hx, r.trans' hx (r.symm' ha), λ hx, r.trans' hx ha⟩ end /-- If x ∈ α is in 2 equivalence classes, the equivalence classes are equal. -/ lemma eq_of_mem_classes {r : setoid α} {x b} (hc : b ∈ r.classes) (hb : x ∈ b) {b'} (hc' : b' ∈ r.classes) (hb' : x ∈ b') : b = b' := eq_of_mem_eqv_class classes_eqv_classes hc hb hc' hb' /-- The elements of a set of sets partitioning α are the equivalence classes of the equivalence relation defined by the set of sets. -/ lemma eq_eqv_class_of_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {s y} (hs : s ∈ c) (hy : y ∈ s) : s = {x | (mk_classes c H).rel x y} := set.ext $ λ x, ⟨λ hs', symm' (mk_classes c H) $ λ b' hb' h', eq_of_mem_eqv_class H hs hy hb' h' ▸ hs', λ hx, (H x).elim2 $ λ b' hc' hb' h', (eq_of_mem_eqv_class H hs hy hc' $ hx b' hc' hb').symm ▸ hb'⟩ /-- The equivalence classes of the equivalence relation defined by a set of sets partitioning α are elements of the set of sets. -/ lemma eqv_class_mem {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) {y} : {x | (mk_classes c H).rel x y} ∈ c := (H y).elim2 $ λ b hc hy hb, eq_eqv_class_of_mem H hc hy ▸ hc /-- Distinct elements of a set of sets partitioning α are disjoint. -/ lemma eqv_classes_disjoint {c : set (set α)} (H : ∀ a, ∃! b ∈ c, a ∈ b) : set.pairwise_disjoint c := λ b₁ h₁ b₂ h₂ h, set.disjoint_left.2 $ λ x hx1 hx2, (H x).elim2 $ λ b hc hx hb, h $ eq_of_mem_eqv_class H h₁ hx1 h₂ hx2 /-- A set of disjoint sets covering α partition α (classical). -/ lemma eqv_classes_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : set.pairwise_disjoint c) (a) : ∃! b ∈ c, a ∈ b := let ⟨b, hc, ha⟩ := set.mem_sUnion.1 $ show a ∈ _, by rw hu; exact set.mem_univ a in exists_unique.intro2 b hc ha $ λ b' hc' ha', H.elim hc' hc a ha' ha /-- Makes an equivalence relation from a set of disjoints sets covering α. -/ def setoid_of_disjoint_union {c : set (set α)} (hu : set.sUnion c = @set.univ α) (H : set.pairwise_disjoint c) : setoid α := setoid.mk_classes c $ eqv_classes_of_disjoint_union hu H /-- The equivalence relation made from the equivalence classes of an equivalence relation r equals r. -/ theorem mk_classes_classes (r : setoid α) : mk_classes r.classes classes_eqv_classes = r := ext' $ λ x y, ⟨λ h, r.symm' (h {z | r.rel z x} (r.mem_classes x) $ r.refl' x), λ h b hb hx, eq_of_mem_classes (r.mem_classes x) (r.refl' x) hb hx ▸ r.symm' h⟩ section partition /-- A collection `c : set (set α)` of sets is a partition of `α` into pairwise disjoint sets if `∅ ∉ c` and each element `a : α` belongs to a unique set `b ∈ c`. -/ def is_partition (c : set (set α)) := ∅ ∉ c ∧ ∀ a, ∃! b ∈ c, a ∈ b /-- A partition of `α` does not contain the empty set. -/ lemma nonempty_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (h : s ∈ c) : s.nonempty := set.ne_empty_iff_nonempty.1 $ λ hs0, hc.1 $ hs0 ▸ h /-- All elements of a partition of α are the equivalence class of some y ∈ α. -/ lemma exists_of_mem_partition {c : set (set α)} (hc : is_partition c) {s} (hs : s ∈ c) : ∃ y, s = {x | (mk_classes c hc.2).rel x y} := let ⟨y, hy⟩ := nonempty_of_mem_partition hc hs in ⟨y, eq_eqv_class_of_mem hc.2 hs hy⟩ /-- The equivalence classes of the equivalence relation defined by a partition of α equal the original partition. -/ theorem classes_mk_classes (c : set (set α)) (hc : is_partition c) : (mk_classes c hc.2).classes = c := set.ext $ λ s, ⟨λ ⟨y, hs⟩, (hc.2 y).elim2 $ λ b hm hb hy, by rwa (show s = b, from hs.symm ▸ set.ext (λ x, ⟨λ hx, symm' (mk_classes c hc.2) hx b hm hb, λ hx b' hc' hx', eq_of_mem_eqv_class hc.2 hm hx hc' hx' ▸ hb⟩)), exists_of_mem_partition hc⟩ /-- Defining `≤` on partitions as the `≤` defined on their induced equivalence relations. -/ instance partition.le : has_le (subtype (@is_partition α)) := ⟨λ x y, mk_classes x.1 x.2.2 ≤ mk_classes y.1 y.2.2⟩ /-- Defining a partial order on partitions as the partial order on their induced equivalence relations. -/ instance partition.partial_order : partial_order (subtype (@is_partition α)) := { le := (≤), lt := λ x y, x ≤ y ∧ ¬y ≤ x, le_refl := λ _, @le_refl (setoid α) _ _, le_trans := λ _ _ _, @le_trans (setoid α) _ _ _ _, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ x y hx hy, let h := @le_antisymm (setoid α) _ _ _ hx hy in by rw [subtype.ext, ←classes_mk_classes x.1 x.2, ←classes_mk_classes y.1 y.2, h] } variables (α) /-- The order-preserving bijection between equivalence relations and partitions of sets. -/ def partition.order_iso : ((≤) : setoid α → setoid α → Prop) ≃o (@setoid.partition.partial_order α).le := { to_fun := λ r, ⟨r.classes, empty_not_mem_classes, classes_eqv_classes⟩, inv_fun := λ x, mk_classes x.1 x.2.2, left_inv := mk_classes_classes, right_inv := λ x, by rw [subtype.ext, ←classes_mk_classes x.1 x.2], ord := λ x y, by conv {to_lhs, rw [←mk_classes_classes x, ←mk_classes_classes y]}; refl } variables {α} /-- A complete lattice instance for partitions; there is more infrastructure for the equivalent complete lattice on equivalence relations. -/ instance partition.complete_lattice : complete_lattice (subtype (@is_partition α)) := galois_insertion.lift_complete_lattice $ @order_iso.to_galois_insertion _ (subtype (@is_partition α)) _ (partial_order.to_preorder _) $ partition.order_iso α end partition end setoid
35a7887b9fa8c81346f61a24d4e6b8e308e488ca
80d0f8071ea62262937ab36f5887a61735adea09
/src/certigrad/aevb/graph.lean
5b3f9630065e4ce1a2f9797d24cfe1317e9c8bf1
[ "Apache-2.0" ]
permissive
wudcscheme/certigrad
94805fa6a61f993c69a824429a103c9613a65a48
c9a06e93f1ec58196d6d3b8563b29868d916727f
refs/heads/master
1,679,386,475,077
1,551,651,022,000
1,551,651,022,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,857
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam The actual graph produced by the naive variational auto-encoder code in aevb/prog.lean. Note: we include this file as an optimization, to avoid repeatedly simplifying the program into the graph. -/ import ..program ..prove_model_ok .util .prog namespace certigrad namespace aevb section nodes open det rand.op label tactic certigrad.tactic #print "Defining graph_naive..." def graph_naive : Π (a : arch) (x_data : T [a^.n_in, a^.n_x]), graph | a x_data := graph.mk [⟨(ID.nat 0, [a^.ne, a^.bs]), [(ID.str W_encode₁, [a^.ne, a^.n_in]), (ID.str x, [a^.n_in, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.nat 1, [a^.ne, a^.bs]), [(ID.nat 0, [a^.ne, a^.bs])], operator.det $ ops.softplus _⟩, ⟨(ID.nat 2, [a^.ne, a^.bs]), [(ID.str W_encode₂, [a^.ne, a^.ne]), (ID.nat 1, [a^.ne, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.str h_encode, [a^.ne, a^.bs]), [(ID.nat 2, [a^.ne, a^.bs])], operator.det $ ops.softplus _⟩, ⟨(ID.str μ, [a^.nz, a^.bs]), [(ID.str W_encode_μ, [a^.nz, a^.ne]), (ID.str h_encode, [a^.ne, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.nat 5, [a^.nz, a^.bs]), [(ID.str W_encode_logσ₂, [a^.nz, a^.ne]), (ID.str h_encode, [a^.ne, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.nat 6, [a^.nz, a^.bs]), [(ID.nat 5, [a^.nz, a^.bs])], operator.det $ ops.exp _⟩, ⟨(ID.str σ, [a^.nz, a^.bs]), [(ID.nat 6, [a^.nz, a^.bs])], operator.det $ ops.sqrt _⟩, ⟨(ID.str z, [a^.nz, a^.bs]), [(ID.str μ, [a^.nz, a^.bs]), (ID.str σ, [a^.nz, a^.bs])], operator.rand $ mvn _⟩, ⟨(ID.str encoding_loss, []), [(ID.str μ, [a^.nz, a^.bs]), (ID.str σ, [a^.nz, a^.bs]), (ID.str z, [a^.nz, a^.bs])], operator.det $ op.mvn_empirical_kl _⟩, ⟨(ID.nat 10, [a^.nd, a^.bs]), [(ID.str W_decode₁, [a^.nd, a^.nz]), (ID.str z, [a^.nz, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.nat 11, [a^.nd, a^.bs]), [(ID.nat 10, [a^.nd, a^.bs])], operator.det $ ops.softplus _⟩, ⟨(ID.nat 12, [a^.nd, a^.bs]), [(ID.str W_decode₂, [a^.nd, a^.nd]), (ID.nat 11, [a^.nd, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.str h_decode, [a^.nd, a^.bs]), [(ID.nat 12, [a^.nd, a^.bs])], operator.det $ ops.softplus _⟩, ⟨(ID.nat 14, [a^.n_in, a^.bs]), [(ID.str W_decode_p, [a^.n_in, a^.nd]), (ID.str h_decode, [a^.nd, a^.bs])], operator.det $ ops.gemm _ _ _⟩, ⟨(ID.str p, [a^.n_in, a^.bs]), [(ID.nat 14, [a^.n_in, a^.bs])], operator.det $ ops.sigmoid _⟩, ⟨(ID.str decoding_loss, []), [(ID.str p, [a^.n_in, a^.bs]), (ID.str x, [a^.n_in, a^.bs])], operator.det $ ops.bernoulli_neglogpdf _⟩] [ID.str encoding_loss, ID.str decoding_loss] [(ID.str W_encode₁, [a^.ne, a^.n_in]), (ID.str W_encode₂, [a^.ne, a^.ne]), (ID.str W_encode_μ, [a^.nz, a^.ne]), (ID.str W_encode_logσ₂, [a^.nz, a^.ne]), (ID.str W_decode₁, [a^.nd, a^.nz]), (ID.str W_decode₂, [a^.nd, a^.nd]), (ID.str W_decode_p, [a^.n_in, a^.nd])] [(ID.str x, [a^.n_in, a^.bs]), (ID.str W_encode₁, [a^.ne, a^.n_in]), (ID.str W_encode₂, [a^.ne, a^.ne]), (ID.str W_encode_μ, [a^.nz, a^.ne]), (ID.str W_encode_logσ₂, [a^.nz, a^.ne]), (ID.str W_decode₁, [a^.nd, a^.nz]), (ID.str W_decode₂, [a^.nd, a^.nd]), (ID.str W_decode_p, [a^.n_in, a^.nd])] attribute [cgsimp] graph_naive open tactic certigrad.tactic #print "proving naive_aevb_as_graph..." @[cgsimp] lemma naive_aevb_as_graph (a : arch) (x_data : T [a^.n_in, a^.n_x]) : naive_aevb a x_data = graph_naive a x_data := by { dunfold naive_aevb, cgsimp, dcgsimp, cgsimp, reflexivity } end nodes end aevb end certigrad
04458fba6cfc433983da88cef7ef700733334b33
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/continuous_function/basic.lean
fffbb5263bd4c48f3acb4f94a6c839460f5418f1
[ "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,647
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import data.set.Union_lift import topology.homeomorph /-! # Continuous bundled maps > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define the type `continuous_map` of continuous bundled maps. We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. -/ open function /-- The type of continuous maps from `α` to `β`. When possible, instead of parametrizing results over `(f : C(α, β))`, you should parametrize over `{F : Type*} [continuous_map_class F α β] (f : F)`. When you extend this structure, make sure to extend `continuous_map_class`. -/ @[protect_proj] structure continuous_map (α β : Type*) [topological_space α] [topological_space β] := (to_fun : α → β) (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') notation `C(` α `, ` β `)` := continuous_map α β section set_option old_structure_cmd true /-- `continuous_map_class F α β` states that `F` is a type of continuous maps. You should extend this class when you extend `continuous_map`. -/ class continuous_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α] [topological_space β] extends fun_like F α (λ _, β) := (map_continuous (f : F) : continuous f) end export continuous_map_class (map_continuous) attribute [continuity] map_continuous section continuous_map_class variables {F α β : Type*} [topological_space α] [topological_space β] [continuous_map_class F α β] include β lemma map_continuous_at (f : F) (a : α) : continuous_at f a := (map_continuous f).continuous_at lemma map_continuous_within_at (f : F) (s : set α) (a : α) : continuous_within_at f s a := (map_continuous f).continuous_within_at instance : has_coe_t F C(α, β) := ⟨λ f, { to_fun := f, continuous_to_fun := map_continuous f }⟩ end continuous_map_class /-! ### Continuous maps-/ namespace continuous_map variables {α β γ δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] instance : continuous_map_class C(α, β) α β := { coe := continuous_map.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_continuous := continuous_map.continuous_to_fun } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (C(α, β)) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : C(α, β)} : f.to_fun = (f : α → β) := rfl -- this must come after the coe_to_fun definition initialize_simps_projections continuous_map (to_fun → apply) @[protected, simp, norm_cast] lemma coe_coe {F : Type*} [continuous_map_class F α β] (f : F) : ⇑(f : C(α, β)) = f := rfl @[ext] lemma ext {f g : C(α, β)} (h : ∀ a, f a = g a) : f = g := fun_like.ext _ _ h /-- Copy of a `continuous_map` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : C(α, β)) (f' : α → β) (h : f' = f) : C(α, β) := { to_fun := f', continuous_to_fun := h.symm ▸ f.continuous_to_fun } @[simp] lemma coe_copy (f : C(α, β)) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : C(α, β)) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h variables {α β} {f g : C(α, β)} /-- Deprecated. Use `map_continuous` instead. -/ protected lemma continuous (f : C(α, β)) : continuous f := f.continuous_to_fun @[continuity] lemma continuous_set_coe (s : set C(α, β)) (f : s) : continuous f := f.1.continuous /-- Deprecated. Use `map_continuous_at` instead. -/ protected lemma continuous_at (f : C(α, β)) (x : α) : continuous_at f x := f.continuous.continuous_at /-- Deprecated. Use `fun_like.congr_fun` instead. -/ protected lemma congr_fun {f g : C(α, β)} (H : f = g) (x : α) : f x = g x := H ▸ rfl /-- Deprecated. Use `fun_like.congr_arg` instead. -/ protected lemma congr_arg (f : C(α, β)) {x y : α} (h : x = y) : f x = f y := h ▸ rfl lemma coe_injective : @function.injective (C(α, β)) (α → β) coe_fn := λ f g h, by cases f; cases g; congr' @[simp] lemma coe_mk (f : α → β) (h : continuous f) : ⇑(⟨f, h⟩ : C(α, β)) = f := rfl lemma map_specializes (f : C(α, β)) {x y : α} (h : x ⤳ y) : f x ⤳ f y := h.map f.2 section variables (α β) /-- The continuous functions from `α` to `β` are the same as the plain functions when `α` is discrete. -/ @[simps] def equiv_fn_of_discrete [discrete_topology α] : C(α, β) ≃ (α → β) := ⟨(λ f, f), (λ f, ⟨f, continuous_of_discrete_topology⟩), λ f, by { ext, refl, }, λ f, by { ext, refl, }⟩ end variables (α) /-- The identity as a continuous map. -/ protected def id : C(α, α) := ⟨id⟩ @[simp] lemma coe_id : ⇑(continuous_map.id α) = id := rfl /-- The constant map as a continuous map. -/ def const (b : β) : C(α, β) := ⟨const α b⟩ @[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl instance [inhabited β] : inhabited C(α, β) := ⟨const α default⟩ variables {α} @[simp] lemma id_apply (a : α) : continuous_map.id α a = a := rfl @[simp] lemma const_apply (b : β) (a : α) : const α b a = b := rfl /-- The composition of continuous maps, as a continuous map. -/ def comp (f : C(β, γ)) (g : C(α, β)) : C(α, γ) := ⟨f ∘ g⟩ @[simp] lemma coe_comp (f : C(β, γ)) (g : C(α, β)) : ⇑(comp f g) = f ∘ g := rfl @[simp] lemma comp_apply (f : C(β, γ)) (g : C(α, β)) (a : α) : comp f g a = f (g a) := rfl @[simp] lemma comp_assoc (f : C(γ, δ)) (g : C(β, γ)) (h : C(α, β)) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma id_comp (f : C(α, β)) : (continuous_map.id _).comp f = f := ext $ λ _, rfl @[simp] lemma comp_id (f : C(α, β)) : f.comp (continuous_map.id _) = f := ext $ λ _, rfl @[simp] lemma const_comp (c : γ) (f : C(α, β)) : (const β c).comp f = const α c := ext $ λ _, rfl @[simp] lemma comp_const (f : C(β, γ)) (b : β) : f.comp (const α b) = const α (f b) := ext $ λ _, rfl lemma cancel_right {f₁ f₂ : C(β, γ)} {g : C(α, β)} (hg : surjective g) : f₁.comp g = f₂.comp g ↔ f₁ = f₂ := ⟨λ h, ext $ hg.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {f : C(β, γ)} {g₁ g₂ : C(α, β)} (hf : injective f) : f.comp g₁ = f.comp g₂ ↔ g₁ = g₂ := ⟨λ h, ext $ λ a, hf $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ instance [nonempty α] [nontrivial β] : nontrivial C(α, β) := ⟨let ⟨b₁, b₂, hb⟩ := exists_pair_ne β in ⟨const _ b₁, const _ b₂, λ h, hb $ fun_like.congr_fun h $ classical.arbitrary α⟩⟩ section prod variables {α₁ α₂ β₁ β₂ : Type*} [topological_space α₁] [topological_space α₂] [topological_space β₁] [topological_space β₂] /-- Given two continuous maps `f` and `g`, this is the continuous map `x ↦ (f x, g x)`. -/ def prod_mk (f : C(α, β₁)) (g : C(α, β₂)) : C(α, β₁ × β₂) := { to_fun := (λ x, (f x, g x)), continuous_to_fun := continuous.prod_mk f.continuous g.continuous } /-- Given two continuous maps `f` and `g`, this is the continuous map `(x, y) ↦ (f x, g y)`. -/ @[simps] def prod_map (f : C(α₁, α₂)) (g : C(β₁, β₂)) : C(α₁ × β₁, α₂ × β₂) := { to_fun := prod.map f g, continuous_to_fun := continuous.prod_map f.continuous g.continuous } @[simp] lemma prod_eval (f : C(α, β₁)) (g : C(α, β₂)) (a : α) : (prod_mk f g) a = (f a, g a) := rfl end prod section pi variables {I A : Type*} {X : I → Type*} [topological_space A] [∀ i, topological_space (X i)] /-- Abbreviation for product of continuous maps, which is continuous -/ def pi (f : Π i, C(A, X i)) : C(A, Π i, X i) := { to_fun := λ (a : A) (i : I), f i a, } @[simp] lemma pi_eval (f : Π i, C(A, X i)) (a : A) : (pi f) a = λ i : I, (f i) a := rfl end pi section restrict variables (s : set α) /-- The restriction of a continuous function `α → β` to a subset `s` of `α`. -/ def restrict (f : C(α, β)) : C(s, β) := ⟨f ∘ coe⟩ @[simp] lemma coe_restrict (f : C(α, β)) : ⇑(f.restrict s) = f ∘ coe := rfl @[simp] lemma restrict_apply (f : C(α, β)) (s : set α) (x : s) : f.restrict s x = f x := rfl @[simp] lemma restrict_apply_mk (f : C(α, β)) (s : set α) (x : α) (hx : x ∈ s) : f.restrict s ⟨x, hx⟩ = f x := rfl /-- The restriction of a continuous map to the preimage of a set. -/ @[simps] def restrict_preimage (f : C(α, β)) (s : set β) : C(f ⁻¹' s, s) := ⟨s.restrict_preimage f, continuous_iff_continuous_at.mpr $ λ x, f.2.continuous_at.restrict_preimage⟩ end restrict section gluing variables {ι : Type*} (S : ι → set α) (φ : Π i : ι, C(S i, β)) (hφ : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), φ i ⟨x, hxi⟩ = φ j ⟨x, hxj⟩) (hS : ∀ x : α, ∃ i, S i ∈ nhds x) include hφ hS /-- A family `φ i` of continuous maps `C(S i, β)`, where the domains `S i` contain a neighbourhood of each point in `α` and the functions `φ i` agree pairwise on intersections, can be glued to construct a continuous map in `C(α, β)`. -/ noncomputable def lift_cover : C(α, β) := begin have H : (⋃ i, S i) = set.univ, { rw set.eq_univ_iff_forall, intros x, rw set.mem_Union, obtain ⟨i, hi⟩ := hS x, exact ⟨i, mem_of_mem_nhds hi⟩ }, refine ⟨set.lift_cover S (λ i, φ i) hφ H, continuous_of_cover_nhds hS $ λ i, _⟩, rw [continuous_on_iff_continuous_restrict], simpa only [set.restrict, set.lift_cover_coe] using (φ i).continuous end variables {S φ hφ hS} @[simp] lemma lift_cover_coe {i : ι} (x : S i) : lift_cover S φ hφ hS x = φ i x := set.lift_cover_coe _ @[simp] lemma lift_cover_restrict {i : ι} : (lift_cover S φ hφ hS).restrict (S i) = φ i := ext $ lift_cover_coe omit hφ hS variables (A : set (set α)) (F : Π (s : set α) (hi : s ∈ A), C(s, β)) (hF : ∀ s (hs : s ∈ A) t (ht : t ∈ A) (x : α) (hxi : x ∈ s) (hxj : x ∈ t), F s hs ⟨x, hxi⟩ = F t ht ⟨x, hxj⟩) (hA : ∀ x : α, ∃ i ∈ A, i ∈ nhds x) include hF hA /-- A family `F s` of continuous maps `C(s, β)`, where (1) the domains `s` are taken from a set `A` of sets in `α` which contain a neighbourhood of each point in `α` and (2) the functions `F s` agree pairwise on intersections, can be glued to construct a continuous map in `C(α, β)`. -/ noncomputable def lift_cover' : C(α, β) := begin let S : A → set α := coe, let F : Π i : A, C(i, β) := λ i, F i i.prop, refine lift_cover S F (λ i j, hF i i.prop j j.prop) _, intros x, obtain ⟨s, hs, hsx⟩ := hA x, exact ⟨⟨s, hs⟩, hsx⟩ end variables {A F hF hA} @[simp] lemma lift_cover_coe' {s : set α} {hs : s ∈ A} (x : s) : lift_cover' A F hF hA x = F s hs x := let x' : (coe : A → set α) ⟨s, hs⟩ := x in lift_cover_coe x' @[simp] lemma lift_cover_restrict' {s : set α} {hs : s ∈ A} : (lift_cover' A F hF hA).restrict s = F s hs := ext $ lift_cover_coe' end gluing end continuous_map namespace homeomorph variables {α β γ : Type*} [topological_space α] [topological_space β] [topological_space γ] variables (f : α ≃ₜ β) (g : β ≃ₜ γ) /-- The forward direction of a homeomorphism, as a bundled continuous map. -/ @[simps] def to_continuous_map (e : α ≃ₜ β) : C(α, β) := ⟨e⟩ /--`homeomorph.to_continuous_map` as a coercion. -/ instance : has_coe (α ≃ₜ β) C(α, β) := ⟨homeomorph.to_continuous_map⟩ lemma to_continuous_map_as_coe : f.to_continuous_map = f := rfl @[simp] lemma coe_refl : (homeomorph.refl α : C(α, α)) = continuous_map.id α := rfl @[simp] lemma coe_trans : (f.trans g : C(α, γ)) = (g : C(β, γ)).comp f := rfl /-- Left inverse to a continuous map from a homeomorphism, mirroring `equiv.symm_comp_self`. -/ @[simp] lemma symm_comp_to_continuous_map : (f.symm : C(β, α)).comp (f : C(α, β)) = continuous_map.id α := by rw [← coe_trans, self_trans_symm, coe_refl] /-- Right inverse to a continuous map from a homeomorphism, mirroring `equiv.self_comp_symm`. -/ @[simp] lemma to_continuous_map_comp_symm : (f : C(α, β)).comp (f.symm : C(β, α)) = continuous_map.id β := by rw [← coe_trans, symm_trans_self, coe_refl] end homeomorph
434652232ef2ede6283f7477b7e2a54659140a98
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/group_theory/group_action/opposite.lean
c7c6e102dc174b38c8caa2d685763957729b0359
[ "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
5,397
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.group.opposite import group_theory.group_action.defs /-! # Scalar actions on and by `Mᵐᵒᵖ` This file defines the actions on the opposite type `has_scalar R Mᵐᵒᵖ`, and actions by the opposite type, `has_scalar Rᵐᵒᵖ M`. Note that `mul_opposite.has_scalar` is provided in an earlier file as it is needed to provide the `add_monoid.nsmul` and `add_comm_group.gsmul` fields. -/ variables (α : Type*) /-! ### Actions _on_ the opposite type Actions on the opposite type just act on the underlying type. -/ namespace mul_opposite @[to_additive] instance (R : Type*) [monoid R] [mul_action R α] : mul_action R αᵐᵒᵖ := { one_smul := λ x, unop_injective $ one_smul R (unop x), mul_smul := λ r₁ r₂ x, unop_injective $ mul_smul r₁ r₂ (unop x), .. mul_opposite.has_scalar α R } instance (R : Type*) [monoid R] [add_monoid α] [distrib_mul_action R α] : distrib_mul_action R αᵐᵒᵖ := { smul_add := λ r x₁ x₂, unop_injective $ smul_add r (unop x₁) (unop x₂), smul_zero := λ r, unop_injective $ smul_zero r, .. mul_opposite.mul_action α R } instance (R : Type*) [monoid R] [monoid α] [mul_distrib_mul_action R α] : mul_distrib_mul_action R αᵐᵒᵖ := { smul_mul := λ r x₁ x₂, unop_injective $ smul_mul' r (unop x₂) (unop x₁), smul_one := λ r, unop_injective $ smul_one r, .. mul_opposite.mul_action α R } instance {M N} [has_scalar M N] [has_scalar M α] [has_scalar N α] [is_scalar_tower M N α] : is_scalar_tower M N αᵐᵒᵖ := ⟨λ x y z, unop_injective $ smul_assoc _ _ _⟩ @[to_additive] instance {M N} [has_scalar M α] [has_scalar N α] [smul_comm_class M N α] : smul_comm_class M N αᵐᵒᵖ := ⟨λ x y z, unop_injective $ smul_comm _ _ _⟩ instance (R : Type*) [has_scalar R α] [has_scalar Rᵐᵒᵖ α] [is_central_scalar R α] : is_central_scalar R αᵐᵒᵖ := ⟨λ r m, unop_injective $ op_smul_eq_smul _ _⟩ lemma op_smul_eq_op_smul_op {R : Type*} [has_scalar R α] [has_scalar Rᵐᵒᵖ α] [is_central_scalar R α] (r : R) (a : α) : op (r • a) = op r • op a := (op_smul_eq_smul r (op a)).symm lemma unop_smul_eq_unop_smul_unop {R : Type*} [has_scalar R α] [has_scalar Rᵐᵒᵖ α] [is_central_scalar R α] (r : Rᵐᵒᵖ) (a : αᵐᵒᵖ) : unop (r • a) = unop r • unop a := (unop_smul_eq_smul r (unop a)).symm end mul_opposite /-! ### Actions _by_ the opposite type (right actions) In `has_mul.to_has_scalar` in another file, we define the left action `a₁ • a₂ = a₁ * a₂`. For the multiplicative opposite, we define `mul_opposite.op a₁ • a₂ = a₂ * a₁`, with the multiplication reversed. -/ open mul_opposite /-- Like `has_mul.to_has_scalar`, but multiplies on the right. See also `monoid.to_opposite_mul_action` and `monoid_with_zero.to_opposite_mul_action_with_zero`. -/ @[to_additive] instance has_mul.to_has_opposite_scalar [has_mul α] : has_scalar αᵐᵒᵖ α := { smul := λ c x, x * c.unop } @[simp, to_additive] lemma op_smul_eq_mul [has_mul α] {a a' : α} : op a • a' = a' * a := rfl /-- The right regular action of a group on itself is transitive. -/ @[to_additive] instance mul_action.opposite_regular.is_pretransitive {G : Type*} [group G] : mul_action.is_pretransitive Gᵐᵒᵖ G := ⟨λ x y, ⟨op (x⁻¹ * y), mul_inv_cancel_left _ _⟩⟩ @[to_additive] instance semigroup.opposite_smul_comm_class [semigroup α] : smul_comm_class αᵐᵒᵖ α α := { smul_comm := λ x y z, (mul_assoc _ _ _) } @[to_additive] instance semigroup.opposite_smul_comm_class' [semigroup α] : smul_comm_class α αᵐᵒᵖ α := smul_comm_class.symm _ _ _ instance comm_semigroup.is_central_scalar [comm_semigroup α] : is_central_scalar α α := ⟨λ r m, mul_comm _ _⟩ /-- Like `monoid.to_mul_action`, but multiplies on the right. -/ @[to_additive] instance monoid.to_opposite_mul_action [monoid α] : mul_action αᵐᵒᵖ α := { smul := (•), one_smul := mul_one, mul_smul := λ x y r, (mul_assoc _ _ _).symm } instance is_scalar_tower.opposite_mid {M N} [monoid N] [has_scalar M N] [smul_comm_class M N N] : is_scalar_tower M Nᵐᵒᵖ N := ⟨λ x y z, mul_smul_comm _ _ _⟩ instance smul_comm_class.opposite_mid {M N} [monoid N] [has_scalar M N] [is_scalar_tower M N N] : smul_comm_class M Nᵐᵒᵖ N := ⟨λ x y z, by { induction y using mul_opposite.rec, simp [smul_mul_assoc] }⟩ -- The above instance does not create an unwanted diamond, the two paths to -- `mul_action αᵐᵒᵖ αᵐᵒᵖ` are defeq. example [monoid α] : monoid.to_mul_action αᵐᵒᵖ = mul_opposite.mul_action α αᵐᵒᵖ := rfl /-- `monoid.to_opposite_mul_action` is faithful on cancellative monoids. -/ @[to_additive] instance left_cancel_monoid.to_has_faithful_opposite_scalar [left_cancel_monoid α] : has_faithful_scalar αᵐᵒᵖ α := ⟨λ x y h, unop_injective $ mul_left_cancel (h 1)⟩ /-- `monoid.to_opposite_mul_action` is faithful on nontrivial cancellative monoids with zero. -/ instance cancel_monoid_with_zero.to_has_faithful_opposite_scalar [cancel_monoid_with_zero α] [nontrivial α] : has_faithful_scalar αᵐᵒᵖ α := ⟨λ x y h, unop_injective $ mul_left_cancel₀ one_ne_zero (h 1)⟩
3fc510bc558aee1b93178a44b606de1c7437c015
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/group_theory/sylow.lean
4dc876f0c11a210eab993d6be884649287f3c755
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
11,859
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 group_theory.group_action import group_theory.quotient_group import group_theory.order_of_element import data.zmod.basic import data.fintype.card import data.list.rotate open equiv fintype finset mul_action function open equiv.perm is_subgroup list quotient_group open_locale big_operators universes u v w variables {G : Type u} {α : Type v} {β : Type w} [group G] local attribute [instance, priority 10] subtype.fintype set_fintype classical.prop_decidable namespace mul_action variables [mul_action G α] lemma mem_fixed_points_iff_card_orbit_eq_one {a : α} [fintype (orbit G a)] : a ∈ fixed_points G α ↔ card (orbit G a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, exact calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end lemma card_modeq_card_fixed_points [fintype α] [fintype G] [fintype (fixed_points G α)] (p : ℕ) {n : ℕ} [hp : fact p.prime] (h : card G = p ^ n) : card α ≡ card (fixed_points G α) [MOD p] := calc card α = card (Σ y : quotient (orbit_rel G α), {x // quotient.mk' x = y}) : card_congr (sigma_preimage_equiv (@quotient.mk' _ (orbit_rel G α))).symm ... = ∑ a : quotient (orbit_rel G α), card {x // quotient.mk' x = a} : card_sigma _ ... ≡ ∑ a : fixed_points G α, 1 [MOD p] : begin rw [← zmod.eq_iff_modeq_nat p, sum_nat_cast, sum_nat_cast], refine eq.symm (sum_bij_ne_zero (λ a _ _, quotient.mk' a.1) (λ _ _ _, mem_univ _) (λ a₁ a₂ _ _ _ _ h, subtype.eq ((mem_fixed_points' α).1 a₂.2 a₁.1 (quotient.exact' h))) (λ b, _) (λ a ha _, by rw [← mem_fixed_points_iff_card_orbit_eq_one.1 a.2]; simp only [quotient.eq']; congr)), { refine quotient.induction_on' b (λ b _ hb, _), have : card (orbit G b) ∣ p ^ n, { rw [← h, fintype.card_congr (orbit_equiv_quotient_stabilizer G b)]; exact card_quotient_dvd_card _ }, rcases (nat.dvd_prime_pow hp).1 this with ⟨k, _, hk⟩, have hb' :¬ p ^ 1 ∣ p ^ k, { rw [nat.pow_one, ← hk, ← nat.modeq.modeq_zero_iff, ← zmod.eq_iff_modeq_nat, nat.cast_zero, ← ne.def], exact eq.mpr (by simp only [quotient.eq']; congr) hb }, have : k = 0 := nat.le_zero_iff.1 (nat.le_of_lt_succ (lt_of_not_ge (mt (nat.pow_dvd_pow p) hb'))), refine ⟨⟨b, mem_fixed_points_iff_card_orbit_eq_one.2 $ by rw [hk, this, nat.pow_zero]⟩, mem_univ _, _, rfl⟩, rw [nat.cast_one], exact one_ne_zero } end ... = _ : by simp; refl end mul_action lemma quotient_group.card_preimage_mk [fintype G] (s : set G) [is_subgroup s] (t : set (quotient s)) : fintype.card (quotient_group.mk ⁻¹' t) = fintype.card s * fintype.card t := by rw [← fintype.card_prod, fintype.card_congr (preimage_mk_equiv_subgroup_times_set _ _)] namespace sylow /-- Given a vector `v` of length `n`, make a vector of length `n+1` whose product is `1`, by consing the the inverse of the product of `v`. -/ def mk_vector_prod_eq_one (n : ℕ) (v : vector G n) : vector G (n+1) := v.to_list.prod⁻¹ :: v lemma mk_vector_prod_eq_one_injective (n : ℕ) : injective (@mk_vector_prod_eq_one G _ n) := λ ⟨v, _⟩ ⟨w, _⟩ h, subtype.eq (show v = w, by injection h with h; injection h) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) : set (vector G n) := {v | v.to_list.prod = 1} lemma mem_vectors_prod_eq_one {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma mem_vectors_prod_eq_one_iff {n : ℕ} (v : vector G (n + 1)) : v ∈ vectors_prod_eq_one G (n + 1) ↔ v ∈ set.range (@mk_vector_prod_eq_one G _ n) := ⟨λ (h : v.to_list.prod = 1), ⟨v.tail, begin unfold mk_vector_prod_eq_one, conv {to_rhs, rw ← vector.cons_head_tail v}, suffices : (v.tail.to_list.prod)⁻¹ = v.head, { rw this }, rw [← mul_left_inj v.tail.to_list.prod, inv_mul_self, ← list.prod_cons, ← vector.to_list_cons, vector.cons_head_tail, h] end⟩, λ ⟨w, hw⟩, by rw [mem_vectors_prod_eq_one, ← hw, mk_vector_prod_eq_one, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩ /-- The rotation action of `zmod n` (viewed as multiplicative group) on `vectors_prod_eq_one G n`, where `G` is a multiplicative group. -/ def rotate_vectors_prod_eq_one (G : Type*) [group G] (n : ℕ) (m : multiplicative (zmod n)) (v : vectors_prod_eq_one G n) : vectors_prod_eq_one G n := ⟨⟨v.1.to_list.rotate m.val, by simp⟩, prod_rotate_eq_one_of_prod_eq_one v.2 _⟩ instance rotate_vectors_prod_eq_one.mul_action (n : ℕ) [fact (0 < n)] : mul_action (multiplicative (zmod n)) (vectors_prod_eq_one G n) := { smul := (rotate_vectors_prod_eq_one G n), one_smul := begin intro v, apply subtype.eq, apply vector.eq _ _, show rotate _ (0 : zmod n).val = _, rw zmod.val_zero, exact rotate_zero v.1.to_list end, mul_smul := λ a b ⟨⟨v, hv₁⟩, hv₂⟩, subtype.eq $ vector.eq _ _ $ show v.rotate ((a + b : zmod n).val) = list.rotate (list.rotate v (b.val)) (a.val), by rw [zmod.val_add, rotate_rotate, ← rotate_mod _ (b.val + a.val), add_comm, hv₁] } lemma one_mem_vectors_prod_eq_one (n : ℕ) : vector.repeat (1 : G) n ∈ vectors_prod_eq_one G n := by simp [vector.repeat, vectors_prod_eq_one] lemma one_mem_fixed_points_rotate (n : ℕ) [fact (0 < n)] : (⟨vector.repeat (1 : G) n, one_mem_vectors_prod_eq_one n⟩ : vectors_prod_eq_one G n) ∈ fixed_points (multiplicative (zmod n)) (vectors_prod_eq_one G n) := λ m, subtype.eq $ vector.eq _ _ $ rotate_eq_self_iff_eq_repeat.2 ⟨(1 : G), show list.repeat (1 : G) n = list.repeat 1 (list.repeat (1 : G) n).length, by simp⟩ _ /-- Cauchy's theorem -/ lemma exists_prime_order_of_dvd_card [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ card G) : ∃ x : G, order_of x = p := let n : ℕ+ := ⟨p - 1, nat.sub_pos_of_lt hp.one_lt⟩ in have hn : p = n + 1 := nat.succ_sub hp.pos, have hcard : card (vectors_prod_eq_one G (n + 1)) = card G ^ (n : ℕ), by rw [set.ext mem_vectors_prod_eq_one_iff, set.card_range_of_injective (mk_vector_prod_eq_one_injective _), card_vector], have hzmod : fintype.card (multiplicative (zmod p)) = p ^ 1, by { rw nat.pow_one p, exact zmod.card p }, have hmodeq : _ = _ := @mul_action.card_modeq_card_fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p) _ _ _ _ _ _ 1 hp hzmod, have hdvdcard : p ∣ fintype.card (vectors_prod_eq_one G (n + 1)) := calc p ∣ card G ^ 1 : by rwa nat.pow_one ... ∣ card G ^ (n : ℕ) : nat.pow_dvd_pow _ n.2 ... = card (vectors_prod_eq_one G (n + 1)) : hcard.symm, have hdvdcard₂ : p ∣ card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)), by { rw nat.dvd_iff_mod_eq_zero at hdvdcard ⊢, rwa [← hn, hmodeq] at hdvdcard }, have hcard_pos : 0 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := fintype.card_pos_iff.2 ⟨⟨⟨vector.repeat 1 p, one_mem_vectors_prod_eq_one _⟩, one_mem_fixed_points_rotate _⟩⟩, have hlt : 1 < card (fixed_points (multiplicative (zmod p)) (vectors_prod_eq_one G p)) := calc (1 : ℕ) < p : hp.one_lt ... ≤ _ : nat.le_of_dvd hcard_pos hdvdcard₂, let ⟨⟨⟨⟨x, hx₁⟩, hx₂⟩, hx₃⟩, hx₄⟩ := fintype.exists_ne_of_one_lt_card hlt ⟨_, one_mem_fixed_points_rotate p⟩ in have hx : x ≠ list.repeat (1 : G) p, from λ h, by simpa [h, vector.repeat] using hx₄, have ∃ a, x = list.repeat a x.length := by exactI rotate_eq_self_iff_eq_repeat.1 (λ n, have list.rotate x (n : zmod p).val = x := subtype.mk.inj (subtype.mk.inj (hx₃ (n : zmod p))), by rwa [zmod.val_cast_nat, ← hx₁, rotate_mod] at this), let ⟨a, ha⟩ := this in ⟨a, have hx1 : x.prod = 1 := hx₂, have ha1: a ≠ 1, from λ h, hx (ha.symm ▸ h ▸ hx₁ ▸ rfl), have a ^ p = 1, by rwa [ha, list.prod_repeat, hx₁] at hx1, (hp.2 _ (order_of_dvd_of_pow_eq_one this)).resolve_left (λ h, ha1 (order_of_eq_one_iff.1 h))⟩ open is_subgroup is_submonoid is_group_hom mul_action lemma mem_fixed_points_mul_left_cosets_iff_mem_normalizer {H : set G} [is_subgroup H] [fintype H] {x : G} : (x : quotient H) ∈ fixed_points H (quotient H) ↔ x ∈ normalizer H := ⟨λ hx, have ha : ∀ {y : quotient H}, y ∈ orbit H (x : quotient H) → y = x, from λ _, ((mem_fixed_points' _).1 hx _), (inv_mem_iff _).1 (mem_normalizer_fintype (λ n hn, have (n⁻¹ * x)⁻¹ * x ∈ H := quotient_group.eq.1 (ha (mem_orbit _ ⟨n⁻¹, inv_mem hn⟩)), by simpa only [mul_inv_rev, inv_inv] using this)), λ (hx : ∀ (n : G), n ∈ H ↔ x * n * x⁻¹ ∈ H), (mem_fixed_points' _).2 $ λ y, quotient.induction_on' y $ λ y hy, quotient_group.eq.2 (let ⟨⟨b, hb₁⟩, hb₂⟩ := hy in have hb₂ : (b * x)⁻¹ * y ∈ H := quotient_group.eq.1 hb₂, (inv_mem_iff H).1 $ (hx _).2 $ (mul_mem_cancel_left H (inv_mem hb₁)).1 $ by rw hx at hb₂; simpa [mul_inv_rev, mul_assoc] using hb₂)⟩ def fixed_points_mul_left_cosets_equiv_quotient (H : set G) [is_subgroup H] [fintype H] : fixed_points H (quotient H) ≃ quotient (subtype.val ⁻¹' H : set (normalizer H)) := @subtype_quotient_equiv_quotient_subtype G (normalizer H) (id _) (id _) (fixed_points _ _) (λ a, mem_fixed_points_mul_left_cosets_iff_mem_normalizer.symm) (by intros; refl) local attribute [instance] set_fintype lemma exists_subgroup_card_pow_prime [fintype G] (p : ℕ) : ∀ {n : ℕ} [hp : fact p.prime] (hdvd : p ^ n ∣ card G), ∃ H : set G, is_subgroup H ∧ fintype.card H = p ^ n | 0 := λ _ _, ⟨trivial G, by apply_instance, by simp⟩ | (n+1) := λ hp hdvd, let ⟨H, ⟨hH1, hH2⟩⟩ := @exists_subgroup_card_pow_prime _ hp (dvd.trans (nat.pow_dvd_pow _ (nat.le_succ _)) hdvd) in let ⟨s, hs⟩ := exists_eq_mul_left_of_dvd hdvd in by exactI have hcard : card (quotient H) = s * p := (nat.mul_left_inj (show card H > 0, from fintype.card_pos_iff.2 ⟨⟨1, is_submonoid.one_mem⟩⟩)).1 (by rwa [← card_eq_card_quotient_mul_card_subgroup, hH2, hs, nat.pow_succ, mul_assoc, mul_comm p]), have hm : s * p % p = card (quotient (subtype.val ⁻¹' H : set (normalizer H))) % p := card_congr (fixed_points_mul_left_cosets_equiv_quotient H) ▸ hcard ▸ card_modeq_card_fixed_points p hH2, have hm' : p ∣ card (quotient (subtype.val ⁻¹' H : set (normalizer H))) := nat.dvd_of_mod_eq_zero (by rwa [nat.mod_eq_zero_of_dvd (dvd_mul_left _ _), eq_comm] at hm), let ⟨x, hx⟩ := @exists_prime_order_of_dvd_card _ (quotient_group.group _) _ _ hp hm' in have hxcard : ∀ {f : fintype (gpowers x)}, card (gpowers x) = p, from λ f, by rw [← hx, order_eq_card_gpowers]; congr, have is_subgroup (mk ⁻¹' gpowers x), from is_group_hom.preimage _ _, have fintype (mk ⁻¹' gpowers x), by apply_instance, have hequiv : H ≃ (subtype.val ⁻¹' H : set (normalizer H)) := ⟨λ a, ⟨⟨a.1, subset_normalizer _ a.2⟩, a.2⟩, λ a, ⟨a.1.1, a.2⟩, λ ⟨_, _⟩, rfl, λ ⟨⟨_, _⟩, _⟩, rfl⟩, ⟨subtype.val '' (mk ⁻¹' gpowers x), by apply_instance, by rw [set.card_image_of_injective (mk ⁻¹' gpowers x) subtype.val_injective, nat.pow_succ, ← hH2, fintype.card_congr hequiv, ← hx, order_eq_card_gpowers, ← fintype.card_prod]; exact @fintype.card_congr _ _ (id _) (id _) (preimage_mk_equiv_subgroup_times_set _ _)⟩ end sylow
50e92ce3862d59b7f89a84eb577534c78716b8a1
ee712cba63470502ae3b6e8fe7e5d109efaa0053
/src/polygonal_connectedness.lean
e5ec2a80439798ac987a53ae7a9046ee580efdaf
[ "Apache-2.0" ]
permissive
chrisilouseph/Xena-Project-2020
cf7837b039a113559a2118ccfa6134be43f8ce8a
5fb76b50ace083a80508f6234887c7d24e1c88c3
refs/heads/master
1,670,447,937,865
1,598,513,203,000
1,598,513,203,000
290,692,541
0
0
null
null
null
null
UTF-8
Lean
false
false
9,723
lean
/- Copyright (c) 2020 Chrisil Ouseph. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chrisil Ouseph -/ import analysis.complex.basic tactic /-! # Polygonally-Connected & Step-Connected Sets in Complex Numbers and Regions This file defines polygonal-connectedness and step-connectedness (polygonal-connectedness using only horizontal and vertical line segments) for pairs of points as well as subsets of ℂ along with regions (domains) in topological spaces. We prove basic related theorems, like step-connectedness implies polygonal-connectedness and all regions in ℂ are step-connected. ## Important definitions * `are_poly_connected` : polygonal-connectedness for pairs of complex numbers * `is_poly_connected` : polygonal-connectedness for subsets of complex numbers * `are_step_connected` : step-connectedness for pairs of complex numbers * `is_step_connected` : step-connectedness for subsets of complex numbers * `is_region` : regions (also called domains, i.e. open and connected sets) of a topological space ## Implementation notes All the above properties are implemented as `Prop`. The pairwise properties are implemented as inductive types, producing a `Prop`. ## References J. Bak, D. J. Newman : *Complex Analysis* : https://www.springer.com/gp/book/9781441972873 -/ open complex set variables z1 z2 z3: ℂ variable A : set ℂ variables l : list ℂ variable rp : {r : ℝ // 0 < r} /-- The closed line segment between two complex numbers -/ def cIcc := {z : ℂ | ∃ t ∈ set.Icc (0 : ℝ) 1, z = z1 + ↑t * (z2 - z1)} lemma cIcc_endpoints : z1 ∈ cIcc z1 z2 ∧ z2 ∈ cIcc z1 z2 := ⟨⟨0, left_mem_Icc.mpr zero_le_one, by norm_cast; ring⟩, ⟨1, right_mem_Icc.mpr zero_le_one, by norm_cast; ring⟩⟩ lemma cIcc_self : cIcc z1 z1 = {z1} := begin refine antisymm _ (singleton_subset_iff.mpr (cIcc_endpoints z1 z1).left), rintros z ⟨t, ht, rfl⟩, rw mem_singleton_iff, ring end lemma cIcc_symm : cIcc z1 z2 = cIcc z2 z1 := begin apply subset.antisymm; { rintros z ⟨t, ⟨ht0, ht1⟩, rfl⟩, refine ⟨1-t, ⟨_, _⟩, _⟩; try { linarith }, push_cast, ring } end /-- Two complex numbers are polygonally-connected in a set `A` iff the line segment joining them is in `A` or by transitivity. -/ inductive are_poly_connected (A : set ℂ) : ℂ → ℂ → Prop | line {z1 z2 : ℂ} : cIcc z1 z2 ⊆ A → are_poly_connected z1 z2 | poly_trans {z1 z2 z3 : ℂ} : are_poly_connected z1 z3 → are_poly_connected z3 z2 → are_poly_connected z1 z2 open are_poly_connected lemma are_poly_connected_refl {A z1} (h : z1 ∈ A) : are_poly_connected A z1 z1 := by apply line; rwa [cIcc_self, singleton_subset_iff] lemma are_poly_connected_symm {A z1 z2} (h12 : are_poly_connected A z1 z2) : are_poly_connected A z2 z1 := begin induction h12, case line : z3 z4 hl { apply line, rwa cIcc_symm }, case poly_trans : _ _ _ _ _ h53 h45 { exact poly_trans h45 h53 } end lemma are_poly_connected_trans {z1 z2 z3 A} (h12 : are_poly_connected A z1 z2) (h23 : are_poly_connected A z2 z3) : are_poly_connected A z1 z3 := poly_trans h12 h23 lemma are_poly_connected_mono {z1 z2 A B} (hs : A ⊆ B) (h : are_poly_connected A z1 z2) : are_poly_connected B z1 z2 := begin induction h, case line : z3 z4 hl { exact line (set.subset.trans hl hs) }, case poly_trans : z3 z4 z5 h35 h54 h53 h45 { exact poly_trans h53 h45 } end /-- A set is polygonally-connected if each pair of points in it is. -/ def is_poly_connected := ∀ {z1 z2}, z1 ∈ A → z2 ∈ A → are_poly_connected A z1 z2 /-- Two complex numbers are step-connected in a set `A` if they are connected by a horizontal or vertical line in `A` or by transitivity. -/ inductive are_step_connected (A : set ℂ) : ℂ → ℂ → Prop | hor {z1 z2 : ℂ} : z1.im = z2.im → cIcc z1 z2 ⊆ A → are_step_connected z1 z2 | ver {z1 z2 : ℂ} : z1.re = z2.re → cIcc z1 z2 ⊆ A → are_step_connected z1 z2 | step_trans {z1 z2 z3 : ℂ} : are_step_connected z1 z3 → are_step_connected z3 z2 → are_step_connected z1 z2 open are_step_connected lemma are_step_connected_refl {A z1} (h : z1 ∈ A) : are_step_connected A z1 z1 := by apply hor rfl; rwa [cIcc_self, singleton_subset_iff] lemma are_step_connected_trans {z1 z2 z3 A} (h12 : are_step_connected A z1 z2) (h23 : are_step_connected A z2 z3) : are_step_connected A z1 z3 := step_trans h12 h23 lemma are_step_connected_symm {A z1 z2} (h12 : are_step_connected A z1 z2) : are_step_connected A z2 z1 := begin induction h12, case hor : z3 z4 hi hl { apply hor hi.symm, rwa cIcc_symm }, case ver : z3 z4 hr hl { apply ver hr.symm, rwa cIcc_symm }, case step_trans : z3 z4 z5 h35 h54 h53 h45 { exact step_trans h45 h53 } end lemma are_step_connected_mem {z1 z2 A} (h : are_step_connected A z1 z2) : z1 ∈ A ∧ z2 ∈ A:= begin induction h, case hor : z3 z4 hi hl { use [hl (cIcc_endpoints _ _).left, hl (cIcc_endpoints _ _).right] }, case ver : z3 z4 hr hl { use [hl (cIcc_endpoints _ _).left, hl (cIcc_endpoints _ _).right] }, case step_trans : z3 z4 z5 h35 h54 h53 h45 { use [h53.left, h45.right] } end lemma are_poly_connected_of_are_step_connected {A z1 z2} (h12 : are_step_connected A z1 z2) : are_poly_connected A z1 z2 := begin induction h12, case hor : z3 z4 hi hl { exact line hl }, case ver : z3 z4 hr hl { exact line hl }, case step_trans : _ _ _ _ _ h1 h2 { exact are_poly_connected_trans h1 h2 } end lemma are_step_connected_mono {z1 z2 A B} (hs : A ⊆ B) (h : are_step_connected A z1 z2): are_step_connected B z1 z2 := begin induction h, case hor : z3 z4 hi hl { exact hor hi (set.subset.trans hl hs) }, case ver : z3 z4 hr hl { exact ver hr (set.subset.trans hl hs) }, case step_trans : _ _ _ _ _ h1 h2 { exact step_trans h1 h2 } end /-- A set is step-connected if each pair of points in it is. -/ def is_step_connected := ∀ {z1 z2}, z1 ∈ A → z2 ∈ A → are_step_connected A z1 z2 lemma is_poly_connected_of_is_step_connected {A} (h : is_step_connected A) : is_poly_connected A := λ x y hx hy, are_poly_connected_of_are_step_connected (h hx hy) open metric lemma is_step_connected_ball : is_step_connected (ball z1 ↑rp) := begin suffices heq : ∀ z ∈ ball z1 ↑rp, are_step_connected (ball z1 ↑rp) z z1, { intros x y hx hy, exact are_step_connected_trans (heq x hx) (are_step_connected_symm (heq y hy))}, intros z hz, apply @step_trans _ _ _ ⟨z.re, z1.im⟩, { refine ver rfl _, rintro w ⟨t, ⟨ht0, ht1⟩, rfl⟩, rw [mem_ball, dist_eq] at hz ⊢, change abs (z + _ * ⟨z.re - z.re, (z1 - z).im⟩ - z1) < _, rw [sub_self, ←sub_add_eq_add_sub, ←re_add_im ⟨0, _⟩], show abs (z - _ + _ * (0 + ↑(z1 - z).im * I)) < _, rw [zero_add, mul_mul_div (_ * I) (two_ne_zero'), mul_right_comm _ I], norm_cast, rw [mul_comm (im _), ←sub_conj, ←mul_one (z-z1), mul_left_comm, ←div_eq_mul_one_div, sub_mul (z1-z), ←add_sub_assoc, ←neg_sub z, ←neg_mul_eq_neg_mul, ←sub_eq_add_neg, ←mul_sub, neg_sub z, sub_eq_add_neg], apply lt_of_le_of_lt (complex.abs_add _ _), norm_cast, rw [complex.abs_neg, complex.abs_mul, complex.abs_mul, abs_conj, complex.abs_sub z1, ←mul_add, ←mul_one ↑rp], refine mul_lt_mul hz _ _ (le_of_lt rp.2); { rw [complex.abs_of_nonneg, complex.abs_of_nonneg]; { linarith }}}, refine hor rfl _, rintro w ⟨t, ⟨ht0, ht1⟩, rfl⟩, rw [mem_ball, dist_eq] at *, rw [←sub_add_eq_add_sub], change abs ((⟨(z - z1).re, z1.im - z1.im⟩ : ℂ) + _ * ⟨(z1 - z).re, z1.im - z1.im⟩) < _, rw [sub_self], change complex.abs (↑(z - z1).re + _ * ↑(z1 - z).re) < _, norm_cast, rw [←one_mul (z - z1).re, ←neg_sub z, neg_re, ←neg_mul_eq_mul_neg, neg_mul_eq_neg_mul], rw [←add_mul, ←one_mul ↑rp, of_real_mul, complex.abs_mul, abs_of_real (re _)], apply mul_lt_mul' _ (lt_of_le_of_lt (abs_re_le_abs _) hz) (abs_nonneg _) (zero_lt_one), rw [complex.abs_of_nonneg]; { linarith } end /-- An open and preconnected set is called a region. -/ def is_region := is_open A ∧ is_preconnected A theorem region_step_connected {A} : is_region A → is_step_connected A := begin classical, rintro ⟨hao, hap⟩ z1 z2 h1 h2, let C := {z | are_step_connected A z1 z}, let D := A ∩ {z | ¬ are_step_connected A z1 z}, by_contra hw, obtain ⟨_, _, _, _, _⟩ := hap C D _ _ _ ⟨_, ⟨h1, are_step_connected_refl h1⟩⟩ ⟨_, h2, ⟨h2, hw⟩⟩, { contradiction }, { rw is_open_iff, rintro x hxz1, rcases (is_open_iff.mp hao) x (are_step_connected_mem hxz1).right with ⟨d, hdp, hb⟩, use [d, hdp], intros y hy, exact are_step_connected_trans hxz1 (are_step_connected_mono hb $ is_step_connected_ball x ⟨d, hdp⟩ (mem_ball_self hdp) hy) }, { rw is_open_iff, rintro x ⟨hx, hxz1⟩, rcases (is_open_iff.mp hao) x hx with ⟨d, hdp, hb⟩, use [d, hdp], intros y hy, use [hb hy], intro hw, replace hw := step_trans hw (are_step_connected_symm (are_step_connected_mono hb $ is_step_connected_ball x ⟨d, hdp⟩ (mem_ball_self hdp) hy)), contradiction }, intros z hz, by_cases hc : are_step_connected A z1 z, { exact or.inl hc }, exact or.inr ⟨hz, hc⟩, end lemma is_poly_connected_ball : is_poly_connected (ball z1 ↑rp) := @is_poly_connected_of_is_step_connected (ball z1 ↑rp) (@is_step_connected_ball z1 rp) lemma is_poly_connected_region (hA : is_region A) : is_poly_connected A := @is_poly_connected_of_is_step_connected A (@region_step_connected A hA)
1f8aa234f7557bdf0e2ce0647746359205440b27
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/category/Top/limits.lean
205dfcc5d2c07b4a828d0c8de60fa52f22e53b44
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
2,735
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Scott Morrison, Mario Carneiro -/ import topology.category.Top.basic import category_theory.limits.types import category_theory.limits.preserves open topological_space open category_theory open category_theory.limits universe u namespace Top variables {J : Type u} [small_category J] local notation `forget` := forget Top def limit (F : J ⥤ Top.{u}) : cone F := { X := ⟨limit (F ⋙ forget), ⨅j, (F.obj j).str.induced (limit.π (F ⋙ forget) j)⟩, π := { app := λ j, ⟨limit.π (F ⋙ forget) j, continuous_iff_le_induced.mpr (infi_le _ _)⟩, naturality' := λ j j' f, subtype.eq ((limit.cone (F ⋙ forget)).π.naturality f) } } def limit_is_limit (F : J ⥤ Top.{u}) : is_limit (limit F) := by { refine is_limit.of_faithful forget (limit.is_limit _) (λ s, ⟨_, _⟩) (λ s, rfl), exact continuous_iff_coinduced_le.mpr (le_infi $ λ j, coinduced_le_iff_le_induced.mp $ continuous_iff_coinduced_le.mp (s.π.app j).property) } instance Top_has_limits : has_limits.{u} Top.{u} := { has_limits_of_shape := λ J 𝒥, { has_limit := λ F, by exactI { cone := limit F, is_limit := limit_is_limit F } } } instance forget_preserves_limits : preserves_limits (forget : Top.{u} ⥤ Type u) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by exactI preserves_limit_of_preserves_limit_cone (limit.is_limit F) (limit.is_limit (F ⋙ forget)) } } def colimit (F : J ⥤ Top.{u}) : cocone F := { X := ⟨colimit (F ⋙ forget), ⨆ j, (F.obj j).str.coinduced (colimit.ι (F ⋙ forget) j)⟩, ι := { app := λ j, ⟨colimit.ι (F ⋙ forget) j, continuous_iff_coinduced_le.mpr (le_supr _ j)⟩, naturality' := λ j j' f, subtype.eq ((colimit.cocone (F ⋙ forget)).ι.naturality f) } } def colimit_is_colimit (F : J ⥤ Top.{u}) : is_colimit (colimit F) := by { refine is_colimit.of_faithful forget (colimit.is_colimit _) (λ s, ⟨_, _⟩) (λ s, rfl), exact continuous_iff_le_induced.mpr (supr_le $ λ j, coinduced_le_iff_le_induced.mp $ continuous_iff_coinduced_le.mp (s.ι.app j).property) } instance Top_has_colimits : has_colimits.{u} Top.{u} := { has_colimits_of_shape := λ J 𝒥, { has_colimit := λ F, by exactI { cocone := colimit F, is_colimit := colimit_is_colimit F } } } instance forget_preserves_colimits : preserves_colimits (forget : Top.{u} ⥤ Type u) := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI preserves_colimit_of_preserves_colimit_cocone (colimit.is_colimit F) (colimit.is_colimit (F ⋙ forget)) } } end Top
037ba6d1fd2398cffff73e5ff60b37cd60c70401
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/differential_object.lean
8ef034bfda0200240cab464eef9dc5a2adff0498
[ "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
8,549
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.shift /-! # Differential objects in a category. A differential object in a category with zero morphisms and a shift is an object `X` equipped with a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`. We build the category of differential objects, and some basic constructions such as the forgetful functor, zero morphisms and zero objects, and the shift functor on differential objects. -/ open category_theory.limits universes v u namespace category_theory variables (C : Type u) [category.{v} C] -- TODO: generaize to `has_shift C A` for an arbitrary `[add_monoid A]` `[has_one A]`. variables [has_zero_morphisms C] [has_shift C ℤ] /-- A differential object in a category with zero morphisms and a shift is an object `X` equipped with a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`. -/ @[nolint has_inhabited_instance] structure differential_object := (X : C) (d : X ⟶ X⟦1⟧) (d_squared' : d ≫ d⟦(1:ℤ)⟧' = 0 . obviously) restate_axiom differential_object.d_squared' attribute [simp] differential_object.d_squared variables {C} namespace differential_object /-- A morphism of differential objects is a morphism commuting with the differentials. -/ @[ext, nolint has_inhabited_instance] structure hom (X Y : differential_object C) := (f : X.X ⟶ Y.X) (comm' : X.d ≫ f⟦1⟧' = f ≫ Y.d . obviously) restate_axiom hom.comm' attribute [simp, reassoc] hom.comm namespace hom /-- The identity morphism of a differential object. -/ @[simps] def id (X : differential_object C) : hom X X := { f := 𝟙 X.X } /-- The composition of morphisms of differential objects. -/ @[simps] def comp {X Y Z : differential_object C} (f : hom X Y) (g : hom Y Z) : hom X Z := { f := f.f ≫ g.f, } end hom instance category_of_differential_objects : category (differential_object C) := { hom := hom, id := hom.id, comp := λ X Y Z f g, hom.comp f g, } @[simp] lemma id_f (X : differential_object C) : ((𝟙 X) : X ⟶ X).f = 𝟙 (X.X) := rfl @[simp] lemma comp_f {X Y Z : differential_object C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).f = f.f ≫ g.f := rfl @[simp] lemma eq_to_hom_f {X Y : differential_object C} (h : X = Y) : hom.f (eq_to_hom h) = eq_to_hom (congr_arg _ h) := by { subst h, rw [eq_to_hom_refl, eq_to_hom_refl], refl } variables (C) /-- The forgetful functor taking a differential object to its underlying object. -/ def forget : (differential_object C) ⥤ C := { obj := λ X, X.X, map := λ X Y f, f.f, } instance forget_faithful : faithful (forget C) := { } instance has_zero_morphisms : has_zero_morphisms (differential_object C) := { has_zero := λ X Y, ⟨{ f := 0 }⟩} variables {C} @[simp] lemma zero_f (P Q : differential_object C) : (0 : P ⟶ Q).f = 0 := rfl /-- An isomorphism of differential objects gives an isomorphism of the underlying objects. -/ @[simps] def iso_app {X Y : differential_object C} (f : X ≅ Y) : X.X ≅ Y.X := ⟨f.hom.f, f.inv.f, by { dsimp, rw [← comp_f, iso.hom_inv_id, id_f] }, by { dsimp, rw [← comp_f, iso.inv_hom_id, id_f] }⟩ @[simp] lemma iso_app_refl (X : differential_object C) : iso_app (iso.refl X) = iso.refl X.X := rfl @[simp] lemma iso_app_symm {X Y : differential_object C} (f : X ≅ Y) : iso_app f.symm = (iso_app f).symm := rfl @[simp] lemma iso_app_trans {X Y Z : differential_object C} (f : X ≅ Y) (g : Y ≅ Z) : iso_app (f ≪≫ g) = iso_app f ≪≫ iso_app g := rfl /-- An isomorphism of differential objects can be constructed from an isomorphism of the underlying objects that commutes with the differentials. -/ @[simps] def mk_iso {X Y : differential_object C} (f : X.X ≅ Y.X) (hf : X.d ≫ f.hom⟦1⟧' = f.hom ≫ Y.d) : X ≅ Y := { hom := ⟨f.hom, hf⟩, inv := ⟨f.inv, by { dsimp, rw [← functor.map_iso_inv, iso.comp_inv_eq, category.assoc, iso.eq_inv_comp, functor.map_iso_hom, hf] }⟩, hom_inv_id' := by { ext1, dsimp, exact f.hom_inv_id }, inv_hom_id' := by { ext1, dsimp, exact f.inv_hom_id } } end differential_object namespace functor universes v' u' variables (D : Type u') [category.{v'} D] variables [has_zero_morphisms D] [has_shift D ℤ] /-- A functor `F : C ⥤ D` which commutes with shift functors on `C` and `D` and preserves zero morphisms can be lifted to a functor `differential_object C ⥤ differential_object D`. -/ @[simps] def map_differential_object (F : C ⥤ D) (η : (shift_functor C (1:ℤ)).comp F ⟶ F.comp (shift_functor D (1:ℤ))) (hF : ∀ c c', F.map (0 : c ⟶ c') = 0) : differential_object C ⥤ differential_object D := { obj := λ X, { X := F.obj X.X, d := F.map X.d ≫ η.app X.X, d_squared' := begin rw [functor.map_comp, ← functor.comp_map F (shift_functor D (1:ℤ))], slice_lhs 2 3 { rw [← η.naturality X.d] }, rw [functor.comp_map], slice_lhs 1 2 { rw [← F.map_comp, X.d_squared, hF] }, rw [zero_comp, zero_comp], end }, map := λ X Y f, { f := F.map f.f, comm' := begin dsimp, slice_lhs 2 3 { rw [← functor.comp_map F (shift_functor D (1:ℤ)), ← η.naturality f.f] }, slice_lhs 1 2 { rw [functor.comp_map, ← F.map_comp, f.comm, F.map_comp] }, rw [category.assoc] end }, map_id' := by { intros, ext, simp }, map_comp' := by { intros, ext, simp }, } end functor end category_theory namespace category_theory namespace differential_object variables (C : Type u) [category.{v} C] variables [has_zero_object C] [has_zero_morphisms C] [has_shift C ℤ] open_locale zero_object instance has_zero_object : has_zero_object (differential_object C) := { zero := { X := (0 : C), d := 0, }, unique_to := λ X, ⟨⟨{ f := 0 }⟩, λ f, (by ext)⟩, unique_from := λ X, ⟨⟨{ f := 0 }⟩, λ f, (by ext)⟩, } end differential_object namespace differential_object variables (C : Type (u+1)) [large_category C] [concrete_category C] [has_zero_morphisms C] [has_shift C ℤ] instance concrete_category_of_differential_objects : concrete_category (differential_object C) := { forget := forget C ⋙ category_theory.forget C } instance : has_forget₂ (differential_object C) C := { forget₂ := forget C } end differential_object /-! The category of differential objects itself has a shift functor. -/ namespace differential_object variables (C : Type u) [category.{v} C] variables [has_zero_morphisms C] [has_shift C ℤ] noncomputable theory /-- The shift functor on `differential_object C`. -/ @[simps] def shift_functor (n : ℤ) : differential_object C ⥤ differential_object C := { obj := λ X, { X := X.X⟦n⟧, d := X.d⟦n⟧' ≫ (shift_comm _ _ _).hom, d_squared' := by rw [functor.map_comp, category.assoc, shift_comm_hom_comp_assoc, ←functor.map_comp_assoc, X.d_squared, is_equivalence_preserves_zero_morphisms, zero_comp] }, map := λ X Y f, { f := f.f⟦n⟧', comm' := by { dsimp, rw [category.assoc, shift_comm_hom_comp, ← functor.map_comp_assoc, f.comm, functor.map_comp_assoc], }, }, map_id' := by { intros X, ext1, dsimp, rw functor.map_id }, map_comp' := by { intros X Y Z f g, ext1, dsimp, rw functor.map_comp } } local attribute [instance] endofunctor_monoidal_category discrete.add_monoidal local attribute [reducible] endofunctor_monoidal_category discrete.add_monoidal shift_comm /-- The shift functor on `differential_object C` is additive. -/ @[simps] def shift_functor_add (m n : ℤ) : shift_functor C (m + n) ≅ shift_functor C m ⋙ shift_functor C n := begin refine nat_iso.of_components (λ X, mk_iso (shift_add X.X _ _) _) _, { dsimp, simp only [obj_μ_app, μ_naturality_assoc, μ_naturalityₗ_assoc, μ_inv_hom_app_assoc, category.assoc, obj_μ_inv_app, functor.map_comp, μ_inv_naturalityᵣ_assoc], simp [opaque_eq_to_iso] }, { intros X Y f, ext, dsimp, exact nat_trans.naturality _ _ } end /-- The shift by zero is naturally isomorphic to the identity. -/ @[simps] def shift_ε : 𝟭 (differential_object C) ≅ shift_functor C 0 := begin refine nat_iso.of_components (λ X, mk_iso ((shift_monoidal_functor C ℤ).ε_iso.app X.X) _) _, { dsimp, simp, dsimp, simp }, { introv, ext, dsimp, simp } end instance : has_shift (differential_object C) ℤ := has_shift_mk _ _ { F := shift_functor C, ε := shift_ε C, μ := λ m n, (shift_functor_add C m n).symm } end differential_object end category_theory
c737cfe01508f72696c189627c80bc6d34d2520e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/634c.lean
40c6a6bc6dd180b01d50532cab5c1fe1b1cdbbf4
[ "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
946
lean
open nat section parameter (X : Type₁) definition A {n : ℕ} : Type₁ := X definition B : Type₁ := X variable {n : ℕ} check @A n check _root_.A nat check _root_.A (X × B) check @_root_.A (X × B) 10 check @_root_.A (_root_.B (@_root_.A X n)) n check @_root_.A (@_root_.B (@_root_.A nat n)) n set_option pp.full_names true check A check _root_.A nat check @_root_.A (X × B) 10 check @_root_.A (@_root_.B (@_root_.A X n)) n check @_root_.A (@_root_.B (@_root_.A nat n)) n set_option pp.full_names false set_option pp.implicit true check @A n check @_root_.A nat 10 check @_root_.A X n set_option pp.full_names true check @_root_.A X n check @_root_.A B n set_option pp.full_names false check @_root_.A X n check @_root_.A B n check @_root_.A (@_root_.B (@A n)) n check @_root_.A (@_root_.B (@_root_.A X n)) n check @_root_.A (@_root_.B (@_root_.A nat n)) n check @A n end